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