1 /*
2 * Copyright (C) 2025 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 namespace {
22 using namespace OHOS;
23 using namespace OHOS::Media;
24 using namespace std;
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 continue;
577 }
578 OH_AVBuffer *buffer = OH_VideoDecoder_GetInputBuffer(vdec_, index);
579 if (buffer == nullptr) {
580 cout << "OH_VideoDecoder_GetInputBuffer fail" << endl;
581 errCount = errCount + 1;
582 continue;
583 }
584 if (!inFile_->eof()) {
585 int ret = PushData(index, buffer);
586 if (ret == 1) {
587 flag = false;
588 break;
589 }
590 }
591 if (sleepOnFPS) {
592 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
593 }
594 }
595 }
596
PushData(uint32_t index,OH_AVBuffer * buffer)597 int32_t VDecAPI11Sample::PushData(uint32_t index, OH_AVBuffer *buffer)
598 {
599 OH_AVCodecBufferAttr attr;
600 if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
601 SetEOS(index, buffer);
602 return 1;
603 }
604 if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
605 memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
606 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
607 BEFORE_EOS_INPUT_INPUT = false;
608 }
609 char ch[4] = {};
610 (void)inFile_->read(ch, START_CODE_SIZE);
611 if (repeatRun && inFile_->eof()) {
612 static uint32_t repeat_count = 0;
613 inFile_->clear();
614 inFile_->seekg(0, ios::beg);
615 cout << "repeat run " << repeat_count << endl;
616 repeat_count++;
617 return 0;
618 }
619 if (inFile_->eof()) {
620 SetEOS(index, buffer);
621 return 1;
622 }
623 uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
624 ((ch[0] & 0xFF) << TWENTY_FOUR));
625 if (useHDRSource) {
626 uint32_t zero = 0;
627 uint32_t one = 1;
628 uint32_t two = 2;
629 uint32_t three = 3;
630 bufferSize = (uint32_t)(((ch[zero] & 0xFF)) | ((ch[one] & 0xFF) << EIGHT) | ((ch[two] & 0xFF) << SIXTEEN) |
631 ((ch[three] & 0xFF) << TWENTY_FOUR));
632 }
633 if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
634 cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
635 return 1;
636 }
637 return SendData(bufferSize, index, buffer);
638 }
639
CheckAndReturnBufferSize(OH_AVBuffer * buffer)640 int32_t VDecAPI11Sample::CheckAndReturnBufferSize(OH_AVBuffer *buffer)
641 {
642 int32_t size = OH_AVBuffer_GetCapacity(buffer);
643 if (maxInputSize > 0 && (size > maxInputSize)) {
644 errCount++;
645 }
646 return size;
647 }
648
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)649 uint32_t VDecAPI11Sample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
650 {
651 OH_AVCodecBufferAttr attr;
652 uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
653 if (fileBuffer == nullptr) {
654 delete[] fileBuffer;
655 return 0;
656 }
657 if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
658 cout << "Fatal: memory copy failed" << endl;
659 }
660 (void)inFile_->read(reinterpret_cast<char *>(fileBuffer) + START_CODE_SIZE, bufferSize);
661 if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
662 (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
663 attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
664 } else {
665 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
666 }
667 int32_t size = CheckAndReturnBufferSize(buffer);
668 if (size < bufferSize + START_CODE_SIZE) {
669 delete[] fileBuffer;
670 return 0;
671 }
672 uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
673 if (avBuffer == nullptr) {
674 inFile_->clear();
675 inFile_->seekg(0, ios::beg);
676 delete[] fileBuffer;
677 return 0;
678 }
679 if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
680 delete[] fileBuffer;
681 return 0;
682 }
683 int64_t startPts = GetSystemTimeUs();
684 attr.pts = startPts;
685 attr.size = bufferSize + START_CODE_SIZE;
686 attr.offset = 0;
687 if (isRunning_.load()) {
688 OH_AVBuffer_SetBufferAttr(buffer, &attr);
689 OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
690 frameCount_ = frameCount_ + 1;
691 outCount = outCount + 1;
692 if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
693 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
694 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
695 }
696 }
697 delete[] fileBuffer;
698 return 0;
699 }
700
CheckOutputDescription()701 void VDecAPI11Sample::CheckOutputDescription()
702 {
703 OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
704 if (newFormat != nullptr) {
705 int32_t cropTop = 0;
706 int32_t cropBottom = 0;
707 int32_t cropLeft = 0;
708 int32_t cropRight = 0;
709 int32_t stride = 0;
710 int32_t sliceHeight = 0;
711 int32_t picWidth = 0;
712 int32_t picHeight = 0;
713 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
714 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
715 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
716 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
717 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
718 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
719 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
720 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
721 if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
722 std::cout << "cropTop:" << cropTop << " cropBottom:" << cropBottom << " cropLeft:" << cropLeft <<std::endl;
723 errCount++;
724 }
725 if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
726 std::cout << "cropRight:" << cropRight << std::endl;
727 std::cout << "stride:" << stride << " sliceHeight:" << sliceHeight << std::endl;
728 errCount++;
729 }
730 if (picWidth != originalWidth || picHeight != originalHeight) {
731 std::cout << "picWidth:" << picWidth << " picHeight:" << picHeight << std::endl;
732 errCount++;
733 }
734 } else {
735 errCount++;
736 }
737 OH_AVFormat_Destroy(newFormat);
738 }
739
AutoSwitchSurface()740 void VDecAPI11Sample::AutoSwitchSurface()
741 {
742 if (autoSwitchSurface) {
743 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
744 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
745 errCount++;
746 }
747 OH_AVFormat *format = OH_AVFormat_Create();
748 int32_t angle = DEFAULT_ANGLE * reinterpret_cast<int32_t>(switchSurfaceFlag);
749 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, angle);
750 OH_VideoDecoder_SetParameter(vdec_, format);
751 OH_AVFormat_Destroy(format);
752 }
753 }
CheckAttrFlag(OH_AVCodecBufferAttr attr)754 int32_t VDecAPI11Sample::CheckAttrFlag(OH_AVCodecBufferAttr attr)
755 {
756 if (needCheckOutputDesc) {
757 CheckOutputDescription();
758 needCheckOutputDesc = false;
759 }
760 if (attr.flags & AVCODEC_BUFFER_FLAGS_EOS) {
761 cout << "AVCODEC_BUFFER_FLAGS_EOS" << endl;
762 AutoSwitchSurface();
763 SHA512_Final(g_md, &g_c);
764 OPENSSL_cleanse(&g_c, sizeof(g_c));
765 MdCompare(g_md, SHA512_DIGEST_LENGTH, fileSourcesha256);
766 return -1;
767 }
768 if (attr.flags == AVCODEC_BUFFER_FLAGS_CODEC_DATA) {
769 cout << "enc AVCODEC_BUFFER_FLAGS_CODEC_DATA" << attr.pts << endl;
770 return 0;
771 }
772 outFrameCount = outFrameCount + 1;
773 return 0;
774 }
775
OutputFuncTest()776 void VDecAPI11Sample::OutputFuncTest()
777 {
778 FILE *outFile = nullptr;
779 if (outputYuvFlag) {
780 outFile = fopen(OUT_DIR, "wb");
781 }
782 SHA512_Init(&g_c);
783 bool flag = true;
784 while (flag) {
785 if (!isRunning_.load()) {
786 flag = false;
787 break;
788 }
789 OH_AVCodecBufferAttr attr;
790 unique_lock<mutex> lock(signal_->outMutex_);
791 signal_->outCond_.wait(lock, [this]() {
792 if (!isRunning_.load()) {
793 return true;
794 }
795 return signal_->outIdxQueue_.size() > 0;
796 });
797 if (!isRunning_.load()) {
798 flag = false;
799 break;
800 }
801 uint32_t index = signal_->outIdxQueue_.front();
802 OH_AVBuffer *buffer = signal_->outBufferQueue_.front();
803 signal_->outBufferQueue_.pop();
804 signal_->outIdxQueue_.pop();
805 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
806 errCount = errCount + 1;
807 }
808 lock.unlock();
809 if (CheckAttrFlag(attr) == -1) {
810 flag = false;
811 break;
812 }
813 ProcessOutputData(buffer, index, attr.size);
814 if (outFile != nullptr) {
815 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
816 }
817 if (errCount > 0) {
818 flag = false;
819 break;
820 }
821 }
822 if (outFile) {
823 (void)fclose(outFile);
824 }
825 }
826
SyncOutputFunc()827 void VDecAPI11Sample::SyncOutputFunc()
828 {
829 FILE *outFile = nullptr;
830 if (outputYuvFlag) {
831 outFile = fopen(OUT_DIR, "wb");
832 }
833 SHA512_Init(&g_c);
834 bool flag = true;
835 while (flag) {
836 if (!isRunning_.load()) {
837 flag = false;
838 break;
839 }
840 OH_AVCodecBufferAttr attr;
841 uint32_t index = 0;
842 if (OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, syncOutputWaitTime) != AV_ERR_OK) {
843 continue;
844 }
845 OH_AVBuffer *buffer = OH_VideoDecoder_GetOutputBuffer(vdec_, index);
846 if (buffer == nullptr) {
847 cout << "OH_VideoDecoder_GetOutputBuffer fail" << endl;
848 errCount = errCount + 1;
849 continue;
850 }
851 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
852 errCount = errCount + 1;
853 }
854 if (SyncOutputFuncEos(attr, index) != AV_ERR_OK) {
855 flag = false;
856 break;
857 }
858 ProcessOutputData(buffer, index, attr.size);
859 if (outFile != nullptr) {
860 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
861 }
862 if (errCount > 0) {
863 flag = false;
864 break;
865 }
866 }
867 if (outFile) {
868 (void)fclose(outFile);
869 }
870 }
871
SyncOutputFuncEos(OH_AVCodecBufferAttr attr,uint32_t index)872 int32_t VDecAPI11Sample::SyncOutputFuncEos(OH_AVCodecBufferAttr attr, uint32_t index)
873 {
874 if (CheckAttrFlag(attr) == -1) {
875 if (queryInputBufferEOS) {
876 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, 0);
877 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, MILLION);
878 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, -1);
879 }
880 if (queryOutputBufferEOS) {
881 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, 0);
882 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, MILLION);
883 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, -1);
884 }
885 return AV_ERR_UNKNOWN;
886 }
887 return AV_ERR_OK;
888 }
889
ProcessOutputData(OH_AVBuffer * buffer,uint32_t index,int32_t size)890 void VDecAPI11Sample::ProcessOutputData(OH_AVBuffer *buffer, uint32_t index, int32_t size)
891 {
892 if (!SF_OUTPUT) {
893 if (size >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
894 uint8_t *cropBuffer = new uint8_t[size];
895 if (memcpy_s(cropBuffer, size, OH_AVBuffer_GetAddr(buffer),
896 DEFAULT_WIDTH * DEFAULT_HEIGHT) != EOK) {
897 cout << "Fatal: memory copy failed Y" << endl;
898 }
899 // copy UV
900 uint32_t uvSize = size - DEFAULT_WIDTH * DEFAULT_HEIGHT;
901 if (memcpy_s(cropBuffer + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize,
902 OH_AVBuffer_GetAddr(buffer) + DEFAULT_WIDTH * DEFAULT_HEIGHT, uvSize) != EOK) {
903 cout << "Fatal: memory copy failed UV" << endl;
904 }
905 SHA512_Update(&g_c, cropBuffer, size);
906 delete[] cropBuffer;
907 }
908 if (OH_VideoDecoder_FreeOutputBuffer(vdec_, index) != AV_ERR_OK) {
909 cout << "Fatal: ReleaseOutputBuffer fail" << endl;
910 errCount = errCount + 1;
911 }
912 } else {
913 if (rsAtTime) {
914 int32_t usTimeNum = 1000;
915 int32_t msTimeNum = 1000000;
916 if (renderTimestampNs == 0) {
917 renderTimestampNs = GetSystemTimeUs() * usTimeNum;
918 }
919 renderTimestampNs = renderTimestampNs + (usTimeNum / DEFAULT_FRAME_RATE * msTimeNum);
920 if (OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, renderTimestampNs) != AV_ERR_OK) {
921 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
922 errCount = errCount + 1;
923 }
924 } else {
925 if (OH_VideoDecoder_RenderOutputBuffer(vdec_, index) != AV_ERR_OK) {
926 cout << "Fatal: RenderOutputBuffer fail" << endl;
927 errCount = errCount + 1;
928 }
929 }
930 }
931 }
932
state_EOS()933 int32_t VDecAPI11Sample::state_EOS()
934 {
935 uint32_t index;
936 unique_lock<mutex> lock(signal_->inMutex_);
937 signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
938 index = signal_->inIdxQueue_.front();
939 signal_->inIdxQueue_.pop();
940 signal_->inBufferQueue_.pop();
941 lock.unlock();
942 return OH_VideoDecoder_PushInputBuffer(vdec_, index);
943 }
944
SetEOS(uint32_t index,OH_AVBuffer * buffer)945 void VDecAPI11Sample::SetEOS(uint32_t index, OH_AVBuffer *buffer)
946 {
947 OH_AVCodecBufferAttr attr;
948 attr.pts = 0;
949 attr.size = 0;
950 attr.offset = 0;
951 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
952 OH_AVBuffer_SetBufferAttr(buffer, &attr);
953 int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
954 cout << "OH_VideoDecoder_PushInputBuffer EOS res: " << res << endl;
955 }
956
Flush()957 int32_t VDecAPI11Sample::Flush()
958 {
959 unique_lock<mutex> inLock(signal_->inMutex_);
960 clearIntqueue(signal_->inIdxQueue_);
961 signal_->inCond_.notify_all();
962 inLock.unlock();
963 unique_lock<mutex> outLock(signal_->outMutex_);
964 clearIntqueue(signal_->outIdxQueue_);
965 clearBufferqueue(signal_->attrQueue_);
966 signal_->outCond_.notify_all();
967 outLock.unlock();
968 isRunning_.store(false);
969 return OH_VideoDecoder_Flush(vdec_);
970 }
971
Reset()972 int32_t VDecAPI11Sample::Reset()
973 {
974 isRunning_.store(false);
975 StopInloop();
976 StopOutloop();
977 ReleaseInFile();
978 return OH_VideoDecoder_Reset(vdec_);
979 }
980
Release()981 int32_t VDecAPI11Sample::Release()
982 {
983 int ret = 0;
984 if (vdec_ != nullptr) {
985 ret = OH_VideoDecoder_Destroy(vdec_);
986 vdec_ = nullptr;
987 }
988
989 if (signal_ != nullptr) {
990 delete signal_;
991 signal_ = nullptr;
992 }
993 return ret;
994 }
995
Stop()996 int32_t VDecAPI11Sample::Stop()
997 {
998 StopInloop();
999 StopOutloop();
1000 ReleaseInFile();
1001 return OH_VideoDecoder_Stop(vdec_);
1002 }
1003
Start()1004 int32_t VDecAPI11Sample::Start()
1005 {
1006 isRunning_.store(true);
1007 return OH_VideoDecoder_Start(vdec_);
1008 }
1009
StopOutloop()1010 void VDecAPI11Sample::StopOutloop()
1011 {
1012 if (outputLoop_ != nullptr && outputLoop_->joinable()) {
1013 unique_lock<mutex> lock(signal_->outMutex_);
1014 clearIntqueue(signal_->outIdxQueue_);
1015 clearBufferqueue(signal_->attrQueue_);
1016 isRunning_.store(false);
1017 signal_->outCond_.notify_all();
1018 lock.unlock();
1019 outputLoop_->join();
1020 outputLoop_.reset();
1021 }
1022 }
1023
SetParameter(OH_AVFormat * format)1024 int32_t VDecAPI11Sample::SetParameter(OH_AVFormat *format)
1025 {
1026 return OH_VideoDecoder_SetParameter(vdec_, format);
1027 }
1028
SwitchSurface()1029 int32_t VDecAPI11Sample::SwitchSurface()
1030 {
1031 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1032 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1033 cout << "manual switch surf "<< switchSurfaceFlag << endl;
1034 return ret;
1035 }
1036
RepeatCallSetSurface()1037 int32_t VDecAPI11Sample::RepeatCallSetSurface()
1038 {
1039 for (int i = 0; i < REPEAT_CALL_TIME; i++) {
1040 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1041 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1042 if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT && ret != AV_ERR_INVALID_STATE) {
1043 return AV_ERR_OPERATE_NOT_PERMIT;
1044 }
1045 }
1046 return AV_ERR_OK;
1047 }
1048
DecodeSetSurface()1049 int32_t VDecAPI11Sample::DecodeSetSurface()
1050 {
1051 CreateSurface();
1052 return OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
1053 }