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