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