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_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 constexpr int32_t DEFAULT_ANGLE = 90;
46 constexpr int32_t SYS_MAX_INPUT_SIZE = 1024 * 1024 * 24;
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->isFlushing_) {
131         return;
132     }
133 
134     if (dec_sample->inputCallbackFlush && dec_sample->outCount > 1) {
135         dec_sample->Flush();
136         cout << "OH_VideoDecoder_Flush end" << endl;
137         dec_sample->isRunning_.store(false);
138         dec_sample->signal_->inCond_.notify_all();
139         dec_sample->signal_->outCond_.notify_all();
140         return;
141     }
142     if (dec_sample->inputCallbackStop && dec_sample->outCount > 1) {
143         OH_VideoDecoder_Stop(codec);
144         cout << "OH_VideoDecoder_Stop end" << endl;
145         dec_sample->isRunning_.store(false);
146         dec_sample->signal_->inCond_.notify_all();
147         dec_sample->signal_->outCond_.notify_all();
148         return;
149     }
150     VDecSignal *signal = static_cast<VDecSignal *>(userData);
151     unique_lock<mutex> lock(signal->inMutex_);
152     signal->inIdxQueue_.push(index);
153     signal->inBufferQueue_.push(data);
154     signal->inCond_.notify_all();
155 }
156 
VdecOutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVMemory * data,OH_AVCodecBufferAttr * attr,void * userData)157 void VdecOutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
158                          void *userData)
159 {
160     if (dec_sample->isFlushing_) {
161         return;
162     }
163     if (dec_sample->outputCallbackFlush && dec_sample->outCount > 1) {
164         dec_sample->Flush();
165         cout << "OH_VideoDecoder_Flush end" << endl;
166         dec_sample->isRunning_.store(false);
167         dec_sample->signal_->inCond_.notify_all();
168         dec_sample->signal_->outCond_.notify_all();
169         return;
170     }
171     if (dec_sample->outputCallbackStop && dec_sample->outCount > 1) {
172         OH_VideoDecoder_Stop(codec);
173         cout << "OH_VideoDecoder_Stop end" << endl;
174         dec_sample->isRunning_.store(false);
175         dec_sample->signal_->inCond_.notify_all();
176         dec_sample->signal_->outCond_.notify_all();
177         return;
178     }
179     VDecSignal *signal = static_cast<VDecSignal *>(userData);
180     unique_lock<mutex> lock(signal->outMutex_);
181     signal->outIdxQueue_.push(index);
182     signal->attrQueue_.push(*attr);
183     signal->outBufferQueue_.push(data);
184     signal->outCond_.notify_all();
185 }
186 
Flush_buffer()187 void VDecNdkSample::Flush_buffer()
188 {
189     unique_lock<mutex> inLock(signal_->inMutex_);
190     clearIntqueue(signal_->inIdxQueue_);
191     std::queue<OH_AVMemory *> empty;
192     swap(empty, signal_->inBufferQueue_);
193     signal_->inCond_.notify_all();
194     inLock.unlock();
195     unique_lock<mutex> outLock(signal_->outMutex_);
196     clearIntqueue(signal_->outIdxQueue_);
197     clearBufferqueue(signal_->attrQueue_);
198     signal_->outCond_.notify_all();
199     outLock.unlock();
200 }
201 
MdCompare(unsigned char buffer[],int len,const char * source[])202 bool VDecNdkSample::MdCompare(unsigned char buffer[], int len, const char *source[])
203 {
204     bool result = true;
205     for (int i = 0; i < len; i++) {
206     }
207     return result;
208 }
209 
GetSystemTimeUs()210 int64_t VDecNdkSample::GetSystemTimeUs()
211 {
212     struct timespec now;
213     (void)clock_gettime(CLOCK_BOOTTIME, &now);
214     int64_t nanoTime = (int64_t)now.tv_sec * NANOS_IN_SECOND + now.tv_nsec;
215     return nanoTime / NANOS_IN_MICRO;
216 }
217 
ConfigureVideoDecoder()218 int32_t VDecNdkSample::ConfigureVideoDecoder()
219 {
220     if (autoSwitchSurface) {
221         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
222         if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_INVALID_STATE) {
223             errCount++;
224         }
225     }
226     OH_AVFormat *format = OH_AVFormat_Create();
227     if (format == nullptr) {
228         cout << "Fatal: Failed to create format" << endl;
229         return AV_ERR_UNKNOWN;
230     }
231     if (maxInputSize != 0) {
232         (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_MAX_INPUT_SIZE, maxInputSize);
233     }
234     originalWidth = DEFAULT_WIDTH;
235     originalHeight = DEFAULT_HEIGHT;
236     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
237     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
238     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
239     (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
240     int ret = OH_VideoDecoder_Configure(vdec_, format);
241     OH_AVFormat_Destroy(format);
242     return ret;
243 }
244 
CreateSurface()245 void VDecNdkSample::CreateSurface()
246 {
247     cs[0] = Surface::CreateSurfaceAsConsumer();
248     sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs[0], OUT_DIR);
249     cs[0]->RegisterConsumerListener(listener);
250     auto p = cs[0]->GetProducer();
251     ps[0] = Surface::CreateSurfaceAsProducer(p);
252     nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
253     if (autoSwitchSurface)  {
254         cs[1] = Surface::CreateSurfaceAsConsumer();
255         sptr<IBufferConsumerListener> listener2 = new TestConsumerListener(cs[1], OUT_DIR2);
256         cs[1]->RegisterConsumerListener(listener2);
257         auto p2 = cs[1]->GetProducer();
258         ps[1] = Surface::CreateSurfaceAsProducer(p2);
259         nativeWindow[1] = CreateNativeWindowFromSurface(&ps[1]);
260     }
261 }
262 
RunVideoDec_Surface(string codeName)263 int32_t VDecNdkSample::RunVideoDec_Surface(string codeName)
264 {
265     SF_OUTPUT = true;
266     int err = AV_ERR_OK;
267     CreateSurface();
268     if (!nativeWindow[0]) {
269         cout << "Failed to create surface" << endl;
270         return AV_ERR_UNKNOWN;
271     }
272     err = CreateVideoDecoder(codeName);
273     if (err != AV_ERR_OK) {
274         cout << "Failed to create video decoder" << endl;
275         return err;
276     }
277     err = SetVideoDecoderCallback();
278     if (err != AV_ERR_OK) {
279         cout << "Failed to setCallback" << endl;
280         Release();
281         return err;
282     }
283     err = ConfigureVideoDecoder();
284     if (err != AV_ERR_OK) {
285         cout << "Failed to configure video decoder" << endl;
286         Release();
287         return err;
288     }
289     err = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
290     if (err != AV_ERR_OK) {
291         cout << "Failed to set surface" << endl;
292         return err;
293     }
294     err = StartVideoDecoder();
295     if (err != AV_ERR_OK) {
296         cout << "Failed to start video decoder" << endl;
297         Release();
298         return err;
299     }
300     return err;
301 }
302 
RunVideoDec(string codeName)303 int32_t VDecNdkSample::RunVideoDec(string codeName)
304 {
305     SF_OUTPUT = false;
306     int err = CreateVideoDecoder(codeName);
307     if (err != AV_ERR_OK) {
308         cout << "Failed to create video decoder" << endl;
309         return err;
310     }
311 
312     err = ConfigureVideoDecoder();
313     if (err != AV_ERR_OK) {
314         cout << "Failed to configure video decoder" << endl;
315         Release();
316         return err;
317     }
318 
319     err = SetVideoDecoderCallback();
320     if (err != AV_ERR_OK) {
321         cout << "Failed to setCallback" << endl;
322         Release();
323         return err;
324     }
325 
326     err = StartVideoDecoder();
327     if (err != AV_ERR_OK) {
328         cout << "Failed to start video decoder" << endl;
329         Release();
330         return err;
331     }
332     return err;
333 }
334 
SetVideoDecoderCallback()335 int32_t VDecNdkSample::SetVideoDecoderCallback()
336 {
337     signal_ = new VDecSignal();
338     if (signal_ == nullptr) {
339         cout << "Failed to new VDecSignal" << endl;
340         return AV_ERR_UNKNOWN;
341     }
342 
343     cb_.onError = VdecError;
344     cb_.onStreamChanged = VdecFormatChanged;
345     cb_.onNeedInputData = VdecInputDataReady;
346     cb_.onNeedOutputData = VdecOutputDataReady;
347     return OH_VideoDecoder_SetCallback(vdec_, cb_, static_cast<void *>(signal_));
348 }
349 
ReleaseInFile()350 void VDecNdkSample::ReleaseInFile()
351 {
352     if (inFile_ != nullptr) {
353         if (inFile_->is_open()) {
354             inFile_->close();
355         }
356         inFile_.reset();
357         inFile_ = nullptr;
358     }
359 }
360 
StopInloop()361 void VDecNdkSample::StopInloop()
362 {
363     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
364         unique_lock<mutex> lock(signal_->inMutex_);
365         clearIntqueue(signal_->inIdxQueue_);
366         isRunning_.store(false);
367         signal_->inCond_.notify_all();
368         lock.unlock();
369 
370         inputLoop_->join();
371         inputLoop_.reset();
372     }
373 }
374 
CreateVideoDecoder(string codeName)375 int32_t VDecNdkSample::CreateVideoDecoder(string codeName)
376 {
377     vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
378     dec_sample = this;
379     return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
380 }
381 
StartVideoDecoder()382 int32_t VDecNdkSample::StartVideoDecoder()
383 {
384     isRunning_.store(true);
385     int ret = OH_VideoDecoder_Start(vdec_);
386     if (ret != AV_ERR_OK) {
387         cout << "Failed to start codec" << endl;
388         isRunning_.store(false);
389         ReleaseInFile();
390         Release();
391         return ret;
392     }
393     inFile_ = make_unique<ifstream>();
394     if (inFile_ == nullptr) {
395         isRunning_.store(false);
396         (void)OH_VideoDecoder_Stop(vdec_);
397         return AV_ERR_UNKNOWN;
398     }
399     inFile_->open(INP_DIR, ios::in | ios::binary);
400     if (!inFile_->is_open()) {
401         cout << "failed open file " << INP_DIR << endl;
402         isRunning_.store(false);
403         (void)OH_VideoDecoder_Stop(vdec_);
404         inFile_->close();
405         inFile_.reset();
406         inFile_ = nullptr;
407         return AV_ERR_UNKNOWN;
408     }
409 
410     inputLoop_ = make_unique<thread>(&VDecNdkSample::InputFuncTest, this);
411     if (inputLoop_ == nullptr) {
412         cout << "Failed to create input loop" << endl;
413         isRunning_.store(false);
414         (void)OH_VideoDecoder_Stop(vdec_);
415         ReleaseInFile();
416         return AV_ERR_UNKNOWN;
417     }
418     outputLoop_ = make_unique<thread>(&VDecNdkSample::OutputFuncTest, this);
419     if (outputLoop_ == nullptr) {
420         cout << "Failed to create output loop" << endl;
421         isRunning_.store(false);
422         (void)OH_VideoDecoder_Stop(vdec_);
423         ReleaseInFile();
424         StopInloop();
425         Release();
426         return AV_ERR_UNKNOWN;
427     }
428 
429     return AV_ERR_OK;
430 }
431 
testAPI()432 void VDecNdkSample::testAPI()
433 {
434     cs[0] = Surface::CreateSurfaceAsConsumer();
435     sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs[0], OUT_DIR);
436     cs[0]->RegisterConsumerListener(listener);
437     auto p = cs[0]->GetProducer();
438     ps[0] = Surface::CreateSurfaceAsProducer(p);
439     nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
440     OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
441 
442     OH_VideoDecoder_Prepare(vdec_);
443     OH_VideoDecoder_Start(vdec_);
444 
445     OH_AVFormat *format = OH_AVFormat_Create();
446     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
447     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
448     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
449     (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
450     OH_VideoDecoder_SetParameter(vdec_, format);
451     OH_AVFormat_Destroy(format);
452     OH_VideoDecoder_GetOutputDescription(vdec_);
453     OH_VideoDecoder_Flush(vdec_);
454     OH_VideoDecoder_Stop(vdec_);
455     OH_VideoDecoder_Reset(vdec_);
456     bool isvalid = false;
457     OH_VideoDecoder_IsValid(vdec_, &isvalid);
458 }
459 
WaitForEOS()460 void VDecNdkSample::WaitForEOS()
461 {
462     if (!AFTER_EOS_DESTORY_CODEC && inputLoop_ && inputLoop_->joinable()) {
463         inputLoop_->join();
464     }
465 
466     if (outputLoop_ && outputLoop_->joinable()) {
467         outputLoop_->join();
468     }
469 }
470 
InputFuncTest()471 void VDecNdkSample::InputFuncTest()
472 {
473     while (true) {
474         if (!isRunning_.load()) {
475             break;
476         }
477         if (REPEAT_START_FLUSH_BEFORE_EOS > 0) {
478             REPEAT_START_FLUSH_BEFORE_EOS--;
479             OH_VideoDecoder_Flush(vdec_);
480             Flush_buffer();
481             OH_VideoDecoder_Start(vdec_);
482         }
483         if (REPEAT_START_STOP_BEFORE_EOS > 0) {
484             REPEAT_START_STOP_BEFORE_EOS--;
485             OH_VideoDecoder_Stop(vdec_);
486             Flush_buffer();
487             OH_VideoDecoder_Start(vdec_);
488         }
489         uint32_t index;
490         unique_lock<mutex> lock(signal_->inMutex_);
491         signal_->inCond_.wait(lock, [this]() {
492             if (!isRunning_.load()) {
493                 return true;
494             }
495             return signal_->inIdxQueue_.size() > 0 && !isFlushing_.load();
496         });
497         if (!isRunning_.load()) {
498             break;
499         }
500         index = signal_->inIdxQueue_.front();
501         auto buffer = signal_->inBufferQueue_.front();
502 
503         signal_->inIdxQueue_.pop();
504         signal_->inBufferQueue_.pop();
505         if (!inFile_->eof()) {
506             int ret = PushData(index, buffer);
507             if (ret == 1) {
508                 break;
509             }
510         }
511         lock.unlock();
512         if (sleepOnFPS) {
513             usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
514         }
515     }
516 }
517 
PushData(uint32_t index,OH_AVMemory * buffer)518 int32_t VDecNdkSample::PushData(uint32_t index, OH_AVMemory *buffer)
519 {
520     static uint32_t repeat_count = 0;
521     OH_AVCodecBufferAttr attr;
522     if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
523         SetEOS(index);
524         return 1;
525     }
526     if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
527         memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
528         attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
529         BEFORE_EOS_INPUT_INPUT = false;
530     }
531     char ch[4] = {};
532     (void)inFile_->read(ch, START_CODE_SIZE);
533     if (repeatRun && inFile_->eof()) {
534         inFile_->clear();
535         inFile_->seekg(0, ios::beg);
536         cout << "repeat run " << repeat_count << endl;
537         repeat_count++;
538         return 0;
539     }
540     if (inFile_->eof()) {
541         SetEOS(index);
542         return 1;
543     }
544     uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
545                                      ((ch[0] & 0xFF) << TWENTY_FOUR));
546     if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
547         cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
548         return 1;
549     }
550 
551     return SendData(bufferSize, index, buffer);
552 }
553 
CheckAndReturnBufferSize(OH_AVMemory * buffer)554 int32_t VDecNdkSample::CheckAndReturnBufferSize(OH_AVMemory *buffer)
555 {
556     int32_t size = OH_AVMemory_GetSize(buffer);
557     if ((maxInputSize < 0) && (size < 0)) {
558         errCount++;
559     } else if ((maxInputSize > 0) && (size > SYS_MAX_INPUT_SIZE)) {
560         errCount++;
561     }
562     return size;
563 }
564 
SendData(uint32_t bufferSize,uint32_t index,OH_AVMemory * buffer)565 uint32_t VDecNdkSample::SendData(uint32_t bufferSize, uint32_t index, OH_AVMemory *buffer)
566 {
567     OH_AVCodecBufferAttr attr;
568     uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
569     if (fileBuffer == nullptr) {
570         delete[] fileBuffer;
571         return 0;
572     }
573     if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
574         cout << "Fatal: memory copy failed" << endl;
575     }
576     (void)inFile_->read((char *)fileBuffer + START_CODE_SIZE, bufferSize);
577     if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
578         (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
579         attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
580     } else {
581         attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
582     }
583     int32_t size = CheckAndReturnBufferSize(buffer);
584     if (size < bufferSize + START_CODE_SIZE) {
585         delete[] fileBuffer;
586         return 0;
587     }
588     uint8_t *avBuffer = OH_AVMemory_GetAddr(buffer);
589     if (avBuffer == nullptr) {
590         cout << "avBuffer == nullptr" << endl;
591         inFile_->clear();
592         inFile_->seekg(0, ios::beg);
593         delete[] fileBuffer;
594         return 0;
595     }
596     if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
597         delete[] fileBuffer;
598         return 0;
599     }
600     int64_t startPts = GetSystemTimeUs();
601     attr.pts = startPts;
602     attr.size = bufferSize + START_CODE_SIZE;
603     attr.offset = 0;
604     if (isRunning_.load()) {
605         OH_VideoDecoder_PushInputData(vdec_, index, attr) == AV_ERR_OK ? (0) : (errCount++);
606         frameCount_ = frameCount_ + 1;
607         outCount = outCount + 1;
608         if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
609             switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
610             OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
611         }
612     }
613     delete[] fileBuffer;
614     return 0;
615 }
616 
CheckOutputDescription()617 void VDecNdkSample::CheckOutputDescription()
618 {
619     OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
620     if (newFormat != nullptr) {
621         int32_t cropTop = 0;
622         int32_t cropBottom = 0;
623         int32_t cropLeft = 0;
624         int32_t cropRight = 0;
625         int32_t stride = 0;
626         int32_t sliceHeight = 0;
627         int32_t picWidth = 0;
628         int32_t picHeight = 0;
629         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
630         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
631         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
632         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
633         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
634         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
635         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
636         OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
637         if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
638             std::cout << "cropTop:" << cropTop << " cropBottom:" << cropBottom << " cropLeft:" << cropLeft <<std::endl;
639             errCount++;
640         }
641         if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
642             std::cout << "cropRight:" << cropRight << std::endl;
643             std::cout << "stride:" << stride << " sliceHeight:" << sliceHeight << std::endl;
644             errCount++;
645         }
646         if (picWidth != originalWidth || picHeight != originalHeight) {
647             std::cout << "picWidth:" << picWidth << " picHeight:" << picHeight << std::endl;
648             errCount++;
649         }
650     } else {
651         errCount++;
652     }
653     OH_AVFormat_Destroy(newFormat);
654 }
655 
AutoSwitchSurface()656 void VDecNdkSample::AutoSwitchSurface()
657 {
658     if (autoSwitchSurface) {
659         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
660         if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
661             errCount++;
662         }
663         OH_AVFormat *format = OH_AVFormat_Create();
664         int32_t angle = DEFAULT_ANGLE * reinterpret_cast<int32_t>(switchSurfaceFlag);
665         (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, angle);
666         OH_VideoDecoder_SetParameter(vdec_, format);
667         OH_AVFormat_Destroy(format);
668     }
669 }
670 
OutputFuncTest()671 void VDecNdkSample::OutputFuncTest()
672 {
673     SHA512_Init(&c);
674     while (true) {
675         if (!isRunning_.load()) {
676             break;
677         }
678         OH_AVCodecBufferAttr attr;
679         uint32_t index;
680         unique_lock<mutex> lock(signal_->outMutex_);
681         signal_->outCond_.wait(lock, [this]() {
682             if (!isRunning_.load()) {
683                 return true;
684             }
685             return signal_->outIdxQueue_.size() > 0 && !isFlushing_.load();
686         });
687         if (!isRunning_.load()) {
688             break;
689         }
690         index = signal_->outIdxQueue_.front();
691         attr = signal_->attrQueue_.front();
692         OH_AVMemory *buffer = signal_->outBufferQueue_.front();
693         signal_->outBufferQueue_.pop();
694         signal_->outIdxQueue_.pop();
695         signal_->attrQueue_.pop();
696         if (needCheckOutputDesc) {
697             CheckOutputDescription();
698             needCheckOutputDesc = false;
699         }
700         if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) {
701             AutoSwitchSurface();
702             SHA512_Final(md, &c);
703             OPENSSL_cleanse(&c, sizeof(c));
704             MdCompare(md, SHA512_DIGEST_LENGTH, fileSourcesha256);
705             break;
706         }
707         ProcessOutputData(buffer, index);
708         lock.unlock();
709         if (errCount > 0) {
710             break;
711         }
712     }
713 }
714 
ProcessOutputData(OH_AVMemory * buffer,uint32_t index)715 void VDecNdkSample::ProcessOutputData(OH_AVMemory *buffer, uint32_t index)
716 {
717     if (!SF_OUTPUT) {
718         uint32_t size = OH_AVMemory_GetSize(buffer);
719         if (size >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
720             uint8_t *cropBuffer = new uint8_t[size];
721             if (memcpy_s(cropBuffer, size, OH_AVMemory_GetAddr(buffer),
722                          DEFAULT_WIDTH * DEFAULT_HEIGHT) != EOK) {
723                 cout << "Fatal: memory copy failed Y" << endl;
724             }
725             // copy UV
726             uint32_t uvSize = size - DEFAULT_WIDTH * DEFAULT_HEIGHT;
727             if (memcpy_s(cropBuffer + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize,
728                          OH_AVMemory_GetAddr(buffer) + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize) != EOK) {
729                 cout << "Fatal: memory copy failed UV" << endl;
730             }
731             SHA512_Update(&c, cropBuffer, size);
732             delete[] cropBuffer;
733         }
734         if (OH_VideoDecoder_FreeOutputData(vdec_, index) != AV_ERR_OK) {
735             cout << "Fatal: ReleaseOutputBuffer fail" << endl;
736             errCount = errCount + 1;
737         }
738     } else {
739         if (OH_VideoDecoder_RenderOutputData(vdec_, index) != AV_ERR_OK) {
740             cout << "Fatal: RenderOutputBuffer fail" << endl;
741             errCount = errCount + 1;
742         }
743     }
744 }
745 
state_EOS()746 int32_t VDecNdkSample::state_EOS()
747 {
748     uint32_t index;
749     unique_lock<mutex> lock(signal_->inMutex_);
750     signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
751     index = signal_->inIdxQueue_.front();
752     signal_->inIdxQueue_.pop();
753     signal_->inBufferQueue_.pop();
754     lock.unlock();
755     OH_AVCodecBufferAttr attr;
756     attr.pts = 0;
757     attr.size = 0;
758     attr.offset = 0;
759     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
760     return OH_VideoDecoder_PushInputData(vdec_, index, attr);
761 }
762 
SetEOS(uint32_t index)763 void VDecNdkSample::SetEOS(uint32_t index)
764 {
765     OH_AVCodecBufferAttr attr;
766     attr.pts = 0;
767     attr.size = 0;
768     attr.offset = 0;
769     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
770     int32_t res = OH_VideoDecoder_PushInputData(vdec_, index, attr);
771     cout << "OH_VideoDecoder_PushInputData    EOS   res: " << res << endl;
772 }
773 
Flush()774 int32_t VDecNdkSample::Flush()
775 {
776     isFlushing_.store(true);
777     unique_lock<mutex> inLock(signal_->inMutex_);
778     clearIntqueue(signal_->inIdxQueue_);
779     signal_->inCond_.notify_all();
780     inLock.unlock();
781     unique_lock<mutex> outLock(signal_->outMutex_);
782     clearIntqueue(signal_->outIdxQueue_);
783     clearBufferqueue(signal_->attrQueue_);
784     signal_->outCond_.notify_all();
785     outLock.unlock();
786     isRunning_.store(false);
787     int32_t ret = OH_VideoDecoder_Flush(vdec_);
788     isFlushing_.store(false);
789     return ret;
790 }
791 
Reset()792 int32_t VDecNdkSample::Reset()
793 {
794     isRunning_.store(false);
795     StopInloop();
796     StopOutloop();
797     ReleaseInFile();
798     return OH_VideoDecoder_Reset(vdec_);
799 }
800 
Release()801 int32_t VDecNdkSample::Release()
802 {
803     int ret = 0;
804     if (vdec_ != nullptr) {
805         ret = OH_VideoDecoder_Destroy(vdec_);
806         vdec_ = nullptr;
807     }
808 
809     if (signal_ != nullptr) {
810         delete signal_;
811         signal_ = nullptr;
812     }
813     return ret;
814 }
815 
Stop()816 int32_t VDecNdkSample::Stop()
817 {
818     StopInloop();
819     StopOutloop();
820     ReleaseInFile();
821     return OH_VideoDecoder_Stop(vdec_);
822 }
823 
Start()824 int32_t VDecNdkSample::Start()
825 {
826     isRunning_.store(true);
827     return OH_VideoDecoder_Start(vdec_);
828 }
829 
StopOutloop()830 void VDecNdkSample::StopOutloop()
831 {
832     if (outputLoop_ != nullptr && outputLoop_->joinable()) {
833         unique_lock<mutex> lock(signal_->outMutex_);
834         clearIntqueue(signal_->outIdxQueue_);
835         clearBufferqueue(signal_->attrQueue_);
836         isRunning_.store(false);
837         signal_->outCond_.notify_all();
838         lock.unlock();
839         outputLoop_->join();
840         outputLoop_.reset();
841     }
842 }
843 
SetParameter(OH_AVFormat * format)844 int32_t VDecNdkSample::SetParameter(OH_AVFormat *format)
845 {
846     return OH_VideoDecoder_SetParameter(vdec_, format);
847 }
848 
SwitchSurface()849 int32_t VDecNdkSample::SwitchSurface()
850 {
851     int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
852     switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
853     cout << "manual switch surf "<< switchSurfaceFlag << endl;
854     return ret;
855 }
856 
RepeatCallSetSurface()857 int32_t VDecNdkSample::RepeatCallSetSurface()
858 {
859     int32_t ret = AV_ERR_OK;
860     for (int i = 0; i < REPEAT_CALL_TIME; i++) {
861         switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
862         ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
863         if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT) {
864             return AV_ERR_OPERATE_NOT_PERMIT;
865         }
866     }
867     return ret;
868 }
869 
DecodeSetSurface()870 int32_t VDecNdkSample::DecodeSetSurface()
871 {
872     CreateSurface();
873     return OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
874 }