• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "BluetoothRendererSinkInner"
17 #endif
18 
19 #include "bluetooth_renderer_sink.h"
20 
21 #include <cstdio>
22 #include <cstring>
23 #include <string>
24 #include <list>
25 #include <cinttypes>
26 
27 #include <dlfcn.h>
28 #include <unistd.h>
29 
30 #include "audio_proxy_manager.h"
31 #include "audio_attribute.h"
32 #ifdef FEATURE_POWER_MANAGER
33 #include "running_lock.h"
34 #include "power_mgr_client.h"
35 #include "audio_running_lock_manager.h"
36 #endif
37 
38 #include "audio_errors.h"
39 #include "audio_hdi_log.h"
40 #include "volume_tools.h"
41 #include "parameters.h"
42 #include "media_monitor_manager.h"
43 #include "audio_utils.h"
44 #include "audio_dump_pcm.h"
45 #include "audio_performance_monitor.h"
46 
47 using namespace std;
48 using namespace OHOS::HDI::Audio_Bluetooth;
49 
50 namespace OHOS {
51 namespace AudioStandard {
52 namespace {
53 const int32_t HALF_FACTOR = 2;
54 const int32_t MAX_AUDIO_ADAPTER_NUM = 8;
55 const int32_t MAX_GET_POSITOIN_TRY_COUNT = 50;
56 const int32_t MAX_GET_POSITION_HANDLE_TIME = 10000000; // 1000000us
57 const int32_t MAX_GET_POSITION_WAIT_TIME = 2000000; // 2000000us
58 const int32_t RENDER_FRAME_NUM = -4;
59 const float DEFAULT_VOLUME_LEVEL = 1.0f;
60 const uint32_t AUDIO_CHANNELCOUNT = 2;
61 const uint32_t AUDIO_SAMPLE_RATE_48K = 48000;
62 const uint32_t DEEP_BUFFER_RENDER_PERIOD_SIZE = 4096;
63 const uint32_t RENDER_FRAME_INTERVAL_IN_MICROSECONDS = 10000;
64 const uint32_t SECOND_TO_NANOSECOND = 1000000000;
65 const uint32_t SECOND_TO_MILLISECOND = 1000;
66 const uint32_t  WAIT_TIME_FOR_RETRY_IN_MICROSECOND = 50000;
67 const uint32_t INT_32_MAX = 0x7fffffff;
68 const uint32_t PCM_8_BIT = 8;
69 const uint32_t PCM_16_BIT = 16;
70 const uint32_t PCM_24_BIT = 24;
71 const uint32_t PCM_32_BIT = 32;
72 const uint32_t STEREO_CHANNEL_COUNT = 2;
73 constexpr uint32_t BIT_TO_BYTES = 8;
74 constexpr int64_t STAMP_THRESHOLD_MS = 20;
75 const char *BLUETOOTH_CANCEL_SUSPEND = "A2dpSuspended=0;";
76 #ifdef FEATURE_POWER_MANAGER
77 constexpr int32_t RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING = -1;
78 #endif
79 const uint16_t GET_MAX_AMPLITUDE_FRAMES_THRESHOLD = 10;
80 }
81 
82 typedef struct {
83     HDI::Audio_Bluetooth::AudioFormat format;
84     uint32_t sampleRate;
85     uint32_t channel;
86     float volume;
87 } BluetoothSinkAttr;
88 
89 class BluetoothRendererSinkInner : public BluetoothRendererSink {
90 public:
91     int32_t Init(const IAudioSinkAttr &attr) override;
92     bool IsInited(void) override;
93     void DeInit(void) override;
94     int32_t Start(void) override;
95     int32_t Stop(void) override;
96     int32_t Flush(void) override;
97     int32_t Reset(void) override;
98     int32_t Pause(void) override;
99     int32_t Resume(void) override;
100     int32_t SuspendRenderSink(void) override;
101     int32_t RestoreRenderSink(void) override;
102     int32_t RenderFrame(char &data, uint64_t len, uint64_t &writeLen) override;
103     int32_t SetVolume(float left, float right) override;
104     int32_t GetVolume(float &left, float &right) override;
105     int32_t GetLatency(uint32_t *latency) override;
106     int32_t GetTransactionId(uint64_t *transactionId) override;
107     void SetAudioMonoState(bool audioMono) override;
108     void SetAudioBalanceValue(float audioBalance) override;
109     int32_t GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec) override;
110 
111     int32_t SetVoiceVolume(float volume) override;
112     int32_t GetAudioScene() override;
113     int32_t SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeDevices) override;
114     int32_t SetOutputRoutes(std::vector<DeviceType> &outputDevices) override;
115     void SetAudioParameter(const AudioParamKey key, const std::string &condition, const std::string &value) override;
116     std::string GetAudioParameter(const AudioParamKey key, const std::string &condition) override;
117     void RegisterAudioSinkCallback(IAudioSinkCallback* callback) override;
118     float GetMaxAmplitude() override;
119 
120     void ResetOutputRouteForDisconnect(DeviceType device) override;
121     int32_t SetPaPower(int32_t flag) override;
122     int32_t SetPriPaPower() override;
123 
124     bool GetAudioMonoState();
125     float GetAudioBalanceValue();
126 
127     int32_t UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],
128         const size_t size) final;
129     int32_t UpdateAppsUid(const std::vector<int32_t> &appsUid) final;
130     int32_t GetRenderId(uint32_t &renderId) const override;
131 
132     int32_t SetSinkMuteForSwitchDevice(bool mute) final;
133 
134     explicit BluetoothRendererSinkInner(bool isBluetoothLowLatency = false);
135     ~BluetoothRendererSinkInner();
136 private:
137     BluetoothSinkAttr attr_;
138     bool rendererInited_;
139     bool started_;
140     bool paused_;
141     std::atomic<bool> suspend_ = false;
142     float leftVolume_;
143     float rightVolume_;
144     struct HDI::Audio_Bluetooth::AudioProxyManager *audioManager_;
145     struct HDI::Audio_Bluetooth::AudioAdapter *audioAdapter_;
146     struct HDI::Audio_Bluetooth::AudioRender *audioRender_;
147     IAudioSinkCallback *callback_ = nullptr;
148     struct HDI::Audio_Bluetooth::AudioPort audioPort = {};
149     void *handle_;
150     bool audioMonoState_ = false;
151     bool audioBalanceState_ = false;
152     float leftBalanceCoef_ = 1.0f;
153     float rightBalanceCoef_ = 1.0f;
154     int32_t initCount_ = 0;
155     int32_t logMode_ = 0;
156     uint32_t sinkId_ = 0;
157     AudioSampleFormat audioSampleFormat_ = SAMPLE_S16LE;
158 
159     // for sink state
160     std::mutex sinkMutex_;
161     // for device switch
162     std::mutex switchDeviceMutex_;
163     int32_t muteCount_ = 0;
164     std::atomic<bool> switchDeviceMute_ = false;
165 
166     // Low latency
167     int32_t PrepareMmapBuffer();
168     int32_t GetMmapBufferInfo(int &fd, uint32_t &totalSizeInframe, uint32_t &spanSizeInframe,
169         uint32_t &byteSizePerFrame) override;
170     int32_t GetMmapHandlePosition(uint64_t &frames, int64_t &timeSec, int64_t &timeNanoSec) override;
171     int32_t CheckPositionTime();
172     int32_t CheckBluetoothScenario();
173 
174     bool isBluetoothLowLatency_ = false;
175     uint32_t bufferTotalFrameSize_ = 0;
176     int32_t bufferFd_ = INVALID_FD;
177     uint32_t frameSizeInByte_ = 1;
178     uint32_t eachReadFrameSize_ = 0;
179     size_t bufferSize_ = 0;
180 
181     // for get amplitude
182     float maxAmplitude_ = 0;
183     int64_t lastGetMaxAmplitudeTime_ = 0;
184     int64_t last10FrameStartTime_ = 0;
185     bool startUpdate_ = false;
186     int renderFrameNum_ = 0;
187     bool signalDetected_ = false;
188     bool latencyMeasEnabled_ = false;
189     std::shared_ptr<SignalDetectAgent> signalDetectAgent_ = nullptr;
190 #ifdef FEATURE_POWER_MANAGER
191     std::shared_ptr<AudioRunningLockManager<PowerMgr::RunningLock>> runningLockManager_;
192     void UnlockRunningLock();
193     void UpdateAppsUid();
194 #endif
195 
196     int32_t CreateRender(struct HDI::Audio_Bluetooth::AudioPort &renderPort);
197     int32_t InitAudioManager();
198     void AdjustStereoToMono(char *data, uint64_t len);
199     void AdjustAudioBalance(char *data, uint64_t len);
200     AudioFormat ConvertToHdiFormat(HdiAdapterFormat format);
201     ConvertHdiFormat ConvertToHdiAdapterFormat(AudioFormat format);
202     int64_t BytesToNanoTime(size_t lens);
203     void CheckUpdateState(char *frame, uint64_t replyBytes);
204     void InitLatencyMeasurement();
205     void DeinitLatencyMeasurement();
206     void CheckLatencySignal(uint8_t *data, size_t len);
207     void UpdateSinkState(bool started);
208     FILE *dumpFile_ = nullptr;
209     std::string dumpFileName_ = "";
210     mutable int64_t volumeDataCount_ = 0;
211     std::string logUtilsTag_ = "";
212 };
213 
BluetoothRendererSinkInner(bool isBluetoothLowLatency)214 BluetoothRendererSinkInner::BluetoothRendererSinkInner(bool isBluetoothLowLatency)
215     : rendererInited_(false), started_(false), paused_(false), suspend_(false), leftVolume_(DEFAULT_VOLUME_LEVEL),
216       rightVolume_(DEFAULT_VOLUME_LEVEL), audioManager_(nullptr), audioAdapter_(nullptr),
217       audioRender_(nullptr), handle_(nullptr), isBluetoothLowLatency_(isBluetoothLowLatency)
218 {
219     attr_ = {};
220 }
221 
~BluetoothRendererSinkInner()222 BluetoothRendererSinkInner::~BluetoothRendererSinkInner()
223 {
224     BluetoothRendererSinkInner::DeInit();
225     AudioPerformanceMonitor::GetInstance().DeleteOvertimeMonitor(ADAPTER_TYPE_BLUETOOTH);
226     AUDIO_INFO_LOG("[%{public}s] volume data counts: %{public}" PRId64, logUtilsTag_.c_str(), volumeDataCount_);
227 }
228 
GetInstance()229 BluetoothRendererSink *BluetoothRendererSink::GetInstance()
230 {
231     static BluetoothRendererSinkInner audioRenderer;
232 
233     return &audioRenderer;
234 }
235 
GetMmapInstance()236 IMmapAudioRendererSink *BluetoothRendererSink::GetMmapInstance()
237 {
238     static BluetoothRendererSinkInner audioRenderer(true);
239 
240     return &audioRenderer;
241 }
242 
IsInited(void)243 bool BluetoothRendererSinkInner::IsInited(void)
244 {
245     return rendererInited_;
246 }
247 
SetVoiceVolume(float volume)248 int32_t BluetoothRendererSinkInner::SetVoiceVolume(float volume)
249 {
250     return ERR_NOT_SUPPORTED;
251 }
252 
GetAudioScene()253 int32_t BluetoothRendererSinkInner::GetAudioScene()
254 {
255     AUDIO_DEBUG_LOG("not supported.");
256     return ERR_NOT_SUPPORTED;
257 }
258 
SetAudioScene(AudioScene audioScene,std::vector<DeviceType> & activeDevices)259 int32_t BluetoothRendererSinkInner::SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeDevices)
260 {
261     return ERR_NOT_SUPPORTED;
262 }
263 
SetOutputRoutes(std::vector<DeviceType> & outputDevices)264 int32_t BluetoothRendererSinkInner::SetOutputRoutes(std::vector<DeviceType> &outputDevices)
265 {
266     AUDIO_DEBUG_LOG("SetOutputRoutes not supported.");
267     return ERR_NOT_SUPPORTED;
268 }
269 
SetAudioParameter(const AudioParamKey key,const std::string & condition,const std::string & value)270 void BluetoothRendererSinkInner::SetAudioParameter(const AudioParamKey key, const std::string &condition,
271     const std::string &value)
272 {
273     AUDIO_INFO_LOG("key %{public}d, condition: %{public}s, value: %{public}s", key,
274         condition.c_str(), value.c_str());
275     if (audioRender_ == nullptr) {
276         AUDIO_ERR_LOG("SetAudioParameter for render failed, audioRender_ is null");
277         return;
278     }
279 
280     int32_t ret = audioRender_->attr.SetExtraParams(reinterpret_cast<AudioHandle>(audioRender_), value.c_str());
281     if (ret != SUCCESS) {
282         AUDIO_WARNING_LOG("SetAudioParameter for render failed, error code: %d", ret);
283     }
284 
285     std::lock_guard<std::mutex> lock(sinkMutex_);
286     if (started_ && isBluetoothLowLatency_ && !strcmp(value.c_str(), BLUETOOTH_CANCEL_SUSPEND)) {
287         int32_t tryCount = 3; // try to start bluetooth render up to 3 times;
288         while (tryCount-- > 0) {
289             AUDIO_INFO_LOG("Try to start bluetooth render");
290             CHECK_AND_RETURN_LOG(audioRender_ != nullptr, "Bluetooth renderer is nullptr");
291             ret = audioRender_->control.Start(reinterpret_cast<AudioHandle>(audioRender_));
292             if (ret == SUCCESS) {
293                 AUDIO_INFO_LOG("Start Fast Success");
294                 CheckBluetoothScenario();
295                 return;
296             } else {
297                 AUDIO_ERR_LOG("Start failed, remaining %{public}d attempt(s)", tryCount);
298                 usleep(WAIT_TIME_FOR_RETRY_IN_MICROSECOND);
299             }
300         }
301     }
302 }
303 
GetAudioParameter(const AudioParamKey key,const std::string & condition)304 std::string BluetoothRendererSinkInner::GetAudioParameter(const AudioParamKey key, const std::string &condition)
305 {
306     AUDIO_ERR_LOG("BluetoothRendererSink GetAudioParameter not supported.");
307     return "";
308 }
309 
RegisterAudioSinkCallback(IAudioSinkCallback * callback)310 void BluetoothRendererSinkInner::RegisterAudioSinkCallback(IAudioSinkCallback* callback)
311 {
312     std::lock_guard<std::mutex> lock(sinkMutex_);
313     if (callback_) {
314         AUDIO_INFO_LOG("AudioSinkCallback registered");
315     } else {
316         callback_ = callback;
317         AUDIO_INFO_LOG("Register AudioSinkCallback");
318     }
319 }
320 
DeInit()321 void BluetoothRendererSinkInner::DeInit()
322 {
323     std::lock_guard<std::mutex> lock(sinkMutex_);
324     Trace trace("BluetoothRendererSinkInner::DeInit");
325 
326     AUDIO_INFO_LOG("DeInit. isFast: %{public}d", isBluetoothLowLatency_);
327 
328     if (--initCount_ > 0) {
329         AUDIO_WARNING_LOG("Sink is still being used, count: %{public}d", initCount_);
330         return;
331     }
332     started_ = false;
333     rendererInited_ = false;
334     if ((audioRender_ != nullptr) && (audioAdapter_ != nullptr)) {
335         audioAdapter_->DestroyRender(audioAdapter_, audioRender_);
336     }
337     audioRender_ = nullptr;
338 
339     if ((audioManager_ != nullptr) && (audioAdapter_ != nullptr)) {
340         audioManager_->UnloadAdapter(audioManager_, audioAdapter_);
341     }
342     audioAdapter_ = nullptr;
343     audioManager_ = nullptr;
344 
345     if (handle_ != nullptr) {
346 #ifndef TEST_COVERAGE
347         dlclose(handle_);
348 #endif
349         handle_ = nullptr;
350     }
351 
352     DumpFileUtil::CloseDumpFile(&dumpFile_);
353 }
354 
InitAttrs(struct AudioSampleAttributes & attrs)355 void InitAttrs(struct AudioSampleAttributes &attrs)
356 {
357     /* Initialization of audio parameters for playback */
358     attrs.format = AUDIO_FORMAT_TYPE_PCM_16_BIT;
359     attrs.channelCount = AUDIO_CHANNELCOUNT;
360     attrs.frameSize = PCM_16_BIT * attrs.channelCount / PCM_8_BIT;
361     attrs.sampleRate = AUDIO_SAMPLE_RATE_48K;
362     attrs.interleaved = 0;
363     // Bluetooth HDI use adapterNameCase to choose lowLatency / normal
364     attrs.type = AUDIO_IN_MEDIA;
365     attrs.period = DEEP_BUFFER_RENDER_PERIOD_SIZE;
366     attrs.isBigEndian = false;
367     attrs.isSignedData = true;
368     attrs.startThreshold = DEEP_BUFFER_RENDER_PERIOD_SIZE / (attrs.frameSize);
369     attrs.stopThreshold = INT_32_MAX;
370     attrs.silenceThreshold = 0;
371 }
372 
SwitchAdapter(struct AudioAdapterDescriptor * descs,string adapterNameCase,enum AudioPortDirection portFlag,struct AudioPort & renderPort,int32_t size)373 static int32_t SwitchAdapter(struct AudioAdapterDescriptor *descs, string adapterNameCase,
374     enum AudioPortDirection portFlag, struct AudioPort &renderPort, int32_t size)
375 {
376     AUDIO_INFO_LOG("SwitchAdapter: adapterNameCase: %{public}s", adapterNameCase.c_str());
377     CHECK_AND_RETURN_RET(descs != nullptr, ERROR);
378 
379     for (int32_t index = 0; index < size; index++) {
380         struct AudioAdapterDescriptor *desc = &descs[index];
381         if (desc == nullptr) {
382             continue;
383         }
384         AUDIO_DEBUG_LOG("SwitchAdapter: adapter name for %{public}d: %{public}s", index, desc->adapterName);
385         if (!strcmp(desc->adapterName, adapterNameCase.c_str())) {
386             for (uint32_t port = 0; port < desc->portNum; port++) {
387                 // Only find out the port of out in the sound card
388                 if (desc->ports[port].dir == portFlag) {
389                     renderPort = desc->ports[port];
390                     AUDIO_DEBUG_LOG("SwitchAdapter: index found %{public}d", index);
391                     return index;
392                 }
393             }
394         }
395     }
396     AUDIO_ERR_LOG("SwitchAdapter Fail");
397 
398     return ERR_INVALID_INDEX;
399 }
400 
InitAudioManager()401 int32_t BluetoothRendererSinkInner::InitAudioManager()
402 {
403     AUDIO_INFO_LOG("Initialize audio proxy manager");
404 
405 #if (defined(__aarch64__) || defined(__x86_64__))
406     char resolvedPath[100] = "/vendor/lib64/chipsetsdk/libaudio_bluetooth_hdi_proxy_server.z.so";
407 #else
408     char resolvedPath[100] = "/vendor/lib/chipsetsdk/libaudio_bluetooth_hdi_proxy_server.z.so";
409 #endif
410     struct AudioProxyManager *(*getAudioManager)() = nullptr;
411 
412     handle_ = dlopen(resolvedPath, 1);
413     CHECK_AND_RETURN_RET_LOG(handle_ != nullptr, ERR_INVALID_HANDLE, "Open so Fail");
414     AUDIO_DEBUG_LOG("dlopen successful");
415 
416     getAudioManager = (struct AudioProxyManager *(*)())(dlsym(handle_, "GetAudioProxyManagerFuncs"));
417     CHECK_AND_RETURN_RET(getAudioManager != nullptr, ERR_INVALID_HANDLE);
418     AUDIO_DEBUG_LOG("getaudiomanager done");
419 
420     audioManager_ = getAudioManager();
421     CHECK_AND_RETURN_RET(audioManager_ != nullptr, ERR_INVALID_HANDLE);
422     AUDIO_DEBUG_LOG("audio manager created");
423 
424     return 0;
425 }
426 
PcmFormatToBits(AudioFormat format)427 uint32_t PcmFormatToBits(AudioFormat format)
428 {
429     switch (format) {
430         case AUDIO_FORMAT_TYPE_PCM_8_BIT:
431             return PCM_8_BIT;
432         case AUDIO_FORMAT_TYPE_PCM_16_BIT:
433             return PCM_16_BIT;
434         case AUDIO_FORMAT_TYPE_PCM_24_BIT:
435             return PCM_24_BIT;
436         case AUDIO_FORMAT_TYPE_PCM_32_BIT:
437             return PCM_32_BIT;
438         default:
439             return PCM_24_BIT;
440     };
441 }
442 
CreateRender(struct AudioPort & renderPort)443 int32_t BluetoothRendererSinkInner::CreateRender(struct AudioPort &renderPort)
444 {
445     struct AudioSampleAttributes param;
446     InitAttrs(param);
447     param.sampleRate = attr_.sampleRate;
448     param.channelCount = attr_.channel;
449     param.format = attr_.format;
450     param.frameSize = PcmFormatToBits(param.format) * param.channelCount / PCM_8_BIT;
451     param.startThreshold = DEEP_BUFFER_RENDER_PERIOD_SIZE / (param.frameSize);
452     struct AudioDeviceDescriptor deviceDesc;
453     deviceDesc.portId = renderPort.portId;
454     deviceDesc.pins = PIN_OUT_SPEAKER;
455     deviceDesc.desc = nullptr;
456 
457     AUDIO_INFO_LOG("Create render rate:%{public}u channel:%{public}u format:%{public}u isFast: %{public}d",
458         param.sampleRate, param.channelCount, param.format, isBluetoothLowLatency_);
459     int32_t ret = audioAdapter_->CreateRender(audioAdapter_, &deviceDesc, &param, &audioRender_);
460     if (ret != 0 || audioRender_ == nullptr) {
461         AUDIO_ERR_LOG("AudioDeviceCreateRender failed");
462         audioManager_->UnloadAdapter(audioManager_, audioAdapter_);
463         return ERR_NOT_STARTED;
464     }
465 
466     return 0;
467 }
468 
ConvertToHdiFormat(HdiAdapterFormat format)469 AudioFormat BluetoothRendererSinkInner::ConvertToHdiFormat(HdiAdapterFormat format)
470 {
471     AudioFormat hdiFormat;
472     switch (format) {
473         case SAMPLE_U8:
474             hdiFormat = AUDIO_FORMAT_TYPE_PCM_8_BIT;
475             break;
476         case SAMPLE_S16:
477             hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
478             break;
479         case SAMPLE_S24:
480             hdiFormat = AUDIO_FORMAT_TYPE_PCM_24_BIT;
481             break;
482         case SAMPLE_S32:
483             hdiFormat = AUDIO_FORMAT_TYPE_PCM_32_BIT;
484             break;
485         default:
486             hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
487             break;
488     }
489 
490     return hdiFormat;
491 }
492 
Init(const IAudioSinkAttr & attr)493 int32_t BluetoothRendererSinkInner::Init(const IAudioSinkAttr &attr)
494 {
495     std::lock_guard<std::mutex> lock(sinkMutex_);
496     AUDIO_INFO_LOG("Init: format: %{public}d isFast: %{public}d", attr.format, isBluetoothLowLatency_);
497     if (rendererInited_) {
498         AUDIO_WARNING_LOG("Already inited");
499         initCount_++;
500         return true;
501     }
502     audioSampleFormat_ = static_cast<AudioSampleFormat>(attr.format);
503 
504     attr_.format = ConvertToHdiFormat(attr.format);
505     attr_.sampleRate = attr.sampleRate;
506     attr_.channel = attr.channel;
507     attr_.volume = attr.volume;
508 
509     string adapterNameCase = isBluetoothLowLatency_ ? "bt_a2dp_fast" : "bt_a2dp";  // Set sound card information
510     enum AudioPortDirection port = PORT_OUT; // Set port information
511 
512     CHECK_AND_RETURN_RET_LOG(InitAudioManager() == 0, ERR_NOT_STARTED,
513         "Init audio manager Fail");
514 
515     int32_t size = 0;
516     struct AudioAdapterDescriptor *descs = nullptr;
517     int32_t ret = audioManager_->GetAllAdapters(audioManager_, &descs, &size);
518     CHECK_AND_RETURN_RET_LOG(size <= MAX_AUDIO_ADAPTER_NUM && size != 0 && descs != nullptr && ret == 0,
519         ERR_NOT_STARTED, "Get adapters Fail");
520 
521     // Get qualified sound card and port
522     int32_t index = SwitchAdapter(descs, adapterNameCase, port, audioPort, size);
523     CHECK_AND_RETURN_RET_LOG(index >= 0, ERR_NOT_STARTED, "Switch Adapter Fail");
524 
525     struct AudioAdapterDescriptor *desc = &descs[index];
526     int32_t loadAdapter = audioManager_->LoadAdapter(audioManager_, desc, &audioAdapter_);
527     CHECK_AND_RETURN_RET_LOG(loadAdapter == 0, ERR_NOT_STARTED, "Load Adapter Fail");
528     CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, ERR_NOT_STARTED, "Load audio device failed");
529 
530     // Initialization port information, can fill through mode and other parameters
531     ret = audioAdapter_->InitAllPorts(audioAdapter_);
532     CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_NOT_STARTED, "InitAllPorts failed");
533 
534     int32_t result = CreateRender(audioPort);
535     CHECK_AND_RETURN_RET_LOG(result == 0, ERR_NOT_STARTED, "Create render failed");
536 
537     if (isBluetoothLowLatency_) {
538         result = PrepareMmapBuffer();
539         CHECK_AND_RETURN_RET_LOG(result == 0, ERR_NOT_STARTED, "Prepare mmap buffer failed");
540     }
541 
542     GetRenderId(sinkId_);
543     logMode_ = system::GetIntParameter("persist.multimedia.audiolog.switch", 0);
544     logUtilsTag_ = "A2dpSink";
545 
546     rendererInited_ = true;
547     initCount_++;
548 
549     return SUCCESS;
550 }
551 
RenderFrame(char & data,uint64_t len,uint64_t & writeLen)552 int32_t BluetoothRendererSinkInner::RenderFrame(char &data, uint64_t len, uint64_t &writeLen)
553 {
554     int32_t ret = SUCCESS;
555     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE, "Bluetooth Render Handle is nullptr!");
556 
557     if (audioMonoState_) { AdjustStereoToMono(&data, len); }
558     if (audioBalanceState_) { AdjustAudioBalance(&data, len); }
559 
560     CheckLatencySignal(reinterpret_cast<uint8_t*>(&data), len);
561     CheckUpdateState(&data, len);
562     if (suspend_) { return ret; }
563 
564     Trace trace("BluetoothRendererSinkInner::RenderFrame");
565     if (switchDeviceMute_) {
566         Trace traceEmpty("BluetoothRendererSinkInner::RenderFrame::renderEmpty");
567         if (memset_s(reinterpret_cast<void*>(&data), static_cast<size_t>(len), 0,
568             static_cast<size_t>(len)) != EOK) {
569             AUDIO_WARNING_LOG("call memset_s failed");
570         }
571     }
572 
573     BufferDesc buffer = { reinterpret_cast<uint8_t*>(&data), len, len };
574     AudioStreamInfo streamInfo(static_cast<AudioSamplingRate>(attr_.sampleRate), AudioEncodingType::ENCODING_PCM,
575         audioSampleFormat_, static_cast<AudioChannel>(attr_.channel));
576     VolumeTools::DfxOperation(buffer, streamInfo, logUtilsTag_, volumeDataCount_);
577     if (AudioDump::GetInstance().GetVersionType() == DumpFileUtil::BETA_VERSION) {
578         DumpFileUtil::WriteDumpFile(dumpFile_, static_cast<void *>(&data), len);
579         AudioCacheMgr::GetInstance().CacheData(dumpFileName_, static_cast<void *>(&data), len);
580     }
581 
582     while (true) {
583         Trace trace("audioRender_->RenderFrame");
584         int64_t stamp = ClockTime::GetCurNano();
585         ret = audioRender_->RenderFrame(audioRender_, (void*)&data, len, &writeLen);
586         AudioPerformanceMonitor::GetInstance().RecordTimeStamp(ADAPTER_TYPE_BLUETOOTH, ClockTime::GetCurNano());
587         stamp = (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND;
588         if (logMode_ || stamp >= STAMP_THRESHOLD_MS) {
589             AUDIO_PRERELEASE_LOGW("A2dp RenderFrame len[%{public}" PRIu64 "] cost[%{public}" PRId64 "]ms " \
590                 "writeLen[%{public}" PRIu64 "] returns: %{public}x", len, stamp, writeLen, ret);
591         }
592         if (ret == RENDER_FRAME_NUM) {
593             AUDIO_ERR_LOG("retry render frame...");
594             usleep(RENDER_FRAME_INTERVAL_IN_MICROSECONDS);
595             continue;
596         }
597         if (ret != 0) {
598             AUDIO_ERR_LOG("A2dp RenderFrame failed ret: %{public}x", ret);
599             ret = ERR_WRITE_FAILED;
600         }
601 
602         break;
603     }
604 
605 #ifdef FEATURE_POWER_MANAGER
606     UpdateAppsUid();
607 #endif
608 
609     return ret;
610 }
611 
612 #ifdef FEATURE_POWER_MANAGER
UpdateAppsUid()613 void BluetoothRendererSinkInner::UpdateAppsUid()
614 {
615     if (runningLockManager_) {
616         runningLockManager_->UpdateAppsUidToPowerMgr();
617     } else {
618         AUDIO_ERR_LOG("runningLockManager_ is nullptr");
619     }
620 }
621 #endif
622 
623 
ConvertToHdiAdapterFormat(AudioFormat format)624 ConvertHdiFormat BluetoothRendererSinkInner::ConvertToHdiAdapterFormat(AudioFormat format)
625 {
626     ConvertHdiFormat hdiFormat;
627     switch (format) {
628         case AUDIO_FORMAT_TYPE_PCM_8_BIT:
629             hdiFormat = SAMPLE_U8_C;
630             break;
631         case AUDIO_FORMAT_TYPE_PCM_16_BIT:
632             hdiFormat = SAMPLE_S16_C;
633             break;
634         case AUDIO_FORMAT_TYPE_PCM_24_BIT:
635             hdiFormat = SAMPLE_S24_C;
636             break;
637         case AUDIO_FORMAT_TYPE_PCM_32_BIT:
638             hdiFormat = SAMPLE_S32_C;
639             break;
640         default:
641             hdiFormat = SAMPLE_S16_C;
642             break;
643     }
644 
645     return hdiFormat;
646 }
647 
CheckUpdateState(char * frame,uint64_t replyBytes)648 void BluetoothRendererSinkInner::CheckUpdateState(char *frame, uint64_t replyBytes)
649 {
650     if (startUpdate_) {
651         if (renderFrameNum_ == 0) {
652             last10FrameStartTime_ = ClockTime::GetCurNano();
653         }
654         renderFrameNum_++;
655         maxAmplitude_ = UpdateMaxAmplitude(ConvertToHdiAdapterFormat(attr_.format), frame, replyBytes);
656         if (renderFrameNum_ == GET_MAX_AMPLITUDE_FRAMES_THRESHOLD) {
657             renderFrameNum_ = 0;
658             if (last10FrameStartTime_ > lastGetMaxAmplitudeTime_) {
659                 startUpdate_ = false;
660                 maxAmplitude_ = 0;
661             }
662         }
663     }
664 }
665 
GetMaxAmplitude()666 float BluetoothRendererSinkInner::GetMaxAmplitude()
667 {
668     lastGetMaxAmplitudeTime_ = ClockTime::GetCurNano();
669     startUpdate_ = true;
670     return maxAmplitude_;
671 }
672 
CheckBluetoothScenario()673 int32_t BluetoothRendererSinkInner::CheckBluetoothScenario()
674 {
675     UpdateSinkState(true);
676     started_ = true;
677     if (isBluetoothLowLatency_ && CheckPositionTime() != SUCCESS) {
678         AUDIO_ERR_LOG("CheckPositionTime failed!");
679 #ifdef FEATURE_POWER_MANAGER
680         UnlockRunningLock();
681 #endif
682         return ERR_NOT_STARTED;
683     }
684     return SUCCESS;
685 }
686 
Start(void)687 int32_t BluetoothRendererSinkInner::Start(void)
688 {
689     std::lock_guard<std::mutex> lock(sinkMutex_);
690     Trace trace("BluetoothRendererSinkInner::Start");
691     AUDIO_INFO_LOG("In isFast: %{public}d", isBluetoothLowLatency_);
692 #ifdef FEATURE_POWER_MANAGER
693     std::shared_ptr<PowerMgr::RunningLock> keepRunningLock;
694     if (runningLockManager_ == nullptr) {
695         WatchTimeout guard("PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock:Start");
696         keepRunningLock = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock("AudioBluetoothBackgroundPlay",
697             PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO);
698         guard.CheckCurrTimeout();
699         if (keepRunningLock) {
700             runningLockManager_ = std::make_shared<AudioRunningLockManager<PowerMgr::RunningLock>> (keepRunningLock);
701         }
702     }
703 
704     if (runningLockManager_ != nullptr) {
705         AUDIO_INFO_LOG("keepRunningLock lock result: %{public}d",
706             runningLockManager_->Lock(RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING)); // -1 for lasting.
707     } else {
708         AUDIO_ERR_LOG("keepRunningLock is null, playback can not work well!");
709     }
710 #endif
711     dumpFileName_ = "bluetooth_audiosink_" + GetTime() + "_" + std::to_string(attr_.sampleRate) + "_"
712         + std::to_string(attr_.channel) + "_" + std::to_string(attr_.format) + ".pcm";
713     DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileName_, &dumpFile_);
714 
715     InitLatencyMeasurement();
716 
717     int32_t tryCount = 3; // try to start bluetooth render up to 3 times;
718     if (!started_) {
719         while (tryCount-- > 0) {
720             AUDIO_INFO_LOG("Try to start bluetooth render");
721             CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERROR, "Bluetooth renderer is nullptr");
722             int32_t ret = audioRender_->control.Start(reinterpret_cast<AudioHandle>(audioRender_));
723             if (!ret) {
724                 AudioPerformanceMonitor::GetInstance().RecordTimeStamp(ADAPTER_TYPE_BLUETOOTH, INIT_LASTWRITTEN_TIME);
725                 return CheckBluetoothScenario();
726             } else {
727                 AUDIO_ERR_LOG("Start failed, remaining %{public}d attempt(s)", tryCount);
728                 usleep(WAIT_TIME_FOR_RETRY_IN_MICROSECOND);
729             }
730         }
731         AUDIO_ERR_LOG("Start bluetooth render failed for three times, return");
732 #ifdef FEATURE_POWER_MANAGER
733         UnlockRunningLock();
734 #endif
735         return ERR_NOT_STARTED;
736     }
737     return SUCCESS;
738 }
739 
740 #ifdef FEATURE_POWER_MANAGER
UnlockRunningLock()741 void BluetoothRendererSinkInner::UnlockRunningLock()
742 {
743     if (runningLockManager_ != nullptr) {
744         AUDIO_INFO_LOG("keepRunningLock unLock");
745         runningLockManager_->UnLock();
746     } else {
747         AUDIO_ERR_LOG("running lock is null");
748     }
749 }
750 #endif
751 
CheckPositionTime()752 int32_t BluetoothRendererSinkInner::CheckPositionTime()
753 {
754     int32_t tryCount = MAX_GET_POSITOIN_TRY_COUNT;
755     uint64_t frames = 0;
756     int64_t timeSec = 0;
757     int64_t timeNanoSec = 0;
758     while (tryCount-- > 0) {
759         ClockTime::RelativeSleep(MAX_GET_POSITION_WAIT_TIME);
760         int32_t ret = GetMmapHandlePosition(frames, timeSec, timeNanoSec);
761         int64_t curTime = ClockTime::GetCurNano();
762         int64_t curSec = curTime / AUDIO_NS_PER_SECOND;
763         int64_t curNanoSec = curTime - curSec * AUDIO_NS_PER_SECOND;
764         if (ret != SUCCESS || curSec != timeSec || curNanoSec - timeNanoSec > MAX_GET_POSITION_HANDLE_TIME) {
765             AUDIO_WARNING_LOG("Try count %{public}d, ret %{public}d", tryCount, ret);
766             continue;
767         } else {
768             AUDIO_INFO_LOG("Finished.");
769             return SUCCESS;
770         }
771     }
772     return ERROR;
773 }
774 
SetVolume(float left,float right)775 int32_t BluetoothRendererSinkInner::SetVolume(float left, float right)
776 {
777     float volume;
778 
779     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
780         "SetVolume failed audioRender_ null");
781 
782     leftVolume_ = left;
783     rightVolume_ = right;
784     if ((leftVolume_ == 0) && (rightVolume_ != 0)) {
785         volume = rightVolume_;
786     } else if ((leftVolume_ != 0) && (rightVolume_ == 0)) {
787         volume = leftVolume_;
788     } else {
789         volume = (leftVolume_ + rightVolume_) / HALF_FACTOR;
790     }
791 
792     int32_t ret = audioRender_->volume.SetVolume(reinterpret_cast<AudioHandle>(audioRender_), volume);
793     if (ret) {
794         AUDIO_WARNING_LOG("Set volume failed!");
795     }
796 
797     return ret;
798 }
799 
GetVolume(float & left,float & right)800 int32_t BluetoothRendererSinkInner::GetVolume(float &left, float &right)
801 {
802     left = leftVolume_;
803     right = rightVolume_;
804     return SUCCESS;
805 }
806 
GetLatency(uint32_t * latency)807 int32_t BluetoothRendererSinkInner::GetLatency(uint32_t *latency)
808 {
809     Trace trace("BluetoothRendererSinkInner::GetLatency");
810     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
811         "GetLatency failed audio render null");
812 
813     CHECK_AND_RETURN_RET_LOG(latency, ERR_INVALID_PARAM, "GetLatency failed latency null");
814 
815     uint32_t hdiLatency;
816     if (audioRender_->GetLatency(audioRender_, &hdiLatency) == 0) {
817         *latency = hdiLatency;
818         return SUCCESS;
819     } else {
820         return ERR_OPERATION_FAILED;
821     }
822 }
823 
GetTransactionId(uint64_t * transactionId)824 int32_t BluetoothRendererSinkInner::GetTransactionId(uint64_t *transactionId)
825 {
826     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
827         "GetTransactionId failed audio render null");
828 
829     CHECK_AND_RETURN_RET_LOG(transactionId, ERR_INVALID_PARAM,
830         "GetTransactionId failed transactionId null");
831 
832     *transactionId = reinterpret_cast<uint64_t>(audioRender_);
833     return SUCCESS;
834 }
835 
Stop(void)836 int32_t BluetoothRendererSinkInner::Stop(void)
837 {
838     std::lock_guard<std::mutex> lock(sinkMutex_);
839     AUDIO_INFO_LOG("in isFast: %{public}d", isBluetoothLowLatency_);
840 
841     Trace trace("BluetoothRendererSinkInner::Stop");
842 
843     DeinitLatencyMeasurement();
844 #ifdef FEATURE_POWER_MANAGER
845     UnlockRunningLock();
846 #endif
847 
848     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
849         "Stop failed audioRender_ null");
850 
851     if (started_) {
852         Trace trace("audioRender_->control.Stop");
853         AUDIO_DEBUG_LOG("Stop control before");
854         int32_t ret = audioRender_->control.Stop(reinterpret_cast<AudioHandle>(audioRender_));
855         UpdateSinkState(false);
856         AUDIO_DEBUG_LOG("Stop control after");
857         if (!ret) {
858             started_ = false;
859             paused_ = false;
860             return SUCCESS;
861         } else {
862             AUDIO_ERR_LOG("Stop failed!");
863             return ERR_OPERATION_FAILED;
864         }
865     }
866 
867     return SUCCESS;
868 }
869 
Pause(void)870 int32_t BluetoothRendererSinkInner::Pause(void)
871 {
872     std::lock_guard<std::mutex> lock(sinkMutex_);
873     AUDIO_INFO_LOG("in");
874 
875     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
876         "Pause failed audioRender_ null");
877 
878     CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED,
879         "Pause invalid state!");
880 
881     if (!paused_) {
882         int32_t ret = audioRender_->control.Pause(reinterpret_cast<AudioHandle>(audioRender_));
883         if (!ret) {
884             paused_ = true;
885             return SUCCESS;
886         } else {
887             AUDIO_ERR_LOG("Pause failed!");
888             return ERR_OPERATION_FAILED;
889         }
890     }
891 
892     return SUCCESS;
893 }
894 
Resume(void)895 int32_t BluetoothRendererSinkInner::Resume(void)
896 {
897     std::lock_guard<std::mutex> lock(sinkMutex_);
898     AUDIO_INFO_LOG("in");
899 
900     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
901         "Resume failed audioRender_ null");
902 
903     CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED,
904         "Resume invalid state!");
905 
906     if (paused_) {
907         int32_t ret = audioRender_->control.Resume(reinterpret_cast<AudioHandle>(audioRender_));
908         if (!ret) {
909             paused_ = false;
910             return SUCCESS;
911         } else {
912             AUDIO_ERR_LOG("Resume failed!");
913             return ERR_OPERATION_FAILED;
914         }
915     }
916     AudioPerformanceMonitor::GetInstance().RecordTimeStamp(ADAPTER_TYPE_BLUETOOTH, INIT_LASTWRITTEN_TIME);
917     return SUCCESS;
918 }
919 
Reset(void)920 int32_t BluetoothRendererSinkInner::Reset(void)
921 {
922     AUDIO_INFO_LOG("in");
923 
924     if (started_ && audioRender_ != nullptr) {
925         int32_t ret = audioRender_->control.Flush(reinterpret_cast<AudioHandle>(audioRender_));
926         if (!ret) {
927             return SUCCESS;
928         } else {
929             AUDIO_ERR_LOG("Reset failed!");
930             return ERR_OPERATION_FAILED;
931         }
932     }
933 
934     return ERR_OPERATION_FAILED;
935 }
936 
Flush(void)937 int32_t BluetoothRendererSinkInner::Flush(void)
938 {
939     AUDIO_INFO_LOG("in");
940 
941     if (started_ && audioRender_ != nullptr) {
942         int32_t ret = audioRender_->control.Flush(reinterpret_cast<AudioHandle>(audioRender_));
943         if (!ret) {
944             return SUCCESS;
945         } else {
946             AUDIO_ERR_LOG("Flush failed!");
947             return ERR_OPERATION_FAILED;
948         }
949     }
950 
951     return ERR_OPERATION_FAILED;
952 }
953 
SuspendRenderSink(void)954 int32_t BluetoothRendererSinkInner::SuspendRenderSink(void)
955 {
956     AUDIO_INFO_LOG("in");
957     Trace trace("BluetoothRendererSinkInner::SuspendRenderSink");
958     suspend_ = true;
959     return SUCCESS;
960 }
961 
RestoreRenderSink(void)962 int32_t BluetoothRendererSinkInner::RestoreRenderSink(void)
963 {
964     AUDIO_INFO_LOG("in");
965     Trace trace("BluetoothRendererSinkInner::RestoreRenderSink");
966     suspend_ = false;
967     return SUCCESS;
968 }
969 
SetAudioMonoState(bool audioMono)970 void BluetoothRendererSinkInner::SetAudioMonoState(bool audioMono)
971 {
972     audioMonoState_ = audioMono;
973 }
974 
SetAudioBalanceValue(float audioBalance)975 void BluetoothRendererSinkInner::SetAudioBalanceValue(float audioBalance)
976 {
977     // reset the balance coefficient value firstly
978     leftBalanceCoef_ = 1.0f;
979     rightBalanceCoef_ = 1.0f;
980 
981     if (std::abs(audioBalance) <= std::numeric_limits<float>::epsilon()) {
982         // audioBalance is equal to 0.0f
983         audioBalanceState_ = false;
984     } else {
985         // audioBalance is not equal to 0.0f
986         audioBalanceState_ = true;
987         // calculate the balance coefficient
988         if (audioBalance > 0.0f) {
989             leftBalanceCoef_ -= audioBalance;
990         } else if (audioBalance < 0.0f) {
991             rightBalanceCoef_ += audioBalance;
992         }
993     }
994 }
995 
GetPresentationPosition(uint64_t & frames,int64_t & timeSec,int64_t & timeNanoSec)996 int32_t BluetoothRendererSinkInner::GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec)
997 {
998     AUDIO_ERR_LOG("BluetoothRendererSink GetPresentationPosition not supported.");
999     return ERR_NOT_SUPPORTED;
1000 }
1001 
AdjustStereoToMono(char * data,uint64_t len)1002 void BluetoothRendererSinkInner::AdjustStereoToMono(char *data, uint64_t len)
1003 {
1004     // only stereo is surpported now (stereo channel count is 2)
1005     CHECK_AND_RETURN_LOG(attr_.channel == STEREO_CHANNEL_COUNT,
1006         "AdjustStereoToMono: Unsupported channel number: %{public}d", attr_.channel);
1007 
1008     switch (attr_.format) {
1009         case AUDIO_FORMAT_TYPE_PCM_8_BIT: {
1010             // this function needs to be further tested for usability
1011             AdjustStereoToMonoForPCM8Bit(reinterpret_cast<int8_t *>(data), len);
1012             break;
1013         }
1014         case AUDIO_FORMAT_TYPE_PCM_16_BIT: {
1015             AdjustStereoToMonoForPCM16Bit(reinterpret_cast<int16_t *>(data), len);
1016             break;
1017         }
1018         case AUDIO_FORMAT_TYPE_PCM_24_BIT: {
1019             // this function needs to be further tested for usability
1020             AdjustStereoToMonoForPCM24Bit(reinterpret_cast<uint8_t *>(data), len);
1021             break;
1022         }
1023         case AUDIO_FORMAT_TYPE_PCM_32_BIT: {
1024             AdjustStereoToMonoForPCM32Bit(reinterpret_cast<int32_t *>(data), len);
1025             break;
1026         }
1027         default: {
1028             // if the audio format is unsupported, the audio data will not be changed
1029             AUDIO_ERR_LOG("AdjustStereoToMono: Unsupported audio format: %{public}d",
1030                 attr_.format);
1031             break;
1032         }
1033     }
1034 }
1035 
AdjustAudioBalance(char * data,uint64_t len)1036 void BluetoothRendererSinkInner::AdjustAudioBalance(char *data, uint64_t len)
1037 {
1038     CHECK_AND_RETURN_LOG(attr_.channel == STEREO_CHANNEL_COUNT,
1039         "Unsupported channel number: %{public}d", attr_.channel);
1040 
1041     switch (attr_.format) {
1042         case AUDIO_FORMAT_TYPE_PCM_8_BIT: {
1043             // this function needs to be further tested for usability
1044             AdjustAudioBalanceForPCM8Bit(reinterpret_cast<int8_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
1045             break;
1046         }
1047         case AUDIO_FORMAT_TYPE_PCM_16_BIT: {
1048             AdjustAudioBalanceForPCM16Bit(reinterpret_cast<int16_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
1049             break;
1050         }
1051         case AUDIO_FORMAT_TYPE_PCM_24_BIT: {
1052             // this function needs to be further tested for usability
1053             AdjustAudioBalanceForPCM24Bit(reinterpret_cast<uint8_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
1054             break;
1055         }
1056         case AUDIO_FORMAT_TYPE_PCM_32_BIT: {
1057             AdjustAudioBalanceForPCM32Bit(reinterpret_cast<int32_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
1058             break;
1059         }
1060         default: {
1061             // if the audio format is unsupported, the audio data will not be changed
1062             AUDIO_ERR_LOG("Unsupported audio format: %{public}d",
1063                 attr_.format);
1064             break;
1065         }
1066     }
1067 }
1068 
ResetOutputRouteForDisconnect(DeviceType device)1069 void BluetoothRendererSinkInner::ResetOutputRouteForDisconnect(DeviceType device)
1070 {
1071     AUDIO_WARNING_LOG("not supported.");
1072 }
1073 
SetPaPower(int32_t flag)1074 int32_t BluetoothRendererSinkInner::SetPaPower(int32_t flag)
1075 {
1076     (void)flag;
1077     return ERR_NOT_SUPPORTED;
1078 }
1079 
SetPriPaPower()1080 int32_t BluetoothRendererSinkInner::SetPriPaPower()
1081 {
1082     return ERR_NOT_SUPPORTED;
1083 }
1084 
HdiFormatToByte(HDI::Audio_Bluetooth::AudioFormat format)1085 static uint32_t HdiFormatToByte(HDI::Audio_Bluetooth::AudioFormat format)
1086 {
1087     return PcmFormatToBits(format) / BIT_TO_BYTES;
1088 }
1089 
BytesToNanoTime(size_t lens)1090 int64_t BluetoothRendererSinkInner::BytesToNanoTime(size_t lens)
1091 {
1092     int64_t res = static_cast<int64_t>(AUDIO_NS_PER_SECOND * lens /
1093         (attr_.sampleRate * attr_.channel * HdiFormatToByte(attr_.format)));
1094     return res;
1095 }
1096 
PrepareMmapBuffer()1097 int32_t BluetoothRendererSinkInner::PrepareMmapBuffer()
1098 {
1099     uint32_t totalBufferInMs = 40; // 5 * (6 + 2 * (1)) = 40ms, the buffer size, not latency.
1100     frameSizeInByte_ = PcmFormatToBits(attr_.format) * attr_.channel / PCM_8_BIT;
1101     uint32_t reqBufferFrameSize = totalBufferInMs * (attr_.sampleRate / SECOND_TO_MILLISECOND);
1102 
1103     struct AudioMmapBufferDescriptor desc = {0};
1104     // reqBufferFrameSize means frames in total, for example, 40ms * 48K = 1920
1105     // transferFrameSize means frames in one block, for example 5ms per block, 5ms * 48K = 240
1106     int32_t ret = audioRender_->attr.ReqMmapBuffer(audioRender_, reqBufferFrameSize, &desc);
1107     CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_OPERATION_FAILED, "ReqMmapBuffer failed, ret:%{public}d", ret);
1108     AUDIO_INFO_LOG("AudioMmapBufferDescriptor memoryAddress[%{private}p] memoryFd[%{public}d] totalBufferFrames"
1109         "[%{public}d] transferFrameSize[%{public}d] isShareable[%{public}d] offset[%{public}d]", desc.memoryAddress,
1110         desc.memoryFd, desc.totalBufferFrames, desc.transferFrameSize, desc.isShareable, desc.offset);
1111 
1112     bufferFd_ = desc.memoryFd; // fcntl(fd, 1030,3) after dup?
1113     int32_t periodFrameMaxSize = 1920000; // 192khz * 10s
1114     CHECK_AND_RETURN_RET_LOG(desc.totalBufferFrames >= 0 && desc.transferFrameSize >= 0 &&
1115         desc.transferFrameSize <= periodFrameMaxSize, ERR_OPERATION_FAILED,
1116         "ReqMmapBuffer invalid values: totalBufferFrames[%{public}d] transferFrameSize[%{public}d]",
1117         desc.totalBufferFrames, desc.transferFrameSize);
1118     bufferTotalFrameSize_ = static_cast<uint32_t>(desc.totalBufferFrames); // 1440 ~ 3840
1119     eachReadFrameSize_ = static_cast<uint32_t>(desc.transferFrameSize); // 240
1120 
1121     CHECK_AND_RETURN_RET_LOG(frameSizeInByte_ <= ULLONG_MAX / bufferTotalFrameSize_, ERR_OPERATION_FAILED,
1122         "BufferSize will overflow!");
1123     bufferSize_ = bufferTotalFrameSize_ * frameSizeInByte_;
1124     return SUCCESS;
1125 }
1126 
GetMmapBufferInfo(int & fd,uint32_t & totalSizeInframe,uint32_t & spanSizeInframe,uint32_t & byteSizePerFrame)1127 int32_t BluetoothRendererSinkInner::GetMmapBufferInfo(int &fd, uint32_t &totalSizeInframe, uint32_t &spanSizeInframe,
1128     uint32_t &byteSizePerFrame)
1129 {
1130     CHECK_AND_RETURN_RET_LOG(bufferFd_ != INVALID_FD, ERR_INVALID_HANDLE, "buffer fd has been released!");
1131     fd = bufferFd_;
1132     totalSizeInframe = bufferTotalFrameSize_;
1133     spanSizeInframe = eachReadFrameSize_;
1134     byteSizePerFrame = PcmFormatToBits(attr_.format) * attr_.channel / PCM_8_BIT;
1135     return SUCCESS;
1136 }
1137 
GetMmapHandlePosition(uint64_t & frames,int64_t & timeSec,int64_t & timeNanoSec)1138 int32_t BluetoothRendererSinkInner::GetMmapHandlePosition(uint64_t &frames, int64_t &timeSec, int64_t &timeNanoSec)
1139 {
1140     CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE, "Audio render is null!");
1141 
1142     struct AudioTimeStamp timestamp = {};
1143     int32_t ret = audioRender_->attr.GetMmapPosition(audioRender_, &frames, &timestamp);
1144     CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_OPERATION_FAILED, "Hdi GetMmapPosition filed, ret:%{public}d!", ret);
1145 
1146     int64_t maxSec = 9223372036; // (9223372036 + 1) * 10^9 > INT64_MAX, seconds should not bigger than it.
1147     CHECK_AND_RETURN_RET_LOG(timestamp.tvSec >= 0 && timestamp.tvSec <= maxSec && timestamp.tvNSec >= 0 &&
1148         timestamp.tvNSec <= SECOND_TO_NANOSECOND, ERR_OPERATION_FAILED,
1149         "Hdi GetMmapPosition get invaild second:%{public}" PRId64 " or nanosecond:%{public}" PRId64 " !",
1150         timestamp.tvSec, timestamp.tvNSec);
1151     timeSec = timestamp.tvSec;
1152     timeNanoSec = timestamp.tvNSec;
1153 
1154     return SUCCESS;
1155 }
1156 
InitLatencyMeasurement()1157 void BluetoothRendererSinkInner::InitLatencyMeasurement()
1158 {
1159     if (!AudioLatencyMeasurement::CheckIfEnabled()) {
1160         return;
1161     }
1162     AUDIO_INFO_LOG("BlueTooth RendererSinkInit");
1163     signalDetectAgent_ = std::make_shared<SignalDetectAgent>();
1164     CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
1165     signalDetectAgent_->sampleFormat_ = attr_.format;
1166     signalDetectAgent_->formatByteSize_ = GetFormatByteSize(attr_.format);
1167     latencyMeasEnabled_ = true;
1168     signalDetected_ = false;
1169 }
1170 
DeinitLatencyMeasurement()1171 void BluetoothRendererSinkInner::DeinitLatencyMeasurement()
1172 {
1173     signalDetectAgent_ = nullptr;
1174     latencyMeasEnabled_ = false;
1175 }
1176 
CheckLatencySignal(uint8_t * data,size_t len)1177 void BluetoothRendererSinkInner::CheckLatencySignal(uint8_t *data, size_t len)
1178 {
1179     if (!latencyMeasEnabled_) {
1180         return;
1181     }
1182     CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
1183     signalDetected_ = signalDetectAgent_->CheckAudioData(data, len);
1184     if (signalDetected_) {
1185         AUDIO_INFO_LOG("LatencyMeas BTSink signal detected");
1186         LatencyMonitor::GetInstance().UpdateSinkOrSourceTime(true,
1187             signalDetectAgent_->lastPeakBufferTime_);
1188         LatencyMonitor::GetInstance().ShowBluetoothTimestamp();
1189     }
1190 }
1191 
1192 // UpdateSinkState must be called with BluetoothRendererSinkInner::sinkMutex_ held
UpdateSinkState(bool started)1193 void BluetoothRendererSinkInner::UpdateSinkState(bool started)
1194 {
1195     if (callback_) {
1196         callback_->OnAudioSinkStateChange(sinkId_, started);
1197     } else {
1198         AUDIO_WARNING_LOG("AudioSinkCallback is nullptr");
1199     }
1200 }
1201 
UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],const size_t size)1202 int32_t BluetoothRendererSinkInner::UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],
1203     const size_t size)
1204 {
1205 #ifdef FEATURE_POWER_MANAGER
1206     if (!runningLockManager_) {
1207         return ERROR;
1208     }
1209 
1210     return runningLockManager_->UpdateAppsUid(appsUid, appsUid + size);
1211 #endif
1212 
1213     return SUCCESS;
1214 }
1215 
UpdateAppsUid(const std::vector<int32_t> & appsUid)1216 int32_t BluetoothRendererSinkInner::UpdateAppsUid(const std::vector<int32_t> &appsUid)
1217 {
1218 #ifdef FEATURE_POWER_MANAGER
1219     if (!runningLockManager_) {
1220         return ERROR;
1221     }
1222 
1223     runningLockManager_->UpdateAppsUid(appsUid.cbegin(), appsUid.cend());
1224     runningLockManager_->UpdateAppsUidToPowerMgr();
1225 #endif
1226 
1227     return SUCCESS;
1228 }
1229 
1230 // LCOV_EXCL_START
SetSinkMuteForSwitchDevice(bool mute)1231 int32_t BluetoothRendererSinkInner::SetSinkMuteForSwitchDevice(bool mute)
1232 {
1233     std::lock_guard<std::mutex> lock(switchDeviceMutex_);
1234     AUDIO_INFO_LOG("set a2dp mute %{public}d", mute);
1235 
1236     if (mute) {
1237         muteCount_++;
1238         if (switchDeviceMute_) {
1239             AUDIO_INFO_LOG("a2dp already muted");
1240             return SUCCESS;
1241         }
1242         switchDeviceMute_ = true;
1243     } else {
1244         muteCount_--;
1245         if (muteCount_ > 0) {
1246             AUDIO_WARNING_LOG("a2dp not all unmuted");
1247             return SUCCESS;
1248         }
1249         switchDeviceMute_ = false;
1250         muteCount_ = 0;
1251     }
1252 
1253     return SUCCESS;
1254 }
1255 
GetRenderId(uint32_t & renderId) const1256 int32_t BluetoothRendererSinkInner::GetRenderId(uint32_t &renderId) const
1257 {
1258     renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_BLUETOOTH);
1259     return SUCCESS;
1260 }
1261 } // namespace AudioStandard
1262 } // namespace OHOS
1263