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