• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024-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 #ifndef LOG_TAG
16 #define LOG_TAG "BluetoothCapturerSourceInner"
17 #endif
18 
19 #include "bluetooth_capturer_source.h"
20 
21 #include <cstring>
22 #include <dlfcn.h>
23 #include <string>
24 #include <cinttypes>
25 #include <thread>
26 #include <future>
27 #include <cstdio>
28 #include <unistd.h>
29 
30 #include "securec.h"
31 #include "parameters.h"
32 #ifdef FEATURE_POWER_MANAGER
33 #include "power_mgr_client.h"
34 #include "running_lock.h"
35 #include "audio_running_lock_manager.h"
36 #endif
37 
38 #include "media_monitor_manager.h"
39 #include "audio_hdi_log.h"
40 #include "audio_errors.h"
41 #include "audio_proxy_manager.h"
42 #include "audio_enhance_chain_manager.h"
43 #include "audio_attribute.h"
44 #include "volume_tools.h"
45 #include "audio_dump_pcm.h"
46 
47 using namespace std;
48 using namespace OHOS::HDI::Audio_Bluetooth;
49 
50 namespace OHOS {
51 namespace AudioStandard {
52 namespace {
53 constexpr uint32_t AUDIO_CHANNELCOUNT = 2;
54 constexpr uint32_t AUDIO_SAMPLE_RATE_48K = 48000;
55 constexpr uint32_t DEEP_BUFFER_CAPTURE_PERIOD_SIZE = 4096;
56 constexpr uint32_t INT_32_MAX = 0x7fffffff;
57 constexpr uint32_t AUDIO_BUFF_SIZE = (16 * 1024);
58 constexpr uint32_t PCM_8_BIT = 8;
59 constexpr uint32_t PCM_16_BIT = 16;
60 constexpr uint16_t GET_MAX_AMPLITUDE_FRAMES_THRESHOLD = 10;
61 #ifdef FEATURE_POWER_MANAGER
62 constexpr int32_t RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING = -1;
63 #endif
64 } // namespace
65 
ConvertToHdiFormat(HdiAdapterFormat format)66 static AudioFormat ConvertToHdiFormat(HdiAdapterFormat format)
67 {
68     AudioFormat hdiFormat;
69     switch (format) {
70         case SAMPLE_U8:
71             hdiFormat = AUDIO_FORMAT_TYPE_PCM_8_BIT;
72             break;
73         case SAMPLE_S16:
74             hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
75             break;
76         case SAMPLE_S24:
77             hdiFormat = AUDIO_FORMAT_TYPE_PCM_24_BIT;
78             break;
79         case SAMPLE_S32:
80             hdiFormat = AUDIO_FORMAT_TYPE_PCM_32_BIT;
81             break;
82         default:
83             hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
84             break;
85     }
86     return hdiFormat;
87 }
88 
SwitchAdapterCapture(struct AudioAdapterDescriptor * descs,uint32_t size,const std::string & adapterNameCase,enum AudioPortDirection portFlag,struct AudioPort & capturePort)89 static int32_t SwitchAdapterCapture(struct AudioAdapterDescriptor *descs, uint32_t size,
90     const std::string &adapterNameCase, enum AudioPortDirection portFlag, struct AudioPort &capturePort)
91 {
92     AUDIO_INFO_LOG("SwitchAdapter: adapterNameCase: %{public}s", adapterNameCase.c_str());
93     CHECK_AND_RETURN_RET(descs != nullptr, ERROR);
94 
95     for (uint32_t index = 0; index < size; ++index) {
96         struct AudioAdapterDescriptor *desc = &descs[index];
97         if (desc == nullptr || desc->adapterName == nullptr) {
98             continue;
99         }
100         AUDIO_DEBUG_LOG("size: %{public}d, adapterNameCase %{public}s, adapterName %{public}s",
101             size, adapterNameCase.c_str(), desc->adapterName);
102         if (adapterNameCase.compare(desc->adapterName)) {
103             continue;
104         }
105         for (uint32_t port = 0; port < desc->portNum; port++) {
106             // only find out the port_in in the sound card
107             if (desc->ports[port].dir == portFlag) {
108                 capturePort = desc->ports[port];
109                 return index;
110             }
111         }
112     }
113     AUDIO_ERR_LOG("SwitchAdapterCapture Fail");
114     return ERR_INVALID_INDEX;
115 }
116 
117 class BluetoothCapturerSourceInner : public BluetoothCapturerSource {
118 public:
119     int32_t Init(const IAudioSourceAttr &attr) override;
120     bool IsInited(void) override;
121     void DeInit(void) override;
122 
123     int32_t Start(void) override;
124     int32_t Stop(void) override;
125     int32_t Flush(void) override;
126     int32_t Reset(void) override;
127     int32_t Pause(void) override;
128     int32_t Resume(void) override;
129     int32_t CaptureFrame(char *frame, uint64_t requestBytes, uint64_t &replyBytes) override;
130     int32_t CaptureFrameWithEc(
131         FrameDesc *fdesc, uint64_t &replyBytes,
132         FrameDesc *fdescEc, uint64_t &replyBytesEc) override;
133 
134     int32_t SetVolume(float left, float right) override;
135     int32_t GetVolume(float &left, float &right) override;
136     int32_t SetMute(bool isMute) override;
137     int32_t GetMute(bool &isMute) override;
138 
139     int32_t SetAudioScene(AudioScene audioScene, DeviceType activeDevice,
140         const std::string &deviceName) override;
141     int32_t SetInputRoute(DeviceType inputDevice, const std::string &deviceName) override;
142     uint64_t GetTransactionId() override;
143     std::string GetAudioParameter(const AudioParamKey key, const std::string &condition) override;
144     int32_t GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec) override;
145 
146     void RegisterWakeupCloseCallback(IAudioSourceCallback *callback) override;
147     void RegisterAudioCapturerSourceCallback(std::unique_ptr<ICapturerStateCallback> callback) override;
148     void RegisterParameterCallback(IAudioSourceCallback *callback) override;
149     float GetMaxAmplitude() override;
150 
151     int32_t UpdateAppsUid(const int32_t appsUid[PA_MAX_OUTPUTS_PER_SOURCE], const size_t size) final;
152     int32_t UpdateAppsUid(const std::vector<int32_t> &appsUid) final;
153     int32_t GetCaptureId(uint32_t &captureId) const override;
154 
155     explicit BluetoothCapturerSourceInner();
156     ~BluetoothCapturerSourceInner() override;
157 
158 private:
159     static constexpr int32_t HALF_FACTOR = 2;
160     static constexpr int32_t MAX_AUDIO_ADAPTER_NUM = 8;
161     static constexpr uint32_t STEREO_CHANNEL_COUNT = 2;
162 
163     int32_t CreateCapture(struct AudioPort &capturePort);
164     int32_t SetAudioRouteInfoForEnhanceChain(const DeviceType &inputDevice, const std::string &deviceName = "");
165     int32_t InitAudioManager();
166     void InitAttrsCapture(struct AudioSampleAttributes &attrs);
167 
168     void InitLatencyMeasurement();
169     void DeinitLatencyMeasurement();
170     void CheckLatencySignal(uint8_t *frame, size_t replyBytes);
171 
172     void CheckUpdateState(char *frame, uint64_t replyBytes);
173     int32_t DoStop();
174 
175     IAudioSourceAttr attr_;
176     bool captureInited_;
177     bool started_;
178     bool paused_;
179     float leftVolume_ = 0.0;
180     float rightVolume_ = 0.0;
181 
182     int32_t logMode_ = 0;
183     mutable int64_t volumeDataCount_ = 0;
184 
185     // for get amplitude
186     float maxAmplitude_ = 0;
187     int64_t lastGetMaxAmplitudeTime_ = 0;
188     int64_t last10FrameStartTime_ = 0;
189     bool startUpdate_ = false;
190     int capFrameNum_ = 0;
191 
192     struct HDI::Audio_Bluetooth::AudioProxyManager *audioManager_;
193     struct HDI::Audio_Bluetooth::AudioAdapter *audioAdapter_;
194     struct HDI::Audio_Bluetooth::AudioCapture *audioCapture_;
195     struct HDI::Audio_Bluetooth::AudioPort audioPort_ = {};
196 
197     void *handle_;
198     const std::string halName_;
199 #ifdef FEATURE_POWER_MANAGER
200     std::shared_ptr<AudioRunningLockManager<PowerMgr::RunningLock>> runningLockManager_;
201 #endif
202 
203     DeviceType currentActiveDevice_ = DEVICE_TYPE_BLUETOOTH_A2DP_IN;
204     std::unique_ptr<ICapturerStateCallback> audioCapturerSourceCallback_ = nullptr;
205     FILE *dumpFile_ = nullptr;
206     std::string dumpFileName_ = "";
207     std::string logUtilsTag_ = "";
208     bool muteState_ = false;
209 
210     bool latencyMeasEnabled_ = false;
211     bool signalDetected_ = false;
212     std::shared_ptr<SignalDetectAgent> signalDetectAgent_ = nullptr;
213     std::mutex signalDetectAgentMutex_;
214     std::mutex managerAndAdapterMutex_;
215     std::mutex statusMutex_;
216 };
217 
BluetoothCapturerSourceInner()218 BluetoothCapturerSourceInner::BluetoothCapturerSourceInner()
219     : captureInited_(false), started_(false), paused_(false), audioManager_(nullptr), audioAdapter_(nullptr),
220       audioCapture_(nullptr), handle_(nullptr), halName_ ("bt_hdap") {}
221 
~BluetoothCapturerSourceInner()222 BluetoothCapturerSourceInner::~BluetoothCapturerSourceInner()
223 {
224     BluetoothCapturerSourceInner::DeInit();
225     AUDIO_INFO_LOG("[%{public}s] volume data counts: %{public}" PRIu64, logUtilsTag_.c_str(), volumeDataCount_);
226 }
227 
GetInstance()228 BluetoothCapturerSource *BluetoothCapturerSource::GetInstance()
229 {
230     Trace trace("BluetoothCapturerSourceInner:GetInstance");
231     static BluetoothCapturerSourceInner audioCapturer;
232     return &audioCapturer;
233 }
234 
IsInited(void)235 bool BluetoothCapturerSourceInner::IsInited(void)
236 {
237     return captureInited_;
238 }
239 
DeInit(void)240 void BluetoothCapturerSourceInner::DeInit(void)
241 {
242     std::lock_guard<std::mutex> statusLock(statusMutex_);
243     Trace trace("BluetoothCapturerSourceInner::Deinit");
244     started_ = false;
245 
246     if (audioAdapter_ != nullptr) {
247         audioAdapter_->DestroyCapture(audioAdapter_, audioCapture_);
248     }
249     captureInited_ = false;
250     audioCapture_ = nullptr;
251     audioAdapter_ = nullptr;
252 
253     DumpFileUtil::CloseDumpFile(&dumpFile_);
254 }
255 
InitAttrsCapture(struct AudioSampleAttributes & attrs)256 void BluetoothCapturerSourceInner::InitAttrsCapture(struct AudioSampleAttributes &attrs)
257 {
258     /* Initialization of audio parameters for hdap record */
259     attrs.format = AUDIO_FORMAT_TYPE_PCM_16_BIT;
260     attrs.channelCount = AUDIO_CHANNELCOUNT;
261     attrs.sampleRate = AUDIO_SAMPLE_RATE_48K;
262     attrs.interleaved = true;
263 
264     attrs.type = AUDIO_IN_MEDIA;
265     attrs.period = DEEP_BUFFER_CAPTURE_PERIOD_SIZE;
266     attrs.frameSize = PCM_16_BIT * attrs.channelCount / PCM_8_BIT;
267     attrs.isBigEndian = false;
268     attrs.isSignedData = true;
269     attrs.startThreshold = DEEP_BUFFER_CAPTURE_PERIOD_SIZE / (attrs.frameSize);
270     attrs.stopThreshold = INT_32_MAX;
271     /* 16 * 1024 */
272     attrs.silenceThreshold = AUDIO_BUFF_SIZE;
273 }
274 
InitAudioManager()275 int32_t BluetoothCapturerSourceInner::InitAudioManager()
276 {
277 #if (defined(__aarch64__) || defined(__x86_64__))
278     char resolvedPath[100] = "/vendor/lib64/chipsetsdk/libaudio_bluetooth_hdi_proxy_server.z.so";
279 #else
280     char resolvedPath[100] = "/vendor/lib/chipsetsdk/libaudio_bluetooth_hdi_proxy_server.z.so";
281 #endif
282     struct AudioProxyManager *(*getAudioManager)() = nullptr;
283 
284     handle_ = dlopen(resolvedPath, 1);
285     CHECK_AND_RETURN_RET_LOG(handle_ != nullptr, ERR_INVALID_HANDLE, "Open so Fail");
286     AUDIO_DEBUG_LOG("dlopen successfully");
287 
288     getAudioManager = (struct AudioProxyManager *(*)())(dlsym(handle_, "GetAudioProxyManagerFuncs"));
289     if (getAudioManager == nullptr) {
290 #ifndef TEST_COVERAGE
291         dlclose(handle_);
292 #endif
293         handle_ = nullptr;
294         AUDIO_ERR_LOG("getaudiomanager fail!");
295         return ERR_INVALID_HANDLE;
296     }
297     AUDIO_DEBUG_LOG("getaudiomanager done");
298 
299     audioManager_ = getAudioManager();
300     if (audioManager_ == nullptr) {
301 #ifndef TEST_COVERAGE
302         dlclose(handle_);
303 #endif
304         handle_ = nullptr;
305         AUDIO_ERR_LOG("getAudioManager() fail!");
306         return ERR_INVALID_HANDLE;
307     }
308     AUDIO_DEBUG_LOG("audio manager created");
309 
310     return 0;
311 }
312 
CreateCapture(struct AudioPort & capturePort)313 int32_t BluetoothCapturerSourceInner::CreateCapture(struct AudioPort &capturePort)
314 {
315     Trace trace("BluetoothCapturerSourceInner::CreateCapture");
316 
317     struct AudioSampleAttributes param;
318     // User needs to set
319     InitAttrsCapture(param);
320     param.sampleRate = attr_.sampleRate;
321     param.format = ConvertToHdiFormat(attr_.format);
322     param.isBigEndian = attr_.isBigEndian;
323     param.channelCount = attr_.channel;
324     param.silenceThreshold = attr_.bufferSize;
325     param.frameSize = param.format * param.channelCount;
326     param.startThreshold = DEEP_BUFFER_CAPTURE_PERIOD_SIZE / (param.frameSize);
327 
328     struct AudioDeviceDescriptor deviceDesc;
329     deviceDesc.portId = capturePort.portId;
330     deviceDesc.pins = PIN_IN_MIC;
331     deviceDesc.desc = nullptr;
332 
333     AUDIO_INFO_LOG("create capture sourceName:%{public}s, " \
334         "rate:%{public}u channel:%{public}u format:%{public}u, devicePin:%{public}u",
335         halName_.c_str(), param.sampleRate, param.channelCount, param.format, deviceDesc.pins);
336     int32_t ret = audioAdapter_->CreateCapture(audioAdapter_, &deviceDesc, &param, &audioCapture_);
337     CHECK_AND_RETURN_RET_LOG(audioCapture_ != nullptr && ret >=0, ERR_NOT_STARTED, "create capture failed");
338 
339     return 0;
340 }
341 
Init(const IAudioSourceAttr & attr)342 int32_t BluetoothCapturerSourceInner::Init(const IAudioSourceAttr &attr)
343 {
344     if (captureInited_) {
345         AUDIO_INFO_LOG("Adapter already inited");
346         return SUCCESS;
347     }
348 
349     std::lock_guard<std::mutex> statusLock(statusMutex_);
350     attr_ = attr;
351     logMode_ = system::GetIntParameter("persist.multimedia.audiolog.switch", 0);
352     logUtilsTag_ = "A2dpSource";
353 
354     std::lock_guard lock(managerAndAdapterMutex_);
355     CHECK_AND_RETURN_RET_LOG(InitAudioManager() == 0, ERR_NOT_STARTED, "Init audio manager Fail");
356 
357     int32_t size = 0;
358     struct AudioAdapterDescriptor *descs = nullptr;
359     int32_t ret = audioManager_->GetAllAdapters(audioManager_, &descs, &size);
360 
361     CHECK_AND_RETURN_RET_LOG(size <= MAX_AUDIO_ADAPTER_NUM && size != 0 && descs != nullptr && ret == 0,
362         ERR_NOT_STARTED, "Get adapters Fail");
363 
364     string adapterNameCase = "bt_hdap";
365     enum AudioPortDirection port = PORT_IN;
366 
367     int32_t index = SwitchAdapterCapture(descs, size, adapterNameCase, port, audioPort_);
368     CHECK_AND_RETURN_RET_LOG(index >= 0, ERR_NOT_STARTED, "Switch Adapter Capturer Fail");
369 
370     struct AudioAdapterDescriptor *desc = &descs[index];
371     int32_t loadAdapter = audioManager_->LoadAdapter(audioManager_, desc, &audioAdapter_);
372     CHECK_AND_RETURN_RET_LOG(loadAdapter == 0, ERR_NOT_STARTED, "Load Adapter Fail");
373     CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, ERR_NOT_STARTED, "Load audio device failed");
374 
375     // Initialize port information, can fill through mode and other parameters
376     ret = audioAdapter_->InitAllPorts(audioAdapter_);
377     CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_DEVICE_INIT, "initAllPorts failed");
378 
379     ret = CreateCapture(audioPort_);
380     CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_NOT_STARTED, "create capture failed");
381 
382     ret = SetAudioRouteInfoForEnhanceChain(currentActiveDevice_, "");
383     if (ret != SUCCESS) {
384         AUDIO_WARNING_LOG("set device %{public}d failed", currentActiveDevice_);
385     }
386 
387     captureInited_ = true;
388     SetMute(muteState_);
389 
390     return SUCCESS;
391 }
392 
CaptureFrame(char * frame,uint64_t requestBytes,uint64_t & replyBytes)393 int32_t BluetoothCapturerSourceInner::CaptureFrame(char *frame, uint64_t requestBytes, uint64_t &replyBytes)
394 {
395     CHECK_AND_RETURN_RET_LOG(audioCapture_ != nullptr, ERR_INVALID_HANDLE, "Audio capture handle is nullpre");
396 
397     Trace trace("BluetoothCapturerSourceInner::CaptureFrame");
398 
399     int64_t stamp = ClockTime::GetCurNano();
400     uint64_t frameLen = static_cast<uint64_t>(requestBytes);
401 
402     int32_t ret = audioCapture_->CaptureFrame(audioCapture_, reinterpret_cast<int8_t*>(frame), frameLen, &replyBytes);
403 
404     CHECK_AND_RETURN_RET_LOG(ret >= 0, ERR_NOT_STARTED, "Capture Frame Fail");
405     CheckLatencySignal(reinterpret_cast<uint8_t*>(frame), replyBytes);
406 
407     BufferDesc tmpBuffer = {reinterpret_cast<uint8_t*>(frame), replyBytes, replyBytes};
408     AudioStreamInfo streamInfo(static_cast<AudioSamplingRate>(attr_.sampleRate), AudioEncodingType::ENCODING_PCM,
409         static_cast<AudioSampleFormat>(attr_.format), static_cast<AudioChannel>(attr_.channel));
410     VolumeTools::DfxOperation(tmpBuffer, streamInfo, logUtilsTag_, volumeDataCount_);
411 
412     if (AudioDump::GetInstance().GetVersionType() == DumpFileUtil::BETA_VERSION) {
413         DumpFileUtil::WriteDumpFile(dumpFile_, frame, replyBytes);
414         AudioCacheMgr::GetInstance().CacheData(dumpFileName_, static_cast<void*>(frame), replyBytes);
415     }
416     CheckUpdateState(frame, requestBytes);
417 
418     stamp = (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND;
419     if (logMode_) {
420         AUDIO_DEBUG_LOG("RenderFrame len[%{public}" PRIu64 "] cost [%{public}" PRIu64 "]ms", requestBytes, stamp);
421     }
422     return SUCCESS;
423 }
424 
CaptureFrameWithEc(FrameDesc * fdesc,uint64_t & replyBytes,FrameDesc * fdescEc,uint64_t & replyBytesEc)425 int32_t BluetoothCapturerSourceInner::CaptureFrameWithEc(
426     FrameDesc *fdesc, uint64_t &replyBytes,
427     FrameDesc *fdescEc, uint64_t &replyBytesEc)
428 {
429     AUDIO_ERR_LOG("Bluetooth captureFrameWithEc is not support!");
430     return ERR_NOT_SUPPORTED;
431 }
432 
CheckUpdateState(char * frame,uint64_t replyBytes)433 void BluetoothCapturerSourceInner::CheckUpdateState(char *frame, uint64_t replyBytes)
434 {
435     if (startUpdate_) {
436         if (capFrameNum_ == 0) {
437             last10FrameStartTime_ = ClockTime::GetCurNano();
438         }
439         capFrameNum_++;
440         maxAmplitude_ = UpdateMaxAmplitude(static_cast<ConvertHdiFormat>(attr_.format), frame, replyBytes);
441         if (capFrameNum_ == GET_MAX_AMPLITUDE_FRAMES_THRESHOLD) {
442             capFrameNum_ = 0;
443             if (last10FrameStartTime_ > lastGetMaxAmplitudeTime_) {
444                 startUpdate_ = false;
445                 maxAmplitude_ = 0;
446             }
447         }
448     }
449 }
450 
GetMaxAmplitude()451 float BluetoothCapturerSourceInner::GetMaxAmplitude()
452 {
453     lastGetMaxAmplitudeTime_ = ClockTime::GetCurNano();
454     startUpdate_ = true;
455     return maxAmplitude_;
456 }
457 
Start(void)458 int32_t BluetoothCapturerSourceInner::Start(void)
459 {
460     std::lock_guard<std::mutex> statusLock(statusMutex_);
461 
462     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
463     Trace trace("BluetoothCapturerSourceInner::Start");
464 
465     InitLatencyMeasurement();
466 #ifdef FEATURE_POWER_MANAGER
467     std::shared_ptr<PowerMgr::RunningLock> keepRunningLock;
468     if (runningLockManager_ == nullptr) {
469         keepRunningLock = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock("AudioBluetoothCapturer",
470             PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO);
471         if (keepRunningLock) {
472             runningLockManager_ = std::make_shared<AudioRunningLockManager<PowerMgr::RunningLock>> (keepRunningLock);
473         }
474     }
475 
476     if (runningLockManager_ != nullptr) {
477         AUDIO_INFO_LOG("keepRunningLock lock result: %{public}d",
478             runningLockManager_->Lock(RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING));
479     } else {
480         AUDIO_WARNING_LOG("keepRunningLock is null, capture can not work well");
481     }
482 #endif
483     dumpFileName_ = halName_ + "_" + std::to_string(attr_.sourceType) + "_" + GetTime()
484         + "_bluetooth_source_" + std::to_string(attr_.sampleRate) + "_" + std::to_string(attr_.channel)
485         + "_" + std::to_string(attr_.format) + ".pcm";
486     DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileName_, &dumpFile_);
487 
488     if (!started_) {
489         if (audioCapturerSourceCallback_ != nullptr) {
490             audioCapturerSourceCallback_->OnCapturerState(true);
491         }
492 
493         int32_t ret = audioCapture_->control.Start(reinterpret_cast<AudioHandle>(audioCapture_));
494         if (ret < 0) {
495 #ifdef FEATURE_POWER_MANAGER
496             if (runningLockManager_ != nullptr) {
497                 AUDIO_WARNING_LOG("capturer start failed, keepRunningLock unLock");
498                 runningLockManager_->UnLock();
499             } else {
500                 AUDIO_WARNING_LOG("capturer start failed, try unlock but KeepRunningLock is null!");
501             }
502 #endif
503             return ERR_NOT_STARTED;
504         }
505         started_ = true;
506     }
507 
508     return SUCCESS;
509 }
510 
SetVolume(float left,float right)511 int32_t BluetoothCapturerSourceInner::SetVolume(float left, float right)
512 {
513     float volume;
514     CHECK_AND_RETURN_RET_LOG(audioCapture_ != nullptr, ERR_INVALID_HANDLE,
515         "SetVolume failed audioCapture_ null");
516 
517     rightVolume_ = right;
518     leftVolume_ = left;
519     if ((leftVolume_ == 0) && (rightVolume_ != 0)) {
520         volume = rightVolume_;
521     } else if ((leftVolume_ != 0) && (rightVolume_ == 0)) {
522         volume = leftVolume_;
523     } else {
524         volume = (leftVolume_ + rightVolume_) / HALF_FACTOR;
525     }
526 
527     audioCapture_->volume.SetVolume(reinterpret_cast<AudioHandle>(audioCapture_), volume);
528 
529     return SUCCESS;
530 }
531 
GetVolume(float & left,float & right)532 int32_t BluetoothCapturerSourceInner::GetVolume(float &left, float &right)
533 {
534     CHECK_AND_RETURN_RET_LOG(audioCapture_ != nullptr, ERR_INVALID_HANDLE,
535         "GetVolume failed audioCapture_ null");
536 
537     float val = 0.0;
538     audioCapture_->volume.GetVolume(reinterpret_cast<AudioHandle>(audioCapture_), &val);
539     left = val;
540     right = val;
541 
542     return SUCCESS;
543 }
544 
SetMute(bool isMute)545 int32_t BluetoothCapturerSourceInner::SetMute(bool isMute)
546 {
547     muteState_ = isMute;
548 
549     if (IsInited() && audioCapture_) {
550         int32_t ret = audioCapture_->volume.SetMute(reinterpret_cast<AudioHandle>(audioCapture_), isMute);
551         if (ret != 0) {
552             AUDIO_WARNING_LOG("SetMute for hdi capturer failed");
553         } else {
554             AUDIO_INFO_LOG("SetMute for hdi capture success");
555         }
556     }
557 
558     AUDIO_INFO_LOG("end isMute=%{public}d", isMute);
559     return SUCCESS;
560 }
561 
GetMute(bool & isMute)562 int32_t BluetoothCapturerSourceInner::GetMute(bool &isMute)
563 {
564     CHECK_AND_RETURN_RET_LOG(audioCapture_ != nullptr, ERR_INVALID_HANDLE,
565         "GetMute failed audioCapture_ handle is null!");
566 
567     bool isHdiMute = false;
568     int32_t ret = audioCapture_->volume.GetMute(reinterpret_cast<AudioHandle>(audioCapture_), &isHdiMute);
569     if (ret != 0) {
570         AUDIO_WARNING_LOG("GetMute failed from hdi");
571     }
572 
573     isMute = muteState_;
574     return SUCCESS;
575 }
576 
SetInputRoute(DeviceType inputDevice,const std::string & deviceName)577 int32_t BluetoothCapturerSourceInner::SetInputRoute(DeviceType inputDevice, const std::string &deviceName)
578 {
579     AUDIO_WARNING_LOG("SetInputRoutes not supported.");
580     return ERR_NOT_SUPPORTED;
581 }
582 
SetAudioRouteInfoForEnhanceChain(const DeviceType & inputDevice,const std::string & deviceName)583 int32_t BluetoothCapturerSourceInner::SetAudioRouteInfoForEnhanceChain(const DeviceType &inputDevice,
584     const std::string &deviceName)
585 {
586     AudioEnhanceChainManager *audioEnhanceChainManager = AudioEnhanceChainManager::GetInstance();
587     CHECK_AND_RETURN_RET_LOG(audioEnhanceChainManager != nullptr, ERROR, "audioEnhanceChainManager is nullptr");
588     uint32_t captureId = 0;
589     int32_t ret = GetCaptureId(captureId);
590     if (ret != SUCCESS) {
591         AUDIO_WARNING_LOG("GetCaptureId failed");
592     }
593 
594     audioEnhanceChainManager->SetInputDevice(captureId, inputDevice, deviceName);
595     return SUCCESS;
596 }
597 
SetAudioScene(AudioScene audioScene,DeviceType activeDevice,const std::string & deviceName)598 int32_t BluetoothCapturerSourceInner::SetAudioScene(AudioScene audioScene, DeviceType activeDevice,
599     const std::string &deviceName)
600 {
601     AUDIO_WARNING_LOG("SetAudioScene not supported.");
602     return ERR_NOT_SUPPORTED;
603 }
604 
GetTransactionId()605 uint64_t BluetoothCapturerSourceInner::GetTransactionId()
606 {
607     return reinterpret_cast<uint64_t>(audioCapture_);
608 }
609 
GetPresentationPosition(uint64_t & frames,int64_t & timeSec,int64_t & timeNanoSec)610 int32_t BluetoothCapturerSourceInner::GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec)
611 {
612     AUDIO_WARNING_LOG("GetPresentationPosition not supported.");
613     return ERR_NOT_SUPPORTED;
614 }
615 
DoStop()616 int32_t BluetoothCapturerSourceInner::DoStop()
617 {
618     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
619 
620     Trace trace("BluetoothCapturerSourceInner::DoStop");
621 
622     DeinitLatencyMeasurement();
623 
624 #ifdef FEATURE_POWER_MANAGER
625     if (runningLockManager_ != nullptr) {
626         AUDIO_INFO_LOG("keepRunningLock unLock");
627         runningLockManager_->UnLock();
628     } else {
629         AUDIO_WARNING_LOG("KeepRunningLock is null, stop can not work well");
630     }
631 #endif
632 
633     if (started_ && audioCapture_ != nullptr) {
634         int32_t ret = audioCapture_->control.Stop(reinterpret_cast<AudioHandle>(audioCapture_));
635         CHECK_AND_RETURN_RET_LOG(ret >= 0, ERR_OPERATION_FAILED, "Stop capture Failed");
636     }
637     started_ = false;
638     paused_ = false;
639 
640     if (audioCapturerSourceCallback_ != nullptr) {
641         audioCapturerSourceCallback_->OnCapturerState(false);
642     }
643 
644     return SUCCESS;
645 }
646 
Stop(void)647 int32_t BluetoothCapturerSourceInner::Stop(void)
648 {
649     Trace trace("BluetoothCapturerSourceInner::Stop");
650     std::promise<void> promiseEnsueThreadLock;
651     auto futureWaitThreadLock = promiseEnsueThreadLock.get_future();
652     std::thread threadAsyncStop([&promiseEnsueThreadLock, this] {
653         std::lock_guard<std::mutex> statusLock(statusMutex_);
654         promiseEnsueThreadLock.set_value();
655         DoStop();
656     });
657     futureWaitThreadLock.get();
658     threadAsyncStop.detach();
659 
660     return SUCCESS;
661 }
662 
Pause(void)663 int32_t BluetoothCapturerSourceInner::Pause(void)
664 {
665     std::lock_guard<std::mutex> statusLock(statusMutex_);
666     CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED, "Pause invalid State");
667     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
668 
669     Trace trace("BluetoothCapturerSourceInner::Pause");
670     if (started_ && audioCapture_ != nullptr) {
671         int32_t ret = audioCapture_->control.Pause(reinterpret_cast<AudioHandle>(audioCapture_));
672         CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_OPERATION_FAILED, "pause capture Failed");
673     }
674     paused_ = true;
675 
676     return SUCCESS;
677 }
678 
Resume(void)679 int32_t BluetoothCapturerSourceInner::Resume(void)
680 {
681     std::lock_guard<std::mutex> statusLock(statusMutex_);
682     CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED, "Resume invalid State");
683     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
684     Trace trace("BluetoothCapturerSourceInner::Resume");
685     if (started_ && audioCapture_ != nullptr) {
686         int32_t ret = audioCapture_->control.Resume(reinterpret_cast<AudioHandle>(audioCapture_));
687         CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_OPERATION_FAILED, "resume capture Failed");
688     }
689     paused_ = false;
690 
691     return SUCCESS;
692 }
693 
Reset(void)694 int32_t BluetoothCapturerSourceInner::Reset(void)
695 {
696     std::lock_guard<std::mutex> statusLock(statusMutex_);
697     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
698     Trace trace("BluetoothCapturerSourceInner::Reset");
699     if (started_ && audioCapture_ != nullptr) {
700         audioCapture_->control.Flush(reinterpret_cast<AudioHandle>(audioCapture_));
701     }
702     return SUCCESS;
703 }
704 
Flush(void)705 int32_t BluetoothCapturerSourceInner::Flush(void)
706 {
707     std::lock_guard<std::mutex> statusLock(statusMutex_);
708     AUDIO_INFO_LOG("sourceName %{public}s", halName_.c_str());
709     Trace trace("BluetoothCapturerSourceInner::Flush");
710     if (started_ && audioCapture_ != nullptr) {
711         audioCapture_->control.Flush(reinterpret_cast<AudioHandle>(audioCapture_));
712     }
713     return SUCCESS;
714 }
715 
RegisterWakeupCloseCallback(IAudioSourceCallback * callback)716 void BluetoothCapturerSourceInner::RegisterWakeupCloseCallback(IAudioSourceCallback *callback)
717 {
718     AUDIO_WARNING_LOG("RegisterWakeupCloseCallback not supported");
719 }
720 
RegisterAudioCapturerSourceCallback(std::unique_ptr<ICapturerStateCallback> callback)721 void BluetoothCapturerSourceInner::RegisterAudioCapturerSourceCallback(std::unique_ptr<ICapturerStateCallback> callback)
722 {
723     AUDIO_INFO_LOG("Register AudioCaptureSource Callback");
724     audioCapturerSourceCallback_ = std::move(callback);
725 }
726 
RegisterParameterCallback(IAudioSourceCallback * callback)727 void BluetoothCapturerSourceInner::RegisterParameterCallback(IAudioSourceCallback *callback)
728 {
729     AUDIO_WARNING_LOG("RegisterParameterCallback not supported");
730 }
731 
GetAudioParameter(const AudioParamKey key,const std::string & condition)732 std::string BluetoothCapturerSourceInner::GetAudioParameter(const AudioParamKey key, const std::string &condition)
733 {
734     AUDIO_WARNING_LOG("GetAudioParameter not supported");
735     return "";
736 }
737 
InitLatencyMeasurement()738 void BluetoothCapturerSourceInner::InitLatencyMeasurement()
739 {
740     std::lock_guard<std::mutex> lock(signalDetectAgentMutex_);
741 
742     if (!AudioLatencyMeasurement::CheckIfEnabled()) {
743         return;
744     }
745 
746     signalDetectAgent_ = std::make_shared<SignalDetectAgent>();
747     CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
748     signalDetectAgent_->sampleFormat_ = attr_.format;
749     signalDetectAgent_->formatByteSize_ = GetFormatByteSize(attr_.format);
750     latencyMeasEnabled_ = true;
751 }
752 
DeinitLatencyMeasurement()753 void BluetoothCapturerSourceInner::DeinitLatencyMeasurement()
754 {
755     std::lock_guard<std::mutex> lock(signalDetectAgentMutex_);
756 
757     signalDetected_ = false;
758     signalDetectAgent_ = nullptr;
759 }
760 
CheckLatencySignal(uint8_t * frame,size_t replyBytes)761 void BluetoothCapturerSourceInner::CheckLatencySignal(uint8_t *frame, size_t replyBytes)
762 {
763     std::lock_guard<std::mutex> lock(signalDetectAgentMutex_);
764     if (!latencyMeasEnabled_) {
765         return;
766     }
767 
768     CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
769     signalDetected_ = signalDetectAgent_->CheckAudioData(frame, replyBytes);
770     if (signalDetected_) {
771         char value[GET_EXTRA_PARAM_LEN];
772         AudioParamKey key = NONE;
773         AudioExtParamKey hdiKey = AudioExtParamKey(key);
774         std::string condition = "debug_audio_latency_measurement";
775         int32_t ret = audioAdapter_->GetExtraParams(audioAdapter_, hdiKey, condition.c_str(), value,
776             DumpFileUtil::PARAM_VALUE_LENTH);
777         AUDIO_INFO_LOG("GetExtraParam ret:%{public}d", ret);
778         LatencyMonitor::GetInstance().UpdateDspTime(value);
779         LatencyMonitor::GetInstance().UpdateSinkOrSourceTime(false,
780             signalDetectAgent_->lastPeakBufferTime_);
781         AUDIO_INFO_LOG("LatencyMeas primarySource signal detected");
782         signalDetected_ = false;
783     }
784 }
785 
UpdateAppsUid(const int32_t appsUid[PA_MAX_OUTPUTS_PER_SOURCE],const size_t size)786 int32_t BluetoothCapturerSourceInner::UpdateAppsUid(const int32_t appsUid[PA_MAX_OUTPUTS_PER_SOURCE],
787     const size_t size)
788 {
789 #ifdef FEATURE_POWER_MANAGER
790     if (!runningLockManager_) {
791         return ERROR;
792     }
793 
794     runningLockManager_->UpdateAppsUid(appsUid, appsUid + size);
795     runningLockManager_->UpdateAppsUidToPowerMgr();
796 #endif
797 
798     return SUCCESS;
799 }
800 
UpdateAppsUid(const std::vector<int32_t> & appsUid)801 int32_t BluetoothCapturerSourceInner::UpdateAppsUid(const std::vector<int32_t> &appsUid)
802 {
803 #ifdef FEATURE_POWER_MANAGER
804     if (!runningLockManager_) {
805         return ERROR;
806     }
807 
808     runningLockManager_->UpdateAppsUid(appsUid.cbegin(), appsUid.cend());
809     runningLockManager_->UpdateAppsUidToPowerMgr();
810 #endif
811 
812     return SUCCESS;
813 }
814 
GetCaptureId(uint32_t & captureId) const815 int32_t BluetoothCapturerSourceInner::GetCaptureId(uint32_t &captureId) const
816 {
817     captureId = GenerateUniqueID(AUDIO_HDI_CAPTURE_ID_BASE, HDI_CAPTURE_OFFSET_BLUETOOTH);
818     return SUCCESS;
819 }
820 
821 } // namespace AudioStandard
822 } // namespace OHOS
823