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
326 int ret = OH_VideoDecoder_Configure(vdec_, format);
327 OH_AVFormat_Destroy(format);
328 return ret;
329 }
330
CreateSurface()331 void VDecAPI11Sample::CreateSurface()
332 {
333 cs[0] = Surface::CreateSurfaceAsConsumer();
334 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
335 cs[0]->RegisterConsumerListener(listener);
336 auto p = cs[0]->GetProducer();
337 ps[0] = Surface::CreateSurfaceAsProducer(p);
338 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
339 if (autoSwitchSurface) {
340 cs[1] = Surface::CreateSurfaceAsConsumer();
341 sptr<IBufferConsumerListener> listener2 = new ConsumerListenerBuffer(cs[1], OUT_DIR2);
342 cs[1]->RegisterConsumerListener(listener2);
343 auto p2 = cs[1]->GetProducer();
344 ps[1] = Surface::CreateSurfaceAsProducer(p2);
345 nativeWindow[1] = CreateNativeWindowFromSurface(&ps[1]);
346 }
347 }
348
RunVideoDec_Surface(string codeName)349 int32_t VDecAPI11Sample::RunVideoDec_Surface(string codeName)
350 {
351 SF_OUTPUT = true;
352 int err = AV_ERR_OK;
353 CreateSurface();
354 if (!nativeWindow[0]) {
355 cout << "Failed to create surface" << endl;
356 return AV_ERR_UNKNOWN;
357 }
358
359 err = CreateVideoDecoder(codeName);
360 if (err != AV_ERR_OK) {
361 cout << "Failed to create video decoder" << endl;
362 return err;
363 }
364
365 err = SetVideoDecoderCallback();
366 if (err != AV_ERR_OK) {
367 cout << "Failed to setCallback" << endl;
368 Release();
369 return err;
370 }
371
372 err = ConfigureVideoDecoder();
373 if (err != AV_ERR_OK) {
374 cout << "Failed to configure video decoder" << endl;
375 Release();
376 return err;
377 }
378
379 err = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
380 if (err != AV_ERR_OK) {
381 cout << "Failed to set surface" << endl;
382 return err;
383 }
384
385 err = StartVideoDecoder();
386 if (err != AV_ERR_OK) {
387 cout << "Failed to start video decoder" << endl;
388 Release();
389 return err;
390 }
391 return err;
392 }
393
RunVideoDec(string codeName)394 int32_t VDecAPI11Sample::RunVideoDec(string codeName)
395 {
396 SF_OUTPUT = false;
397 int err = CreateVideoDecoder(codeName);
398 if (err != AV_ERR_OK) {
399 cout << "Failed to create video decoder" << err << endl;
400 return err;
401 }
402
403 err = ConfigureVideoDecoder();
404 if (err != AV_ERR_OK) {
405 cout << "Failed to configure video decoder" << err << endl;
406 Release();
407 return err;
408 }
409
410 err = SetVideoDecoderCallback();
411 if (err != AV_ERR_OK) {
412 cout << "Failed to setCallback" << err << endl;
413 Release();
414 return err;
415 }
416
417 err = StartVideoDecoder();
418 if (err != AV_ERR_OK) {
419 cout << "Failed to start video decoder" << err << endl;
420 Release();
421 return err;
422 }
423 return err;
424 }
425
SetVideoDecoderCallback()426 int32_t VDecAPI11Sample::SetVideoDecoderCallback()
427 {
428 signal_ = new VDecAPI11Signal();
429 if (signal_ == nullptr) {
430 cout << "Failed to new VDecAPI11Signal" << endl;
431 return AV_ERR_UNKNOWN;
432 }
433
434 cb_.onError = VdecAPI11Error;
435 cb_.onStreamChanged = VdecAPI11FormatChanged;
436 cb_.onNeedInputBuffer = VdecAPI11InputDataReady;
437 cb_.onNewOutputBuffer = VdecAPI11OutputDataReady;
438 return OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
439 }
440
ReleaseInFile()441 void VDecAPI11Sample::ReleaseInFile()
442 {
443 if (inFile_ != nullptr) {
444 if (inFile_->is_open()) {
445 inFile_->close();
446 }
447 inFile_.reset();
448 inFile_ = nullptr;
449 }
450 }
451
StopInloop()452 void VDecAPI11Sample::StopInloop()
453 {
454 if (inputLoop_ != nullptr && inputLoop_->joinable()) {
455 unique_lock<mutex> lock(signal_->inMutex_);
456 clearIntqueue(signal_->inIdxQueue_);
457 isRunning_.store(false);
458 signal_->inCond_.notify_all();
459 lock.unlock();
460
461 inputLoop_->join();
462 inputLoop_.reset();
463 }
464 }
465
CreateVideoDecoder(string codeName)466 int32_t VDecAPI11Sample::CreateVideoDecoder(string codeName)
467 {
468 vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
469 dec_sample = this;
470 return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
471 }
472
StartDecoder()473 int32_t VDecAPI11Sample::StartDecoder()
474 {
475 isRunning_.store(true);
476 inFile_ = make_unique<ifstream>();
477 if (inFile_ == nullptr) {
478 isRunning_.store(false);
479 (void)OH_VideoDecoder_Stop(vdec_);
480 return AV_ERR_UNKNOWN;
481 }
482 inFile_->open(INP_DIR, ios::in | ios::binary);
483 if (!inFile_->is_open()) {
484 cout << "failed open file " << INP_DIR << endl;
485 isRunning_.store(false);
486 (void)OH_VideoDecoder_Stop(vdec_);
487 inFile_->close();
488 inFile_.reset();
489 inFile_ = nullptr;
490 return AV_ERR_UNKNOWN;
491 }
492 inputLoop_ = make_unique<thread>(&VDecAPI11Sample::InputFuncTest, this);
493 if (inputLoop_ == nullptr) {
494 cout << "Failed to create input loop" << endl;
495 isRunning_.store(false);
496 (void)OH_VideoDecoder_Stop(vdec_);
497 ReleaseInFile();
498 return AV_ERR_UNKNOWN;
499 }
500 outputLoop_ = make_unique<thread>(&VDecAPI11Sample::OutputFuncTest, this);
501 if (outputLoop_ == nullptr) {
502 cout << "Failed to create output loop" << endl;
503 isRunning_.store(false);
504 (void)OH_VideoDecoder_Stop(vdec_);
505 ReleaseInFile();
506 StopInloop();
507 Release();
508 return AV_ERR_UNKNOWN;
509 }
510
511 return AV_ERR_OK;
512 }
513
StartVideoDecoder()514 int32_t VDecAPI11Sample::StartVideoDecoder()
515 {
516 isRunning_.store(true);
517 if (PREPARE_FLAG) {
518 int res = OH_VideoDecoder_Prepare(vdec_);
519 if (res != AV_ERR_OK) {
520 cout << "Failed to start codec, prepare failed! " << res << endl;
521 isRunning_.store(false);
522 ReleaseInFile();
523 Release();
524 return res;
525 }
526 }
527 int ret = OH_VideoDecoder_Start(vdec_);
528 if (ret != AV_ERR_OK) {
529 cout << "Failed to start codec" << endl;
530 isRunning_.store(false);
531 ReleaseInFile();
532 Release();
533 return ret;
534 }
535 StartDecoder();
536 return AV_ERR_OK;
537 }
538
testAPI()539 void VDecAPI11Sample::testAPI()
540 {
541 cs[0] = Surface::CreateSurfaceAsConsumer();
542 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
543 cs[0]->RegisterConsumerListener(listener);
544 auto p = cs[0]->GetProducer();
545 ps[0] = Surface::CreateSurfaceAsProducer(p);
546 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
547 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
548
549 OH_VideoDecoder_Prepare(vdec_);
550 OH_VideoDecoder_Start(vdec_);
551
552 OH_AVFormat *format = OH_AVFormat_Create();
553 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
554 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
555 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
556 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
557 OH_VideoDecoder_SetParameter(vdec_, format);
558 OH_AVFormat_Destroy(format);
559 OH_VideoDecoder_GetOutputDescription(vdec_);
560 OH_VideoDecoder_Flush(vdec_);
561 OH_VideoDecoder_Stop(vdec_);
562 OH_VideoDecoder_Reset(vdec_);
563 bool isvalid = false;
564 OH_VideoDecoder_IsValid(vdec_, &isvalid);
565 }
566
WaitForEOS()567 void VDecAPI11Sample::WaitForEOS()
568 {
569 if (!AFTER_EOS_DESTORY_CODEC && inputLoop_ && inputLoop_->joinable()) {
570 inputLoop_->join();
571 }
572
573 if (outputLoop_ && outputLoop_->joinable()) {
574 outputLoop_->join();
575 }
576 }
577
InFuncTest()578 void VDecAPI11Sample::InFuncTest()
579 {
580 if (REPEAT_START_FLUSH_BEFORE_EOS > 0) {
581 REPEAT_START_FLUSH_BEFORE_EOS--;
582 OH_VideoDecoder_Flush(vdec_);
583 Flush_buffer();
584 OH_VideoDecoder_Start(vdec_);
585 }
586 if (REPEAT_START_STOP_BEFORE_EOS > 0) {
587 REPEAT_START_STOP_BEFORE_EOS--;
588 OH_VideoDecoder_Stop(vdec_);
589 Flush_buffer();
590 inFile_->clear();
591 inFile_->seekg(0, ios::beg);
592 OH_VideoDecoder_Start(vdec_);
593 }
594 }
595
InputFuncTest()596 void VDecAPI11Sample::InputFuncTest()
597 {
598 bool flag = true;
599 while (flag) {
600 if (!isRunning_.load()) {
601 flag = false;
602 break;
603 }
604 InFuncTest();
605 uint32_t index;
606 unique_lock<mutex> lock(signal_->inMutex_);
607 signal_->inCond_.wait(lock, [this]() {
608 if (!isRunning_.load()) {
609 return true;
610 }
611 return signal_->inIdxQueue_.size() > 0 && !isFlushing_.load();
612 });
613 if (!isRunning_.load()) {
614 flag = false;
615 break;
616 }
617 index = signal_->inIdxQueue_.front();
618 auto buffer = signal_->inBufferQueue_.front();
619
620 signal_->inIdxQueue_.pop();
621 signal_->inBufferQueue_.pop();
622 if (!inFile_->eof()) {
623 int ret = PushData(index, buffer);
624 if (ret == 1) {
625 flag = false;
626 break;
627 }
628 }
629 lock.unlock();
630 if (sleepOnFPS) {
631 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
632 }
633 }
634 }
635
PushData(uint32_t index,OH_AVBuffer * buffer)636 int32_t VDecAPI11Sample::PushData(uint32_t index, OH_AVBuffer *buffer)
637 {
638 OH_AVCodecBufferAttr attr;
639 if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
640 SetEOS(index, buffer);
641 return 1;
642 }
643 if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
644 memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
645 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
646 BEFORE_EOS_INPUT_INPUT = false;
647 }
648 char ch[4] = {};
649 (void)inFile_->read(ch, START_CODE_SIZE);
650 if (repeatRun && inFile_->eof()) {
651 static uint32_t repeat_count = 0;
652 inFile_->clear();
653 inFile_->seekg(0, ios::beg);
654 cout << "repeat run " << repeat_count << endl;
655 repeat_count++;
656 return 0;
657 }
658 if (inFile_->eof()) {
659 SetEOS(index, buffer);
660 return 1;
661 }
662 uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
663 ((ch[0] & 0xFF) << TWENTY_FOUR));
664 if (useHDRSource) {
665 uint32_t zero = 0;
666 uint32_t one = 1;
667 uint32_t two = 2;
668 uint32_t three = 3;
669 bufferSize = (uint32_t)(((ch[zero] & 0xFF)) | ((ch[one] & 0xFF) << EIGHT) | ((ch[two] & 0xFF) << SIXTEEN) |
670 ((ch[three] & 0xFF) << TWENTY_FOUR));
671 }
672 if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
673 cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
674 return 1;
675 }
676 return SendData(bufferSize, index, buffer);
677 }
678
CheckAndReturnBufferSize(OH_AVBuffer * buffer)679 int32_t VDecAPI11Sample::CheckAndReturnBufferSize(OH_AVBuffer *buffer)
680 {
681 int32_t size = OH_AVBuffer_GetCapacity(buffer);
682 if (maxInputSize > 0 && (size > maxInputSize)) {
683 errCount++;
684 }
685 return size;
686 }
687
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)688 uint32_t VDecAPI11Sample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
689 {
690 OH_AVCodecBufferAttr attr;
691 uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
692 if (fileBuffer == nullptr) {
693 delete[] fileBuffer;
694 return 0;
695 }
696 if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
697 cout << "Fatal: memory copy failed" << endl;
698 }
699 (void)inFile_->read(reinterpret_cast<char *>(fileBuffer) + START_CODE_SIZE, bufferSize);
700 if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
701 (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
702 attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
703 } else {
704 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
705 }
706 int32_t size = CheckAndReturnBufferSize(buffer);
707 if (size < bufferSize + START_CODE_SIZE) {
708 delete[] fileBuffer;
709 return 0;
710 }
711 uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
712 if (avBuffer == nullptr) {
713 inFile_->clear();
714 inFile_->seekg(0, ios::beg);
715 delete[] fileBuffer;
716 return 0;
717 }
718 if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
719 delete[] fileBuffer;
720 return 0;
721 }
722 int64_t startPts = GetSystemTimeUs();
723 attr.pts = startPts;
724 attr.size = bufferSize + START_CODE_SIZE;
725 attr.offset = 0;
726 if (isRunning_.load()) {
727 OH_AVBuffer_SetBufferAttr(buffer, &attr);
728 OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
729 frameCount_ = frameCount_ + 1;
730 outCount = outCount + 1;
731 if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
732 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
733 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
734 }
735 }
736 delete[] fileBuffer;
737 return 0;
738 }
739
CheckOutputDescription()740 void VDecAPI11Sample::CheckOutputDescription()
741 {
742 OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
743 if (newFormat != nullptr) {
744 int32_t cropTop = 0;
745 int32_t cropBottom = 0;
746 int32_t cropLeft = 0;
747 int32_t cropRight = 0;
748 int32_t stride = 0;
749 int32_t sliceHeight = 0;
750 int32_t picWidth = 0;
751 int32_t picHeight = 0;
752 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
753 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
754 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
755 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
756 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
757 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
758 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
759 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
760 if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
761 std::cout << "cropTop:" << cropTop << " cropBottom:" << cropBottom << " cropLeft:" << cropLeft <<std::endl;
762 errCount++;
763 }
764 if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
765 std::cout << "cropRight:" << cropRight << std::endl;
766 std::cout << "stride:" << stride << " sliceHeight:" << sliceHeight << std::endl;
767 errCount++;
768 }
769 if (picWidth != originalWidth || picHeight != originalHeight) {
770 std::cout << "picWidth:" << picWidth << " picHeight:" << picHeight << std::endl;
771 errCount++;
772 }
773 } else {
774 errCount++;
775 }
776 OH_AVFormat_Destroy(newFormat);
777 }
778
AutoSwitchSurface()779 void VDecAPI11Sample::AutoSwitchSurface()
780 {
781 if (autoSwitchSurface) {
782 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
783 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
784 errCount++;
785 }
786 OH_AVFormat *format = OH_AVFormat_Create();
787 int32_t angle = DEFAULT_ANGLE * reinterpret_cast<int32_t>(switchSurfaceFlag);
788 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, angle);
789 OH_VideoDecoder_SetParameter(vdec_, format);
790 OH_AVFormat_Destroy(format);
791 }
792 }
793
CheckAttrFlag(OH_AVCodecBufferAttr attr)794 int32_t VDecAPI11Sample::CheckAttrFlag(OH_AVCodecBufferAttr attr)
795 {
796 if (IS_FIRST_FRAME) {
797 GetStride();
798 IS_FIRST_FRAME = false;
799 }
800 if (needCheckOutputDesc) {
801 CheckOutputDescription();
802 needCheckOutputDesc = false;
803 }
804 if (attr.flags & AVCODEC_BUFFER_FLAGS_EOS) {
805 cout << "AVCODEC_BUFFER_FLAGS_EOS" << endl;
806 AutoSwitchSurface();
807 SHA512_Final(g_md, &g_c);
808 OPENSSL_cleanse(&g_c, sizeof(g_c));
809 if (!SF_OUTPUT) {
810 if (!MdCompare(g_md)) {
811 errCount++;
812 }
813 }
814 return -1;
815 }
816 if (attr.flags == AVCODEC_BUFFER_FLAGS_CODEC_DATA) {
817 cout << "enc AVCODEC_BUFFER_FLAGS_CODEC_DATA" << attr.pts << endl;
818 return 0;
819 }
820 outFrameCount = outFrameCount + 1;
821 return 0;
822 }
823
GetStride()824 void VDecAPI11Sample::GetStride()
825 {
826 OH_AVFormat *format = OH_VideoDecoder_GetOutputDescription(vdec_);
827 int32_t currentWidth = 0;
828 int32_t currentHeight = 0;
829 int32_t stride = 0;
830 int32_t sliceHeight = 0;
831 int32_t picWidth = 0;
832 int32_t picHeight = 0;
833 OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, ¤tWidth);
834 OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, ¤tHeight);
835 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_STRIDE, &stride);
836 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
837 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
838 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
839 dec_sample->DEFAULT_WIDTH = currentWidth;
840 dec_sample->DEFAULT_HEIGHT = currentHeight;
841 dec_sample->stride_ = stride;
842 dec_sample->sliceHeight_ = sliceHeight;
843 dec_sample->picWidth_ = picWidth;
844 dec_sample->picHeight_ = picHeight;
845 OH_AVFormat_Destroy(format);
846 }
847
OutputFuncTest()848 void VDecAPI11Sample::OutputFuncTest()
849 {
850 FILE *outFile = nullptr;
851 if (outputYuvFlag) {
852 outFile = fopen(OUT_DIR, "wb");
853 }
854 SHA512_Init(&g_c);
855 bool flag = true;
856 while (flag) {
857 if (!isRunning_.load()) {
858 flag = false;
859 break;
860 }
861 OH_AVCodecBufferAttr attr;
862 unique_lock<mutex> lock(signal_->outMutex_);
863 signal_->outCond_.wait(lock, [this]() {
864 if (!isRunning_.load()) {
865 return true;
866 }
867 return signal_->outIdxQueue_.size() > 0 && !isFlushing_.load();
868 });
869 if (!isRunning_.load()) {
870 flag = false;
871 break;
872 }
873 uint32_t index = signal_->outIdxQueue_.front();
874 OH_AVBuffer *buffer = signal_->outBufferQueue_.front();
875 signal_->outBufferQueue_.pop();
876 signal_->outIdxQueue_.pop();
877 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
878 errCount = errCount + 1;
879 }
880 if (CheckAttrFlag(attr) == -1) {
881 flag = false;
882 break;
883 }
884 ProcessOutputData(buffer, index);
885 if (outFile != nullptr) {
886 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
887 }
888 lock.unlock();
889 if (errCount > 0) {
890 flag = false;
891 break;
892 }
893 }
894 if (outFile) {
895 (void)fclose(outFile);
896 }
897 }
898
ProcessOutputData(OH_AVBuffer * buffer,uint32_t index)899 void VDecAPI11Sample::ProcessOutputData(OH_AVBuffer *buffer, uint32_t index)
900 {
901 if (!SF_OUTPUT) {
902 uint8_t *bufferAddr = OH_AVBuffer_GetAddr(buffer);
903 uint32_t cropSize = (picWidth_ * picHeight_ * THREE) >> 1;
904 uint8_t *cropBuffer = new uint8_t[cropSize];
905 uint8_t *copyPos = cropBuffer;
906 //copy y
907 for (int32_t i = 0; i < picHeight_; i++) {
908 memcpy_s(copyPos, picWidth_, bufferAddr, picWidth_);
909 bufferAddr += stride_;
910 copyPos += picWidth_;
911 }
912 bufferAddr += (sliceHeight_ - picHeight_) * stride_;
913 //copy uv
914 for (int32_t i = 0; i < picHeight_ >> 1; i++) {
915 memcpy_s(copyPos, picWidth_, bufferAddr, picWidth_);
916 bufferAddr += stride_;
917 copyPos += picWidth_;
918 }
919 SHA512_Update(&g_c, cropBuffer, cropSize);
920 delete[] cropBuffer;
921 if (OH_VideoDecoder_FreeOutputBuffer(vdec_, index) != AV_ERR_OK) {
922 cout << "Fatal: ReleaseOutputBuffer fail" << endl;
923 errCount = errCount + 1;
924 }
925 } else {
926 if (rsAtTime) {
927 RenderOutAtTime(index);
928 } else {
929 if (OH_VideoDecoder_RenderOutputBuffer(vdec_, index) != AV_ERR_OK) {
930 cout << "Fatal: RenderOutputBuffer fail" << endl;
931 errCount = errCount + 1;
932 }
933 }
934 }
935 }
936
RenderOutAtTime(uint32_t index)937 void VDecAPI11Sample::RenderOutAtTime(uint32_t index)
938 {
939 if (isAPI) {
940 OH_AVErrCode code = OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, -100000000);
941 if (code != AV_ERR_OK) {
942 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
943 errCount = code;
944 }
945 } else {
946 int32_t usTimeNum = 1000;
947 int32_t msTimeNum = 1000000;
948 if (renderTimestampNs == 0) {
949 renderTimestampNs = GetSystemTimeUs() / usTimeNum;
950 }
951 renderTimestampNs = renderTimestampNs + (usTimeNum / DEFAULT_FRAME_RATE * msTimeNum);
952 OH_AVErrCode code = OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, renderTimestampNs);
953 if (code != AV_ERR_OK) {
954 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
955 errCount = code;
956 }
957 }
958 }
959
state_EOS()960 int32_t VDecAPI11Sample::state_EOS()
961 {
962 uint32_t index;
963 unique_lock<mutex> lock(signal_->inMutex_);
964 signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
965 index = signal_->inIdxQueue_.front();
966 signal_->inIdxQueue_.pop();
967 signal_->inBufferQueue_.pop();
968 lock.unlock();
969 return OH_VideoDecoder_PushInputBuffer(vdec_, index);
970 }
971
SetEOS(uint32_t index,OH_AVBuffer * buffer)972 void VDecAPI11Sample::SetEOS(uint32_t index, OH_AVBuffer *buffer)
973 {
974 OH_AVCodecBufferAttr attr;
975 attr.pts = 0;
976 attr.size = 0;
977 attr.offset = 0;
978 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
979 OH_AVBuffer_SetBufferAttr(buffer, &attr);
980 int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
981 cout << "OH_VideoDecoder_PushInputBuffer EOS res: " << res << endl;
982 }
983
Flush()984 int32_t VDecAPI11Sample::Flush()
985 {
986 isFlushing_.store(true);
987 unique_lock<mutex> inLock(signal_->inMutex_);
988 clearIntqueue(signal_->inIdxQueue_);
989 signal_->inCond_.notify_all();
990 inLock.unlock();
991 unique_lock<mutex> outLock(signal_->outMutex_);
992 clearIntqueue(signal_->outIdxQueue_);
993 clearBufferqueue(signal_->attrQueue_);
994 signal_->outCond_.notify_all();
995 outLock.unlock();
996 isRunning_.store(false);
997 int32_t ret = OH_VideoDecoder_Flush(vdec_);
998 isFlushing_.store(false);
999 return ret;
1000 }
1001
Reset()1002 int32_t VDecAPI11Sample::Reset()
1003 {
1004 isRunning_.store(false);
1005 StopInloop();
1006 StopOutloop();
1007 ReleaseInFile();
1008 return OH_VideoDecoder_Reset(vdec_);
1009 }
1010
Release()1011 int32_t VDecAPI11Sample::Release()
1012 {
1013 int ret = 0;
1014 if (vdec_ != nullptr) {
1015 ret = OH_VideoDecoder_Destroy(vdec_);
1016 vdec_ = nullptr;
1017 }
1018
1019 if (signal_ != nullptr) {
1020 delete signal_;
1021 signal_ = nullptr;
1022 }
1023 return ret;
1024 }
1025
Stop()1026 int32_t VDecAPI11Sample::Stop()
1027 {
1028 StopInloop();
1029 StopOutloop();
1030 ReleaseInFile();
1031 return OH_VideoDecoder_Stop(vdec_);
1032 }
1033
Prepare()1034 int32_t VDecAPI11Sample::Prepare()
1035 {
1036 return OH_VideoDecoder_Prepare(vdec_);
1037 }
1038
Start()1039 int32_t VDecAPI11Sample::Start()
1040 {
1041 isRunning_.store(true);
1042 return OH_VideoDecoder_Start(vdec_);
1043 }
1044
StopOutloop()1045 void VDecAPI11Sample::StopOutloop()
1046 {
1047 if (outputLoop_ != nullptr && outputLoop_->joinable()) {
1048 unique_lock<mutex> lock(signal_->outMutex_);
1049 clearIntqueue(signal_->outIdxQueue_);
1050 clearBufferqueue(signal_->attrQueue_);
1051 isRunning_.store(false);
1052 signal_->outCond_.notify_all();
1053 lock.unlock();
1054 outputLoop_->join();
1055 outputLoop_.reset();
1056 }
1057 }
1058
SetParameter(OH_AVFormat * format)1059 int32_t VDecAPI11Sample::SetParameter(OH_AVFormat *format)
1060 {
1061 return OH_VideoDecoder_SetParameter(vdec_, format);
1062 }
1063
SwitchSurface()1064 int32_t VDecAPI11Sample::SwitchSurface()
1065 {
1066 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1067 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1068 cout << "manual switch surf "<< switchSurfaceFlag << endl;
1069 return ret;
1070 }
1071
RepeatCallSetSurface()1072 int32_t VDecAPI11Sample::RepeatCallSetSurface()
1073 {
1074 for (int i = 0; i < REPEAT_CALL_TIME; i++) {
1075 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1076 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1077 if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT && ret != AV_ERR_INVALID_STATE) {
1078 return AV_ERR_OPERATE_NOT_PERMIT;
1079 }
1080 }
1081 return AV_ERR_OK;
1082 }
1083
DecodeSetSurface()1084 int32_t VDecAPI11Sample::DecodeSetSurface()
1085 {
1086 CreateSurface();
1087 return OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
1088 }