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 ONE = 1;
37 constexpr int32_t SIX = 6;
38 constexpr int32_t TEN = 10;
39 constexpr int32_t ZERO = 0;
40 constexpr int32_t SIXTEEN = 16;
41 constexpr int32_t TWENTY_FOUR = 24;
42 constexpr uint8_t H264_NALU_TYPE = 0x1f;
43 constexpr uint32_t START_CODE_SIZE = 4;
44 constexpr uint32_t MILLION = 1000000;
45 constexpr uint32_t HUNDRED = 100;
46 constexpr uint8_t START_CODE[START_CODE_SIZE] = {0, 0, 0, 1};
47 constexpr uint8_t SPS = 7;
48 constexpr uint8_t PPS = 8;
49 constexpr int32_t RES_CHANGE_TIME = 4;
50 constexpr int32_t CROP_INFO_SIZE = 2;
51 constexpr int32_t CROP_INFO[RES_CHANGE_TIME][CROP_INFO_SIZE] = {{621, 1103},
52 {1079, 1919}, {719, 1279}, {855, 1919}};
53
54 constexpr int32_t CROP_BOTTOM = 0;
55 constexpr int32_t CROP_RIGHT = 1;
56 constexpr int32_t DEFAULT_ANGLE = 90;
57 int32_t g_strideSurface = 0;
58 int32_t g_sliceSurface = 0;
59 bool g_yuvSurface = false;
60 SHA512_CTX g_c;
61 uint8_t g_md[SHA512_DIGEST_LENGTH];
62 VDecAPI11Sample *dec_sample = nullptr;
63 int32_t g_inBufferCounts = 0;
64
clearIntqueue(std::queue<uint32_t> & q)65 void clearIntqueue(std::queue<uint32_t> &q)
66 {
67 std::queue<uint32_t> empty;
68 swap(empty, q);
69 }
70
clearBufferqueue(std::queue<OH_AVCodecBufferAttr> & q)71 void clearBufferqueue(std::queue<OH_AVCodecBufferAttr> &q)
72 {
73 std::queue<OH_AVCodecBufferAttr> empty;
74 swap(empty, q);
75 }
76 } // namespace
77
78 class ConsumerListenerBuffer : public IBufferConsumerListener {
79 public:
ConsumerListenerBuffer(sptr<Surface> cs,std::string_view name)80 ConsumerListenerBuffer(sptr<Surface> cs, std::string_view name) : cs(cs)
81 {
82 outFile_ = std::make_unique<std::ofstream>();
83 outFile_->open(name.data(), std::ios::out | std::ios::binary);
84 };
~ConsumerListenerBuffer()85 ~ConsumerListenerBuffer()
86 {
87 if (outFile_ != nullptr) {
88 outFile_->close();
89 }
90 }
OnBufferAvailable()91 void OnBufferAvailable() override
92 {
93 sptr<SurfaceBuffer> buffer;
94 int32_t flushFence;
95 cs->AcquireBuffer(buffer, flushFence, timestamp, damage);
96 if (buffer == nullptr) {
97 cout << "surface is nullptr" << endl;
98 return;
99 } else {
100 int32_t frameSize = (g_strideSurface * g_sliceSurface * THREE) >> 1;
101 if (g_yuvSurface && outFile_ != nullptr && frameSize <= buffer->GetSize()) {
102 outFile_->write(reinterpret_cast<char *>(buffer->GetVirAddr()), frameSize);
103 }
104 }
105 cs->ReleaseBuffer(buffer, -1);
106 }
107
108 private:
109 int64_t timestamp = 0;
110 Rect damage = {};
111 sptr<Surface> cs {nullptr};
112 std::unique_ptr<std::ofstream> outFile_;
113 };
114
~VDecAPI11Sample()115 VDecAPI11Sample::~VDecAPI11Sample()
116 {
117 for (int i = 0; i < MAX_SURF_NUM; i++) {
118 if (nativeWindow[i]) {
119 OH_NativeWindow_DestroyNativeWindow(nativeWindow[i]);
120 nativeWindow[i] = nullptr;
121 }
122 }
123 g_yuvSurface = false;
124 abnormalIndexValue = false;
125 g_inBufferCounts = ZERO;
126 Stop();
127 Release();
128 }
129
VdecAPI11Error(OH_AVCodec * codec,int32_t errorCode,void * userData)130 void VdecAPI11Error(OH_AVCodec *codec, int32_t errorCode, void *userData)
131 {
132 if (dec_sample == nullptr) {
133 return;
134 }
135 if ((errorCode == AV_ERR_VIDEO_UNSUPPORTED_COLOR_SPACE_CONVERSION) || (errorCode == AV_ERR_UNSUPPORT)) {
136 dec_sample->isRunning_.store(false);
137 dec_sample->signal_->inCond_.notify_all();
138 dec_sample->signal_->outCond_.notify_all();
139 }
140 cout << "Error errorCode=" << errorCode << endl;
141 }
142
VdecAPI11FormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)143 void VdecAPI11FormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
144 {
145 if (dec_sample == nullptr) {
146 return;
147 }
148 int32_t currentWidth = 0;
149 int32_t currentHeight = 0;
150 int32_t stride = 0;
151 int32_t sliceHeight = 0;
152 int32_t picWidth = 0;
153 int32_t picHeight = 0;
154 OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, ¤tWidth);
155 OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, ¤tHeight);
156 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_STRIDE, &stride);
157 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
158 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
159 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
160 dec_sample->DEFAULT_WIDTH = currentWidth;
161 dec_sample->DEFAULT_HEIGHT = currentHeight;
162 dec_sample->stride_ = stride;
163 dec_sample->sliceHeight_ = sliceHeight;
164 dec_sample->picWidth_ = picWidth;
165 dec_sample->picHeight_ = picHeight;
166 g_strideSurface = stride;
167 g_sliceSurface = sliceHeight;
168 if (dec_sample->isResChangeStream) {
169 static int32_t resCount = 0;
170 int32_t cropBottom = 0;
171 int32_t cropRight = 0;
172 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
173 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
174 if (cropBottom != CROP_INFO[resCount][CROP_BOTTOM] || cropRight != CROP_INFO[resCount][CROP_RIGHT]) {
175 dec_sample->errCount++;
176 }
177 if (stride <= 0 || sliceHeight <= 0) {
178 dec_sample->errCount++;
179 }
180 resCount++;
181 }
182 }
183
VdecAPI11InputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)184 void VdecAPI11InputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
185 {
186 if (dec_sample == nullptr) {
187 return;
188 }
189 if (dec_sample->isFlushing_) {
190 return;
191 }
192 if (dec_sample->inputCallbackFlush && dec_sample->outCount > 1) {
193 dec_sample->Flush();
194 cout << "OH_VideoDecoder_Flush end" << endl;
195 dec_sample->isRunning_.store(false);
196 dec_sample->signal_->inCond_.notify_all();
197 dec_sample->signal_->outCond_.notify_all();
198 return;
199 }
200 if (dec_sample->inputCallbackStop && dec_sample->outCount > 1) {
201 OH_VideoDecoder_Stop(codec);
202 cout << "OH_VideoDecoder_Stop end" << endl;
203 dec_sample->isRunning_.store(false);
204 dec_sample->signal_->inCond_.notify_all();
205 dec_sample->signal_->outCond_.notify_all();
206 return;
207 }
208 VDecAPI11Signal *signal = static_cast<VDecAPI11Signal *>(userData);
209 unique_lock<mutex> lock(signal->inMutex_);
210 signal->inIdxQueue_.push(index);
211 signal->inBufferQueue_.push(data);
212 if (dec_sample->isCheckFlush && g_inBufferCounts <= ONE && index < THREE) {
213 dec_sample->indexBufferBefore.insert({index, data});
214 }
215 if (dec_sample->isCheckFlush && THREE <= g_inBufferCounts && g_inBufferCounts < SIX && index < THREE) {
216 dec_sample->indexBufferAfter.insert({index, data});
217 }
218 signal->inCond_.notify_all();
219 g_inBufferCounts++;
220 }
221
VdecAPI11OutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)222 void VdecAPI11OutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
223 {
224 if (dec_sample == nullptr) {
225 return;
226 }
227 if (dec_sample->isFlushing_) {
228 return;
229 }
230 if (dec_sample->outputCallbackFlush && dec_sample->outCount > 1) {
231 dec_sample->Flush();
232 cout << "OH_VideoDecoder_Flush end" << endl;
233 dec_sample->isRunning_.store(false);
234 dec_sample->signal_->inCond_.notify_all();
235 dec_sample->signal_->outCond_.notify_all();
236 return;
237 }
238 if (dec_sample->outputCallbackStop && dec_sample->outCount > 1) {
239 OH_VideoDecoder_Stop(codec);
240 cout << "OH_VideoDecoder_Stop end" << endl;
241 dec_sample->isRunning_.store(false);
242 dec_sample->signal_->inCond_.notify_all();
243 dec_sample->signal_->outCond_.notify_all();
244 return;
245 }
246 VDecAPI11Signal *signal = static_cast<VDecAPI11Signal *>(userData);
247 unique_lock<mutex> lock(signal->outMutex_);
248 signal->outIdxQueue_.push(index);
249 signal->outBufferQueue_.push(data);
250 signal->outCond_.notify_all();
251 }
252
Flush_buffer()253 void VDecAPI11Sample::Flush_buffer()
254 {
255 unique_lock<mutex> inLock(signal_->inMutex_);
256 clearIntqueue(signal_->inIdxQueue_);
257 std::queue<OH_AVBuffer *> empty;
258 swap(empty, signal_->inBufferQueue_);
259 signal_->inCond_.notify_all();
260 inLock.unlock();
261 unique_lock<mutex> outLock(signal_->outMutex_);
262 clearIntqueue(signal_->outIdxQueue_);
263 clearBufferqueue(signal_->attrQueue_);
264 signal_->outCond_.notify_all();
265 outLock.unlock();
266 }
267
LoadHashFile()268 std::vector<uint8_t> VDecAPI11Sample::LoadHashFile()
269 {
270 std::ifstream f("/data/test/media/hash_val.json", ios::in);
271 std::vector<uint8_t> ret;
272 if (f) {
273 json data = json::parse(f);
274 filesystem::path filePath = INP_DIR;
275 std::string pixFmt = defualtPixelFormat == AV_PIXEL_FORMAT_NV12 ? "nv12" : "nv21";
276 std::string fileName = filePath.filename();
277 std::string hashValue = data[fileName.c_str()][pixFmt];
278 std::stringstream ss(hashValue);
279 std::string item;
280 while (getline(ss, item, ',')) {
281 if (!item.empty()) {
282 ret.push_back(stol(item, nullptr, SIXTEEN));
283 }
284 }
285 }
286 return ret;
287 }
288
DumpHashValue(std::vector<uint8_t> & srcHashVal,uint8_t outputHashVal[])289 static void DumpHashValue(std::vector<uint8_t> &srcHashVal, uint8_t outputHashVal[])
290 {
291 printf("-----------output hash value-----------\n");
292 for (int i = 1; i < SHA512_DIGEST_LENGTH + 1; i++) {
293 printf("%02x,", outputHashVal[i - 1]);
294 if (i % SIXTEEN == 0) {
295 printf("\n");
296 }
297 }
298 printf("-----------standard hash value-----------\n");
299 for (int i = 1; i < SHA512_DIGEST_LENGTH + 1; i++) {
300 printf("%02x,", srcHashVal[i - 1]);
301 if (i % SIXTEEN == 0) {
302 printf("\n");
303 }
304 }
305 }
306
MdCompare(uint8_t source[])307 bool VDecAPI11Sample::MdCompare(uint8_t source[])
308 {
309 std::vector<uint8_t> srcHashVal = LoadHashFile();
310 DumpHashValue(srcHashVal, source);
311 if (srcHashVal.size() != SHA512_DIGEST_LENGTH) {
312 cout << "get hash value failed, size " << srcHashVal.size() << endl;
313 return false;
314 }
315 for (int32_t i = 0; i < SHA512_DIGEST_LENGTH; i++) {
316 if (source[i] != srcHashVal[i]) {
317 cout << "decoded hash value mismatch" << endl;
318 return false;
319 }
320 }
321 return true;
322 }
323
GetSystemTimeUs()324 int64_t VDecAPI11Sample::GetSystemTimeUs()
325 {
326 struct timespec now;
327 (void)clock_gettime(CLOCK_BOOTTIME, &now);
328 int64_t nanoTime = (int64_t)now.tv_sec * NANOS_IN_SECOND + now.tv_nsec;
329 return nanoTime / NANOS_IN_MICRO;
330 }
331
ConfigureVideoDecoder()332 int32_t VDecAPI11Sample::ConfigureVideoDecoder()
333 {
334 if (autoSwitchSurface && enbleSyncMode == 0) {
335 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
336 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_INVALID_STATE) {
337 errCount++;
338 }
339 }
340 OH_AVFormat *format = OH_AVFormat_Create();
341 if (format == nullptr) {
342 cout << "Fatal: Failed to create format" << endl;
343 return AV_ERR_UNKNOWN;
344 }
345 if (maxInputSize > 0) {
346 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_MAX_INPUT_SIZE, maxInputSize);
347 }
348 originalWidth = DEFAULT_WIDTH;
349 originalHeight = DEFAULT_HEIGHT;
350 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
351 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
352 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, defualtPixelFormat);
353 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
354 if (useHDRSource) {
355 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, DEFAULT_PROFILE);
356 } else {
357 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, DEFAULT_PROFILE);
358 }
359
360 if (TRANSFER_FLAG) {
361 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_OUTPUT_COLOR_SPACE, OH_COLORSPACE_BT709_LIMIT);
362 }
363 if (NV21_FLAG) {
364 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV21);
365 }
366 if (enableVRR) {
367 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_OUTPUT_ENABLE_VRR, 1);
368 }
369 if (enableLowLatency) {
370 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENABLE_LOW_LATENCY, 1);
371 }
372 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ENABLE_SYNC_MODE, enbleSyncMode);
373 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_BLANK_FRAME_ON_SHUTDOWN, enbleBlankFrame);
374 int ret = OH_VideoDecoder_Configure(vdec_, format);
375 OH_AVFormat_Destroy(format);
376 return ret;
377 }
378
CreateSurface()379 void VDecAPI11Sample::CreateSurface()
380 {
381 cs[0] = Surface::CreateSurfaceAsConsumer();
382 if (cs[0] == nullptr) {
383 cout << "Create the surface consummer fail" << endl;
384 return;
385 }
386 GSError err = cs[0]->SetDefaultUsage(BUFFER_USAGE_MEM_DMA | BUFFER_USAGE_VIDEO_DECODER | BUFFER_USAGE_CPU_READ);
387 if (err == GSERROR_OK) {
388 cout << "set consumer usage succ" << endl;
389 } else {
390 cout << "set consumer usage failed" << endl;
391 }
392 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
393 cs[0]->RegisterConsumerListener(listener);
394 auto p = cs[0]->GetProducer();
395 ps[0] = Surface::CreateSurfaceAsProducer(p);
396 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
397 if (autoSwitchSurface) {
398 cs[1] = Surface::CreateSurfaceAsConsumer();
399 sptr<IBufferConsumerListener> listener2 = new ConsumerListenerBuffer(cs[1], OUT_DIR2);
400 cs[1]->RegisterConsumerListener(listener2);
401 auto p2 = cs[1]->GetProducer();
402 ps[1] = Surface::CreateSurfaceAsProducer(p2);
403 nativeWindow[1] = CreateNativeWindowFromSurface(&ps[1]);
404 }
405 }
406
RunVideoDec_Surface(string codeName)407 int32_t VDecAPI11Sample::RunVideoDec_Surface(string codeName)
408 {
409 SF_OUTPUT = true;
410 int err = AV_ERR_OK;
411 CreateSurface();
412 if (!nativeWindow[0]) {
413 cout << "Failed to create surface" << endl;
414 return AV_ERR_UNKNOWN;
415 }
416
417 err = CreateVideoDecoder(codeName);
418 if (err != AV_ERR_OK) {
419 cout << "Failed to create video decoder" << endl;
420 return err;
421 }
422
423 err = SetVideoDecoderCallback();
424 if (err != AV_ERR_OK) {
425 cout << "Failed to setCallback" << endl;
426 Release();
427 return err;
428 }
429
430 err = ConfigureVideoDecoder();
431 if (err != AV_ERR_OK) {
432 cout << "Failed to configure video decoder" << endl;
433 Release();
434 return err;
435 }
436
437 err = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
438 if (err != AV_ERR_OK) {
439 cout << "Failed to set surface" << endl;
440 return err;
441 }
442
443 err = StartVideoDecoder();
444 if (err != AV_ERR_OK) {
445 cout << "Failed to start video decoder" << endl;
446 Release();
447 return err;
448 }
449 return err;
450 }
451
RunVideoDec(string codeName)452 int32_t VDecAPI11Sample::RunVideoDec(string codeName)
453 {
454 SF_OUTPUT = false;
455 int err = CreateVideoDecoder(codeName);
456 if (err != AV_ERR_OK) {
457 cout << "Failed to create video decoder" << err << endl;
458 return err;
459 }
460
461 err = ConfigureVideoDecoder();
462 if (err != AV_ERR_OK) {
463 cout << "Failed to configure video decoder" << err << endl;
464 Release();
465 return err;
466 }
467
468 err = SetVideoDecoderCallback();
469 if (err != AV_ERR_OK) {
470 cout << "Failed to setCallback" << err << endl;
471 Release();
472 return err;
473 }
474
475 err = StartVideoDecoder();
476 if (err != AV_ERR_OK) {
477 cout << "Failed to start video decoder" << err << endl;
478 Release();
479 return err;
480 }
481 return err;
482 }
483
SetVideoDecoderCallback()484 int32_t VDecAPI11Sample::SetVideoDecoderCallback()
485 {
486 signal_ = new VDecAPI11Signal();
487 if (signal_ == nullptr) {
488 cout << "Failed to new VDecAPI11Signal" << endl;
489 return AV_ERR_UNKNOWN;
490 }
491
492 cb_.onError = VdecAPI11Error;
493 cb_.onStreamChanged = VdecAPI11FormatChanged;
494 cb_.onNeedInputBuffer = VdecAPI11InputDataReady;
495 cb_.onNewOutputBuffer = VdecAPI11OutputDataReady;
496 return OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
497 }
498
ReleaseInFile()499 void VDecAPI11Sample::ReleaseInFile()
500 {
501 if (inFile_ != nullptr) {
502 if (inFile_->is_open()) {
503 inFile_->close();
504 }
505 inFile_.reset();
506 inFile_ = nullptr;
507 }
508 }
509
StopInloop()510 void VDecAPI11Sample::StopInloop()
511 {
512 if (inputLoop_ != nullptr && inputLoop_->joinable()) {
513 unique_lock<mutex> lock(signal_->inMutex_);
514 clearIntqueue(signal_->inIdxQueue_);
515 isRunning_.store(false);
516 signal_->inCond_.notify_all();
517 lock.unlock();
518
519 inputLoop_->join();
520 inputLoop_.reset();
521 }
522 }
523
CreateVideoDecoder(string codeName)524 int32_t VDecAPI11Sample::CreateVideoDecoder(string codeName)
525 {
526 vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
527 dec_sample = this;
528 return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
529 }
530
StartDecoder()531 int32_t VDecAPI11Sample::StartDecoder()
532 {
533 isRunning_.store(true);
534 inFile_ = make_unique<ifstream>();
535 if (inFile_ == nullptr) {
536 isRunning_.store(false);
537 (void)OH_VideoDecoder_Stop(vdec_);
538 return AV_ERR_UNKNOWN;
539 }
540 inFile_->open(INP_DIR, ios::in | ios::binary);
541 if (!inFile_->is_open()) {
542 cout << "failed open file " << INP_DIR << endl;
543 isRunning_.store(false);
544 (void)OH_VideoDecoder_Stop(vdec_);
545 inFile_->close();
546 inFile_.reset();
547 inFile_ = nullptr;
548 return AV_ERR_UNKNOWN;
549 }
550 inputLoop_ = make_unique<thread>(&VDecAPI11Sample::InputFuncTest, this);
551 if (inputLoop_ == nullptr) {
552 cout << "Failed to create input loop" << endl;
553 isRunning_.store(false);
554 (void)OH_VideoDecoder_Stop(vdec_);
555 ReleaseInFile();
556 return AV_ERR_UNKNOWN;
557 }
558 outputLoop_ = make_unique<thread>(&VDecAPI11Sample::OutputFuncTest, this);
559 if (outputLoop_ == nullptr) {
560 cout << "Failed to create output loop" << endl;
561 isRunning_.store(false);
562 (void)OH_VideoDecoder_Stop(vdec_);
563 ReleaseInFile();
564 StopInloop();
565 Release();
566 return AV_ERR_UNKNOWN;
567 }
568
569 return AV_ERR_OK;
570 }
571
StartSyncDecoder()572 int32_t VDecAPI11Sample::StartSyncDecoder()
573 {
574 isRunning_.store(true);
575 inFile_ = make_unique<ifstream>();
576 if (inFile_ == nullptr) {
577 isRunning_.store(false);
578 (void)OH_VideoDecoder_Stop(vdec_);
579 return AV_ERR_UNKNOWN;
580 }
581 inFile_->open(INP_DIR, ios::in | ios::binary);
582 if (!inFile_->is_open()) {
583 cout << "failed open file " << INP_DIR << endl;
584 isRunning_.store(false);
585 (void)OH_VideoDecoder_Stop(vdec_);
586 inFile_->close();
587 inFile_.reset();
588 inFile_ = nullptr;
589 return AV_ERR_UNKNOWN;
590 }
591 signal_ = new VDecAPI11Signal();
592 inputLoop_ = make_unique<thread>(&VDecAPI11Sample::SyncInputFunc, this);
593 if (inputLoop_ == nullptr) {
594 cout << "Failed to create input loop" << endl;
595 isRunning_.store(false);
596 (void)OH_VideoDecoder_Stop(vdec_);
597 ReleaseInFile();
598 return AV_ERR_UNKNOWN;
599 }
600 outputLoop_ = make_unique<thread>(&VDecAPI11Sample::SyncOutputFunc, this);
601 if (outputLoop_ == nullptr) {
602 cout << "Failed to create output loop" << endl;
603 isRunning_.store(false);
604 (void)OH_VideoDecoder_Stop(vdec_);
605 ReleaseInFile();
606 StopInloop();
607 Release();
608 return AV_ERR_UNKNOWN;
609 }
610
611 return AV_ERR_OK;
612 }
613
StartVideoDecoder()614 int32_t VDecAPI11Sample::StartVideoDecoder()
615 {
616 isRunning_.store(true);
617 if (PREPARE_FLAG) {
618 int res = OH_VideoDecoder_Prepare(vdec_);
619 if (res != AV_ERR_OK) {
620 cout << "Failed to start codec, prepare failed! " << res << endl;
621 isRunning_.store(false);
622 ReleaseInFile();
623 Release();
624 return res;
625 }
626 }
627 int ret = OH_VideoDecoder_Start(vdec_);
628 if (ret != AV_ERR_OK) {
629 cout << "Failed to start codec" << endl;
630 isRunning_.store(false);
631 ReleaseInFile();
632 Release();
633 return ret;
634 }
635 if (enbleSyncMode == 0) {
636 StartDecoder();
637 } else {
638 StartSyncDecoder();
639 }
640 return AV_ERR_OK;
641 }
642
testAPI()643 void VDecAPI11Sample::testAPI()
644 {
645 cs[0] = Surface::CreateSurfaceAsConsumer();
646 sptr<IBufferConsumerListener> listener = new ConsumerListenerBuffer(cs[0], OUT_DIR);
647 cs[0]->RegisterConsumerListener(listener);
648 auto p = cs[0]->GetProducer();
649 ps[0] = Surface::CreateSurfaceAsProducer(p);
650 nativeWindow[0] = CreateNativeWindowFromSurface(&ps[0]);
651 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
652
653 OH_VideoDecoder_Prepare(vdec_);
654 OH_VideoDecoder_Start(vdec_);
655
656 OH_AVFormat *format = OH_AVFormat_Create();
657 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
658 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
659 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
660 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, DEFAULT_FRAME_RATE);
661 OH_VideoDecoder_SetParameter(vdec_, format);
662 OH_AVFormat_Destroy(format);
663 OH_VideoDecoder_GetOutputDescription(vdec_);
664 OH_VideoDecoder_Flush(vdec_);
665 OH_VideoDecoder_Stop(vdec_);
666 OH_VideoDecoder_Reset(vdec_);
667 bool isvalid = false;
668 OH_VideoDecoder_IsValid(vdec_, &isvalid);
669 }
670
WaitForEOS()671 void VDecAPI11Sample::WaitForEOS()
672 {
673 if (!AFTER_EOS_DESTORY_CODEC && inputLoop_ && inputLoop_->joinable()) {
674 inputLoop_->join();
675 }
676
677 if (outputLoop_ && outputLoop_->joinable()) {
678 outputLoop_->join();
679 }
680 }
681
InFuncTest()682 void VDecAPI11Sample::InFuncTest()
683 {
684 if (REPEAT_START_FLUSH_BEFORE_EOS > 0) {
685 REPEAT_START_FLUSH_BEFORE_EOS--;
686 OH_VideoDecoder_Flush(vdec_);
687 Flush_buffer();
688 OH_VideoDecoder_Start(vdec_);
689 }
690 if (REPEAT_START_STOP_BEFORE_EOS > 0) {
691 REPEAT_START_STOP_BEFORE_EOS--;
692 OH_VideoDecoder_Stop(vdec_);
693 Flush_buffer();
694 inFile_->clear();
695 inFile_->seekg(0, ios::beg);
696 OH_VideoDecoder_Start(vdec_);
697 }
698 if (isCheckFlush && FLUSH_COUNTS > 0) {
699 FLUSH_COUNTS--;
700 if (FLUSH_COUNTS == 0) {
701 OH_VideoDecoder_Flush(vdec_);
702 Flush_buffer();
703 OH_VideoDecoder_Start(vdec_);
704 }
705 }
706 }
707
SyncInputFunc()708 void VDecAPI11Sample::SyncInputFunc()
709 {
710 if (outputYuvSurface) {
711 g_yuvSurface = true;
712 }
713 bool flag = true;
714 uint32_t last_index = 0;
715 while (flag) {
716 if (!isRunning_.load()) {
717 flag = false;
718 break;
719 }
720 uint32_t index;
721 if (OH_VideoDecoder_QueryInputBuffer(vdec_, &index, syncInputWaitTime) != AV_ERR_OK) {
722 continue;
723 }
724 OH_AVBuffer *buffer = OH_VideoDecoder_GetInputBuffer(vdec_, index);
725 if (buffer == nullptr) {
726 cout << "OH_VideoDecoder_GetInputBuffer fail" << endl;
727 errCount = errCount + 1;
728 continue;
729 }
730 if (frameCount_ == 0 && getInputBufferIndexRepeat) {
731 last_index = index;
732 } else if (frameCount_ == 1 && getInputBufferIndexRepeat) {
733 cout << "getInputBufferIndexRepeat last_index: " << last_index << "index: " << index << endl;
734 if (OH_VideoDecoder_GetInputBuffer(vdec_, last_index) == nullptr) {
735 cout << "getInputBufferIndexRepeat OH_VideoDecoder_GetInputBuffer nullptr" << endl;
736 abnormalIndexValue = true;
737 }
738 break;
739 }
740 if (!inFile_->eof()) {
741 int ret = PushData(index, buffer);
742 if (ret == 1) {
743 flag = false;
744 break;
745 }
746 }
747 if (sleepOnFPS) {
748 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
749 }
750 }
751 }
752
InputFuncTest()753 void VDecAPI11Sample::InputFuncTest()
754 {
755 if (outputYuvSurface) {
756 g_yuvSurface = true;
757 }
758 bool flag = true;
759 while (flag) {
760 if (!isRunning_.load()) {
761 flag = false;
762 break;
763 }
764 InFuncTest();
765 uint32_t index;
766 unique_lock<mutex> lock(signal_->inMutex_);
767 signal_->inCond_.wait(lock, [this]() {
768 if (!isRunning_.load()) {
769 return true;
770 }
771 return signal_->inIdxQueue_.size() > 0 && !isFlushing_.load();
772 });
773 if (!isRunning_.load()) {
774 flag = false;
775 break;
776 }
777 index = signal_->inIdxQueue_.front();
778 auto buffer = signal_->inBufferQueue_.front();
779
780 signal_->inIdxQueue_.pop();
781 signal_->inBufferQueue_.pop();
782 if (!inFile_->eof()) {
783 int ret = PushData(index, buffer);
784 if (ret == 1) {
785 flag = false;
786 break;
787 }
788 }
789 lock.unlock();
790 if (sleepOnFPS) {
791 usleep(MICRO_IN_SECOND / (int32_t)DEFAULT_FRAME_RATE);
792 }
793 }
794 }
795
PushData(uint32_t index,OH_AVBuffer * buffer)796 int32_t VDecAPI11Sample::PushData(uint32_t index, OH_AVBuffer *buffer)
797 {
798 OH_AVCodecBufferAttr attr;
799 if (BEFORE_EOS_INPUT && frameCount_ > TEN) {
800 SetEOS(index, buffer);
801 return 1;
802 }
803 if (BEFORE_EOS_INPUT_INPUT && frameCount_ > TEN) {
804 memset_s(&attr, sizeof(OH_AVCodecBufferAttr), 0, sizeof(OH_AVCodecBufferAttr));
805 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
806 BEFORE_EOS_INPUT_INPUT = false;
807 }
808 char ch[4] = {};
809 (void)inFile_->read(ch, START_CODE_SIZE);
810 if (repeatRun && inFile_->eof()) {
811 static uint32_t repeat_count = 0;
812 inFile_->clear();
813 inFile_->seekg(0, ios::beg);
814 cout << "repeat run " << repeat_count << endl;
815 repeat_count++;
816 return 0;
817 }
818 if (inFile_->eof()) {
819 SetEOS(index, buffer);
820 return 1;
821 }
822 uint32_t bufferSize = (uint32_t)(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) | ((ch[1] & 0xFF) << SIXTEEN) |
823 ((ch[0] & 0xFF) << TWENTY_FOUR));
824 if (useHDRSource) {
825 uint32_t zero = 0;
826 uint32_t one = 1;
827 uint32_t two = 2;
828 uint32_t three = 3;
829 bufferSize = (uint32_t)(((ch[zero] & 0xFF)) | ((ch[one] & 0xFF) << EIGHT) | ((ch[two] & 0xFF) << SIXTEEN) |
830 ((ch[three] & 0xFF) << TWENTY_FOUR));
831 }
832 if (bufferSize >= DEFAULT_WIDTH * DEFAULT_HEIGHT * THREE >> 1) {
833 cout << "read bufferSize abnormal. buffersize = " << bufferSize << endl;
834 }
835 return SendData(bufferSize, index, buffer);
836 }
837
CheckAndReturnBufferSize(OH_AVBuffer * buffer)838 int32_t VDecAPI11Sample::CheckAndReturnBufferSize(OH_AVBuffer *buffer)
839 {
840 int32_t size = OH_AVBuffer_GetCapacity(buffer);
841 if (maxInputSize > 0 && (size > maxInputSize)) {
842 errCount++;
843 }
844 return size;
845 }
846
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)847 uint32_t VDecAPI11Sample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
848 {
849 OH_AVCodecBufferAttr attr;
850 uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
851 if (fileBuffer == nullptr) {
852 delete[] fileBuffer;
853 return 0;
854 }
855 if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
856 cout << "Fatal: memory copy failed" << endl;
857 }
858 (void)inFile_->read(reinterpret_cast<char *>(fileBuffer) + START_CODE_SIZE, bufferSize);
859 if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
860 (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
861 attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
862 } else {
863 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
864 }
865 int32_t size = CheckAndReturnBufferSize(buffer);
866 if (size < bufferSize + START_CODE_SIZE) {
867 delete[] fileBuffer;
868 return 0;
869 }
870 uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
871 if (avBuffer == nullptr) {
872 inFile_->clear();
873 inFile_->seekg(0, ios::beg);
874 delete[] fileBuffer;
875 return 0;
876 }
877 if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
878 delete[] fileBuffer;
879 return 0;
880 }
881 int64_t startPts = GetSystemTimeUs();
882 attr.pts = startPts;
883 attr.size = bufferSize + START_CODE_SIZE;
884 attr.offset = 0;
885 if (isRunning_.load()) {
886 OH_AVBuffer_SetBufferAttr(buffer, &attr);
887 OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
888 frameCount_ = frameCount_ + 1;
889 outCount = outCount + 1;
890 if (autoSwitchSurface && (frameCount_ % (int32_t)DEFAULT_FRAME_RATE == 0)) {
891 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
892 OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) == AV_ERR_OK ? (0) : (errCount++);
893 }
894 }
895 delete[] fileBuffer;
896 return 0;
897 }
898
CheckOutputDescription()899 void VDecAPI11Sample::CheckOutputDescription()
900 {
901 OH_AVFormat *newFormat = OH_VideoDecoder_GetOutputDescription(vdec_);
902 if (newFormat != nullptr) {
903 int32_t cropTop = 0;
904 int32_t cropBottom = 0;
905 int32_t cropLeft = 0;
906 int32_t cropRight = 0;
907 int32_t stride = 0;
908 int32_t sliceHeight = 0;
909 int32_t picWidth = 0;
910 int32_t picHeight = 0;
911 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_TOP, &cropTop);
912 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_BOTTOM, &cropBottom);
913 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_LEFT, &cropLeft);
914 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_CROP_RIGHT, &cropRight);
915 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_STRIDE, &stride);
916 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
917 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
918 OH_AVFormat_GetIntValue(newFormat, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
919 if (cropTop != expectCropTop || cropBottom != expectCropBottom || cropLeft != expectCropLeft) {
920 std::cout << "cropTop:" << cropTop << " cropBottom:" << cropBottom << " cropLeft:" << cropLeft <<std::endl;
921 errCount++;
922 }
923 if (cropRight != expectCropRight || stride <= 0 || sliceHeight <= 0) {
924 std::cout << "cropRight:" << cropRight << std::endl;
925 std::cout << "stride:" << stride << " sliceHeight:" << sliceHeight << std::endl;
926 errCount++;
927 }
928 if (picWidth != originalWidth || picHeight != originalHeight) {
929 std::cout << "picWidth:" << picWidth << " picHeight:" << picHeight << std::endl;
930 errCount++;
931 }
932 } else {
933 errCount++;
934 }
935 OH_AVFormat_Destroy(newFormat);
936 }
937
AutoSwitchSurface()938 void VDecAPI11Sample::AutoSwitchSurface()
939 {
940 if (autoSwitchSurface) {
941 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
942 if (OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]) != AV_ERR_OK) {
943 errCount++;
944 }
945 OH_AVFormat *format = OH_AVFormat_Create();
946 int32_t angle = DEFAULT_ANGLE * reinterpret_cast<int32_t>(switchSurfaceFlag);
947 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, angle);
948 OH_VideoDecoder_SetParameter(vdec_, format);
949 OH_AVFormat_Destroy(format);
950 }
951 }
952
CheckAttrFlag(OH_AVCodecBufferAttr attr)953 int32_t VDecAPI11Sample::CheckAttrFlag(OH_AVCodecBufferAttr attr)
954 {
955 if (IS_FIRST_FRAME) {
956 GetStride();
957 IS_FIRST_FRAME = false;
958 }
959 if (needCheckOutputDesc) {
960 CheckOutputDescription();
961 needCheckOutputDesc = false;
962 }
963 if (attr.flags & AVCODEC_BUFFER_FLAGS_EOS) {
964 cout << "AVCODEC_BUFFER_FLAGS_EOS" << endl;
965 AutoSwitchSurface();
966 SHA512_Final(g_md, &g_c);
967 OPENSSL_cleanse(&g_c, sizeof(g_c));
968 if (!SF_OUTPUT && !NocaleHash) {
969 if (!MdCompare(g_md)) {
970 errCount++;
971 }
972 }
973 return -1;
974 }
975 if (attr.flags == AVCODEC_BUFFER_FLAGS_CODEC_DATA) {
976 cout << "enc AVCODEC_BUFFER_FLAGS_CODEC_DATA" << attr.pts << endl;
977 return 0;
978 }
979 outFrameCount = outFrameCount + 1;
980 return 0;
981 }
982
GetStride()983 void VDecAPI11Sample::GetStride()
984 {
985 OH_AVFormat *format = OH_VideoDecoder_GetOutputDescription(vdec_);
986 int32_t currentWidth = 0;
987 int32_t currentHeight = 0;
988 int32_t stride = 0;
989 int32_t sliceHeight = 0;
990 int32_t picWidth = 0;
991 int32_t picHeight = 0;
992 OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, ¤tWidth);
993 OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, ¤tHeight);
994 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_STRIDE, &stride);
995 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_SLICE_HEIGHT, &sliceHeight);
996 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_WIDTH, &picWidth);
997 OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_HEIGHT, &picHeight);
998 dec_sample->DEFAULT_WIDTH = currentWidth;
999 dec_sample->DEFAULT_HEIGHT = currentHeight;
1000 dec_sample->stride_ = stride;
1001 dec_sample->sliceHeight_ = sliceHeight;
1002 dec_sample->picWidth_ = picWidth;
1003 dec_sample->picHeight_ = picHeight;
1004 OH_AVFormat_Destroy(format);
1005 }
1006
OutputFuncTest()1007 void VDecAPI11Sample::OutputFuncTest()
1008 {
1009 FILE *outFile = nullptr;
1010 if (outputYuvFlag) {
1011 outFile = fopen(OUT_DIR, "wb");
1012 }
1013 SHA512_Init(&g_c);
1014 bool flag = true;
1015 while (flag) {
1016 if (!isRunning_.load()) {
1017 flag = false;
1018 break;
1019 }
1020 OH_AVCodecBufferAttr attr;
1021 unique_lock<mutex> lock(signal_->outMutex_);
1022 signal_->outCond_.wait(lock, [this]() {
1023 if (!isRunning_.load()) {
1024 return true;
1025 }
1026 return signal_->outIdxQueue_.size() > 0 && !isFlushing_.load();
1027 });
1028 if (!isRunning_.load()) {
1029 flag = false;
1030 break;
1031 }
1032 uint32_t index = signal_->outIdxQueue_.front();
1033 OH_AVBuffer *buffer = signal_->outBufferQueue_.front();
1034 signal_->outBufferQueue_.pop();
1035 signal_->outIdxQueue_.pop();
1036 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
1037 errCount = errCount + 1;
1038 }
1039 if (CheckAttrFlag(attr) == -1) {
1040 flag = false;
1041 break;
1042 }
1043 if (outFile != nullptr) {
1044 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
1045 }
1046 if (FLUSH_COUNTS == 0) {
1047 ProcessOutputData(buffer, index);
1048 }
1049 lock.unlock();
1050 if (errCount > 0) {
1051 break;
1052 }
1053 }
1054 if (outFile) {
1055 (void)fclose(outFile);
1056 }
1057 }
1058
SyncOutputFunc()1059 void VDecAPI11Sample::SyncOutputFunc()
1060 {
1061 uint32_t outFrames = 0;
1062 FILE *outFile = nullptr;
1063 if (outputYuvFlag) {
1064 outFile = fopen(OUT_DIR, "wb");
1065 }
1066 SHA512_Init(&g_c);
1067 uint32_t last_index = 0;
1068 while (isRunning_.load()) {
1069 OH_AVCodecBufferAttr attr;
1070 uint32_t index = 0;
1071 int32_t ret = OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, syncOutputWaitTime);
1072 if (ret == AV_ERR_STREAM_CHANGED) {
1073 GetStride();
1074 cout << "stream changed" << ret << endl;
1075 continue;
1076 }
1077 if (ret != AV_ERR_OK) {
1078 continue;
1079 }
1080 OH_AVBuffer *buffer = OH_VideoDecoder_GetOutputBuffer(vdec_, index);
1081 if (buffer == nullptr) {
1082 cout << "OH_VideoDecoder_GetOutputBuffer fail" << endl;
1083 errCount = errCount + 1;
1084 continue;
1085 }
1086 if (SyncOutputFuncEos(last_index, outFrames, index, buffer, attr)) {
1087 isRunning_.store(false);
1088 break;
1089 }
1090 if (outFile != nullptr) {
1091 fwrite(OH_AVBuffer_GetAddr(buffer), 1, attr.size, outFile);
1092 }
1093 ProcessOutputData(buffer, index);
1094 outFrames = outFrames + 1;
1095 if (errCount > 0) {
1096 isRunning_.store(false);
1097 break;
1098 }
1099 }
1100 if (outFile) {
1101 (void)fclose(outFile);
1102 }
1103 }
1104
SyncOutputFuncEos(uint32_t & last_index,uint32_t & outFrames,uint32_t & index,OH_AVBuffer * buffer,OH_AVCodecBufferAttr & attr)1105 int32_t VDecAPI11Sample::SyncOutputFuncEos(uint32_t &last_index, uint32_t &outFrames, uint32_t &index,
1106 OH_AVBuffer *buffer, OH_AVCodecBufferAttr &attr)
1107 {
1108 if (getOutputBufferIndexNoExisted) {
1109 buffer = OH_VideoDecoder_GetOutputBuffer(vdec_, index + HUNDRED);
1110 if (buffer == nullptr) {
1111 abnormalIndexValue = true;
1112 cout << "OH_VideoDecoder_GetOutputBuffer noexist buffer nullptr" << endl;
1113 }
1114 return AV_ERR_UNKNOWN;
1115 }
1116 if (outFrames == 0 && getOutputBufferIndexRepeated) {
1117 last_index = index;
1118 } else if (outFrames == 1 && getOutputBufferIndexRepeated) {
1119 cout << "getOutputBufferIndexRepeated last_index: " << last_index << "index: " << index << endl;
1120 buffer = OH_VideoDecoder_GetOutputBuffer(vdec_, last_index);
1121 if (buffer == nullptr) {
1122 abnormalIndexValue = true;
1123 cout << "OH_VideoDecoder_GetOutputBuffer repeat buffer nullptr" << endl;
1124 }
1125 return AV_ERR_UNKNOWN;
1126 }
1127 if (OH_AVBuffer_GetBufferAttr(buffer, &attr) != AV_ERR_OK) {
1128 errCount = errCount + 1;
1129 }
1130 if (CheckAttrFlag(attr) == -1) {
1131 if (queryInputBufferEOS) {
1132 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, 0);
1133 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, MILLION);
1134 OH_VideoDecoder_QueryInputBuffer(vdec_, &index, -1);
1135 }
1136 if (queryOutputBufferEOS) {
1137 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, 0);
1138 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, MILLION);
1139 OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, -1);
1140 }
1141 return AV_ERR_UNKNOWN;
1142 }
1143 return AV_ERR_OK;
1144 }
1145
ProcessOutputData(OH_AVBuffer * buffer,uint32_t index)1146 void VDecAPI11Sample::ProcessOutputData(OH_AVBuffer *buffer, uint32_t index)
1147 {
1148 if (!SF_OUTPUT) {
1149 GetStride();
1150 uint8_t *bufferAddr = OH_AVBuffer_GetAddr(buffer);
1151 int32_t size = OH_AVBuffer_GetCapacity(buffer);
1152 uint32_t cropSize = (picWidth_ * picHeight_ * THREE) >> 1;
1153 uint8_t *cropBuffer = new uint8_t[cropSize];
1154 uint8_t *copyPos = cropBuffer;
1155 if (size >= cropSize && !NocaleHash) {
1156 //copy y
1157 for (int32_t i = 0; i < picHeight_; i++) {
1158 memcpy_s(copyPos, picWidth_, bufferAddr, picWidth_);
1159 bufferAddr += stride_;
1160 copyPos += picWidth_;
1161 }
1162 bufferAddr += (sliceHeight_ - picHeight_) * stride_;
1163 //copy uv
1164 for (int32_t i = 0; i < picHeight_ >> 1; i++) {
1165 memcpy_s(copyPos, picWidth_, bufferAddr, picWidth_);
1166 bufferAddr += stride_;
1167 copyPos += picWidth_;
1168 }
1169 SHA512_Update(&g_c, cropBuffer, cropSize);
1170 }
1171 delete[] cropBuffer;
1172 if (OH_VideoDecoder_FreeOutputBuffer(vdec_, index) != AV_ERR_OK) {
1173 cout << "Fatal: ReleaseOutputBuffer fail" << endl;
1174 errCount = errCount + 1;
1175 }
1176 } else {
1177 if (rsAtTime) {
1178 RenderOutAtTime(index);
1179 } else {
1180 if (OH_VideoDecoder_RenderOutputBuffer(vdec_, index) != AV_ERR_OK) {
1181 cout << "Fatal: RenderOutputBuffer fail" << endl;
1182 errCount = errCount + 1;
1183 }
1184 }
1185 }
1186 }
1187
RenderOutAtTime(uint32_t index)1188 void VDecAPI11Sample::RenderOutAtTime(uint32_t index)
1189 {
1190 if (isAPI) {
1191 OH_AVErrCode code = OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, -100000000);
1192 if (code != AV_ERR_OK) {
1193 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
1194 errCount = code;
1195 }
1196 } else {
1197 int32_t usTimeNum = 1000;
1198 int32_t msTimeNum = 1000000;
1199 if (renderTimestampNs == 0) {
1200 renderTimestampNs = GetSystemTimeUs() * usTimeNum;
1201 }
1202 renderTimestampNs = renderTimestampNs + (usTimeNum / DEFAULT_FRAME_RATE * msTimeNum);
1203 OH_AVErrCode code = OH_VideoDecoder_RenderOutputBufferAtTime(vdec_, index, renderTimestampNs);
1204 if (code != AV_ERR_OK) {
1205 cout << "Fatal: RenderOutputBufferAtTime fail" << endl;
1206 errCount = code;
1207 }
1208 }
1209 }
1210
state_EOS()1211 int32_t VDecAPI11Sample::state_EOS()
1212 {
1213 uint32_t index;
1214 unique_lock<mutex> lock(signal_->inMutex_);
1215 signal_->inCond_.wait(lock, [this]() { return signal_->inIdxQueue_.size() > 0; });
1216 index = signal_->inIdxQueue_.front();
1217 signal_->inIdxQueue_.pop();
1218 signal_->inBufferQueue_.pop();
1219 lock.unlock();
1220 return OH_VideoDecoder_PushInputBuffer(vdec_, index);
1221 }
1222
SetEOS(uint32_t index,OH_AVBuffer * buffer)1223 void VDecAPI11Sample::SetEOS(uint32_t index, OH_AVBuffer *buffer)
1224 {
1225 OH_AVCodecBufferAttr attr;
1226 attr.pts = 0;
1227 attr.size = 0;
1228 attr.offset = 0;
1229 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
1230 OH_AVBuffer_SetBufferAttr(buffer, &attr);
1231 int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
1232 cout << "OH_VideoDecoder_PushInputBuffer EOS res: " << res << endl;
1233 }
1234
Flush()1235 int32_t VDecAPI11Sample::Flush()
1236 {
1237 isFlushing_.store(true);
1238 if (enbleSyncMode == 0) {
1239 unique_lock<mutex> inLock(signal_->inMutex_);
1240 clearIntqueue(signal_->inIdxQueue_);
1241 signal_->inCond_.notify_all();
1242 inLock.unlock();
1243 unique_lock<mutex> outLock(signal_->outMutex_);
1244 clearIntqueue(signal_->outIdxQueue_);
1245 clearBufferqueue(signal_->attrQueue_);
1246 signal_->outCond_.notify_all();
1247 outLock.unlock();
1248 }
1249 isRunning_.store(false);
1250 int32_t ret = OH_VideoDecoder_Flush(vdec_);
1251 isFlushing_.store(false);
1252 return ret;
1253 }
1254
Reset()1255 int32_t VDecAPI11Sample::Reset()
1256 {
1257 isRunning_.store(false);
1258 StopInloop();
1259 StopOutloop();
1260 ReleaseInFile();
1261 return OH_VideoDecoder_Reset(vdec_);
1262 }
1263
Release()1264 int32_t VDecAPI11Sample::Release()
1265 {
1266 int ret = 0;
1267 if (vdec_ != nullptr) {
1268 ret = OH_VideoDecoder_Destroy(vdec_);
1269 vdec_ = nullptr;
1270 }
1271
1272 if (signal_ != nullptr) {
1273 delete signal_;
1274 signal_ = nullptr;
1275 }
1276 return ret;
1277 }
1278
Stop()1279 int32_t VDecAPI11Sample::Stop()
1280 {
1281 StopInloop();
1282 StopOutloop();
1283 ReleaseInFile();
1284 return OH_VideoDecoder_Stop(vdec_);
1285 }
1286
Prepare()1287 int32_t VDecAPI11Sample::Prepare()
1288 {
1289 return OH_VideoDecoder_Prepare(vdec_);
1290 }
1291
Start()1292 int32_t VDecAPI11Sample::Start()
1293 {
1294 isRunning_.store(true);
1295 return OH_VideoDecoder_Start(vdec_);
1296 }
1297
QueryInputBuffer(uint32_t index,int64_t timeoutUs)1298 int32_t VDecAPI11Sample::QueryInputBuffer(uint32_t index, int64_t timeoutUs)
1299 {
1300 return OH_VideoDecoder_QueryInputBuffer(vdec_, &index, timeoutUs);
1301 }
1302
GetInputBuffer(uint32_t index)1303 OH_AVBuffer *VDecAPI11Sample::GetInputBuffer(uint32_t index)
1304 {
1305 return OH_VideoDecoder_GetInputBuffer(vdec_, index);
1306 }
1307
QueryOutputBuffer(uint32_t index,int64_t timeoutUs)1308 int32_t VDecAPI11Sample::QueryOutputBuffer(uint32_t index, int64_t timeoutUs)
1309 {
1310 return OH_VideoDecoder_QueryOutputBuffer(vdec_, &index, timeoutUs);
1311 }
1312
GetOutputBuffer(uint32_t index)1313 OH_AVBuffer *VDecAPI11Sample::GetOutputBuffer(uint32_t index)
1314 {
1315 return OH_VideoDecoder_GetOutputBuffer(vdec_, index);
1316 }
1317
PushInputBuffer(uint32_t index)1318 int32_t VDecAPI11Sample::PushInputBuffer(uint32_t index)
1319 {
1320 return OH_VideoDecoder_PushInputBuffer(vdec_, index);
1321 }
1322
StopOutloop()1323 void VDecAPI11Sample::StopOutloop()
1324 {
1325 if (outputLoop_ != nullptr && outputLoop_->joinable()) {
1326 unique_lock<mutex> lock(signal_->outMutex_);
1327 clearIntqueue(signal_->outIdxQueue_);
1328 clearBufferqueue(signal_->attrQueue_);
1329 isRunning_.store(false);
1330 signal_->outCond_.notify_all();
1331 lock.unlock();
1332 outputLoop_->join();
1333 outputLoop_.reset();
1334 }
1335 }
1336
SetParameter(OH_AVFormat * format)1337 int32_t VDecAPI11Sample::SetParameter(OH_AVFormat *format)
1338 {
1339 return OH_VideoDecoder_SetParameter(vdec_, format);
1340 }
1341
SwitchSurface()1342 int32_t VDecAPI11Sample::SwitchSurface()
1343 {
1344 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1345 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1346 cout << "manual switch surf "<< switchSurfaceFlag << endl;
1347 return ret;
1348 }
1349
RepeatCallSetSurface()1350 int32_t VDecAPI11Sample::RepeatCallSetSurface()
1351 {
1352 for (int i = 0; i < REPEAT_CALL_TIME; i++) {
1353 switchSurfaceFlag = (switchSurfaceFlag == 1) ? 0 : 1;
1354 int32_t ret = OH_VideoDecoder_SetSurface(vdec_, nativeWindow[switchSurfaceFlag]);
1355 if (ret != AV_ERR_OK && ret != AV_ERR_OPERATE_NOT_PERMIT && ret != AV_ERR_INVALID_STATE) {
1356 return AV_ERR_OPERATE_NOT_PERMIT;
1357 }
1358 }
1359 return AV_ERR_OK;
1360 }
1361
DecodeSetSurface()1362 int32_t VDecAPI11Sample::DecodeSetSurface()
1363 {
1364 CreateSurface();
1365 return OH_VideoDecoder_SetSurface(vdec_, nativeWindow[0]);
1366 }
1367
OpenFile()1368 int32_t VDecAPI11Sample::OpenFile()
1369 {
1370 inFile_ = make_unique<ifstream>();
1371 if (inFile_ == nullptr) {
1372 return AV_ERR_UNKNOWN;
1373 }
1374 inFile_->open(INP_DIR, ios::in | ios::binary);
1375 if (!inFile_->is_open()) {
1376 cout << "failed open file " << INP_DIR << endl;
1377 inFile_->close();
1378 inFile_.reset();
1379 inFile_ = nullptr;
1380 return AV_ERR_UNKNOWN;
1381 }
1382 return AV_ERR_OK;
1383 }