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_api11_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 uint32_t MILLION = 1000000;
36 constexpr uint8_t START_CODE[START_CODE_SIZE] = {0, 0, 0, 1};
37 constexpr uint8_t SPS = 7;
38 constexpr uint8_t PPS = 8;
39 constexpr int32_t RES_CHANGE_TIME = 4;
40 constexpr int32_t CROP_INFO_SIZE = 2;
41 constexpr int32_t CROP_INFO[RES_CHANGE_TIME][CROP_INFO_SIZE] = {{621, 1103},
42 {1079, 1919}, {719, 1279}, {855, 1919}};
43
44 constexpr int32_t CROP_BOTTOM = 0;
45 constexpr int32_t CROP_RIGHT = 1;
46 constexpr int32_t DEFAULT_ANGLE = 90;
47 SHA512_CTX g_c;
48 unsigned char g_md[SHA512_DIGEST_LENGTH];
49 VDecAPI11Sample *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 ConsumerListenerBuffer : public IBufferConsumerListener {
65 public:
ConsumerListenerBuffer(sptr<Surface> cs,std::string_view name)66 ConsumerListenerBuffer(sptr<Surface> cs, std::string_view name) : cs(cs) {};
~ConsumerListenerBuffer()67 ~ConsumerListenerBuffer() {}
OnBufferAvailable()68 void OnBufferAvailable() override
69 {
70 sptr<SurfaceBuffer> buffer;
71 int32_t flushFence;
72 cs->AcquireBuffer(buffer, flushFence, timestamp, damage);
73 cs->ReleaseBuffer(buffer, -1);
74 }
75
76 private:
77 int64_t timestamp = 0;
78 Rect damage = {};
79 sptr<Surface> cs {nullptr};
80 };
81
~VDecAPI11Sample()82 VDecAPI11Sample::~VDecAPI11Sample()
83 {
84 for (int i = 0; i < MAX_SURF_NUM; i++) {
85 if (nativeWindow[i]) {
86 OH_NativeWindow_DestroyNativeWindow(nativeWindow[i]);
87 nativeWindow[i] = nullptr;
88 }
89 }
90 Stop();
91 Release();
92 }
93
VdecAPI11Error(OH_AVCodec * codec,int32_t errorCode,void * userData)94 void VdecAPI11Error(OH_AVCodec *codec, int32_t errorCode, void *userData)
95 {
96 cout << "Error errorCode=" << errorCode << endl;
97 }
98
VdecAPI11FormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)99 void VdecAPI11FormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
100 {
101 int32_t currentWidth = 0;
102 int32_t currentHeight = 0;
103 OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, ¤tWidth);
104 OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, ¤tHeight);
105 dec_sample->DEFAULT_WIDTH = currentWidth;
106 dec_sample->DEFAULT_HEIGHT = currentHeight;
107 if (dec_sample->isResChangeStream) {
108 static int32_t resCount = 0;
109 int32_t cropBottom = 0;
110 int32_t cropRight = 0;
111 int32_t stride = 0;
112 int32_t sliceHeight = 0;
113 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
114 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
115 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_STRIDE, &stride);
116 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
117 if (cropBottom != CROP_INFO[resCount][CROP_BOTTOM] || cropRight != CROP_INFO[resCount][CROP_RIGHT]) {
118 dec_sample->errCount++;
119 }
120 if (stride <= 0 || sliceHeight <= 0) {
121 dec_sample->errCount++;
122 }
123 resCount++;
124 }
125 }
126
VdecAPI11InputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)127 void VdecAPI11InputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
128 {
129 if (dec_sample->inputCallbackFlush && dec_sample->outCount > 1) {
130 OH_VideoDecoder_Flush(codec);
131 cout << "OH_VideoDecoder_Flush end" << endl;
132 dec_sample->isRunning_.store(false);
133 dec_sample->signal_->inCond_.notify_all();
134 dec_sample->signal_->outCond_.notify_all();
135 return;
136 }
137 if (dec_sample->inputCallbackStop && dec_sample->outCount > 1) {
138 OH_VideoDecoder_Stop(codec);
139 cout << "OH_VideoDecoder_Stop end" << endl;
140 dec_sample->isRunning_.store(false);
141 dec_sample->signal_->inCond_.notify_all();
142 dec_sample->signal_->outCond_.notify_all();
143 return;
144 }
145 VDecAPI11Signal *signal = static_cast<VDecAPI11Signal *>(userData);
146 unique_lock<mutex> lock(signal->inMutex_);
147 signal->inIdxQueue_.push(index);
148 signal->inBufferQueue_.push(data);
149 signal->inCond_.notify_all();
150 }
151
VdecAPI11OutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)152 void VdecAPI11OutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
153 {
154 if (dec_sample->outputCallbackFlush && dec_sample->outCount > 1) {
155 OH_VideoDecoder_Flush(codec);
156 cout << "OH_VideoDecoder_Flush end" << endl;
157 dec_sample->isRunning_.store(false);
158 dec_sample->signal_->inCond_.notify_all();
159 dec_sample->signal_->outCond_.notify_all();
160 return;
161 }
162 if (dec_sample->outputCallbackStop && dec_sample->outCount > 1) {
163 OH_VideoDecoder_Stop(codec);
164 cout << "OH_VideoDecoder_Stop end" << endl;
165 dec_sample->isRunning_.store(false);
166 dec_sample->signal_->inCond_.notify_all();
167 dec_sample->signal_->outCond_.notify_all();
168 return;
169 }
170 VDecAPI11Signal *signal = static_cast<VDecAPI11Signal *>(userData);
171 unique_lock<mutex> lock(signal->outMutex_);
172 signal->outIdxQueue_.push(index);
173 signal->outBufferQueue_.push(data);
174 signal->outCond_.notify_all();
175 }
176
Flush_buffer()177 void VDecAPI11Sample::Flush_buffer()
178 {
179 unique_lock<mutex> inLock(signal_->inMutex_);
180 clearIntqueue(signal_->inIdxQueue_);
181 std::queue<OH_AVBuffer *> empty;
182 swap(empty, signal_->inBufferQueue_);
183 signal_->inCond_.notify_all();
184 inLock.unlock();
185 unique_lock<mutex> outLock(signal_->outMutex_);
186 clearIntqueue(signal_->outIdxQueue_);
187 clearBufferqueue(signal_->attrQueue_);
188 signal_->outCond_.notify_all();
189 outLock.unlock();
190 }
191
MdCompare(unsigned char buffer[],int len,const char * source[])192 bool VDecAPI11Sample::MdCompare(unsigned char buffer[], int len, const char *source[])
193 {
194 bool result = true;
195 for (int i = 0; i < len; i++) {
196 }
197 return result;
198 }
199
GetSystemTimeUs()200 int64_t VDecAPI11Sample::GetSystemTimeUs()
201 {
202 struct timespec now;
203 (void)clock_gettime(CLOCK_BOOTTIME, &now);
204 int64_t nanoTime = (int64_t)now.tv_sec * NANOS_IN_SECOND + now.tv_nsec;
205 return nanoTime / NANOS_IN_MICRO;
206 }
207
ConfigureVideoDecoder()208 int32_t VDecAPI11Sample::ConfigureVideoDecoder()
209 {
210 if (autoSwitchSurface) {
211 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
212 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_INVALID_STATE) {
213 errCount++;
214 }
215 }
216 OH_AVFormat *format = OH_AVFormat_Create();
217 if (format == nullptr) {
218 cout << "Fatal: Failed to create format" << endl;
219 return AV_ERR_UNKNOWN;
220 }
221 if (maxInputSize > 0) {
222 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_MAX_INPUT_SIZE, maxInputSize);
223 }
224 originalWidth = DEFAULT_WIDTH;
225 originalHeight = DEFAULT_HEIGHT;
226 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
227 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
228 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, defualtPixelFormat);
229 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
230 if (useHDRSource) {
231 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, DEFAULT_PROFILE);
232 }
233 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ENABLE_SYNC_MODE, enbleSyncMode);
234 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_BLANK_FRAME_ON_SHUTDOWN, enbleBlankFrame);
235 int ret = OH_VideoDecoder_Configure(vdec_, format);
236 OH_AVFormat_Destroy(format);
237 return ret;
238 }
239
CreateSurface()240 void VDecAPI11Sample::CreateSurface()
241 {
242 cs[0] = Surface::CreateSurfaceAsConsumer();
243 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
244 cs[0]->RegisterConsumerListener(listener);
245 auto p = cs[0]->GetProducer();
246 ps[0] = Surface::CreateSurfaceAsProducer(p);
247 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
248 if (autoSwitchSurface) {
249 cs[1] = Surface::CreateSurfaceAsConsumer();
250 sptr<IBufferConsumerListener> listener2 = new ConsumerListenerBuffer(cs[1], OUT_DIR2);
251 cs[1]->RegisterConsumerListener(listener2);
252 auto p2 = cs[1]->GetProducer();
253 ps[1] = Surface::CreateSurfaceAsProducer(p2);
254 nativeWindow[1] = CreateNativeWindowFromSurface(&ps[1]);
255 }
256 }
257
RunVideoDec_Surface(string codeName)258 int32_t VDecAPI11Sample::RunVideoDec_Surface(string codeName)
259 {
260 SF_OUTPUT = true;
261 int err = AV_ERR_OK;
262 CreateSurface();
263 if (!nativeWindow[0]) {
264 cout << "Failed to create surface" << endl;
265 return AV_ERR_UNKNOWN;
266 }
267 err = CreateVideoDecoder(codeName);
268 if (err != AV_ERR_OK) {
269 cout << "Failed to create video decoder" << endl;
270 return err;
271 }
272 err = SetVideoDecoderCallback();
273 if (err != AV_ERR_OK) {
274 cout << "Failed to setCallback" << endl;
275 Release();
276 return err;
277 }
278 err = ConfigureVideoDecoder();
279 if (err != AV_ERR_OK) {
280 cout << "Failed to configure video decoder" << endl;
281 Release();
282 return err;
283 }
284 err = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
285 if (err != AV_ERR_OK) {
286 cout << "Failed to set surface" << endl;
287 return err;
288 }
289 err = StartVideoDecoder();
290 if (err != AV_ERR_OK) {
291 cout << "Failed to start video decoder" << endl;
292 Release();
293 return err;
294 }
295 return err;
296 }
297
RunVideoDec(string codeName)298 int32_t VDecAPI11Sample::RunVideoDec(string codeName)
299 {
300 SF_OUTPUT = false;
301 int err = CreateVideoDecoder(codeName);
302 if (err != AV_ERR_OK) {
303 cout << "Failed to create video decoder" << endl;
304 return err;
305 }
306
307 err = ConfigureVideoDecoder();
308 if (err != AV_ERR_OK) {
309 cout << "Failed to configure video decoder" << endl;
310 Release();
311 return err;
312 }
313
314 err = SetVideoDecoderCallback();
315 if (err != AV_ERR_OK) {
316 cout << "Failed to setCallback" << endl;
317 Release();
318 return err;
319 }
320
321 err = StartVideoDecoder();
322 if (err != AV_ERR_OK) {
323 cout << "Failed to start video decoder" << endl;
324 Release();
325 return err;
326 }
327 return err;
328 }
329
SetVideoDecoderCallback()330 int32_t VDecAPI11Sample::SetVideoDecoderCallback()
331 {
332 signal_ = new VDecAPI11Signal();
333 if (signal_ == nullptr) {
334 cout << "Failed to new VDecAPI11Signal" << endl;
335 return AV_ERR_UNKNOWN;
336 }
337
338 cb_.onError = VdecAPI11Error;
339 cb_.onStreamChanged = VdecAPI11FormatChanged;
340 cb_.onNeedInputBuffer = VdecAPI11InputDataReady;
341 cb_.onNewOutputBuffer = VdecAPI11OutputDataReady;
342 return OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
343 }
344
ReleaseInFile()345 void VDecAPI11Sample::ReleaseInFile()
346 {
347 if (inFile_ != nullptr) {
348 if (inFile_->is_open()) {
349 inFile_->close();
350 }
351 inFile_.reset();
352 inFile_ = nullptr;
353 }
354 }
355
StopInloop()356 void VDecAPI11Sample::StopInloop()
357 {
358 if (inputLoop_ != nullptr && inputLoop_->joinable()) {
359 unique_lock<mutex> lock(signal_->inMutex_);
360 clearIntqueue(signal_->inIdxQueue_);
361 isRunning_.store(false);
362 signal_->inCond_.notify_all();
363 lock.unlock();
364
365 inputLoop_->join();
366 inputLoop_.reset();
367 }
368 }
369
CreateVideoDecoder(string codeName)370 int32_t VDecAPI11Sample::CreateVideoDecoder(string codeName)
371 {
372 vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
373 dec_sample = this;
374 return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
375 }
376
StartVideoDecoder()377 int32_t VDecAPI11Sample::StartVideoDecoder()
378 {
379 isRunning_.store(true);
380 int ret = OH_VideoDecoder_Start(vdec_);
381 if (ret != AV_ERR_OK) {
382 cout << "Failed to start codec" << endl;
383 isRunning_.store(false);
384 ReleaseInFile();
385 Release();
386 return ret;
387 }
388 inFile_ = make_unique<ifstream>();
389 if (inFile_ == nullptr) {
390 isRunning_.store(false);
391 (void)OH_VideoDecoder_Stop(vdec_);
392 return AV_ERR_UNKNOWN;
393 }
394 inFile_->open(INP_DIR, ios::in | ios::binary);
395 if (!inFile_->is_open()) {
396 cout << "failed open file " << INP_DIR << endl;
397 isRunning_.store(false);
398 (void)OH_VideoDecoder_Stop(vdec_);
399 inFile_->close();
400 inFile_.reset();
401 inFile_ = nullptr;
402 return AV_ERR_UNKNOWN;
403 }
404 inputLoop_ = make_unique<thread>(&VDecAPI11Sample::InputFuncTest, this);
405 if (inputLoop_ == nullptr) {
406 cout << "Failed to create input loop" << endl;
407 isRunning_.store(false);
408 (void)OH_VideoDecoder_Stop(vdec_);
409 ReleaseInFile();
410 return AV_ERR_UNKNOWN;
411 }
412 outputLoop_ = make_unique<thread>(&VDecAPI11Sample::OutputFuncTest, this);
413 if (outputLoop_ == nullptr) {
414 cout << "Failed to create output loop" << endl;
415 isRunning_.store(false);
416 (void)OH_VideoDecoder_Stop(vdec_);
417 ReleaseInFile();
418 StopInloop();
419 Release();
420 return AV_ERR_UNKNOWN;
421 }
422
423 return AV_ERR_OK;
424 }
425
StartSyncVideoDecoder()426 int32_t VDecAPI11Sample::StartSyncVideoDecoder()
427 {
428 isRunning_.store(true);
429 int ret = OH_VideoDecoder_Start(vdec_);
430 if (ret != AV_ERR_OK) {
431 cout << "Failed to start codec" << endl;
432 isRunning_.store(false);
433 ReleaseInFile();
434 Release();
435 return ret;
436 }
437 inFile_ = make_unique<ifstream>();
438 if (inFile_ == nullptr) {
439 isRunning_.store(false);
440 (void)OH_VideoDecoder_Stop(vdec_);
441 return AV_ERR_UNKNOWN;
442 }
443 inFile_->open(INP_DIR, ios::in | ios::binary);
444 if (!inFile_->is_open()) {
445 cout << "failed open file " << INP_DIR << endl;
446 isRunning_.store(false);
447 (void)OH_VideoDecoder_Stop(vdec_);
448 inFile_->close();
449 inFile_.reset();
450 inFile_ = nullptr;
451 return AV_ERR_UNKNOWN;
452 }
453 signal_ = new VDecAPI11Signal();
454 inputLoop_ = make_unique<thread>(&VDecAPI11Sample::SyncInputFunc, this);
455 if (inputLoop_ == nullptr) {
456 cout << "Failed to create input loop" << endl;
457 isRunning_.store(false);
458 (void)OH_VideoDecoder_Stop(vdec_);
459 ReleaseInFile();
460 return AV_ERR_UNKNOWN;
461 }
462 outputLoop_ = make_unique<thread>(&VDecAPI11Sample::SyncOutputFunc, this);
463 if (outputLoop_ == nullptr) {
464 cout << "Failed to create output loop" << endl;
465 isRunning_.store(false);
466 (void)OH_VideoDecoder_Stop(vdec_);
467 ReleaseInFile();
468 StopInloop();
469 Release();
470 return AV_ERR_UNKNOWN;
471 }
472
473 return AV_ERR_OK;
474 }
475
testAPI()476 void VDecAPI11Sample::testAPI()
477 {
478 cs[0] = Surface::CreateSurfaceAsConsumer();
479 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
480 cs[0]->RegisterConsumerListener(listener);
481 auto p = cs[0]->GetProducer();
482 ps[0] = Surface::CreateSurfaceAsProducer(p);
483 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
484 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
485
486 OH_VideoDecoder_Prepare(vdec_);
487 OH_VideoDecoder_Start(vdec_);
488
489 OH_AVFormat *format = OH_AVFormat_Create();
490 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
491 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
492 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
493 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
494 OH_VideoDecoder_SetParameter(vdec_, format);
495 OH_AVFormat_Destroy(format);
496 OH_VideoDecoder_GetOutputDescription(vdec_);
497 OH_VideoDecoder_Flush(vdec_);
498 OH_VideoDecoder_Stop(vdec_);
499 OH_VideoDecoder_Reset(vdec_);
500 bool isvalid = false;
501 OH_VideoDecoder_IsValid(vdec_, &isvalid);
502 }
503
WaitForEOS()504 void VDecAPI11Sample::WaitForEOS()
505 {
506 if (!AFTER_EOS_DESTORY_CODEC && inputLoop_ && inputLoop_->joinable()) {
507 inputLoop_->join();
508 }
509
510 if (outputLoop_ && outputLoop_->joinable()) {
511 outputLoop_->join();
512 }
513 }
514
InputFuncTest()515 void VDecAPI11Sample::InputFuncTest()
516 {
517 bool flag = true;
518 while (flag) {
519 if (!isRunning_.load()) {
520 flag = false;
521 break;
522 }
523 if (REPEAT_START_FLUSH_BEFORE_EOS > 0) {
524 REPEAT_START_FLUSH_BEFORE_EOS--;
525 OH_VideoDecoder_Flush(vdec_);
526 Flush_buffer();
527 OH_VideoDecoder_Start(vdec_);
528 }
529 if (REPEAT_START_STOP_BEFORE_EOS > 0) {
530 REPEAT_START_STOP_BEFORE_EOS--;
531 OH_VideoDecoder_Stop(vdec_);
532 Flush_buffer();
533 OH_VideoDecoder_Start(vdec_);
534 }
535 uint32_t index;
536 unique_lock<mutex> lock(signal_->inMutex_);
537 signal_->inCond_.wait(lock, [this]() {
538 if (!isRunning_.load()) {
539 return true;
540 }
541 return signal_->inIdxQueue_.size() > 0;
542 });
543 if (!isRunning_.load()) {
544 flag = false;
545 break;
546 }
547 index = signal_->inIdxQueue_.front();
548 auto buffer = signal_->inBufferQueue_.front();
549
550 signal_->inIdxQueue_.pop();
551 signal_->inBufferQueue_.pop();
552 lock.unlock();
553 if (!inFile_->eof()) {
554 int ret = PushData(index, buffer);
555 if (ret == 1) {
556 flag = false;
557 break;
558 }
559 }
560 if (sleepOnFPS) {
561 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
562 }
563 }
564 }
565
SyncInputFunc()566 void VDecAPI11Sample::SyncInputFunc()
567 {
568 bool flag = true;
569 while (flag) {
570 if (!isRunning_.load()) {
571 flag = false;
572 break;
573 }
574 uint32_t index;
575 if (OH_VideoDecoder_QueryInputBuffer(vdec_, &index, syncInputWaitTime) != AV_ERR_OK) {
576 cout << "OH_VideoDecoder_QueryInputBuffer fail" << endl;
577 continue;
578 }
579 OH_AVBuffer *buffer = OH_VideoDecoder_GetInputBuffer(vdec_, index);
580 if (buffer == nullptr) {
581 cout << "OH_VideoDecoder_GetInputBuffer fail" << endl;
582 errCount = errCount + 1;
583 continue;
584 }
585 if (!inFile_->eof()) {
586 int ret = PushData(index, buffer);
587 if (ret == 1) {
588 flag = false;
589 break;
590 }
591 }
592 if (sleepOnFPS) {
593 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
594 }
595 }
596 }
597
PushData(uint32_t index,OH_AVBuffer * buffer)598 int32_t VDecAPI11Sample::PushData(uint32_t index, OH_AVBuffer *buffer)
599 {
600 OH_AVCodecBufferAttr attr;
601 if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
602 SetEOS(index, buffer);
603 return 1;
604 }
605 if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
606 memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
607 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
608 BEFORE_EOS_INPUT_INPUT = false;
609 }
610 char ch[4] = {};
611 (void)inFile_->read(ch, START_CODE_SIZE);
612 if (repeatRun && inFile_->eof()) {
613 static uint32_t repeat_count = 0;
614 inFile_->clear();
615 inFile_->seekg(0, ios::beg);
616 cout << "repeat run " << repeat_count << endl;
617 repeat_count++;
618 return 0;
619 }
620 if (inFile_->eof()) {
621 SetEOS(index, buffer);
622 return 1;
623 }
624 uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
625 ((ch[0] & 0xFF) << TWENTY_FOUR));
626 if (useHDRSource) {
627 uint32_t zero = 0;
628 uint32_t one = 1;
629 uint32_t two = 2;
630 uint32_t three = 3;
631 bufferSize = (uint32_t)(((ch[zero] & 0xFF)) | ((ch[one] & 0xFF) << EIGHT) | ((ch[two] & 0xFF) << SIXTEEN) |
632 ((ch[three] & 0xFF) << TWENTY_FOUR));
633 }
634 if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
635 cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
636 return 1;
637 }
638 return SendData(bufferSize, index, buffer);
639 }
640
CheckAndReturnBufferSize(OH_AVBuffer * buffer)641 int32_t VDecAPI11Sample::CheckAndReturnBufferSize(OH_AVBuffer *buffer)
642 {
643 int32_t size = OH_AVBuffer_GetCapacity(buffer);
644 if (maxInputSize > 0 && (size > maxInputSize)) {
645 errCount++;
646 }
647 return size;
648 }
649
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)650 uint32_t VDecAPI11Sample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
651 {
652 OH_AVCodecBufferAttr attr;
653 uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
654 if (fileBuffer == nullptr) {
655 delete[] fileBuffer;
656 return 0;
657 }
658 if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
659 cout << "Fatal: memory copy failed" << endl;
660 }
661 (void)inFile_->read(reinterpret_cast<char *>(fileBuffer) + START_CODE_SIZE, bufferSize);
662 if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
663 (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
664 attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
665 } else {
666 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
667 }
668 int32_t size = CheckAndReturnBufferSize(buffer);
669 if (size < bufferSize + START_CODE_SIZE) {
670 delete[] fileBuffer;
671 return 0;
672 }
673 uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
674 if (avBuffer == nullptr) {
675 inFile_->clear();
676 inFile_->seekg(0, ios::beg);
677 delete[] fileBuffer;
678 return 0;
679 }
680 if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
681 delete[] fileBuffer;
682 return 0;
683 }
684 int64_t startPts = GetSystemTimeUs();
685 attr.pts = startPts;
686 attr.size = bufferSize + START_CODE_SIZE;
687 attr.offset = 0;
688 if (isRunning_.load()) {
689 OH_AVBuffer_SetBufferAttr(buffer, &attr);
690 OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
691 frameCount_ = frameCount_ + 1;
692 outCount = outCount + 1;
693 if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
694 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
695 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
696 }
697 }
698 delete[] fileBuffer;
699 return 0;
700 }
701
CheckOutputDescription()702 void VDecAPI11Sample::CheckOutputDescription()
703 {
704 OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
705 if (newFormat != nullptr) {
706 int32_t cropTop = 0;
707 int32_t cropBottom = 0;
708 int32_t cropLeft = 0;
709 int32_t cropRight = 0;
710 int32_t stride = 0;
711 int32_t sliceHeight = 0;
712 int32_t picWidth = 0;
713 int32_t picHeight = 0;
714 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
715 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
716 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
717 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
718 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
719 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
720 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
721 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
722 if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
723 std::cout << "cropTop:" << cropTop << " cropBottom:" << cropBottom << " cropLeft:" << cropLeft <<std::endl;
724 errCount++;
725 }
726 if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
727 std::cout << "cropRight:" << cropRight << std::endl;
728 std::cout << "stride:" << stride << " sliceHeight:" << sliceHeight << std::endl;
729 errCount++;
730 }
731 if (picWidth != originalWidth || picHeight != originalHeight) {
732 std::cout << "picWidth:" << picWidth << " picHeight:" << picHeight << std::endl;
733 errCount++;
734 }
735 } else {
736 errCount++;
737 }
738 OH_AVFormat_Destroy(newFormat);
739 }
740
AutoSwitchSurface()741 void VDecAPI11Sample::AutoSwitchSurface()
742 {
743 if (autoSwitchSurface) {
744 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
745 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
746 errCount++;
747 }
748 OH_AVFormat *format = OH_AVFormat_Create();
749 int32_t angle = DEFAULT_ANGLE * reinterpret_cast<int32_t>(switchSurfaceFlag);
750 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, angle);
751 OH_VideoDecoder_SetParameter(vdec_, format);
752 OH_AVFormat_Destroy(format);
753 }
754 }
CheckAttrFlag(OH_AVCodecBufferAttr attr)755 int32_t VDecAPI11Sample::CheckAttrFlag(OH_AVCodecBufferAttr attr)
756 {
757 if (needCheckOutputDesc) {
758 CheckOutputDescription();
759 needCheckOutputDesc = false;
760 }
761 if (attr.flags & AVCODEC_BUFFER_FLAGS_EOS) {
762 cout << "AVCODEC_BUFFER_FLAGS_EOS" << endl;
763 AutoSwitchSurface();
764 SHA512_Final(g_md, &g_c);
765 OPENSSL_cleanse(&g_c, sizeof(g_c));
766 MdCompare(g_md, SHA512_DIGEST_LENGTH, fileSourcesha256);
767 return -1;
768 }
769 if (attr.flags == AVCODEC_BUFFER_FLAGS_CODEC_DATA) {
770 cout << "enc AVCODEC_BUFFER_FLAGS_CODEC_DATA" << attr.pts << endl;
771 return 0;
772 }
773 outFrameCount = outFrameCount + 1;
774 return 0;
775 }
776
OutputFuncTest()777 void VDecAPI11Sample::OutputFuncTest()
778 {
779 FILE *outFile = nullptr;
780 if (outputYuvFlag) {
781 outFile = fopen(OUT_DIR, "wb");
782 }
783 SHA512_Init(&g_c);
784 bool flag = true;
785 while (flag) {
786 if (!isRunning_.load()) {
787 flag = false;
788 break;
789 }
790 OH_AVCodecBufferAttr attr;
791 unique_lock<mutex> lock(signal_->outMutex_);
792 signal_->outCond_.wait(lock, [this]() {
793 if (!isRunning_.load()) {
794 return true;
795 }
796 return signal_->outIdxQueue_.size() > 0;
797 });
798 if (!isRunning_.load()) {
799 flag = false;
800 break;
801 }
802 uint32_t index = signal_->outIdxQueue_.front();
803 OH_AVBuffer *buffer = signal_->outBufferQueue_.front();
804 signal_->outBufferQueue_.pop();
805 signal_->outIdxQueue_.pop();
806 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
807 errCount = errCount + 1;
808 }
809 lock.unlock();
810 if (CheckAttrFlag(attr) == -1) {
811 flag = false;
812 break;
813 }
814 ProcessOutputData(buffer, index, attr.size);
815 if (outFile != nullptr) {
816 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
817 }
818 if (errCount > 0) {
819 flag = false;
820 break;
821 }
822 }
823 if (outFile) {
824 (void)fclose(outFile);
825 }
826 }
827
SyncOutputFunc()828 void VDecAPI11Sample::SyncOutputFunc()
829 {
830 FILE *outFile = nullptr;
831 if (outputYuvFlag) {
832 outFile = fopen(OUT_DIR, "wb");
833 }
834 SHA512_Init(&g_c);
835 bool flag = true;
836 while (flag) {
837 if (!isRunning_.load()) {
838 flag = false;
839 break;
840 }
841 OH_AVCodecBufferAttr attr;
842 uint32_t index = 0;
843 if (OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, syncOutputWaitTime) != AV_ERR_OK) {
844 cout << "OH_VideoDecoder_QueryOutputBuffer fail" << endl;
845 continue;
846 }
847 OH_AVBuffer *buffer = OH_VideoDecoder_GetOutputBuffer(vdec_, index);
848 if (buffer == nullptr) {
849 cout << "OH_VideoDecoder_GetOutputBuffer fail" << endl;
850 errCount = errCount + 1;
851 continue;
852 }
853 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
854 errCount = errCount + 1;
855 }
856 if (SyncOutputFuncEos(attr, index) != AV_ERR_OK) {
857 flag = false;
858 break;
859 }
860 ProcessOutputData(buffer, index, attr.size);
861 if (outFile != nullptr) {
862 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
863 }
864 if (errCount > 0) {
865 flag = false;
866 break;
867 }
868 }
869 if (outFile) {
870 (void)fclose(outFile);
871 }
872 }
873
SyncOutputFuncEos(OH_AVCodecBufferAttr attr,uint32_t index)874 int32_t VDecAPI11Sample::SyncOutputFuncEos(OH_AVCodecBufferAttr attr, uint32_t index)
875 {
876 if (CheckAttrFlag(attr) == -1) {
877 if (queryInputBufferEOS) {
878 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, 0);
879 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, MILLION);
880 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, -1);
881 }
882 if (queryOutputBufferEOS) {
883 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, 0);
884 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, MILLION);
885 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, -1);
886 }
887 return AV_ERR_UNKNOWN;
888 }
889 return AV_ERR_OK;
890 }
891
ProcessOutputData(OH_AVBuffer * buffer,uint32_t index,int32_t size)892 void VDecAPI11Sample::ProcessOutputData(OH_AVBuffer *buffer, uint32_t index, int32_t size)
893 {
894 if (!SF_OUTPUT) {
895 if (size >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
896 uint8_t *cropBuffer = new uint8_t[size];
897 if (memcpy_s(cropBuffer, size, OH_AVBuffer_GetAddr(buffer),
898 DEFAULT_WIDTH * DEFAULT_HEIGHT) != EOK) {
899 cout << "Fatal: memory copy failed Y" << endl;
900 }
901 // copy UV
902 uint32_t uvSize = size - DEFAULT_WIDTH * DEFAULT_HEIGHT;
903 if (memcpy_s(cropBuffer + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize,
904 OH_AVBuffer_GetAddr(buffer) + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize) != EOK) {
905 cout << "Fatal: memory copy failed UV" << endl;
906 }
907 SHA512_Update(&g_c, cropBuffer, size);
908 delete[] cropBuffer;
909 }
910 if (OH_VideoDecoder_FreeOutputBuffer(vdec_, index) != AV_ERR_OK) {
911 cout << "Fatal: ReleaseOutputBuffer fail" << endl;
912 errCount = errCount + 1;
913 }
914 } else {
915 if (rsAtTime) {
916 int32_t usTimeNum = 1000;
917 int32_t msTimeNum = 1000000;
918 if (renderTimestampNs == 0) {
919 renderTimestampNs = GetSystemTimeUs() * usTimeNum;
920 }
921 renderTimestampNs = renderTimestampNs + (usTimeNum / DEFAULT_FRAME_RATE * msTimeNum);
922 if (OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, renderTimestampNs) != AV_ERR_OK) {
923 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
924 errCount = errCount + 1;
925 }
926 } else {
927 if (OH_VideoDecoder_RenderOutputBuffer(vdec_, index) != AV_ERR_OK) {
928 cout << "Fatal: RenderOutputBuffer fail" << endl;
929 errCount = errCount + 1;
930 }
931 }
932 }
933 }
934
state_EOS()935 int32_t VDecAPI11Sample::state_EOS()
936 {
937 uint32_t index;
938 unique_lock<mutex> lock(signal_->inMutex_);
939 signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
940 index = signal_->inIdxQueue_.front();
941 signal_->inIdxQueue_.pop();
942 signal_->inBufferQueue_.pop();
943 lock.unlock();
944 return OH_VideoDecoder_PushInputBuffer(vdec_, index);
945 }
946
SetEOS(uint32_t index,OH_AVBuffer * buffer)947 void VDecAPI11Sample::SetEOS(uint32_t index, OH_AVBuffer *buffer)
948 {
949 OH_AVCodecBufferAttr attr;
950 attr.pts = 0;
951 attr.size = 0;
952 attr.offset = 0;
953 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
954 OH_AVBuffer_SetBufferAttr(buffer, &attr);
955 int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
956 cout << "OH_VideoDecoder_PushInputBuffer EOS res: " << res << endl;
957 }
958
Flush()959 int32_t VDecAPI11Sample::Flush()
960 {
961 unique_lock<mutex> inLock(signal_->inMutex_);
962 clearIntqueue(signal_->inIdxQueue_);
963 signal_->inCond_.notify_all();
964 inLock.unlock();
965 unique_lock<mutex> outLock(signal_->outMutex_);
966 clearIntqueue(signal_->outIdxQueue_);
967 clearBufferqueue(signal_->attrQueue_);
968 signal_->outCond_.notify_all();
969 outLock.unlock();
970 isRunning_.store(false);
971 return OH_VideoDecoder_Flush(vdec_);
972 }
973
Reset()974 int32_t VDecAPI11Sample::Reset()
975 {
976 isRunning_.store(false);
977 StopInloop();
978 StopOutloop();
979 ReleaseInFile();
980 return OH_VideoDecoder_Reset(vdec_);
981 }
982
Release()983 int32_t VDecAPI11Sample::Release()
984 {
985 int ret = 0;
986 if (vdec_ != nullptr) {
987 ret = OH_VideoDecoder_Destroy(vdec_);
988 vdec_ = nullptr;
989 }
990
991 if (signal_ != nullptr) {
992 delete signal_;
993 signal_ = nullptr;
994 }
995 return ret;
996 }
997
Stop()998 int32_t VDecAPI11Sample::Stop()
999 {
1000 StopInloop();
1001 StopOutloop();
1002 ReleaseInFile();
1003 return OH_VideoDecoder_Stop(vdec_);
1004 }
1005
Start()1006 int32_t VDecAPI11Sample::Start()
1007 {
1008 isRunning_.store(true);
1009 return OH_VideoDecoder_Start(vdec_);
1010 }
1011
StopOutloop()1012 void VDecAPI11Sample::StopOutloop()
1013 {
1014 if (outputLoop_ != nullptr && outputLoop_->joinable()) {
1015 unique_lock<mutex> lock(signal_->outMutex_);
1016 clearIntqueue(signal_->outIdxQueue_);
1017 clearBufferqueue(signal_->attrQueue_);
1018 isRunning_.store(false);
1019 signal_->outCond_.notify_all();
1020 lock.unlock();
1021 outputLoop_->join();
1022 outputLoop_.reset();
1023 }
1024 }
1025
SetParameter(OH_AVFormat * format)1026 int32_t VDecAPI11Sample::SetParameter(OH_AVFormat *format)
1027 {
1028 return OH_VideoDecoder_SetParameter(vdec_, format);
1029 }
1030
SwitchSurface()1031 int32_t VDecAPI11Sample::SwitchSurface()
1032 {
1033 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1034 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1035 cout << "manual switch surf "<< switchSurfaceFlag << endl;
1036 return ret;
1037 }
1038
RepeatCallSetSurface()1039 int32_t VDecAPI11Sample::RepeatCallSetSurface()
1040 {
1041 for (int i = 0; i < REPEAT_CALL_TIME; i++) {
1042 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1043 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1044 if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT && ret != AV_ERR_INVALID_STATE) {
1045 return AV_ERR_OPERATE_NOT_PERMIT;
1046 }
1047 }
1048 return AV_ERR_OK;
1049 }
1050
DecodeSetSurface()1051 int32_t VDecAPI11Sample::DecodeSetSurface()
1052 {
1053 CreateSurface();
1054 return OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
1055 }