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
16 #include "audio_capturer.h"
17 #include "sample_callback.h"
18
19
~AudioCapturer()20 AudioCapturer::~AudioCapturer()
21 {
22 AudioCapturerRelease();
23 }
24
25 // AudioCapturer Callback
AudioCapturerOnReadData(OH_AudioCapturer * capturer,void * userData,void * buffer,int32_t bufferLen)26 static int32_t AudioCapturerOnReadData(OH_AudioCapturer *capturer, void *userData, void *buffer, int32_t bufferLen)
27 {
28 (void)capturer;
29 CodecUserData *codecUserData = static_cast<CodecUserData *>(userData);
30 if (codecUserData != nullptr) {
31 std::unique_lock<std::mutex> lock(codecUserData->inputMutex);
32 codecUserData->WriteCache(buffer, bufferLen);
33 codecUserData->inputCond.notify_all();
34 }
35 return 0;
36 }
37
AudioCapturerInit(SampleInfo & sampleInfo,CodecUserData * audioEncContext)38 void AudioCapturer::AudioCapturerInit(SampleInfo &sampleInfo, CodecUserData *audioEncContext)
39 {
40 AudioCapturerRelease();
41
42 // Create builder
43 OH_AudioStream_Type type = AUDIOSTREAM_TYPE_CAPTURER;
44 OH_AudioStreamBuilder_Create(&builder_, type);
45 // set params and callbacks
46 OH_AudioStreamBuilder_SetSamplingRate(builder_, sampleInfo.audioSampleRate);
47 OH_AudioStreamBuilder_SetChannelCount(builder_, sampleInfo.audioChannelCount);
48 OH_AudioStreamBuilder_SetSampleFormat(builder_, AUDIOSTREAM_SAMPLE_S16LE);
49 OH_AudioStreamBuilder_SetLatencyMode(builder_, AUDIOSTREAM_LATENCY_MODE_NORMAL);
50 OH_AudioStreamBuilder_SetEncodingType(builder_, AUDIOSTREAM_ENCODING_TYPE_RAW);
51 OH_AudioCapturer_Callbacks callbacks;
52 callbacks.OH_AudioCapturer_OnReadData = AudioCapturerOnReadData;
53 OH_AudioStreamBuilder_SetCapturerCallback(builder_, callbacks, audioEncContext);
54 // create OH_AudioCapturer
55 OH_AudioStreamBuilder_GenerateCapturer(builder_, &audioCapturer_);
56 }
57
AudioCapturerStart()58 void AudioCapturer::AudioCapturerStart()
59 {
60 if (audioCapturer_ != nullptr) {
61 OH_AudioCapturer_Start(audioCapturer_);
62 }
63 }
64
AudioCapturerRelease()65 void AudioCapturer::AudioCapturerRelease()
66 {
67 if (audioCapturer_ != nullptr) {
68 OH_AudioCapturer_Stop(audioCapturer_);
69 OH_AudioCapturer_Release(audioCapturer_);
70 audioCapturer_ = nullptr;
71 }
72 if (builder_ != nullptr) {
73 OH_AudioStreamBuilder_Destroy(builder_);
74 builder_ = nullptr;
75 }
76 }