• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <arpa/inet.h>
16 #include <sys/time.h>
17 #include <utility>
18 #include "openssl/crypto.h"
19 #include "openssl/sha.h"
20 #include "videodec_ndk_sample.h"
21 using namespace OHOS;
22 using namespace OHOS::Media;
23 using namespace std;
24 namespace {
25 constexpr int64_t NANOS_IN_SECOND = 1000000000L;
26 constexpr int64_t MICRO_IN_SECOND = 1000000L;
27 constexpr int64_t NANOS_IN_MICRO = 1000L;
28 constexpr int32_t THREE = 3;
29 constexpr int32_t EIGHT = 8;
30 constexpr int32_t TEN = 10;
31 constexpr int32_t SIXTEEN = 16;
32 constexpr int32_t TWENTY_FOUR = 24;
33 constexpr uint8_t H264_NALU_TYPE = 0x1f;
34 constexpr uint32_t START_CODE_SIZE = 4;
35 constexpr uint8_t START_CODE[START_CODE_SIZE] = {0, 0, 0, 1};
36 constexpr uint8_t SPS = 7;
37 constexpr uint8_t PPS = 8;
38 constexpr int32_t RES_CHANGE_TIME = 4;
39 constexpr int32_t CROP_INFO_SIZE = 2;
40 constexpr int32_t CROP_INFO[RES_CHANGE_TIME][CROP_INFO_SIZE] = {{621, 1103},
41     {1079, 1919}, {719, 1279}, {855, 1919}};
42 
43 constexpr int32_t CROP_BOTTOM = 0;
44 constexpr int32_t CROP_RIGHT = 1;
45 
46 
47 SHA512_CTX c;
48 unsigned char md[SHA512_DIGEST_LENGTH];
49 VDecNdkSample *dec_sample = nullptr;
50 
clearIntqueue(std::queue<uint32_t> & q)51 void clearIntqueue(std::queue<uint32_t> &q)
52 {
53     std::queue<uint32_t> empty;
54     swap(empty, q);
55 }
56 
clearBufferqueue(std::queue<OH_AVCodecBufferAttr> & q)57 void clearBufferqueue(std::queue<OH_AVCodecBufferAttr> &q)
58 {
59     std::queue<OH_AVCodecBufferAttr> empty;
60     swap(empty, q);
61 }
62 } // namespace
63 
64 class TestConsumerListener : public IBufferConsumerListener {
65 public:
TestConsumerListener(sptr<Surface> cs,std::string_view name)66     TestConsumerListener(sptr<Surface> cs, std::string_view name) : cs(cs) {};
~TestConsumerListener()67     ~TestConsumerListener() {}
OnBufferAvailable()68     void OnBufferAvailable() override
69     {
70         sptr<SurfaceBuffer> buffer;
71         int32_t flushFence;
72         cs->AcquireBuffer(buffer, flushFence, timestamp, damage);
73 
74         cs->ReleaseBuffer(buffer, -1);
75     }
76 
77 private:
78     int64_t timestamp = 0;
79     Rect damage = {};
80     sptr<Surface> cs {nullptr};
81 };
82 
~VDecNdkSample()83 VDecNdkSample::~VDecNdkSample()
84 {
85     for (int i = 0; i < MAX_SURF_NUM; i++) {
86         if (nativeWindow[i]) {
87             OH_NativeWindow_DestroyNativeWindow(nativeWindow[i]);
88             nativeWindow[i] = nullptr;
89         }
90     }
91     Stop();
92     Release();
93 }
94 
VdecError(OH_AVCodec * codec,int32_t errorCode,void * userData)95 void VdecError(OH_AVCodec *codec, int32_t errorCode, void *userData)
96 {
97     cout << "Error errorCode=" << errorCode << endl;
98 }
99 
VdecFormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)100 void VdecFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
101 {
102     int32_t current_width = 0;
103     int32_t current_height = 0;
104     OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, &current_width);
105     OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, &current_height);
106     dec_sample->DEFAULT_WIDTH = current_width;
107     dec_sample->DEFAULT_HEIGHT = current_height;
108     if (dec_sample->isResChangeStream) {
109         static int32_t resCount = 0;
110         int32_t cropBottom = 0;
111         int32_t cropRight = 0;
112         int32_t stride = 0;
113         int32_t sliceHeight = 0;
114         OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
115         OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
116         OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_STRIDE, &stride);
117         OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
118         if (cropBottom != CROP_INFO[resCount][CROP_BOTTOM] || cropRight != CROP_INFO[resCount][CROP_RIGHT]) {
119             dec_sample->errCount++;
120         }
121         if (stride <= 0 || sliceHeight <= 0) {
122             dec_sample->errCount++;
123         }
124         resCount++;
125     }
126 }
127 
VdecInputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVMemory * data,void * userData)128 void VdecInputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
129 {
130     if (dec_sample->inputCallbackFlush && dec_sample->outCount > 1) {
131         OH_VideoDecoder_Flush(codec);
132         cout << "OH_VideoDecoder_Flush end" << endl;
133         dec_sample->isRunning_.store(false);
134         dec_sample->signal_->inCond_.notify_all();
135         dec_sample->signal_->outCond_.notify_all();
136         return;
137     }
138     if (dec_sample->inputCallbackStop && dec_sample->outCount > 1) {
139         OH_VideoDecoder_Stop(codec);
140         cout << "OH_VideoDecoder_Stop end" << endl;
141         dec_sample->isRunning_.store(false);
142         dec_sample->signal_->inCond_.notify_all();
143         dec_sample->signal_->outCond_.notify_all();
144         return;
145     }
146     VDecSignal *signal = static_cast<VDecSignal *>(userData);
147     unique_lock<mutex> lock(signal->inMutex_);
148     signal->inIdxQueue_.push(index);
149     signal->inBufferQueue_.push(data);
150     signal->inCond_.notify_all();
151 }
152 
VdecOutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVMemory * data,OH_AVCodecBufferAttr * attr,void * userData)153 void VdecOutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
154                          void *userData)
155 {
156     if (dec_sample->outputCallbackFlush && dec_sample->outCount > 1) {
157         OH_VideoDecoder_Flush(codec);
158         cout << "OH_VideoDecoder_Flush end" << endl;
159         dec_sample->isRunning_.store(false);
160         dec_sample->signal_->inCond_.notify_all();
161         dec_sample->signal_->outCond_.notify_all();
162         return;
163     }
164     if (dec_sample->outputCallbackStop && dec_sample->outCount > 1) {
165         OH_VideoDecoder_Stop(codec);
166         cout << "OH_VideoDecoder_Stop end" << endl;
167         dec_sample->isRunning_.store(false);
168         dec_sample->signal_->inCond_.notify_all();
169         dec_sample->signal_->outCond_.notify_all();
170         return;
171     }
172     VDecSignal *signal = static_cast<VDecSignal *>(userData);
173     unique_lock<mutex> lock(signal->outMutex_);
174     signal->outIdxQueue_.push(index);
175     signal->attrQueue_.push(*attr);
176     signal->outBufferQueue_.push(data);
177     signal->outCond_.notify_all();
178 }
179 
Flush_buffer()180 void VDecNdkSample::Flush_buffer()
181 {
182     unique_lock<mutex> inLock(signal_->inMutex_);
183     clearIntqueue(signal_->inIdxQueue_);
184     std::queue<OH_AVMemory *> empty;
185     swap(empty, signal_->inBufferQueue_);
186     signal_->inCond_.notify_all();
187     inLock.unlock();
188     unique_lock<mutex> outLock(signal_->outMutex_);
189     clearIntqueue(signal_->outIdxQueue_);
190     clearBufferqueue(signal_->attrQueue_);
191     signal_->outCond_.notify_all();
192     outLock.unlock();
193 }
194 
MdCompare(unsigned char buffer[],int len,const char * source[])195 bool VDecNdkSample::MdCompare(unsigned char buffer[], int len, const char *source[])
196 {
197     bool result = true;
198     for (int i = 0; i < len; i++) {
199     }
200     return result;
201 }
202 
GetSystemTimeUs()203 int64_t VDecNdkSample::GetSystemTimeUs()
204 {
205     struct timespec now;
206     (void)clock_gettime(CLOCK_BOOTTIME, &now);
207     int64_t nanoTime = (int64_t)now.tv_sec * NANOS_IN_SECOND + now.tv_nsec;
208     return nanoTime / NANOS_IN_MICRO;
209 }
210 
ConfigureVideoDecoder()211 int32_t VDecNdkSample::ConfigureVideoDecoder()
212 {
213     if (autoSwitchSurface) {
214         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
215         if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_INVALID_STATE) {
216             errCount++;
217         }
218     }
219     OH_AVFormat *format = OH_AVFormat_Create();
220     if (format == nullptr) {
221         cout << "Fatal: Failed to create format" << endl;
222         return AV_ERR_UNKNOWN;
223     }
224     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
225     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
226     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
227     (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
228     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENABLE_LOW_LATENCY, 1);
229     int ret = OH_VideoDecoder_Configure(vdec_, format);
230     OH_AVFormat_Destroy(format);
231     return ret;
232 }
233 
CreateSurface()234 void VDecNdkSample::CreateSurface()
235 {
236     cs[0] = Surface::CreateSurfaceAsConsumer();
237     sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs[0], OUT_DIR);
238     cs[0]->RegisterConsumerListener(listener);
239     auto p = cs[0]->GetProducer();
240     ps[0] = Surface::CreateSurfaceAsProducer(p);
241     nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
242     if (autoSwitchSurface)  {
243         cs[1] = Surface::CreateSurfaceAsConsumer();
244         sptr<IBufferConsumerListener> listener2 = new TestConsumerListener(cs[1], OUT_DIR2);
245         cs[1]->RegisterConsumerListener(listener2);
246         auto p2 = cs[1]->GetProducer();
247         ps[1] = Surface::CreateSurfaceAsProducer(p2);
248         nativeWindow[1] = CreateNativeWindowFromSurface(&ps[1]);
249     }
250 }
251 
RunVideoDec_Surface(string codeName)252 int32_t VDecNdkSample::RunVideoDec_Surface(string codeName)
253 {
254     SF_OUTPUT = true;
255     int err = AV_ERR_OK;
256     CreateSurface();
257     if (!nativeWindow[0]) {
258         cout << "Failed to create surface" << endl;
259         return AV_ERR_UNKNOWN;
260     }
261     err = CreateVideoDecoder(codeName);
262     if (err != AV_ERR_OK) {
263         cout << "Failed to create video decoder" << endl;
264         return err;
265     }
266     err = SetVideoDecoderCallback();
267     if (err != AV_ERR_OK) {
268         cout << "Failed to setCallback" << endl;
269         Release();
270         return err;
271     }
272     err = ConfigureVideoDecoder();
273     if (err != AV_ERR_OK) {
274         cout << "Failed to configure video decoder" << endl;
275         Release();
276         return err;
277     }
278     err = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
279     if (err != AV_ERR_OK) {
280         cout << "Failed to set surface" << endl;
281         return err;
282     }
283     err = StartVideoDecoder();
284     if (err != AV_ERR_OK) {
285         cout << "Failed to start video decoder" << endl;
286         Release();
287         return err;
288     }
289     return err;
290 }
291 
RunVideoDec(string codeName)292 int32_t VDecNdkSample::RunVideoDec(string codeName)
293 {
294     SF_OUTPUT = false;
295     int err = CreateVideoDecoder(codeName);
296     if (err != AV_ERR_OK) {
297         cout << "Failed to create video decoder" << endl;
298         return err;
299     }
300 
301     err = ConfigureVideoDecoder();
302     if (err != AV_ERR_OK) {
303         cout << "Failed to configure video decoder" << endl;
304         Release();
305         return err;
306     }
307 
308     err = SetVideoDecoderCallback();
309     if (err != AV_ERR_OK) {
310         cout << "Failed to setCallback" << endl;
311         Release();
312         return err;
313     }
314 
315     err = StartVideoDecoder();
316     if (err != AV_ERR_OK) {
317         cout << "Failed to start video decoder" << endl;
318         Release();
319         return err;
320     }
321     return err;
322 }
323 
SetVideoDecoderCallback()324 int32_t VDecNdkSample::SetVideoDecoderCallback()
325 {
326     signal_ = new VDecSignal();
327     if (signal_ == nullptr) {
328         cout << "Failed to new VDecSignal" << endl;
329         return AV_ERR_UNKNOWN;
330     }
331 
332     cb_.onError = VdecError;
333     cb_.onStreamChanged = VdecFormatChanged;
334     cb_.onNeedInputData = VdecInputDataReady;
335     cb_.onNeedOutputData = VdecOutputDataReady;
336     return OH_VideoDecoder_SetCallback(vdec_, cb_, static_cast<void *>(signal_));
337 }
338 
ReleaseInFile()339 void VDecNdkSample::ReleaseInFile()
340 {
341     if (inFile_ != nullptr) {
342         if (inFile_->is_open()) {
343             inFile_->close();
344         }
345         inFile_.reset();
346         inFile_ = nullptr;
347     }
348 }
349 
StopInloop()350 void VDecNdkSample::StopInloop()
351 {
352     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
353         unique_lock<mutex> lock(signal_->inMutex_);
354         clearIntqueue(signal_->inIdxQueue_);
355         isRunning_.store(false);
356         signal_->inCond_.notify_all();
357         lock.unlock();
358 
359         inputLoop_->join();
360         inputLoop_.reset();
361     }
362 }
363 
CreateVideoDecoder(string codeName)364 int32_t VDecNdkSample::CreateVideoDecoder(string codeName)
365 {
366     vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
367     dec_sample = this;
368     return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
369 }
370 
StartVideoDecoder()371 int32_t VDecNdkSample::StartVideoDecoder()
372 {
373     isRunning_.store(true);
374     int ret = OH_VideoDecoder_Start(vdec_);
375     if (ret != AV_ERR_OK) {
376         cout << "Failed to start codec" << endl;
377         isRunning_.store(false);
378         ReleaseInFile();
379         Release();
380         return ret;
381     }
382     inFile_ = make_unique<ifstream>();
383     if (inFile_ == nullptr) {
384         isRunning_.store(false);
385         (void)OH_VideoDecoder_Stop(vdec_);
386         return AV_ERR_UNKNOWN;
387     }
388     inFile_->open(INP_DIR, ios::in | ios::binary);
389     if (!inFile_->is_open()) {
390         cout << "failed open file " << INP_DIR << endl;
391         isRunning_.store(false);
392         (void)OH_VideoDecoder_Stop(vdec_);
393         inFile_->close();
394         inFile_.reset();
395         inFile_ = nullptr;
396         return AV_ERR_UNKNOWN;
397     }
398 
399     inputLoop_ = make_unique<thread>(&VDecNdkSample::InputFuncTest, this);
400     if (inputLoop_ == nullptr) {
401         cout << "Failed to create input loop" << endl;
402         isRunning_.store(false);
403         (void)OH_VideoDecoder_Stop(vdec_);
404         ReleaseInFile();
405         return AV_ERR_UNKNOWN;
406     }
407     outputLoop_ = make_unique<thread>(&VDecNdkSample::OutputFuncTest, this);
408     if (outputLoop_ == nullptr) {
409         cout << "Failed to create output loop" << endl;
410         isRunning_.store(false);
411         (void)OH_VideoDecoder_Stop(vdec_);
412         ReleaseInFile();
413         StopInloop();
414         Release();
415         return AV_ERR_UNKNOWN;
416     }
417 
418     return AV_ERR_OK;
419 }
420 
testAPI()421 void VDecNdkSample::testAPI()
422 {
423     cs[0] = Surface::CreateSurfaceAsConsumer();
424     sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs[0], OUT_DIR);
425     cs[0]->RegisterConsumerListener(listener);
426     auto p = cs[0]->GetProducer();
427     ps[0] = Surface::CreateSurfaceAsProducer(p);
428     nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
429     OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
430 
431     OH_VideoDecoder_Prepare(vdec_);
432     OH_VideoDecoder_Start(vdec_);
433 
434     OH_AVFormat *format = OH_AVFormat_Create();
435     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
436     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
437     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
438     (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
439     OH_VideoDecoder_SetParameter(vdec_, format);
440     OH_AVFormat_Destroy(format);
441     OH_VideoDecoder_GetOutputDescription(vdec_);
442     OH_VideoDecoder_Flush(vdec_);
443     OH_VideoDecoder_Stop(vdec_);
444     OH_VideoDecoder_Reset(vdec_);
445     bool isvalid = false;
446     OH_VideoDecoder_IsValid(vdec_, &isvalid);
447 }
448 
WaitForEOS()449 void VDecNdkSample::WaitForEOS()
450 {
451     if (!AFTER_EOS_DESTORY_CODEC && inputLoop_ && inputLoop_->joinable()) {
452         inputLoop_->join();
453     }
454 
455     if (outputLoop_ && outputLoop_->joinable()) {
456         outputLoop_->join();
457     }
458 }
459 
InputFuncTest()460 void VDecNdkSample::InputFuncTest()
461 {
462     while (true) {
463         if (!isRunning_.load()) {
464             break;
465         }
466         if (REPEAT_START_FLUSH_BEFORE_EOS > 0) {
467             REPEAT_START_FLUSH_BEFORE_EOS--;
468             OH_VideoDecoder_Flush(vdec_);
469             Flush_buffer();
470             OH_VideoDecoder_Start(vdec_);
471         }
472         if (REPEAT_START_STOP_BEFORE_EOS > 0) {
473             REPEAT_START_STOP_BEFORE_EOS--;
474             OH_VideoDecoder_Stop(vdec_);
475             Flush_buffer();
476             OH_VideoDecoder_Start(vdec_);
477         }
478         uint32_t index;
479         unique_lock<mutex> lock(signal_->inMutex_);
480         signal_->inCond_.wait(lock, [this]() {
481             if (!isRunning_.load()) {
482                 return true;
483             }
484             return signal_->inIdxQueue_.size() > 0;
485         });
486         if (!isRunning_.load()) {
487             break;
488         }
489         index = signal_->inIdxQueue_.front();
490         auto buffer = signal_->inBufferQueue_.front();
491 
492         signal_->inIdxQueue_.pop();
493         signal_->inBufferQueue_.pop();
494         lock.unlock();
495         if (!inFile_->eof()) {
496             int ret = PushData(index, buffer);
497             if (ret == 1) {
498                 break;
499             }
500         }
501         if (sleepOnFPS) {
502             usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
503         }
504     }
505 }
506 
PushData(uint32_t index,OH_AVMemory * buffer)507 int32_t VDecNdkSample::PushData(uint32_t index, OH_AVMemory *buffer)
508 {
509     static uint32_t repeat_count = 0;
510     OH_AVCodecBufferAttr attr;
511     if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
512         SetEOS(index);
513         return 1;
514     }
515     if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
516         memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
517         attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
518         BEFORE_EOS_INPUT_INPUT = false;
519     }
520     char ch[4] = {};
521     (void)inFile_->read(ch, START_CODE_SIZE);
522     if (repeatRun && inFile_->eof()) {
523         inFile_->clear();
524         inFile_->seekg(0, ios::beg);
525         cout << "repeat run " << repeat_count << endl;
526         repeat_count++;
527         return 0;
528     }
529     if (inFile_->eof()) {
530         SetEOS(index);
531         return 1;
532     }
533     uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
534                                      ((ch[0] & 0xFF) << TWENTY_FOUR));
535     if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
536         cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
537         return 1;
538     }
539 
540     return SendData(bufferSize, index, buffer);
541 }
542 
SendData(uint32_t bufferSize,uint32_t index,OH_AVMemory * buffer)543 uint32_t VDecNdkSample::SendData(uint32_t bufferSize, uint32_t index, OH_AVMemory *buffer)
544 {
545     OH_AVCodecBufferAttr attr;
546     uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
547     if (fileBuffer == nullptr) {
548         delete[] fileBuffer;
549         return 0;
550     }
551     if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
552         cout << "Fatal: memory copy failed" << endl;
553     }
554     (void)inFile_->read((char *)fileBuffer + START_CODE_SIZE, bufferSize);
555     if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
556         (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
557         attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
558     } else {
559         attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
560     }
561     int32_t size = OH_AVMemory_GetSize(buffer);
562     if (size < bufferSize + START_CODE_SIZE) {
563         delete[] fileBuffer;
564         return 0;
565     }
566     uint8_t *avBuffer = OH_AVMemory_GetAddr(buffer);
567     if (avBuffer == nullptr) {
568         cout << "avBuffer == nullptr" << endl;
569         inFile_->clear();
570         inFile_->seekg(0, ios::beg);
571         delete[] fileBuffer;
572         return 0;
573     }
574     if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
575         delete[] fileBuffer;
576         return 0;
577     }
578     int64_t startPts = GetSystemTimeUs();
579     attr.pts = startPts;
580     attr.size = bufferSize + START_CODE_SIZE;
581     attr.offset = 0;
582     if (isRunning_.load()) {
583         OH_VideoDecoder_PushInputData(vdec_, index, attr) == AV_ERR_OK ? (0) : (errCount++);
584         frameCount_ = frameCount_ + 1;
585         outCount = outCount + 1;
586         if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
587             switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
588             OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
589         }
590     }
591     delete[] fileBuffer;
592     return 0;
593 }
594 
CheckOutputDescription()595 void VDecNdkSample::CheckOutputDescription()
596 {
597     OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
598     if (newFormat != nullptr) {
599         int32_t cropTop = 0;
600         int32_t cropBottom = 0;
601         int32_t cropLeft = 0;
602         int32_t cropRight = 0;
603         int32_t stride = 0;
604         int32_t sliceHeight = 0;
605         int32_t picWidth = 0;
606         int32_t picHeight = 0;
607         int32_t qp_average = 0;
608         double mse = 1.0;
609         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
610         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
611         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
612         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
613         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
614         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
615         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
616         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
617         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_ENCODER_QP_AVERAGE, &qp_average);
618         OH_AVFormat_GetDoubleValue(newFormat, OH_MD_KEY_VIDEO_ENCODER_MSE, &mse);
619 
620         if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
621             errCount++;
622         }
623         if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
624             errCount++;
625         }
626     } else {
627         errCount++;
628     }
629     OH_AVFormat_Destroy(newFormat);
630 }
631 
AutoSwitchSurface()632 void VDecNdkSample::AutoSwitchSurface()
633 {
634     if (autoSwitchSurface) {
635         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
636         if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
637             errCount++;
638         }
639     }
640 }
641 
OutputFuncTest()642 void VDecNdkSample::OutputFuncTest()
643 {
644     SHA512_Init(&c);
645     while (true) {
646         if (!isRunning_.load()) {
647             break;
648         }
649         OH_AVCodecBufferAttr attr;
650         uint32_t index;
651         unique_lock<mutex> lock(signal_->outMutex_);
652         signal_->outCond_.wait(lock, [this]() {
653             if (!isRunning_.load()) {
654                 return true;
655             }
656             return signal_->outIdxQueue_.size() > 0;
657         });
658         if (!isRunning_.load()) {
659             break;
660         }
661         index = signal_->outIdxQueue_.front();
662         attr = signal_->attrQueue_.front();
663         OH_AVMemory *buffer = signal_->outBufferQueue_.front();
664         signal_->outBufferQueue_.pop();
665         signal_->outIdxQueue_.pop();
666         signal_->attrQueue_.pop();
667         lock.unlock();
668         if (needCheckOutputDesc) {
669             CheckOutputDescription();
670             needCheckOutputDesc = false;
671         }
672         if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) {
673             AutoSwitchSurface();
674             SHA512_Final(md, &c);
675             OPENSSL_cleanse(&c, sizeof(c));
676             MdCompare(md, SHA512_DIGEST_LENGTH, fileSourcesha256);
677             break;
678         }
679         ProcessOutputData(buffer, index);
680         if (errCount > 0) {
681             break;
682         }
683     }
684 }
685 
ProcessOutputData(OH_AVMemory * buffer,uint32_t index)686 void VDecNdkSample::ProcessOutputData(OH_AVMemory *buffer, uint32_t index)
687 {
688     if (!SF_OUTPUT) {
689         uint32_t size = OH_AVMemory_GetSize(buffer);
690         if (size >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
691             uint8_t *cropBuffer = new uint8_t[size];
692             if (memcpy_s(cropBuffer, size, OH_AVMemory_GetAddr(buffer),
693                          DEFAULT_WIDTH * DEFAULT_HEIGHT) != EOK) {
694                 cout << "Fatal: memory copy failed Y" << endl;
695             }
696             // copy UV
697             uint32_t uvSize = size - DEFAULT_WIDTH * DEFAULT_HEIGHT;
698             if (memcpy_s(cropBuffer + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize,
699                          OH_AVMemory_GetAddr(buffer) + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize) != EOK) {
700                 cout << "Fatal: memory copy failed UV" << endl;
701             }
702             SHA512_Update(&c, cropBuffer, size);
703             delete[] cropBuffer;
704         }
705         if (OH_VideoDecoder_FreeOutputData(vdec_, index) != AV_ERR_OK) {
706             cout << "Fatal: ReleaseOutputBuffer fail" << endl;
707             errCount = errCount + 1;
708         }
709     } else {
710         if (OH_VideoDecoder_RenderOutputData(vdec_, index) != AV_ERR_OK) {
711             cout << "Fatal: RenderOutputBuffer fail" << endl;
712             errCount = errCount + 1;
713         }
714     }
715 }
716 
state_EOS()717 int32_t VDecNdkSample::state_EOS()
718 {
719     uint32_t index;
720     unique_lock<mutex> lock(signal_->inMutex_);
721     signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
722     index = signal_->inIdxQueue_.front();
723     signal_->inIdxQueue_.pop();
724     signal_->inBufferQueue_.pop();
725     lock.unlock();
726     OH_AVCodecBufferAttr attr;
727     attr.pts = 0;
728     attr.size = 0;
729     attr.offset = 0;
730     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
731     return OH_VideoDecoder_PushInputData(vdec_, index, attr);
732 }
733 
SetEOS(uint32_t index)734 void VDecNdkSample::SetEOS(uint32_t index)
735 {
736     OH_AVCodecBufferAttr attr;
737     attr.pts = 0;
738     attr.size = 0;
739     attr.offset = 0;
740     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
741     int32_t res = OH_VideoDecoder_PushInputData(vdec_, index, attr);
742     cout << "OH_VideoDecoder_PushInputData    EOS   res: " << res << endl;
743 }
744 
Flush()745 int32_t VDecNdkSample::Flush()
746 {
747     unique_lock<mutex> inLock(signal_->inMutex_);
748     clearIntqueue(signal_->inIdxQueue_);
749     signal_->inCond_.notify_all();
750     inLock.unlock();
751     unique_lock<mutex> outLock(signal_->outMutex_);
752     clearIntqueue(signal_->outIdxQueue_);
753     clearBufferqueue(signal_->attrQueue_);
754     signal_->outCond_.notify_all();
755     outLock.unlock();
756     isRunning_.store(false);
757     return OH_VideoDecoder_Flush(vdec_);
758 }
759 
Reset()760 int32_t VDecNdkSample::Reset()
761 {
762     isRunning_.store(false);
763     StopInloop();
764     StopOutloop();
765     ReleaseInFile();
766     return OH_VideoDecoder_Reset(vdec_);
767 }
768 
Release()769 int32_t VDecNdkSample::Release()
770 {
771     int ret = 0;
772     if (vdec_ != nullptr) {
773         ret = OH_VideoDecoder_Destroy(vdec_);
774         vdec_ = nullptr;
775     }
776 
777     if (signal_ != nullptr) {
778         delete signal_;
779         signal_ = nullptr;
780     }
781     return ret;
782 }
783 
Stop()784 int32_t VDecNdkSample::Stop()
785 {
786     StopInloop();
787     StopOutloop();
788     ReleaseInFile();
789     return OH_VideoDecoder_Stop(vdec_);
790 }
791 
Start()792 int32_t VDecNdkSample::Start()
793 {
794     isRunning_.store(true);
795     return OH_VideoDecoder_Start(vdec_);
796 }
797 
StopOutloop()798 void VDecNdkSample::StopOutloop()
799 {
800     if (outputLoop_ != nullptr && outputLoop_->joinable()) {
801         unique_lock<mutex> lock(signal_->outMutex_);
802         clearIntqueue(signal_->outIdxQueue_);
803         clearBufferqueue(signal_->attrQueue_);
804         isRunning_.store(false);
805         signal_->outCond_.notify_all();
806         lock.unlock();
807         outputLoop_->join();
808         outputLoop_.reset();
809     }
810 }
811 
SetParameter(OH_AVFormat * format)812 int32_t VDecNdkSample::SetParameter(OH_AVFormat *format)
813 {
814     return OH_VideoDecoder_SetParameter(vdec_, format);
815 }
816 
SwitchSurface()817 int32_t VDecNdkSample::SwitchSurface()
818 {
819     int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
820     switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
821     cout << "manual switch surf "<< switchSurfaceFlag << endl;
822     return ret;
823 }
824 
RepeatCallSetSurface()825 int32_t VDecNdkSample::RepeatCallSetSurface()
826 {
827     int32_t ret = AV_ERR_OK;
828     for (int i = 0; i < REPEAT_CALL_TIME; i++) {
829         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
830         ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
831         if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT && ret != AV_ERR_INVALID_STATE) {
832             return AV_ERR_OPERATE_NOT_PERMIT;
833         }
834     }
835     return AV_ERR_OK;
836 }