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