1 /*
2 * Copyright (C) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <arpa/inet.h>
16 #include <sys/time.h>
17 #include <utility>
18 #include "videodec_api11_sample.h"
19 #include "native_avcapability.h"
20 using namespace OHOS;
21 using namespace OHOS::Media;
22 using namespace std;
23 namespace {
24 const string MIME_TYPE = "video/avc";
25 constexpr int64_t NANOS_IN_SECOND = 1000000000L;
26 constexpr int64_t NANOS_IN_MICRO = 1000L;
27
28 constexpr uint32_t START_CODE_SIZE = 4;
29 constexpr uint8_t SPS = 7;
30 constexpr uint8_t PPS = 8;
31 constexpr int32_t EIGHT = 8;
32 constexpr int32_t SIXTEEN = 16;
33 constexpr int32_t TWENTY_FOUR = 24;
34 constexpr uint8_t H264_NALU_TYPE = 0x1f;
35
36 constexpr uint8_t START_CODE[START_CODE_SIZE] = {0, 0, 0, 1};
37 VDecApi11FuzzSample *g_decSample = nullptr;
38
clearIntqueue(std::queue<uint32_t> & q)39 void clearIntqueue(std::queue<uint32_t> &q)
40 {
41 std::queue<uint32_t> empty;
42 swap(empty, q);
43 }
44
clearAvBufferQueue(std::queue<OH_AVBuffer * > & q)45 void clearAvBufferQueue(std::queue<OH_AVBuffer *> &q)
46 {
47 std::queue<OH_AVBuffer *> empty;
48 swap(empty, q);
49 }
50 } // namespace
51
52 class TestConsumerListener : public IBufferConsumerListener {
53 public:
TestConsumerListener(sptr<Surface> cs)54 TestConsumerListener(sptr<Surface> cs) : cs(cs) {};
~TestConsumerListener()55 ~TestConsumerListener() {}
OnBufferAvailable()56 void OnBufferAvailable() override
57 {
58 sptr<SurfaceBuffer> buffer;
59 int32_t flushFence;
60 cs->AcquireBuffer(buffer, flushFence, timestamp, damage);
61
62 cs->ReleaseBuffer(buffer, -1);
63 }
64
65 private:
66 int64_t timestamp = 0;
67 Rect damage = {};
68 sptr<Surface> cs {nullptr};
69 };
70
~VDecApi11FuzzSample()71 VDecApi11FuzzSample::~VDecApi11FuzzSample()
72 {
73 Release();
74 }
75
VdecError(OH_AVCodec * codec,int32_t errorCode,void * userData)76 void VdecError(OH_AVCodec *codec, int32_t errorCode, void *userData)
77 {
78 cout << "Error errorCode=" << errorCode << endl;
79 g_decSample->isRunning_.store(false);
80 g_decSample->signal_->inCond_.notify_all();
81 }
82
VdecFormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)83 void VdecFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
84 {
85 cout << "Format Changed" << endl;
86 int32_t currentWidth = 0;
87 int32_t currentHeight = 0;
88 OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, ¤tWidth);
89 OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, ¤tHeight);
90 g_decSample->defaultWidth = currentWidth;
91 g_decSample->defaultHeight = currentHeight;
92 }
93
VdecInputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * buffer,void * userData)94 void VdecInputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData)
95 {
96 VDecSignal *signal = static_cast<VDecSignal *>(userData);
97 if (signal == nullptr) {
98 return;
99 }
100 unique_lock<mutex> lock(signal->inMutex_);
101 signal->inIdxQueue_.push(index);
102 signal->inBufferQueue_.push(buffer);
103 signal->inCond_.notify_all();
104 }
105
VdecOutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * buffer,void * userData)106 void VdecOutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData)
107 {
108 int32_t ret = 0;
109 if (g_decSample->isSurfMode) {
110 if (g_decSample->isRenderAttime) {
111 ret = OH_VideoDecoder_RenderOutputBufferAtTime(codec, index, g_decSample->renderTimestampNs);
112 } else {
113 ret = OH_VideoDecoder_RenderOutputBuffer(codec, index);
114 }
115 } else {
116 ret = OH_VideoDecoder_FreeOutputBuffer(codec, index);
117 }
118 if (ret != AV_ERR_OK) {
119 g_decSample->Flush();
120 g_decSample->Start();
121 }
122 }
123
GetSystemTimeUs()124 int64_t VDecApi11FuzzSample::GetSystemTimeUs()
125 {
126 struct timespec now;
127 (void)clock_gettime(CLOCK_BOOTTIME, &now);
128 int64_t nanoTime = static_cast<int64_t>(now.tv_sec) * NANOS_IN_SECOND + now.tv_nsec;
129 return nanoTime / NANOS_IN_MICRO;
130 }
131
ConfigureVideoDecoder()132 int32_t VDecApi11FuzzSample::ConfigureVideoDecoder()
133 {
134 OH_AVFormat *format = OH_AVFormat_Create();
135 if (format == nullptr) {
136 cout << "Fatal: Failed to create format" << endl;
137 return AV_ERR_UNKNOWN;
138 }
139 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, defaultWidth);
140 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, defaultHeight);
141 (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, defaultFrameRate);
142 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, 0);
143 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12);
144 int ret = OH_VideoDecoder_Configure(vdec_, format);
145 OH_AVFormat_Destroy(format);
146 if (isSurfMode) {
147 cs = Surface::CreateSurfaceAsConsumer();
148 sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs);
149 cs->RegisterConsumerListener(listener);
150 auto p = cs->GetProducer();
151 ps = Surface::CreateSurfaceAsProducer(p);
152 nativeWindow = CreateNativeWindowFromSurface(&ps);
153 OH_VideoDecoder_SetSurface(vdec_, nativeWindow);
154 }
155 return ret;
156 }
157
SetVideoDecoderCallback()158 int32_t VDecApi11FuzzSample::SetVideoDecoderCallback()
159 {
160 signal_ = new VDecSignal();
161 if (signal_ == nullptr) {
162 cout << "Failed to new VDecSignal" << endl;
163 return AV_ERR_UNKNOWN;
164 }
165
166 cb_.onError = VdecError;
167 cb_.onStreamChanged = VdecFormatChanged;
168 cb_.onNeedInputBuffer = VdecInputDataReady;
169 cb_.onNewOutputBuffer = VdecOutputDataReady;
170 OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
171 return OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
172 }
173
CreateVideoDecoder()174 int32_t VDecApi11FuzzSample::CreateVideoDecoder()
175 {
176 OH_AVCapability *cap = OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false, HARDWARE);
177 string codecName = OH_AVCapability_GetName(cap);
178 vdec_ = OH_VideoDecoder_CreateByName("aabbcc");
179 if (vdec_) {
180 OH_VideoDecoder_Destroy(vdec_);
181 vdec_ = nullptr;
182 }
183 OH_AVCodec *tmpDec = OH_VideoDecoder_CreateByMime("aabbcc");
184 if (tmpDec) {
185 OH_VideoDecoder_Destroy(tmpDec);
186 tmpDec = nullptr;
187 }
188 tmpDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC);
189 if (tmpDec) {
190 OH_VideoDecoder_Destroy(tmpDec);
191 tmpDec = nullptr;
192 }
193 vdec_ = OH_VideoDecoder_CreateByName(codecName.c_str());
194 g_decSample = this;
195 return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
196 }
197
WaitForEOS()198 void VDecApi11FuzzSample::WaitForEOS()
199 {
200 if (inputLoop_ && inputLoop_->joinable()) {
201 inputLoop_->join();
202 }
203 }
204
InputFuncFUZZ(const uint8_t * data,size_t size)205 OH_AVErrCode VDecApi11FuzzSample::InputFuncFUZZ(const uint8_t *data, size_t size)
206 {
207 uint32_t index;
208 unique_lock<mutex> lock(signal_->inMutex_);
209 if (!isRunning_.load()) {
210 return AV_ERR_NO_MEMORY;
211 }
212 signal_->inCond_.wait(lock, [this]() {
213 if (!isRunning_.load()) {
214 return true;
215 }
216 return signal_->inIdxQueue_.size() > 0;
217 });
218 if (!isRunning_.load()) {
219 return AV_ERR_NO_MEMORY;
220 }
221 index = signal_->inIdxQueue_.front();
222 auto buffer = signal_->inBufferQueue_.front();
223 signal_->inIdxQueue_.pop();
224 signal_->inBufferQueue_.pop();
225 lock.unlock();
226 int32_t bufferSize = OH_AVBuffer_GetCapacity(buffer);
227 uint8_t *bufferAddr = OH_AVBuffer_GetAddr(buffer);
228 if (size > bufferSize - START_CODE_SIZE) {
229 OH_VideoDecoder_PushInputBuffer(vdec_, index);
230 return AV_ERR_NO_MEMORY;
231 }
232 if (memcpy_s(bufferAddr, bufferSize, START_CODE, START_CODE_SIZE) != EOK) {
233 OH_VideoDecoder_PushInputBuffer(vdec_, index);
234 return AV_ERR_NO_MEMORY;
235 }
236 if (memcpy_s(bufferAddr + START_CODE_SIZE, bufferSize - START_CODE_SIZE, data, size) != EOK) {
237 OH_VideoDecoder_PushInputBuffer(vdec_, index);
238 cout << "Fatal: memcpy fail" << endl;
239 return AV_ERR_NO_MEMORY;
240 }
241 OH_AVCodecBufferAttr attr;
242 attr.pts = GetSystemTimeUs();
243 attr.size = size;
244 attr.offset = 0;
245 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
246 OH_AVBuffer_SetBufferAttr(buffer, &attr);
247 OH_AVErrCode ret = OH_VideoDecoder_PushInputBuffer(vdec_, index);
248 return ret;
249 }
250
SetEOS(OH_AVBuffer * buffer,uint32_t index)251 void VDecApi11FuzzSample::SetEOS(OH_AVBuffer *buffer, uint32_t index)
252 {
253 OH_AVCodecBufferAttr attr;
254 attr.pts = 0;
255 attr.size = 0;
256 attr.offset = 0;
257 attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
258 OH_AVBuffer_SetBufferAttr(buffer, &attr);
259 int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
260 cout << "OH_VideoDecoder_PushInputData EOS res: " << res << endl;
261 }
262
Flush()263 int32_t VDecApi11FuzzSample::Flush()
264 {
265 unique_lock<mutex> inLock(signal_->inMutex_);
266 clearIntqueue(signal_->inIdxQueue_);
267 clearAvBufferQueue(signal_->inBufferQueue_);
268 signal_->inCond_.notify_all();
269 inLock.unlock();
270 unique_lock<mutex> outLock(signal_->outMutex_);
271 clearIntqueue(signal_->outIdxQueue_);
272 signal_->outCond_.notify_all();
273 isRunning_.store(false);
274 outLock.unlock();
275
276 return OH_VideoDecoder_Flush(vdec_);
277 }
278
Reset()279 int32_t VDecApi11FuzzSample::Reset()
280 {
281 isRunning_.store(false);
282 return OH_VideoDecoder_Reset(vdec_);
283 }
284
Release()285 int32_t VDecApi11FuzzSample::Release()
286 {
287 int ret = 0;
288 if (vdec_ != nullptr) {
289 ret = OH_VideoDecoder_Destroy(vdec_);
290 vdec_ = nullptr;
291 }
292 if (signal_ != nullptr) {
293 clearAvBufferQueue(signal_->inBufferQueue_);
294 delete signal_;
295 signal_ = nullptr;
296 }
297 return ret;
298 }
299
Stop()300 int32_t VDecApi11FuzzSample::Stop()
301 {
302 clearIntqueue(signal_->outIdxQueue_);
303 isRunning_.store(false);
304 return OH_VideoDecoder_Stop(vdec_);
305 }
306
Start()307 int32_t VDecApi11FuzzSample::Start()
308 {
309 int32_t ret = OH_VideoDecoder_Start(vdec_);
310 if (ret == AV_ERR_OK) {
311 isRunning_.store(true);
312 }
313 return ret;
314 }
315
SetParameter(int32_t data)316 void VDecApi11FuzzSample::SetParameter(int32_t data)
317 {
318 OH_AVFormat *format = OH_AVFormat_Create();
319 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, data);
320 (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, data);
321 OH_VideoDecoder_SetParameter(vdec_, format);
322 OH_AVFormat_Destroy(format);
323 }
324
StopInloop()325 void VDecApi11FuzzSample::StopInloop()
326 {
327 if (inputLoop_ != nullptr && inputLoop_->joinable()) {
328 unique_lock<mutex> lock(signal_->inMutex_);
329 clearIntqueue(signal_->inIdxQueue_);
330 isRunning_.store(false);
331 signal_->inCond_.notify_all();
332 lock.unlock();
333
334 inputLoop_->join();
335 inputLoop_.reset();
336 }
337 }
338
ReleaseInFile()339 void VDecApi11FuzzSample::ReleaseInFile()
340 {
341 if (inFile_ != nullptr) {
342 if (inFile_->is_open()) {
343 inFile_->close();
344 }
345 inFile_.reset();
346 inFile_ = nullptr;
347 }
348 }
349
StartVideoDecoder()350 int32_t VDecApi11FuzzSample::StartVideoDecoder()
351 {
352 isRunning_.store(true);
353 int ret = OH_VideoDecoder_Start(vdec_);
354 if (ret != AV_ERR_OK) {
355 isRunning_.store(false);
356 ReleaseInFile();
357 Release();
358 cout << "Failed to start codec" << endl;
359 return ret;
360 }
361 inFile_ = make_unique<ifstream>();
362 if (inFile_ == nullptr) {
363 isRunning_.store(false);
364 (void)OH_VideoDecoder_Stop(vdec_);
365 return AV_ERR_UNKNOWN;
366 }
367 inFile_->open(inpDir, ios::in | ios::binary);
368 if (!inFile_->is_open()) {
369 cout << "open input file failed" << endl;
370 isRunning_.store(false);
371 (void)OH_VideoDecoder_Stop(vdec_);
372 inFile_->close();
373 inFile_.reset();
374 inFile_ = nullptr;
375 return AV_ERR_UNKNOWN;
376 }
377
378 inputLoop_ = make_unique<thread>(&VDecApi11FuzzSample::InputFuncTest, this);
379 if (inputLoop_ == nullptr) {
380 cout << "Failed to create input loop" << endl;
381 isRunning_.store(false);
382 (void)OH_VideoDecoder_Stop(vdec_);
383 ReleaseInFile();
384 return AV_ERR_UNKNOWN;
385 }
386 return AV_ERR_OK;
387 }
388
InputFuncTest()389 void VDecApi11FuzzSample::InputFuncTest()
390 {
391 while (isRunning_.load()) {
392 uint32_t index;
393 unique_lock<mutex> lock(signal_->inMutex_);
394 signal_->inCond_.wait(lock, [this]() {
395 if (!isRunning_.load()) {
396 return true;
397 }
398 return signal_->inIdxQueue_.size() > 0;
399 });
400 if (!isRunning_.load()) {
401 break;
402 }
403 index = signal_->inIdxQueue_.front();
404 auto buffer = signal_->inBufferQueue_.front();
405
406 signal_->inIdxQueue_.pop();
407 signal_->inBufferQueue_.pop();
408 lock.unlock();
409 if (!inFile_->eof()) {
410 int ret = PushData(index, buffer);
411 if (ret == 1) {
412 break;
413 }
414 }
415 }
416 }
417
PushData(uint32_t index,OH_AVBuffer * buffer)418 int32_t VDecApi11FuzzSample::PushData(uint32_t index, OH_AVBuffer *buffer)
419 {
420 char ch[4] = {};
421 (void)inFile_->read(ch, START_CODE_SIZE);
422 if (inFile_->eof()) {
423 SetEOS(buffer, index);
424 return 1;
425 }
426 uint32_t bufferSize = static_cast<uint32_t>(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) |
427 ((ch[1] & 0xFF) << SIXTEEN) | ((ch[0] & 0xFF) << TWENTY_FOUR));
428
429 return SendData(bufferSize, index, buffer);
430 }
431
432
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)433 uint32_t VDecApi11FuzzSample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
434 {
435 OH_AVCodecBufferAttr attr;
436 uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
437 if (fileBuffer == nullptr) {
438 delete[] fileBuffer;
439 return 0;
440 }
441 if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
442 cout << "Fatal: memory copy failed" << endl;
443 }
444 (void)inFile_->read((char *)fileBuffer + START_CODE_SIZE, bufferSize);
445 if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
446 (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
447 attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
448 } else {
449 attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
450 }
451 int32_t size = OH_AVBuffer_GetCapacity(buffer);
452 if (size < bufferSize + START_CODE_SIZE) {
453 delete[] fileBuffer;
454 return 0;
455 }
456 uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
457 if (avBuffer == nullptr) {
458 cout << "avBuffer == nullptr" << endl;
459 inFile_->clear();
460 inFile_->seekg(0, ios::beg);
461 delete[] fileBuffer;
462 return 0;
463 }
464 if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
465 delete[] fileBuffer;
466 return 0;
467 }
468 int64_t startPts = GetSystemTimeUs();
469 attr.pts = startPts;
470 attr.size = bufferSize + START_CODE_SIZE;
471 attr.offset = 0;
472 OH_AVBuffer_SetBufferAttr(buffer, &attr);
473 if (isRunning_.load()) {
474 OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
475 frameCount_ = frameCount_ + 1;
476 }
477 delete[] fileBuffer;
478 return 0;
479 }