• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "videodec_sample.h"
19 using namespace OHOS;
20 using namespace OHOS::Media;
21 using namespace std;
22 namespace {
23 const string MIME_TYPE = "video/avc";
24 constexpr int64_t NANOS_IN_SECOND = 1000000000L;
25 constexpr int64_t NANOS_IN_MICRO = 1000L;
26 
27 constexpr int32_t EIGHT = 8;
28 constexpr int32_t SIXTEEN = 16;
29 constexpr int32_t TWENTY_FOUR = 24;
30 constexpr uint8_t SEI = 6;
31 constexpr uint8_t SPS = 7;
32 constexpr uint8_t PPS = 8;
33 constexpr uint32_t START_CODE_SIZE = 4;
34 constexpr uint8_t START_CODE[START_CODE_SIZE] = {0, 0, 0, 1};
35 VDecFuzzSample *g_decSample = nullptr;
36 constexpr uint8_t H264_NALU_TYPE = 0x1f;
37 
38 bool g_fuzzError = false;
39 
clearIntqueue(std::queue<uint32_t> & q)40 void clearIntqueue(std::queue<uint32_t> &q)
41 {
42     std::queue<uint32_t> empty;
43     swap(empty, q);
44 }
45 
clearBufferqueue(std::queue<OH_AVCodecBufferAttr> & q)46 void clearBufferqueue(std::queue<OH_AVCodecBufferAttr> &q)
47 {
48     std::queue<OH_AVCodecBufferAttr> empty;
49     swap(empty, q);
50 }
51 
clearAvBufferQueue(std::queue<OH_AVMemory * > & q)52 void clearAvBufferQueue(std::queue<OH_AVMemory *> &q)
53 {
54     std::queue<OH_AVMemory *> empty;
55     swap(empty, q);
56 }
57 } // namespace
58 
59 class TestConsumerListener : public IBufferConsumerListener {
60 public:
TestConsumerListener(sptr<Surface> cs)61     TestConsumerListener(sptr<Surface> cs) : cs(cs) {};
~TestConsumerListener()62     ~TestConsumerListener() {}
OnBufferAvailable()63     void OnBufferAvailable() override
64     {
65         sptr<SurfaceBuffer> buffer;
66         int32_t flushFence;
67         cs->AcquireBuffer(buffer, flushFence, timestamp, damage);
68 
69         cs->ReleaseBuffer(buffer, -1);
70     }
71 
72 private:
73     int64_t timestamp = 0;
74     Rect damage = {};
75     sptr<Surface> cs {nullptr};
76 };
77 
~VDecFuzzSample()78 VDecFuzzSample::~VDecFuzzSample()
79 {
80     Release();
81 }
82 
VdecError(OH_AVCodec * codec,int32_t errorCode,void * userData)83 void VdecError(OH_AVCodec *codec, int32_t errorCode, void *userData)
84 {
85     VDecSignal *signal = static_cast<VDecSignal *>(userData);
86     if (signal == nullptr) {
87         return;
88     }
89     cout << "Error errorCode=" << errorCode << endl;
90     g_fuzzError = true;
91     signal->inCond_.notify_all();
92 }
93 
VdecFormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)94 void VdecFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
95 {
96     cout << "Format Changed" << endl;
97     int32_t currentWidth = 0;
98     int32_t currentHeight = 0;
99     OH_AVFormat_GetIntValue(format, OH_MD_KEY_WIDTH, &currentWidth);
100     OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, &currentHeight);
101     g_decSample->defaultWidth = currentWidth;
102     g_decSample->defaultHeight = currentHeight;
103 }
104 
VdecInputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVMemory * data,void * userData)105 void VdecInputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
106 {
107     VDecSignal *signal = static_cast<VDecSignal *>(userData);
108     if (signal == nullptr) {
109         return;
110     }
111     unique_lock<mutex> lock(signal->inMutex_);
112     signal->inIdxQueue_.push(index);
113     signal->inBufferQueue_.push(data);
114     signal->inCond_.notify_all();
115 }
116 
VdecOutputDataReady(OH_AVCodec * codec,uint32_t index,OH_AVMemory * data,OH_AVCodecBufferAttr * attr,void * userData)117 void VdecOutputDataReady(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
118                          void *userData)
119 {
120     VDecSignal *signal = static_cast<VDecSignal *>(userData);
121     if (signal == nullptr) {
122         return;
123     }
124     unique_lock<mutex> lock(signal->outMutex_);
125     signal->outIdxQueue_.push(index);
126     signal->attrQueue_.push(*attr);
127     signal->outBufferQueue_.push(data);
128     signal->outCond_.notify_all();
129     if (g_decSample->isSurfMode) {
130         OH_VideoDecoder_RenderOutputData(codec, index);
131     } else {
132         OH_VideoDecoder_FreeOutputData(codec, index);
133     }
134 }
135 
GetSystemTimeUs()136 int64_t VDecFuzzSample::GetSystemTimeUs()
137 {
138     struct timespec now;
139     (void)clock_gettime(CLOCK_BOOTTIME, &now);
140     int64_t nanoTime = static_cast<int64_t>(now.tv_sec) * NANOS_IN_SECOND + now.tv_nsec;
141     return nanoTime / NANOS_IN_MICRO;
142 }
143 
ConfigureVideoDecoder()144 int32_t VDecFuzzSample::ConfigureVideoDecoder()
145 {
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     OH_AVFormat *format = OH_AVFormat_Create();
156     if (format == nullptr) {
157         cout << "Fatal: Failed to create format" << endl;
158         return AV_ERR_UNKNOWN;
159     }
160     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, defaultWidth);
161     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, defaultHeight);
162     (void)OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, defaultFrameRate);
163     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, defaultRotation);
164     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, defaultPixelFormat);
165     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_BLANK_FRAME_ON_SHUTDOWN, enbleBlankFrame);
166     int ret = OH_VideoDecoder_Configure(vdec_, format);
167     OH_AVFormat_Destroy(format);
168     return ret;
169 }
170 
RunVideoDec(string codeName)171 int32_t VDecFuzzSample::RunVideoDec(string codeName)
172 {
173     int err = CreateVideoDecoder(codeName);
174     if (err != AV_ERR_OK) {
175         cout << "Failed to create video decoder" << endl;
176         return err;
177     }
178     err = ConfigureVideoDecoder();
179     if (err != AV_ERR_OK) {
180         cout << "Failed to configure video decoder" << endl;
181         Release();
182         return err;
183     }
184     err = SetVideoDecoderCallback();
185     if (err != AV_ERR_OK) {
186         cout << "Failed to setCallback" << endl;
187         Release();
188         return err;
189     }
190     err = StartVideoDecoder();
191     if (err != AV_ERR_OK) {
192         cout << "Failed to start video decoder" << endl;
193         Release();
194         return err;
195     }
196     return err;
197 }
198 
SetVideoDecoderCallback()199 int32_t VDecFuzzSample::SetVideoDecoderCallback()
200 {
201     signal_ = new VDecSignal();
202     if (signal_ == nullptr) {
203         cout << "Failed to new VDecSignal" << endl;
204         return AV_ERR_UNKNOWN;
205     }
206 
207     cb_.onError = VdecError;
208     cb_.onStreamChanged = VdecFormatChanged;
209     cb_.onNeedInputData = VdecInputDataReady;
210     cb_.onNeedOutputData = VdecOutputDataReady;
211     return OH_VideoDecoder_SetCallback(vdec_, cb_, static_cast<void *>(signal_));
212 }
213 
ReleaseInFile()214 void VDecFuzzSample::ReleaseInFile()
215 {
216     if (inFile_ != nullptr) {
217         if (inFile_->is_open()) {
218             inFile_->close();
219         }
220         inFile_.reset();
221         inFile_ = nullptr;
222     }
223 }
224 
StopInloop()225 void VDecFuzzSample::StopInloop()
226 {
227     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
228         unique_lock<mutex> lock(signal_->inMutex_);
229         clearIntqueue(signal_->inIdxQueue_);
230         signal_->inCond_.notify_all();
231         lock.unlock();
232 
233         inputLoop_->join();
234         inputLoop_.reset();
235     }
236 }
237 
StartVideoDecoder()238 int32_t VDecFuzzSample::StartVideoDecoder()
239 {
240     int ret = OH_VideoDecoder_Start(vdec_);
241     if (ret != AV_ERR_OK) {
242         cout << "Failed to start codec" << endl;
243         return ret;
244     }
245 
246     isRunning_.store(true);
247 
248     inFile_ = make_unique<ifstream>();
249     if (inFile_ == nullptr) {
250         isRunning_.store(false);
251         (void)OH_VideoDecoder_Stop(vdec_);
252         return AV_ERR_UNKNOWN;
253     }
254     inFile_->open(inpDir, ios::in | ios::binary);
255     if (!inFile_->is_open()) {
256         cout << "open input file failed" << endl;
257         isRunning_.store(false);
258         (void)OH_VideoDecoder_Stop(vdec_);
259         inFile_->close();
260         inFile_.reset();
261         inFile_ = nullptr;
262         return AV_ERR_UNKNOWN;
263     }
264 
265     inputLoop_ = make_unique<thread>(&VDecFuzzSample::InputFuncAVCC, this);
266     if (inputLoop_ == nullptr) {
267         cout << "Failed to create input loop" << endl;
268         isRunning_.store(false);
269         (void)OH_VideoDecoder_Stop(vdec_);
270         ReleaseInFile();
271         return AV_ERR_UNKNOWN;
272     }
273     return AV_ERR_OK;
274 }
275 
CreateVideoDecoder(string codeName)276 int32_t VDecFuzzSample::CreateVideoDecoder(string codeName)
277 {
278     vdec_ = OH_VideoDecoder_CreateByName(randomName.c_str());
279     if (vdec_) {
280         OH_VideoDecoder_Destroy(vdec_);
281         vdec_ = nullptr;
282     }
283     OH_AVCodec *tmpDec = OH_VideoDecoder_CreateByMime(randomMime.c_str());
284     if (tmpDec) {
285         OH_VideoDecoder_Destroy(tmpDec);
286         tmpDec = nullptr;
287     }
288     tmpDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC);
289     if (tmpDec) {
290         OH_VideoDecoder_Destroy(tmpDec);
291         tmpDec = nullptr;
292     }
293     vdec_ = OH_VideoDecoder_CreateByName(codeName.c_str());
294     g_decSample = this;
295     return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
296 }
297 
WaitForEOS()298 void VDecFuzzSample::WaitForEOS()
299 {
300     if (inputLoop_ && inputLoop_->joinable()) {
301         inputLoop_->join();
302     }
303 }
304 
CopyStartCode(uint8_t * frameBuffer,uint32_t bufferSize,OH_AVCodecBufferAttr & attr)305 void VDecFuzzSample::CopyStartCode(uint8_t *frameBuffer, uint32_t bufferSize, OH_AVCodecBufferAttr &attr)
306 {
307     switch (frameBuffer[START_CODE_SIZE] & H264_NALU_TYPE) {
308         case SPS:
309         case PPS:
310         case SEI:
311             if (memcpy_s(frameBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
312                 cout << "Fatal: memory copy failed" << endl;
313             }
314             attr.pts = GetSystemTimeUs();
315             attr.size = bufferSize + START_CODE_SIZE;
316             attr.offset = 0;
317             attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
318             break;
319         default: {
320             if (memcpy_s(frameBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
321                 cout << "Fatal: memory copy failed" << endl;
322             }
323             attr.pts = GetSystemTimeUs();
324             attr.size = bufferSize + START_CODE_SIZE;
325             attr.offset = 0;
326             attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
327         }
328     }
329 }
330 
ReadData(uint32_t index,OH_AVMemory * buffer)331 int32_t VDecFuzzSample::ReadData(uint32_t index, OH_AVMemory *buffer)
332 {
333     uint8_t ch[4] = {};
334     (void)inFile_->read(reinterpret_cast<char *>(ch), START_CODE_SIZE);
335     if (repeatRun && inFile_->eof()) {
336         inFile_->clear();
337         inFile_->seekg(0, ios::beg);
338         cout << "repeat" << endl;
339         return 0;
340     } else if (inFile_->eof()) {
341         SetEOS(index);
342         return 1;
343     }
344     uint32_t bufferSize = static_cast<uint32_t>(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) |
345     ((ch[1] & 0xFF) << SIXTEEN) | ((ch[0] & 0xFF) << TWENTY_FOUR));
346     return SendData(bufferSize, index, buffer);
347 }
348 
SendData(uint32_t bufferSize,uint32_t index,OH_AVMemory * buffer)349 uint32_t VDecFuzzSample::SendData(uint32_t bufferSize, uint32_t index, OH_AVMemory *buffer)
350 {
351     OH_AVCodecBufferAttr attr;
352     uint8_t *frameBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
353     (void)inFile_->read(reinterpret_cast<char *>(frameBuffer + START_CODE_SIZE), bufferSize);
354     CopyStartCode(frameBuffer, bufferSize, attr);
355     int32_t size = OH_AVMemory_GetSize(buffer);
356     if (size < attr.size) {
357         delete[] frameBuffer;
358         cout << "ERROR:AVMemory not enough, buffer size" << attr.size << "   AVMemory Size " << size << endl;
359         isRunning_.store(false);
360         return 1;
361     }
362     uint8_t *bufferAddr = OH_AVMemory_GetAddr(buffer);
363     if (memcpy_s(bufferAddr, size, frameBuffer, attr.size) != EOK) {
364         delete[] frameBuffer;
365         cout << "Fatal: memcpy fail" << endl;
366         isRunning_.store(false);
367         return 1;
368     }
369     delete[] frameBuffer;
370     int32_t ret = OH_VideoDecoder_PushInputData(vdec_, index, attr);
371     if (ret != AV_ERR_OK) {
372         errCount++;
373         cout << "push input data failed, error:" << ret << endl;
374     }
375     frameCount_ = frameCount_ + 1;
376     if (inFile_->eof()) {
377         isRunning_.store(false);
378     }
379     return 0;
380 }
381 
InputFuncAVCC()382 void VDecFuzzSample::InputFuncAVCC()
383 {
384     frameCount_ = 1;
385     errCount = 0;
386     while (true) {
387         if (!isRunning_.load()) {
388             break;
389         }
390         unique_lock<mutex> lock(signal_->inMutex_);
391         signal_->inCond_.wait(lock, [this]() {
392             if (!isRunning_.load()) {
393                 cout << "quit signal" << endl;
394                 return true;
395             }
396             return signal_->inIdxQueue_.size() > 0;
397         });
398         if (!isRunning_.load()) {
399             break;
400         }
401         uint32_t index = signal_->inIdxQueue_.front();
402         auto buffer = signal_->inBufferQueue_.front();
403         signal_->inIdxQueue_.pop();
404         signal_->inBufferQueue_.pop();
405         lock.unlock();
406         if (!inFile_->eof()) {
407             int ret = ReadData(index, buffer);
408             if (ret == 1) {
409                 break;
410             }
411         }
412     }
413 }
414 
InputFuncFUZZ(const uint8_t * data,size_t size)415 OH_AVErrCode VDecFuzzSample::InputFuncFUZZ(const uint8_t *data, size_t size)
416 {
417     uint32_t index;
418     unique_lock<mutex> lock(signal_->inMutex_);
419     signal_->inCond_.wait(lock, [this]() {
420         if (!isRunning_.load() && g_fuzzError) {
421             return true;
422         }
423         return signal_->inIdxQueue_.size() > 0;
424     });
425     if (g_fuzzError)
426         return AV_ERR_TIMEOUT;
427     index = signal_->inIdxQueue_.front();
428     auto buffer = signal_->inBufferQueue_.front();
429     signal_->inIdxQueue_.pop();
430     signal_->inBufferQueue_.pop();
431     lock.unlock();
432     int32_t bufferSize = OH_AVMemory_GetSize(buffer);
433     uint8_t *bufferAddr = OH_AVMemory_GetAddr(buffer);
434 
435     if (memcpy_s(bufferAddr, bufferSize, data, size) != EOK) {
436         cout << "Fatal: memcpy fail" << endl;
437         return AV_ERR_NO_MEMORY;
438     }
439     OH_AVCodecBufferAttr attr;
440     attr.pts = GetSystemTimeUs();
441     attr.size = bufferSize;
442     attr.offset = 0;
443     attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
444     OH_AVErrCode ret = OH_VideoDecoder_PushInputData(vdec_, index, attr);
445     return ret;
446 }
447 
SetEOS(uint32_t index)448 void VDecFuzzSample::SetEOS(uint32_t index)
449 {
450     OH_AVCodecBufferAttr attr;
451     attr.pts = 0;
452     attr.size = 0;
453     attr.offset = 0;
454     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
455     int32_t res = OH_VideoDecoder_PushInputData(vdec_, index, attr);
456     cout << "OH_VideoDecoder_PushInputData    EOS   res: " << res << endl;
457 }
458 
Flush()459 int32_t VDecFuzzSample::Flush()
460 {
461     unique_lock<mutex> inLock(signal_->inMutex_);
462     clearIntqueue(signal_->inIdxQueue_);
463     signal_->inCond_.notify_all();
464     inLock.unlock();
465     unique_lock<mutex> outLock(signal_->outMutex_);
466     clearIntqueue(signal_->outIdxQueue_);
467     clearBufferqueue(signal_->attrQueue_);
468     signal_->outCond_.notify_all();
469     isRunning_.store(false);
470     outLock.unlock();
471 
472     return OH_VideoDecoder_Flush(vdec_);
473 }
474 
Reset()475 int32_t VDecFuzzSample::Reset()
476 {
477     isRunning_.store(false);
478     StopInloop();
479     ReleaseInFile();
480     return OH_VideoDecoder_Reset(vdec_);
481 }
482 
Release()483 int32_t VDecFuzzSample::Release()
484 {
485     int ret = 0;
486     if (vdec_ != nullptr) {
487         ret = OH_VideoDecoder_Destroy(vdec_);
488         vdec_ = nullptr;
489     }
490     if (signal_ != nullptr) {
491         clearAvBufferQueue(signal_->inBufferQueue_);
492         clearAvBufferQueue(signal_->outBufferQueue_);
493         delete signal_;
494         signal_ = nullptr;
495     }
496     return ret;
497 }
498 
Stop()499 int32_t VDecFuzzSample::Stop()
500 {
501     StopInloop();
502     clearIntqueue(signal_->outIdxQueue_);
503     clearBufferqueue(signal_->attrQueue_);
504     ReleaseInFile();
505     return OH_VideoDecoder_Stop(vdec_);
506 }
507 
Start()508 int32_t VDecFuzzSample::Start()
509 {
510     int32_t ret = 0;
511     ret = OH_VideoDecoder_Start(vdec_);
512     if (ret == AV_ERR_OK) {
513         isRunning_.store(true);
514     }
515     return ret;
516 }
517 
SetParameter(OH_AVFormat * format)518 int32_t VDecFuzzSample::SetParameter(OH_AVFormat *format)
519 {
520     return OH_VideoDecoder_SetParameter(vdec_, format);
521 }