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