• 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 
16 #include "audio_decoder_aac_demo.h"
17 #include <iostream>
18 #include <fstream>
19 #include <unistd.h>
20 #include <sys/stat.h>
21 #include <chrono>
22 #include <fcntl.h>
23 #include "avcodec_codec_name.h"
24 #include "avcodec_common.h"
25 #include "avcodec_errors.h"
26 #include "demo_log.h"
27 #include "media_description.h"
28 #include "native_avcodec_base.h"
29 #include "native_avformat.h"
30 #include "native_avbuffer.h"
31 #include "native_avmemory.h"
32 #include "securec.h"
33 
34 using namespace OHOS;
35 using namespace OHOS::MediaAVCodec;
36 using namespace OHOS::MediaAVCodec::AudioBufferDemo;
37 
38 using namespace std;
39 namespace {
40 constexpr uint32_t CHANNEL_COUNT = 2;
41 constexpr uint32_t SAMPLE_RATE = 44100;
42 constexpr uint32_t DEFAULT_AAC_TYPE = 1;
43 } // namespace
44 
OnError(OH_AVCodec * codec,int32_t errorCode,void * userData)45 static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
46 {
47     (void)codec;
48     (void)errorCode;
49     (void)userData;
50 }
51 
OnOutputFormatChanged(OH_AVCodec * codec,OH_AVFormat * format,void * userData)52 static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
53 {
54     (void)codec;
55     (void)format;
56     (void)userData;
57     cout << "OnOutputFormatChanged received" << endl;
58 }
59 
OnInputBufferAvailable(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)60 static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
61 {
62     (void)codec;
63     ADecBufferSignal *signal = static_cast<ADecBufferSignal *>(userData);
64     unique_lock<mutex> lock(signal->inMutex_);
65     signal->inQueue_.push(index);
66     signal->inBufferQueue_.push(data);
67     signal->inCond_.notify_all();
68 }
69 
OnOutputBufferAvailable(OH_AVCodec * codec,uint32_t index,OH_AVBuffer * data,void * userData)70 static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData)
71 {
72     (void)codec;
73     ADecBufferSignal *signal = static_cast<ADecBufferSignal *>(userData);
74     unique_lock<mutex> lock(signal->outMutex_);
75     signal->outQueue_.push(index);
76     signal->outBufferQueue_.push(data);
77     signal->outCond_.notify_all();
78 }
79 
SplitStringFully(const string & str,const string & separator)80 vector<string> SplitStringFully(const string& str, const string& separator)
81 {
82     vector<string> dest;
83     string substring;
84     string::size_type start = 0;
85     string::size_type index = str.find_first_of(separator, start);
86 
87     while (index != string::npos) {
88         substring = str.substr(start, index - start);
89         dest.push_back(substring);
90         start = str.find_first_not_of(separator, index);
91         if (start == string::npos) {
92             return dest;
93         }
94         index = str.find_first_of(separator, start);
95     }
96     substring = str.substr(start);
97     dest.push_back(substring);
98 
99     return dest;
100 }
101 
StringReplace(std::string & strBig,const std::string & strsrc,const std::string & strdst)102 void StringReplace(std::string& strBig, const std::string& strsrc, const std::string& strdst)
103 {
104     std::string::size_type pos = 0;
105     std::string::size_type srclen = strsrc.size();
106     std::string::size_type dstlen = strdst.size();
107 
108     while ((pos = strBig.find(strsrc, pos)) != std::string::npos) {
109         strBig.replace(pos, srclen, strdst);
110         pos += dstlen;
111     }
112 }
113 
RunCase(const uint8_t * data,size_t size)114 bool ADecBufferDemo::RunCase(const uint8_t *data, size_t size)
115 {
116     std::string codecdata(reinterpret_cast<const char *>(data), size);
117     inputdata = codecdata;
118     inputdatasize = size;
119     DEMO_CHECK_AND_RETURN_RET_LOG(CreateDec() == AVCS_ERR_OK, false, "Fatal: CreateDec fail");
120 
121     OH_AVFormat *format = OH_AVFormat_Create();
122     auto res = InitFormat(format);
123     if (res == false) {
124         return false;
125     }
126     DEMO_CHECK_AND_RETURN_RET_LOG(Start() == AVCS_ERR_OK, false, "Fatal: Start fail");
127     auto start = chrono::steady_clock::now();
128     unique_lock<mutex> lock(signal_->startMutex_);
129     signal_->startCond_.wait(lock, [this]() { return (!(isRunning_.load())); });
130     auto end = chrono::steady_clock::now();
131     std::cout << "decode finished, time = " << std::chrono::duration_cast<chrono::milliseconds>(end - start).count()
132               << " ms" << std::endl;
133     DEMO_CHECK_AND_RETURN_RET_LOG(Stop() == AVCS_ERR_OK, false, "Fatal: Stop fail");
134     DEMO_CHECK_AND_RETURN_RET_LOG(Release() == AVCS_ERR_OK, false, "Fatal: Release fail");
135     OH_AVFormat_Destroy(format);
136     sleep(1);
137     return true;
138 }
139 
InitFormat(OH_AVFormat * format)140 bool ADecBufferDemo::InitFormat(OH_AVFormat *format)
141 {
142     // AAC_PROFILE_HE
143     int32_t channelCount = CHANNEL_COUNT;
144     int32_t sampleRate = SAMPLE_RATE;
145     OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AAC_IS_ADTS.data(), DEFAULT_AAC_TYPE);
146     OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, AAC_PROFILE_HE_V2);
147     OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(), channelCount);
148     OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(), sampleRate);
149     DEMO_CHECK_AND_RETURN_RET_LOG(Configure(format) == AVCS_ERR_OK, false, "Fatal: Configure fail");
150     return true;
151 }
152 
InitFile(const std::string & inputFile)153 bool ADecBufferDemo::InitFile(const std::string& inputFile)
154 {
155     if (inputFile.find("mp4") != std::string::npos || inputFile.find("m4a") != std::string::npos ||
156         inputFile.find("vivid") != std::string::npos || inputFile.find("ts") != std::string::npos) {
157         audioType_ = AudioBufferFormatType::TYPE_VIVID;
158     } else if (inputFile.find("aac") != std::string::npos) {
159         audioType_ = AudioBufferFormatType::TYPE_AAC;
160     } else if (inputFile.find("flac") != std::string::npos) {
161         audioType_ = AudioBufferFormatType::TYPE_FLAC;
162     } else if (inputFile.find("mp3") != std::string::npos) {
163         audioType_ = AudioBufferFormatType::TYPE_MP3;
164     } else if (inputFile.find("vorbis") != std::string::npos) {
165         audioType_ = AudioBufferFormatType::TYPE_VORBIS;
166     } else if (inputFile.find("amrnb") != std::string::npos) {
167         audioType_ = AudioBufferFormatType::TYPE_AMRNB;
168     } else if (inputFile.find("amrwb") != std::string::npos) {
169         audioType_ = AudioBufferFormatType::TYPE_AMRWB;
170     } else if (inputFile.find("opus") != std::string::npos) {
171         audioType_ = AudioBufferFormatType::TYPE_OPUS;
172     } else if (inputFile.find("g711mu") != std::string::npos) {
173         audioType_ = AudioBufferFormatType::TYPE_G711MU;
174     } else if (inputFile.find("ape") != std::string::npos) {
175         audioType_ = AudioBufferFormatType::TYPE_APE;
176     } else if (inputFile.find("lbvc") != std::string::npos) {
177         audioType_ = AudioBufferFormatType::TYPE_LBVC;
178     } else {
179         audioType_ = AudioBufferFormatType::TYPE_AAC;
180     }
181     return true;
182 }
183 
ADecBufferDemo()184 ADecBufferDemo::ADecBufferDemo() : audioDec_(nullptr), signal_(nullptr), audioType_(AudioBufferFormatType::TYPE_AAC)
185 {
186     signal_ = new ADecBufferSignal();
187     DEMO_CHECK_AND_RETURN_LOG(signal_ != nullptr, "Fatal: No memory");
188 }
189 
~ADecBufferDemo()190 ADecBufferDemo::~ADecBufferDemo()
191 {
192     if (signal_) {
193         delete signal_;
194         signal_ = nullptr;
195     }
196 }
197 
CreateDec()198 int32_t ADecBufferDemo::CreateDec()
199 {
200     audioDec_ = OH_AudioCodec_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC, false);
201     DEMO_CHECK_AND_RETURN_RET_LOG(audioDec_ != nullptr, AVCS_ERR_UNKNOWN, "Fatal: CreateByName fail");
202     if (audioDec_ == nullptr) {
203         return AVCS_ERR_UNKNOWN;
204     }
205     if (signal_ == nullptr) {
206         signal_ = new ADecBufferSignal();
207         DEMO_CHECK_AND_RETURN_RET_LOG(signal_ != nullptr, AVCS_ERR_UNKNOWN, "Fatal: No memory");
208     }
209     cb_ = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable};
210     int32_t ret = OH_AudioCodec_RegisterCallback(audioDec_, cb_, signal_);
211     DEMO_CHECK_AND_RETURN_RET_LOG(ret == AVCS_ERR_OK, AVCS_ERR_UNKNOWN, "Fatal: SetCallback fail");
212     return AVCS_ERR_OK;
213 }
214 
Configure(OH_AVFormat * format)215 int32_t ADecBufferDemo::Configure(OH_AVFormat *format)
216 {
217     return OH_AudioCodec_Configure(audioDec_, format);
218 }
219 
Start()220 int32_t ADecBufferDemo::Start()
221 {
222     isRunning_.store(true);
223 
224     inputLoop_ = make_unique<thread>(&ADecBufferDemo::InputFunc, this);
225     DEMO_CHECK_AND_RETURN_RET_LOG(inputLoop_ != nullptr, AVCS_ERR_UNKNOWN, "Fatal: No memory");
226 
227     outputLoop_ = make_unique<thread>(&ADecBufferDemo::OutputFunc, this);
228     DEMO_CHECK_AND_RETURN_RET_LOG(outputLoop_ != nullptr, AVCS_ERR_UNKNOWN, "Fatal: No memory");
229 
230     return OH_AudioCodec_Start(audioDec_);
231 }
232 
Stop()233 int32_t ADecBufferDemo::Stop()
234 {
235     isRunning_.store(false);
236     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
237         {
238             unique_lock<mutex> lock(signal_->inMutex_);
239             signal_->inCond_.notify_all();
240         }
241         inputLoop_->join();
242         inputLoop_ = nullptr;
243         while (!signal_->inQueue_.empty()) {
244             signal_->inQueue_.pop();
245         }
246         while (!signal_->inBufferQueue_.empty()) {
247             signal_->inBufferQueue_.pop();
248         }
249     }
250 
251     if (outputLoop_ != nullptr && outputLoop_->joinable()) {
252         {
253             unique_lock<mutex> lock(signal_->outMutex_);
254             signal_->outCond_.notify_all();
255         }
256         outputLoop_->join();
257         outputLoop_ = nullptr;
258         while (!signal_->outQueue_.empty()) {
259             signal_->outQueue_.pop();
260         }
261         while (!signal_->outBufferQueue_.empty()) {
262             signal_->outBufferQueue_.pop();
263         }
264     }
265     std::cout << "start stop!\n";
266     return OH_AudioCodec_Stop(audioDec_);
267 }
268 
Flush()269 int32_t ADecBufferDemo::Flush()
270 {
271     isRunning_.store(false);
272     if (inputLoop_ != nullptr && inputLoop_->joinable()) {
273         {
274             unique_lock<mutex> lock(signal_->inMutex_);
275             signal_->inCond_.notify_all();
276         }
277         inputLoop_->join();
278         inputLoop_ = nullptr;
279         while (!signal_->inQueue_.empty()) {
280             signal_->inQueue_.pop();
281         }
282         while (!signal_->inBufferQueue_.empty()) {
283             signal_->inBufferQueue_.pop();
284         }
285         std::cout << "clear input buffer!\n";
286     }
287 
288     if (outputLoop_ != nullptr && outputLoop_->joinable()) {
289         {
290             unique_lock<mutex> lock(signal_->outMutex_);
291             signal_->outCond_.notify_all();
292         }
293         outputLoop_->join();
294         outputLoop_ = nullptr;
295         while (!signal_->outQueue_.empty()) {
296             signal_->outQueue_.pop();
297         }
298         while (!signal_->outBufferQueue_.empty()) {
299             signal_->outBufferQueue_.pop();
300         }
301         std::cout << "clear output buffer!\n";
302     }
303     return OH_AudioCodec_Flush(audioDec_);
304 }
305 
Reset()306 int32_t ADecBufferDemo::Reset()
307 {
308     return OH_AudioCodec_Reset(audioDec_);
309 }
310 
Release()311 int32_t ADecBufferDemo::Release()
312 {
313     return OH_AudioCodec_Destroy(audioDec_);
314 }
315 
HandleInputEOS(const uint32_t index)316 void ADecBufferDemo::HandleInputEOS(const uint32_t index)
317 {
318     OH_AudioCodec_PushInputBuffer(audioDec_, index);
319     signal_->inBufferQueue_.pop();
320     signal_->inQueue_.pop();
321 }
322 
InputFunc()323 void ADecBufferDemo::InputFunc()
324 {
325     size_t frameBytes = 1024;
326     size_t currentSize = inputdatasize < frameBytes ? inputdatasize : frameBytes;
327     while (isRunning_.load()) {
328         unique_lock<mutex> lock(signal_->inMutex_);
329         signal_->inCond_.wait(lock, [this]() { return (signal_->inQueue_.size() > 0 || !isRunning_.load()); });
330         if (!isRunning_.load()) {
331             break;
332         }
333         uint32_t index = signal_->inQueue_.front();
334         auto buffer = signal_->inBufferQueue_.front();
335         DEMO_CHECK_AND_BREAK_LOG(buffer != nullptr, "Fatal: GetInputBuffer fail");
336         int ret;
337         strncpy_s(reinterpret_cast<char*>(OH_AVBuffer_GetAddr(buffer)), currentSize, inputdata.c_str(), currentSize);
338         buffer->buffer_->memory_->SetSize(currentSize);
339         if (isFirstFrame_) {
340             buffer->buffer_->flag_ = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
341             ret = OH_AudioCodec_PushInputBuffer(audioDec_, index);
342             isFirstFrame_ = false;
343         } else {
344             buffer->buffer_->flag_ = AVCODEC_BUFFER_FLAGS_NONE;
345             ret = OH_AudioCodec_PushInputBuffer(audioDec_, index);
346             isRunning_.store(false);
347             break;
348         }
349         signal_->inQueue_.pop();
350         signal_->inBufferQueue_.pop();
351         frameCount_++;
352         if (ret != AVCS_ERR_OK) {
353             isRunning_.store(false);
354             break;
355         }
356     }
357     signal_->startCond_.notify_all();
358 }
359 
OutputFunc()360 void ADecBufferDemo::OutputFunc()
361 {
362     while (isRunning_.load()) {
363         unique_lock<mutex> lock(signal_->outMutex_);
364         signal_->outCond_.wait(lock, [this]() { return (signal_->outQueue_.size() > 0 || !isRunning_.load()); });
365         if (!isRunning_.load()) {
366             cout << "wait to stop, exit" << endl;
367             break;
368         }
369 
370         uint32_t index = signal_->outQueue_.front();
371         OH_AVBuffer *data = signal_->outBufferQueue_.front();
372         cout << "OutputFunc index:" << index << endl;
373         if (data == nullptr) {
374             cout << "OutputFunc OH_AVBuffer is nullptr" << endl;
375             continue;
376         }
377         if (data != nullptr &&
378             (data->buffer_->flag_ == AVCODEC_BUFFER_FLAGS_EOS || data->buffer_->memory_->GetSize() == 0)) {
379             cout << "decode eos" << endl;
380             isRunning_.store(false);
381             signal_->startCond_.notify_all();
382         }
383         signal_->outBufferQueue_.pop();
384         signal_->outQueue_.pop();
385         if (OH_AudioCodec_FreeOutputBuffer(audioDec_, index) != AV_ERR_OK) {
386             cout << "Fatal: FreeOutputData fail" << endl;
387             break;
388         }
389         if (data->buffer_->flag_ == AVCODEC_BUFFER_FLAGS_EOS) {
390             cout << "decode eos" << endl;
391             isRunning_.store(false);
392             signal_->startCond_.notify_all();
393         }
394     }
395     signal_->startCond_.notify_all();
396 }