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