• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, &currentWidth);
89     OH_AVFormat_GetIntValue(format, OH_MD_KEY_HEIGHT, &currentHeight);
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     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_BLANK_FRAME_ON_SHUTDOWN, enbleBlankFrame);
145     int ret = OH_VideoDecoder_Configure(vdec_, format);
146     OH_AVFormat_Destroy(format);
147     if (isSurfMode) {
148         cs = Surface::CreateSurfaceAsConsumer();
149         sptr<IBufferConsumerListener> listener = new TestConsumerListener(cs);
150         cs->RegisterConsumerListener(listener);
151         auto p = cs->GetProducer();
152         ps = Surface::CreateSurfaceAsProducer(p);
153         nativeWindow = CreateNativeWindowFromSurface(&ps);
154         OH_VideoDecoder_SetSurface(vdec_, nativeWindow);
155     }
156     return ret;
157 }
158 
SetVideoDecoderCallback()159 int32_t VDecApi11FuzzSample::SetVideoDecoderCallback()
160 {
161     signal_ = new VDecSignal();
162     if (signal_ == nullptr) {
163         cout << "Failed to new VDecSignal" << endl;
164         return AV_ERR_UNKNOWN;
165     }
166 
167     cb_.onError = VdecError;
168     cb_.onStreamChanged = VdecFormatChanged;
169     cb_.onNeedInputBuffer = VdecInputDataReady;
170     cb_.onNewOutputBuffer = VdecOutputDataReady;
171     OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
172     return OH_VideoDecoder_RegisterCallback(vdec_, cb_, static_cast<void *>(signal_));
173 }
174 
CreateVideoDecoder()175 int32_t VDecApi11FuzzSample::CreateVideoDecoder()
176 {
177     OH_AVCapability *cap = OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false, HARDWARE);
178     string codecName = OH_AVCapability_GetName(cap);
179     vdec_ = OH_VideoDecoder_CreateByName("aabbcc");
180     bool isValid = false;
181     if (vdec_) {
182         OH_VideoDecoder_IsValid(vdec_, &isValid);
183         OH_VideoDecoder_Destroy(vdec_);
184         vdec_ = nullptr;
185     }
186     OH_AVCodec *tmpDec = OH_VideoDecoder_CreateByMime("aabbcc");
187     if (tmpDec) {
188         OH_VideoDecoder_Destroy(tmpDec);
189         tmpDec = nullptr;
190     }
191     tmpDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC);
192     OH_VideoDecoder_IsValid(vdec_, &isValid);
193     if (tmpDec) {
194         OH_VideoDecoder_Destroy(tmpDec);
195         tmpDec = nullptr;
196     }
197     vdec_ = OH_VideoDecoder_CreateByName(codecName.c_str());
198     g_decSample = this;
199     return vdec_ == nullptr ? AV_ERR_UNKNOWN : AV_ERR_OK;
200 }
201 
WaitForEOS()202 void VDecApi11FuzzSample::WaitForEOS()
203 {
204     if (inputLoop_ && inputLoop_->joinable()) {
205         inputLoop_->join();
206     }
207 }
208 
InputFuncFUZZ(const uint8_t * data,size_t size)209 OH_AVErrCode VDecApi11FuzzSample::InputFuncFUZZ(const uint8_t *data, size_t size)
210 {
211     uint32_t index;
212     unique_lock<mutex> lock(signal_->inMutex_);
213     if (!isRunning_.load()) {
214         return AV_ERR_NO_MEMORY;
215     }
216     signal_->inCond_.wait(lock, [this]() {
217         if (!isRunning_.load()) {
218             return true;
219         }
220         return signal_->inIdxQueue_.size() > 0;
221     });
222     if (!isRunning_.load()) {
223         return AV_ERR_NO_MEMORY;
224     }
225     index = signal_->inIdxQueue_.front();
226     auto buffer = signal_->inBufferQueue_.front();
227     signal_->inIdxQueue_.pop();
228     signal_->inBufferQueue_.pop();
229     lock.unlock();
230     int32_t bufferSize = OH_AVBuffer_GetCapacity(buffer);
231     uint8_t *bufferAddr = OH_AVBuffer_GetAddr(buffer);
232     if (size > bufferSize - START_CODE_SIZE) {
233         OH_VideoDecoder_PushInputBuffer(vdec_, index);
234         return AV_ERR_NO_MEMORY;
235     }
236     if (memcpy_s(bufferAddr, bufferSize, START_CODE, START_CODE_SIZE) != EOK) {
237         OH_VideoDecoder_PushInputBuffer(vdec_, index);
238         return AV_ERR_NO_MEMORY;
239     }
240     if (memcpy_s(bufferAddr + START_CODE_SIZE, bufferSize - START_CODE_SIZE, data, size) != EOK) {
241         OH_VideoDecoder_PushInputBuffer(vdec_, index);
242         cout << "Fatal: memcpy fail" << endl;
243         return AV_ERR_NO_MEMORY;
244     }
245     OH_AVCodecBufferAttr attr;
246     attr.pts = GetSystemTimeUs();
247     attr.size = size;
248     attr.offset = 0;
249     attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
250     OH_AVBuffer_SetBufferAttr(buffer, &attr);
251     OH_AVErrCode ret = OH_VideoDecoder_PushInputBuffer(vdec_, index);
252     return ret;
253 }
254 
SetEOS(OH_AVBuffer * buffer,uint32_t index)255 void VDecApi11FuzzSample::SetEOS(OH_AVBuffer *buffer, uint32_t index)
256 {
257     OH_AVCodecBufferAttr attr;
258     attr.pts = 0;
259     attr.size = 0;
260     attr.offset = 0;
261     attr.flags = AVCODEC_BUFFER_FLAGS_EOS;
262     OH_AVBuffer_SetBufferAttr(buffer, &attr);
263     int32_t res = OH_VideoDecoder_PushInputBuffer(vdec_, index);
264     cout << "OH_VideoDecoder_PushInputData    EOS   res: " << res << endl;
265 }
266 
Flush()267 int32_t VDecApi11FuzzSample::Flush()
268 {
269     unique_lock<mutex> inLock(signal_->inMutex_);
270     clearIntqueue(signal_->inIdxQueue_);
271     clearAvBufferQueue(signal_->inBufferQueue_);
272     signal_->inCond_.notify_all();
273     inLock.unlock();
274     unique_lock<mutex> outLock(signal_->outMutex_);
275     clearIntqueue(signal_->outIdxQueue_);
276     signal_->outCond_.notify_all();
277     isRunning_.store(false);
278     outLock.unlock();
279 
280     return OH_VideoDecoder_Flush(vdec_);
281 }
282 
Reset()283 int32_t VDecApi11FuzzSample::Reset()
284 {
285     isRunning_.store(false);
286     return OH_VideoDecoder_Reset(vdec_);
287 }
288 
Release()289 int32_t VDecApi11FuzzSample::Release()
290 {
291     int ret = 0;
292     if (vdec_ != nullptr) {
293         ret = OH_VideoDecoder_Destroy(vdec_);
294         vdec_ = nullptr;
295     }
296     if (signal_ != nullptr) {
297         clearAvBufferQueue(signal_->inBufferQueue_);
298         delete signal_;
299         signal_ = nullptr;
300     }
301     return ret;
302 }
303 
Stop()304 int32_t VDecApi11FuzzSample::Stop()
305 {
306     clearIntqueue(signal_->outIdxQueue_);
307     isRunning_.store(false);
308     return OH_VideoDecoder_Stop(vdec_);
309 }
310 
Start()311 int32_t VDecApi11FuzzSample::Start()
312 {
313     int32_t ret = OH_VideoDecoder_Start(vdec_);
314     if (ret == AV_ERR_OK) {
315         isRunning_.store(true);
316     }
317     return ret;
318 }
319 
SetParameter(int32_t data)320 void VDecApi11FuzzSample::SetParameter(int32_t data)
321 {
322     OH_AVFormat *format = OH_AVFormat_Create();
323     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, data);
324     (void)OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, data);
325     OH_VideoDecoder_SetParameter(vdec_, format);
326     OH_AVFormat_Destroy(format);
327 }
328 
StopInloop()329 void VDecApi11FuzzSample::StopInloop()
330 {
331     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
332         unique_lock<mutex> lock(signal_->inMutex_);
333         clearIntqueue(signal_->inIdxQueue_);
334         isRunning_.store(false);
335         signal_->inCond_.notify_all();
336         lock.unlock();
337 
338         inputLoop_->join();
339         inputLoop_.reset();
340     }
341 }
342 
ReleaseInFile()343 void VDecApi11FuzzSample::ReleaseInFile()
344 {
345     if (inFile_ != nullptr) {
346         if (inFile_->is_open()) {
347             inFile_->close();
348         }
349         inFile_.reset();
350         inFile_ = nullptr;
351     }
352 }
353 
StartVideoDecoder()354 int32_t VDecApi11FuzzSample::StartVideoDecoder()
355 {
356     isRunning_.store(true);
357     int ret = OH_VideoDecoder_Start(vdec_);
358     if (ret != AV_ERR_OK) {
359         isRunning_.store(false);
360         ReleaseInFile();
361         Release();
362         cout << "Failed to start codec" << endl;
363         return ret;
364     }
365     inFile_ = make_unique<ifstream>();
366     if (inFile_ == nullptr) {
367         isRunning_.store(false);
368         (void)OH_VideoDecoder_Stop(vdec_);
369         return AV_ERR_UNKNOWN;
370     }
371     inFile_->open(inpDir, ios::in | ios::binary);
372     if (!inFile_->is_open()) {
373         cout << "open input file failed" << endl;
374         isRunning_.store(false);
375         (void)OH_VideoDecoder_Stop(vdec_);
376         inFile_->close();
377         inFile_.reset();
378         inFile_ = nullptr;
379         return AV_ERR_UNKNOWN;
380     }
381 
382     inputLoop_ = make_unique<thread>(&VDecApi11FuzzSample::InputFuncTest, this);
383     if (inputLoop_ == nullptr) {
384         cout << "Failed to create input loop" << endl;
385         isRunning_.store(false);
386         (void)OH_VideoDecoder_Stop(vdec_);
387         ReleaseInFile();
388         return AV_ERR_UNKNOWN;
389     }
390     return AV_ERR_OK;
391 }
392 
InputFuncTest()393 void VDecApi11FuzzSample::InputFuncTest()
394 {
395     while (isRunning_.load()) {
396         uint32_t index;
397         unique_lock<mutex> lock(signal_->inMutex_);
398         signal_->inCond_.wait(lock, [this]() {
399             if (!isRunning_.load()) {
400                 return true;
401             }
402             return signal_->inIdxQueue_.size() > 0;
403         });
404         if (!isRunning_.load()) {
405             break;
406         }
407         index = signal_->inIdxQueue_.front();
408         auto buffer = signal_->inBufferQueue_.front();
409 
410         signal_->inIdxQueue_.pop();
411         signal_->inBufferQueue_.pop();
412         lock.unlock();
413         if (!inFile_->eof()) {
414             int ret = PushData(index, buffer);
415             if (ret == 1) {
416                 break;
417             }
418         }
419     }
420 }
421 
PushData(uint32_t index,OH_AVBuffer * buffer)422 int32_t VDecApi11FuzzSample::PushData(uint32_t index, OH_AVBuffer *buffer)
423 {
424     char ch[4] = {};
425     (void)inFile_->read(ch, START_CODE_SIZE);
426     if (inFile_->eof()) {
427         SetEOS(buffer, index);
428         return 1;
429     }
430     uint32_t bufferSize = static_cast<uint32_t>(((ch[3] & 0xFF)) | ((ch[2] & 0xFF) << EIGHT) |
431      ((ch[1] & 0xFF) << SIXTEEN) | ((ch[0] & 0xFF) << TWENTY_FOUR));
432 
433     return SendData(bufferSize, index, buffer);
434 }
435 
436 
SendData(uint32_t bufferSize,uint32_t index,OH_AVBuffer * buffer)437 uint32_t VDecApi11FuzzSample::SendData(uint32_t bufferSize, uint32_t index, OH_AVBuffer *buffer)
438 {
439     OH_AVCodecBufferAttr attr;
440     uint8_t *fileBuffer = new uint8_t[bufferSize + START_CODE_SIZE];
441     if (fileBuffer == nullptr) {
442         delete[] fileBuffer;
443         return 0;
444     }
445     if (memcpy_s(fileBuffer, bufferSize + START_CODE_SIZE, START_CODE, START_CODE_SIZE) != EOK) {
446         cout << "Fatal: memory copy failed" << endl;
447     }
448     (void)inFile_->read((char *)fileBuffer + START_CODE_SIZE, bufferSize);
449     if ((fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == SPS ||
450         (fileBuffer[START_CODE_SIZE] & H264_NALU_TYPE) == PPS) {
451         attr.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
452     } else {
453         attr.flags = AVCODEC_BUFFER_FLAGS_NONE;
454     }
455     int32_t size = OH_AVBuffer_GetCapacity(buffer);
456     if (size < bufferSize + START_CODE_SIZE) {
457         delete[] fileBuffer;
458         return 0;
459     }
460     uint8_t *avBuffer = OH_AVBuffer_GetAddr(buffer);
461     if (avBuffer == nullptr) {
462         cout << "avBuffer == nullptr" << endl;
463         inFile_->clear();
464         inFile_->seekg(0, ios::beg);
465         delete[] fileBuffer;
466         return 0;
467     }
468     if (memcpy_s(avBuffer, size, fileBuffer, bufferSize + START_CODE_SIZE) != EOK) {
469         delete[] fileBuffer;
470         return 0;
471     }
472     int64_t startPts = GetSystemTimeUs();
473     attr.pts = startPts;
474     attr.size = bufferSize + START_CODE_SIZE;
475     attr.offset = 0;
476     OH_AVBuffer_SetBufferAttr(buffer, &attr);
477     if (isRunning_.load()) {
478         OH_VideoDecoder_PushInputBuffer(vdec_, index) == AV_ERR_OK ? (0) : (errCount++);
479         frameCount_ = frameCount_ + 1;
480     }
481     delete[] fileBuffer;
482     return 0;
483 }