1 /*
2 * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef LOG_TAG
16 #define LOG_TAG "AudioRendererSinkInner"
17 #endif
18
19 #include "audio_renderer_sink.h"
20
21 #include <atomic>
22 #include <cstring>
23 #include <cinttypes>
24 #include <condition_variable>
25 #include <dlfcn.h>
26 #include <string>
27 #include <unistd.h>
28 #include <mutex>
29 #include <thread>
30 #include "ctime"
31
32 #include "securec.h"
33 #ifdef FEATURE_POWER_MANAGER
34 #include "power_mgr_client.h"
35 #include "running_lock.h"
36 #include "audio_running_lock_manager.h"
37 #endif
38 #include "v4_0/iaudio_manager.h"
39 #include "hdf_remote_service.h"
40 #include "audio_errors.h"
41 #include "audio_hdi_log.h"
42 #include "parameters.h"
43 #include "media_monitor_manager.h"
44 #include "audio_enhance_chain_manager.h"
45 #include "audio_dump_pcm.h"
46 #include "volume_tools.h"
47 #include "audio_performance_monitor.h"
48 #include "ipc_skeleton.h"
49
50 using namespace std;
51
52 namespace OHOS {
53 namespace AudioStandard {
54 namespace {
55 const int32_t HALF_FACTOR = 2;
56 const int32_t MAX_AUDIO_ADAPTER_NUM = 5;
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 INT_32_MAX = 0x7fffffff;
62 const uint32_t PCM_8_BIT = 8;
63 const uint32_t PCM_16_BIT = 16;
64 const uint32_t PCM_24_BIT = 24;
65 const uint32_t PCM_32_BIT = 32;
66 const uint32_t STEREO_CHANNEL_COUNT = 2;
67 const unsigned int BUFFER_CALC_20MS = 20;
68 const unsigned int BUFFER_CALC_1000MS = 1000;
69 const unsigned int FORMAT_1_BYTE = 1;
70 const unsigned int FORMAT_2_BYTE = 2;
71 const unsigned int FORMAT_3_BYTE = 3;
72 const unsigned int FORMAT_4_BYTE = 4;
73 constexpr uid_t UID_BLUETOOTH_SA = 1002;
74
75 #ifdef FEATURE_POWER_MANAGER
76 const unsigned int TIME_OUT_SECONDS = 10;
77 constexpr int32_t RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING = -1;
78 #endif
79
80 const int64_t SECOND_TO_NANOSECOND = 1000000000;
81
82 static int32_t g_paStatus = 1;
83 const double INTREVAL = 3.0;
84
85 const uint16_t GET_MAX_AMPLITUDE_FRAMES_THRESHOLD = 10;
86 const uint32_t DEVICE_PARAM_MAX_LEN = 40;
87
88 const std::string VOIP_HAL_NAME = "voip";
89 const std::string DIRECT_HAL_NAME = "direct";
90 const std::string PRIMARY_HAL_NAME = "primary";
91 const std::string USB_HAL_NAME = "usb";
92 #ifdef FEATURE_POWER_MANAGER
93 const std::string PRIMARY_LOCK_NAME_BASE = "AudioBackgroundPlay";
94 #endif
95 }
96
ConvertByteToAudioFormat(int32_t format)97 int32_t ConvertByteToAudioFormat(int32_t format)
98 {
99 int32_t audioSampleFormat = 0;
100 switch (format) {
101 case FORMAT_1_BYTE:
102 audioSampleFormat = SAMPLE_U8;
103 break;
104 case FORMAT_2_BYTE:
105 audioSampleFormat = SAMPLE_S16LE;
106 break;
107 case FORMAT_3_BYTE:
108 audioSampleFormat = SAMPLE_S24LE;
109 break;
110 case FORMAT_4_BYTE:
111 audioSampleFormat = SAMPLE_S32LE;
112 break;
113 default:
114 audioSampleFormat = SAMPLE_S16LE;
115 }
116 return audioSampleFormat;
117 }
118
ParseAudioFormatToStr(int32_t format)119 static string ParseAudioFormatToStr(int32_t format)
120 {
121 switch (format) {
122 case FORMAT_1_BYTE:
123 return "u8";
124 case FORMAT_2_BYTE:
125 return "s16";
126 case FORMAT_3_BYTE:
127 return "s24";
128 case FORMAT_4_BYTE:
129 return "s32";
130 default:
131 return "s16";
132 }
133 return "";
134 }
135
ParseAudioFormat(const std::string & format)136 static HdiAdapterFormat ParseAudioFormat(const std::string &format)
137 {
138 if (format == "AUDIO_FORMAT_PCM_16_BIT") {
139 return HdiAdapterFormat::SAMPLE_S16;
140 } else if (format == "AUDIO_FORMAT_PCM_24_BIT" || format == "AUDIO_FORMAT_PCM_24_BIT_PACKED") {
141 return HdiAdapterFormat::SAMPLE_S24;
142 } else if (format == "AUDIO_FORMAT_PCM_32_BIT") {
143 return HdiAdapterFormat::SAMPLE_S32;
144 } else {
145 return HdiAdapterFormat::SAMPLE_S16;
146 }
147 }
148
AudioHostOnRemoteDied(struct HdfDeathRecipient * recipient,struct HdfRemoteService * service)149 static void AudioHostOnRemoteDied(struct HdfDeathRecipient *recipient, struct HdfRemoteService *service)
150 {
151 if (recipient == nullptr || service == nullptr) {
152 AUDIO_ERR_LOG("Receive die message but params are null");
153 return;
154 }
155
156 AUDIO_ERR_LOG("Auto exit for audio host die");
157 _Exit(0);
158 }
159
160 class AudioRendererSinkInner : public AudioRendererSink {
161 public:
162 int32_t Init(const IAudioSinkAttr &attr) override;
163 bool IsInited(void) override;
164 void DeInit(void) override;
165
166 int32_t Flush(void) override;
167 int32_t Pause(void) override;
168 int32_t Reset(void) override;
169 int32_t Resume(void) override;
170 int32_t Start(void) override;
171 int32_t Stop(void) override;
172 int32_t SuspendRenderSink(void) override;
173 int32_t RestoreRenderSink(void) override;
174
175 int32_t RenderFrame(char &data, uint64_t len, uint64_t &writeLen) override;
176 int32_t SetVolume(float left, float right) override;
177 int32_t GetVolume(float &left, float &right) override;
178 int32_t SetVoiceVolume(float volume) override;
179 int32_t GetLatency(uint32_t *latency) override;
180 int32_t GetTransactionId(uint64_t *transactionId) override;
181 int32_t GetAudioScene() override;
182 int32_t SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeDevices) override;
183
184 void SetAudioParameter(const AudioParamKey key, const std::string &condition, const std::string &value) override;
185 std::string GetAudioParameter(const AudioParamKey key, const std::string &condition) override;
186 void RegisterAudioSinkCallback(IAudioSinkCallback* callback) override;
187
188 void SetAudioMonoState(bool audioMono) override;
189 void SetAudioBalanceValue(float audioBalance) override;
190 int32_t GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec) override;
191
192 int32_t SetOutputRoutes(std::vector<DeviceType> &outputDevices) override;
193 int32_t SetOutputRoutes(std::vector<std::pair<DeviceType, AudioPortPin>> &outputDevices);
194
195 int32_t Preload(const std::string &usbInfoStr) override;
196
197 void ResetOutputRouteForDisconnect(DeviceType device) override;
198 float GetMaxAmplitude() override;
199 int32_t SetPaPower(int32_t flag) override;
200 int32_t SetPriPaPower() override;
201 int32_t GetRenderId(uint32_t &renderId) const override;
202
203 void SetAddress(const std::string &address) override;
204
205 int32_t UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],
206 const size_t size) final;
207 int32_t UpdateAppsUid(const std::vector<int32_t> &appsUid) final;
208
209 int32_t SetSinkMuteForSwitchDevice(bool mute) final;
210
211 std::string GetDPDeviceAttrInfo(const std::string &condition);
212 void WriterSmartPAStatusSysEvent(int32_t status);
213
214 explicit AudioRendererSinkInner(const std::string &halName = "primary");
215 ~AudioRendererSinkInner();
216 private:
217 IAudioSinkAttr attr_ = {};
218 bool sinkInited_ = false;
219 bool adapterInited_ = false;
220 bool renderInited_ = false;
221 bool started_ = false;
222 bool paused_ = false;
223 float leftVolume_ = 0.0f;
224 float rightVolume_ = 0.0f;
225 int32_t routeHandle_ = -1;
226 int32_t logMode_ = 0;
227 uint32_t openSpeaker_ = 0;
228 uint32_t renderId_ = 0;
229 uint32_t sinkId_ = 0;
230 std::string adapterNameCase_ = "";
231 struct IAudioManager *audioManager_ = nullptr;
232 struct IAudioAdapter *audioAdapter_ = nullptr;
233 struct IAudioRender *audioRender_ = nullptr;
234 IAudioSinkCallback *callback_ = nullptr;
235 const std::string halName_ = "";
236 struct AudioAdapterDescriptor adapterDesc_ = {};
237 struct AudioPort audioPort_ = {};
238 bool audioMonoState_ = false;
239 bool audioBalanceState_ = false;
240 float leftBalanceCoef_ = 1.0f;
241 float rightBalanceCoef_ = 1.0f;
242 // for get amplitude
243 float maxAmplitude_ = 0;
244 int64_t lastGetMaxAmplitudeTime_ = 0;
245 int64_t last10FrameStartTime_ = 0;
246 bool startUpdate_ = false;
247 int renderFrameNum_ = 0;
248 bool signalDetected_ = false;
249 size_t detectedTime_ = 0;
250 bool latencyMeasEnabled_ = false;
251 std::shared_ptr<SignalDetectAgent> signalDetectAgent_ = nullptr;
252 mutable int64_t volumeDataCount_ = 0;
253 std::string logUtilsTag_ = "";
254 time_t startTime = time(nullptr);
255 #ifdef FEATURE_POWER_MANAGER
256 std::shared_ptr<AudioRunningLockManager<PowerMgr::RunningLock>> runningLockManager_;
257 #endif
258 std::string audioAttrInfo_ = "";
259
260 // for device switch
261 std::mutex switchDeviceMutex_;
262 // for adapter_
263 std::mutex sinkMutex_;
264 int32_t muteCount_ = 0;
265 std::atomic<bool> switchDeviceMute_ = false;
266 AdapterType sinkType_ = ADAPTER_TYPE_PRIMARY;
267
268 // for sco recovery
269 bool hasAudioParamInfo_ = false;
270 AudioParamKey audioParamKey_ = AudioParamKey::NONE;
271 string audioParamCondition_ = "";
272 string audioParamValue_ = "";
273
274 private:
275 int32_t CreateRender(const struct AudioPort &renderPort);
276 int32_t InitAudioManager();
277 AudioFormat ConvertToHdiFormat(HdiAdapterFormat format);
278 void AdjustStereoToMono(char *data, uint64_t len);
279 void AdjustAudioBalance(char *data, uint64_t len);
280 void InitLatencyMeasurement();
281 void DeinitLatencyMeasurement();
282 void CheckLatencySignal(uint8_t *data, size_t len);
283
284 int32_t UpdateUsbAttrs(const std::string &usbInfoStr);
285 int32_t InitAdapter();
286 int32_t InitRender();
287 void ReleaseRunningLock();
288 void CheckUpdateState(char *frame, uint64_t replyBytes);
289
290 int32_t UpdateDPAttrs(const std::string &usbInfoStr);
291 bool AttributesCheck(AudioSampleAttributes &attrInfo);
292 int32_t SetAudioAttrInfo(AudioSampleAttributes &attrInfo);
293 std::string GetAudioAttrInfo();
294 int32_t GetCurDeviceParam(char *keyValueList, size_t len);
295
296 AudioPortPin GetAudioPortPin() const noexcept;
297 int32_t SetAudioRoute(DeviceType outputDevice, AudioRoute route);
298 int32_t SetAudioRouteInfoForEnhanceChain(const DeviceType &outputDevice);
299 void UpdateSinkState(bool started);
300
301 // use static because only register once for primary hal
302 static struct HdfRemoteService *hdfRemoteService_;
303 static struct HdfDeathRecipient *hdfDeathRecipient_;
304
305 FILE *dumpFile_ = nullptr;
306 std::string dumpFileName_ = "";
307 DeviceType currentActiveDevice_ = DEVICE_TYPE_NONE;
308 AudioScene currentAudioScene_ = AUDIO_SCENE_INVALID;
309 int32_t currentDevicesSize_ = 0;
310 std::string usbAddress_;
311 };
312
313 struct HdfRemoteService *AudioRendererSinkInner::hdfRemoteService_ = nullptr;
314 struct HdfDeathRecipient *AudioRendererSinkInner::hdfDeathRecipient_ = nullptr;
315
AudioRendererSinkInner(const std::string & halName)316 AudioRendererSinkInner::AudioRendererSinkInner(const std::string &halName)
317 : sinkInited_(false), adapterInited_(false), renderInited_(false), started_(false), paused_(false),
318 leftVolume_(DEFAULT_VOLUME_LEVEL), rightVolume_(DEFAULT_VOLUME_LEVEL), openSpeaker_(0),
319 audioManager_(nullptr), audioAdapter_(nullptr), audioRender_(nullptr), halName_(halName)
320 {
321 if (halName_ == DIRECT_HAL_NAME || halName_ == VOIP_HAL_NAME) {
322 sinkType_ = ADAPTER_TYPE_DIRECT;
323 }
324 }
325
~AudioRendererSinkInner()326 AudioRendererSinkInner::~AudioRendererSinkInner()
327 {
328 AUDIO_WARNING_LOG("~AudioRendererSinkInner");
329 AUDIO_INFO_LOG("[%{public}s] volume data counts: %{public}" PRId64, logUtilsTag_.c_str(), volumeDataCount_);
330 #ifdef FEATURE_POWER_MANAGER
331 if (runningLockManager_ != nullptr) {
332 AUDIO_INFO_LOG("~AudioRendererSinkInner unLock");
333 runningLockManager_->UnLock();
334 } else {
335 AUDIO_WARNING_LOG("runningLockManager is null, playback can not work well!");
336 }
337 #endif
338 AudioPerformanceMonitor::GetInstance().DeleteOvertimeMonitor(sinkType_);
339 }
340
GetInstance(std::string halName)341 AudioRendererSink *AudioRendererSink::GetInstance(std::string halName)
342 {
343 if (halName == "usb") {
344 static AudioRendererSinkInner audioRendererUsb(halName);
345 return &audioRendererUsb;
346 } else if (halName == "dp") {
347 static AudioRendererSinkInner audioRendererDp(halName);
348 return &audioRendererDp;
349 } else if (halName == VOIP_HAL_NAME) {
350 static AudioRendererSinkInner audioRendererVoip(halName);
351 return &audioRendererVoip;
352 } else if (halName == DIRECT_HAL_NAME) {
353 static AudioRendererSinkInner audioRendererDirect(halName);
354 return &audioRendererDirect;
355 }
356
357 static AudioRendererSinkInner audioRenderer;
358 return &audioRenderer;
359 }
360
SwitchAdapterRender(struct AudioAdapterDescriptor * descs,string adapterNameCase,enum AudioPortDirection portFlag,struct AudioPort & renderPort,uint32_t size)361 static int32_t SwitchAdapterRender(struct AudioAdapterDescriptor *descs, string adapterNameCase,
362 enum AudioPortDirection portFlag, struct AudioPort &renderPort, uint32_t size)
363 {
364 CHECK_AND_RETURN_RET(descs != nullptr, ERROR);
365 for (uint32_t index = 0; index < size; index++) {
366 struct AudioAdapterDescriptor *desc = &descs[index];
367 if (desc == nullptr || desc->adapterName == nullptr) {
368 continue;
369 }
370 AUDIO_INFO_LOG("size: %{public}d, adapterNameCase %{public}s, adapterName %{public}s",
371 size, adapterNameCase.c_str(), desc->adapterName);
372 if (!strcmp(desc->adapterName, adapterNameCase.c_str())) {
373 for (uint32_t port = 0; port < desc->portsLen; port++) {
374 // Only find out the port of out in the sound card
375 if (desc->ports[port].dir == portFlag) {
376 renderPort = desc->ports[port];
377 return index;
378 }
379 }
380 }
381 }
382 AUDIO_ERR_LOG("SwitchAdapterRender Fail");
383
384 return ERR_INVALID_INDEX;
385 }
386
SetAudioParameter(const AudioParamKey key,const std::string & condition,const std::string & value)387 void AudioRendererSinkInner::SetAudioParameter(const AudioParamKey key, const std::string &condition,
388 const std::string &value)
389 {
390 AUDIO_INFO_LOG("SetAudioParameter: key %{public}d, condition: %{public}s, value: %{public}s", key,
391 condition.c_str(), value.c_str());
392 AudioExtParamKey hdiKey = AudioExtParamKey(key);
393
394 // LCOV_EXCL_START
395 if (audioAdapter_ == nullptr) {
396 auto callerUid = IPCSkeleton::GetCallingUid();
397 AUDIO_ERR_LOG("audioAdapter_ is null, callerUid: %{public}d", callerUid);
398 CHECK_AND_RETURN_LOG(callerUid == UID_BLUETOOTH_SA && key == AudioParamKey::BT_WBS,
399 "Only allowed to set bt_wbs audio parameter when audioAdapter_ is null");
400 hasAudioParamInfo_ = true;
401 audioParamKey_ = key;
402 audioParamCondition_ = condition;
403 audioParamValue_ = value;
404 return;
405 }
406 // LCOV_EXCL_STOP
407
408 int32_t ret = audioAdapter_->SetExtraParams(audioAdapter_, hdiKey, condition.c_str(), value.c_str());
409 if (ret != SUCCESS) {
410 AUDIO_WARNING_LOG("SetAudioParameter failed, error code: %d", ret);
411 }
412 }
413
AttributesCheck(AudioSampleAttributes & attrInfo)414 bool AudioRendererSinkInner::AttributesCheck(AudioSampleAttributes &attrInfo)
415 {
416 CHECK_AND_RETURN_RET_LOG(attrInfo.sampleRate > 0, false, "rate failed %{public}d", attrInfo.sampleRate);
417 CHECK_AND_RETURN_RET_LOG(attrInfo.format > 0, false, "format failed %{public}d", attrInfo.format);
418 CHECK_AND_RETURN_RET_LOG(attrInfo.channelCount > 0, false, "channel failed %{public}d", attrInfo.channelCount);
419 return true;
420 }
421
SetAudioAttrInfo(AudioSampleAttributes & attrInfo)422 int32_t AudioRendererSinkInner::SetAudioAttrInfo(AudioSampleAttributes &attrInfo)
423 {
424 CHECK_AND_RETURN_RET_LOG(AttributesCheck(attrInfo), ERROR, "AttributesCheck failed");
425 uint32_t bufferSize = attrInfo.sampleRate * attrInfo.format * attrInfo.channelCount *
426 BUFFER_CALC_20MS / BUFFER_CALC_1000MS;
427 audioAttrInfo_ = "rate="+to_string(attrInfo.sampleRate)+" format=" + ParseAudioFormatToStr(attrInfo.format) +
428 " channels=" + to_string(attrInfo.channelCount) + " buffer_size="+to_string(bufferSize);
429 AUDIO_INFO_LOG("audio attributes %{public}s ", audioAttrInfo_.c_str());
430 return SUCCESS;
431 }
432
GetAudioAttrInfo()433 std::string AudioRendererSinkInner::GetAudioAttrInfo()
434 {
435 return audioAttrInfo_;
436 }
437
GetDPDeviceAttrInfo(const std::string & condition)438 std::string AudioRendererSinkInner::GetDPDeviceAttrInfo(const std::string &condition)
439 {
440 int32_t ret = UpdateDPAttrs(condition);
441 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "GetDPDeviceAttrInfo failed when init attr");
442
443 adapterNameCase_ = "dp";
444 ret = InitAdapter();
445 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "GetDPDeviceAttrInfo failed when init adapter");
446
447 ret = InitRender();
448 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "GetDPDeviceAttrInfo failed when init render");
449
450 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, "", "GetDPDeviceAttrInfo failed when audioRender_ is null");
451 struct AudioSampleAttributes attrInfo = {};
452 ret = audioRender_->GetSampleAttributes(audioRender_, &attrInfo);
453 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "GetDPDeviceAttrInfo failed when GetSampleAttributes");
454 AUDIO_DEBUG_LOG("GetSampleAttributes: sampleRate %{public}d, format: %{public}d, channelCount: %{public}d," \
455 "size: %{public}d", attrInfo.sampleRate, attrInfo.format, attrInfo.channelCount, attrInfo.frameSize);
456 ret = SetAudioAttrInfo(attrInfo);
457 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "SetAudioAttrInfo failed when SetAudioAttrInfo");
458
459 return GetAudioAttrInfo();
460 }
461
GetAudioParameter(const AudioParamKey key,const std::string & condition)462 std::string AudioRendererSinkInner::GetAudioParameter(const AudioParamKey key, const std::string &condition)
463 {
464 std::lock_guard<std::mutex> lock(sinkMutex_);
465 AUDIO_INFO_LOG("GetAudioParameter: key %{public}d, condition: %{public}s, halName: %{public}s",
466 key, condition.c_str(), halName_.c_str());
467 if (condition.starts_with("get_usb_info#C")) {
468 // Init adapter to get parameter before load sink module (need fix)
469 adapterNameCase_ = "usb";
470 int32_t ret = InitAdapter();
471 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "", "Init adapter failed for get usb info param");
472 }
473 if (key == AudioParamKey::GET_DP_DEVICE_INFO) {
474 // Init adapter and render to get parameter before load sink module (need fix)
475 return GetDPDeviceAttrInfo(condition);
476 }
477
478 AudioExtParamKey hdiKey = AudioExtParamKey(key);
479 char value[DumpFileUtil::PARAM_VALUE_LENTH];
480 CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, "", "GetAudioParameter failed, audioAdapter_ is null");
481 int32_t ret = audioAdapter_->GetExtraParams(audioAdapter_, hdiKey, condition.c_str(), value,
482 DumpFileUtil::PARAM_VALUE_LENTH);
483 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, "",
484 "GetAudioParameter failed, error code: %d", ret);
485
486 return value;
487 }
488
SetAudioMonoState(bool audioMono)489 void AudioRendererSinkInner::SetAudioMonoState(bool audioMono)
490 {
491 audioMonoState_ = audioMono;
492 }
493
SetAudioBalanceValue(float audioBalance)494 void AudioRendererSinkInner::SetAudioBalanceValue(float audioBalance)
495 {
496 // reset the balance coefficient value firstly
497 leftBalanceCoef_ = 1.0f;
498 rightBalanceCoef_ = 1.0f;
499
500 if (std::abs(audioBalance - 0.0f) <= std::numeric_limits<float>::epsilon()) {
501 // audioBalance is equal to 0.0f
502 audioBalanceState_ = false;
503 } else {
504 // audioBalance is not equal to 0.0f
505 audioBalanceState_ = true;
506 // calculate the balance coefficient
507 if (audioBalance > 0.0f) {
508 leftBalanceCoef_ -= audioBalance;
509 } else if (audioBalance < 0.0f) {
510 rightBalanceCoef_ += audioBalance;
511 }
512 }
513 }
514
GetPresentationPosition(uint64_t & frames,int64_t & timeSec,int64_t & timeNanoSec)515 int32_t AudioRendererSinkInner::GetPresentationPosition(uint64_t& frames, int64_t& timeSec, int64_t& timeNanoSec)
516 {
517 if (audioRender_ == nullptr) {
518 AUDIO_ERR_LOG("failed audioRender_ is NULL");
519 return ERR_INVALID_HANDLE;
520 }
521 struct AudioTimeStamp timestamp = {};
522 int32_t ret = audioRender_->GetRenderPosition(audioRender_, &frames, ×tamp);
523 if (ret != 0) {
524 AUDIO_ERR_LOG("GetRenderPosition from hdi failed");
525 return ERR_OPERATION_FAILED;
526 }
527 int64_t maxSec = 9223372036; // (9223372036 + 1) * 10^9 > INT64_MAX, seconds should not bigger than it;
528 if (timestamp.tvSec < 0 || timestamp.tvSec > maxSec || timestamp.tvNSec < 0 ||
529 timestamp.tvNSec > SECOND_TO_NANOSECOND) {
530 AUDIO_ERR_LOG(
531 "Hdi GetRenderPosition get invaild second:%{public}" PRIu64 " or nanosecond:%{public}" PRIu64 " !",
532 timestamp.tvSec, timestamp.tvNSec);
533 return ERR_OPERATION_FAILED;
534 }
535
536 timeSec = timestamp.tvSec;
537 timeNanoSec = timestamp.tvNSec;
538 return ret;
539 }
540
AdjustStereoToMono(char * data,uint64_t len)541 void AudioRendererSinkInner::AdjustStereoToMono(char *data, uint64_t len)
542 {
543 // only stereo is surpported now (stereo channel count is 2)
544 CHECK_AND_RETURN_LOG(attr_.channel == STEREO_CHANNEL_COUNT,
545 "AdjustStereoToMono: Unsupported channel number: %{public}d", attr_.channel);
546
547 switch (attr_.format) {
548 case SAMPLE_U8: {
549 AdjustStereoToMonoForPCM8Bit(reinterpret_cast<int8_t *>(data), len);
550 break;
551 }
552 case SAMPLE_S16: {
553 AdjustStereoToMonoForPCM16Bit(reinterpret_cast<int16_t *>(data), len);
554 break;
555 }
556 case SAMPLE_S24: {
557 AdjustStereoToMonoForPCM24Bit(reinterpret_cast<uint8_t *>(data), len);
558 break;
559 }
560 case SAMPLE_S32: {
561 AdjustStereoToMonoForPCM32Bit(reinterpret_cast<int32_t *>(data), len);
562 break;
563 }
564 default: {
565 // if the audio format is unsupported, the audio data will not be changed
566 AUDIO_ERR_LOG("AdjustStereoToMono: Unsupported audio format: %{public}d", attr_.format);
567 break;
568 }
569 }
570 }
571
AdjustAudioBalance(char * data,uint64_t len)572 void AudioRendererSinkInner::AdjustAudioBalance(char *data, uint64_t len)
573 {
574 // only stereo is surpported now (stereo channel count is 2)
575 CHECK_AND_RETURN_LOG(attr_.channel == STEREO_CHANNEL_COUNT,
576 "AdjustAudioBalance: Unsupported channel number: %{public}d", attr_.channel);
577
578 switch (attr_.format) {
579 case SAMPLE_U8: {
580 // this function needs to be further tested for usability
581 AdjustAudioBalanceForPCM8Bit(reinterpret_cast<int8_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
582 break;
583 }
584 case SAMPLE_S16LE: {
585 AdjustAudioBalanceForPCM16Bit(reinterpret_cast<int16_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
586 break;
587 }
588 case SAMPLE_S24LE: {
589 // this function needs to be further tested for usability
590 AdjustAudioBalanceForPCM24Bit(reinterpret_cast<uint8_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
591 break;
592 }
593 case SAMPLE_S32LE: {
594 AdjustAudioBalanceForPCM32Bit(reinterpret_cast<int32_t *>(data), len, leftBalanceCoef_, rightBalanceCoef_);
595 break;
596 }
597 default: {
598 // if the audio format is unsupported, the audio data will not be changed
599 AUDIO_ERR_LOG("AdjustAudioBalance: Unsupported audio format: %{public}d", attr_.format);
600 break;
601 }
602 }
603 }
604
IsInited()605 bool AudioRendererSinkInner::IsInited()
606 {
607 return sinkInited_;
608 }
609
RegisterAudioSinkCallback(IAudioSinkCallback * callback)610 void AudioRendererSinkInner::RegisterAudioSinkCallback(IAudioSinkCallback* callback)
611 {
612 std::lock_guard<std::mutex> lock(sinkMutex_);
613 if (callback_) {
614 AUDIO_INFO_LOG("AudioSinkCallback registered");
615 } else {
616 callback_ = callback;
617 AUDIO_INFO_LOG("Register AudioSinkCallback");
618 }
619 }
620
DeInit()621 void AudioRendererSinkInner::DeInit()
622 {
623 std::lock_guard<std::mutex> lock(sinkMutex_);
624 AUDIO_INFO_LOG("DeInit.");
625 started_ = false;
626 sinkInited_ = false;
627
628 if (audioAdapter_ != nullptr) {
629 AUDIO_INFO_LOG("DestroyRender rendererid: %{public}u", renderId_);
630 audioAdapter_->DestroyRender(audioAdapter_, renderId_);
631 }
632 audioRender_ = nullptr;
633 renderInited_ = false;
634
635 if (audioManager_ != nullptr) {
636 AUDIO_INFO_LOG("UnloadAdapter");
637 audioManager_->UnloadAdapter(audioManager_, adapterDesc_.adapterName);
638 }
639 audioAdapter_ = nullptr;
640 audioManager_ = nullptr;
641 adapterInited_ = false;
642 }
643
InitAttrs(struct AudioSampleAttributes & attrs)644 void InitAttrs(struct AudioSampleAttributes &attrs)
645 {
646 /* Initialization of audio parameters for playback */
647 attrs.channelCount = AUDIO_CHANNELCOUNT;
648 attrs.sampleRate = AUDIO_SAMPLE_RATE_48K;
649 attrs.interleaved = true;
650 attrs.streamId = static_cast<int32_t>(GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_PRIMARY));
651 attrs.type = AUDIO_IN_MEDIA;
652 attrs.period = DEEP_BUFFER_RENDER_PERIOD_SIZE;
653 attrs.isBigEndian = false;
654 attrs.isSignedData = true;
655 attrs.stopThreshold = INT_32_MAX;
656 attrs.silenceThreshold = 0;
657 }
658
InitAudioManager()659 int32_t AudioRendererSinkInner::InitAudioManager()
660 {
661 AUDIO_INFO_LOG("Initialize audio proxy manager");
662
663 audioManager_ = IAudioManagerGet(false);
664 CHECK_AND_RETURN_RET(audioManager_ != nullptr, ERR_INVALID_HANDLE);
665
666 // Only primary sink register death recipient once
667 if (halName_ == PRIMARY_HAL_NAME && hdfRemoteService_ == nullptr) {
668 AUDIO_INFO_LOG("Add death recipient for primary hdf");
669
670 hdfRemoteService_ = audioManager_->AsObject(audioManager_);
671 // Don't need to free, existing with process
672 hdfDeathRecipient_ = (struct HdfDeathRecipient *)calloc(1, sizeof(*hdfDeathRecipient_));
673 hdfDeathRecipient_->OnRemoteDied = AudioHostOnRemoteDied;
674
675 HdfRemoteServiceAddDeathRecipient(hdfRemoteService_, hdfDeathRecipient_);
676 }
677
678 return 0;
679 }
680
PcmFormatToBits(enum AudioFormat format)681 uint32_t PcmFormatToBits(enum AudioFormat format)
682 {
683 switch (format) {
684 case AUDIO_FORMAT_TYPE_PCM_8_BIT:
685 return PCM_8_BIT;
686 case AUDIO_FORMAT_TYPE_PCM_16_BIT:
687 return PCM_16_BIT;
688 case AUDIO_FORMAT_TYPE_PCM_24_BIT:
689 return PCM_24_BIT;
690 case AUDIO_FORMAT_TYPE_PCM_32_BIT:
691 return PCM_32_BIT;
692 default:
693 AUDIO_DEBUG_LOG("Unkown format type,set it to default");
694 return PCM_24_BIT;
695 }
696 }
697
ConvertToHdiFormat(HdiAdapterFormat format)698 AudioFormat AudioRendererSinkInner::ConvertToHdiFormat(HdiAdapterFormat format)
699 {
700 AudioFormat hdiFormat;
701 switch (format) {
702 case SAMPLE_U8:
703 hdiFormat = AUDIO_FORMAT_TYPE_PCM_8_BIT;
704 break;
705 case SAMPLE_S16:
706 hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
707 break;
708 case SAMPLE_S24:
709 hdiFormat = AUDIO_FORMAT_TYPE_PCM_24_BIT;
710 break;
711 case SAMPLE_S32:
712 hdiFormat = AUDIO_FORMAT_TYPE_PCM_32_BIT;
713 break;
714 default:
715 hdiFormat = AUDIO_FORMAT_TYPE_PCM_16_BIT;
716 break;
717 }
718
719 return hdiFormat;
720 }
721
CreateRender(const struct AudioPort & renderPort)722 int32_t AudioRendererSinkInner::CreateRender(const struct AudioPort &renderPort)
723 {
724 Trace trace("AudioRendererSinkInner::CreateRender");
725
726 struct AudioSampleAttributes param;
727 struct AudioDeviceDescriptor deviceDesc;
728 InitAttrs(param);
729 param.sampleRate = attr_.sampleRate;
730 param.channelCount = attr_.channel;
731 if (param.channelCount == MONO) {
732 param.channelLayout = CH_LAYOUT_MONO;
733 } else if (param.channelCount == STEREO) {
734 param.channelLayout = CH_LAYOUT_STEREO;
735 }
736 if (halName_ == "dp") {
737 param.type = AUDIO_DP;
738 } else if (halName_ == DIRECT_HAL_NAME) {
739 param.type = AUDIO_DIRECT;
740 param.streamId = static_cast<int32_t>(GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_DIRECT));
741 } else if (halName_ == VOIP_HAL_NAME) {
742 param.type = AUDIO_IN_COMMUNICATION;
743 param.streamId = static_cast<int32_t>(GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_VOIP));
744 }
745 param.format = ConvertToHdiFormat(attr_.format);
746 param.frameSize = PcmFormatToBits(param.format) * param.channelCount / PCM_8_BIT;
747 param.startThreshold = DEEP_BUFFER_RENDER_PERIOD_SIZE / (param.frameSize);
748 deviceDesc.portId = renderPort.portId;
749 std::string desc = halName_ == USB_HAL_NAME ? usbAddress_ : attr_.address;
750 deviceDesc.desc = const_cast<char*>(desc.c_str());
751 deviceDesc.pins = PIN_OUT_SPEAKER;
752 if (halName_ == "usb") {
753 deviceDesc.pins = PIN_OUT_USB_HEADSET;
754 } else if (halName_ == "dp") {
755 deviceDesc.pins = PIN_OUT_DP;
756 } else {
757 deviceDesc.pins = GetAudioPortPin();
758 }
759
760 AUDIO_INFO_LOG("Create render sinkName:%{public}s, rate:%{public}u channel:%{public}u format:%{public}u, " \
761 "devicePin:%{public}u desc:%{public}s",
762 halName_.c_str(), param.sampleRate, param.channelCount, param.format, deviceDesc.pins, deviceDesc.desc);
763 CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, ERR_INVALID_HANDLE,
764 "CreateRender failed, audioAdapter_ is null");
765 int32_t ret = audioAdapter_->CreateRender(audioAdapter_, &deviceDesc, ¶m, &audioRender_, &renderId_);
766 if (ret != 0 || audioRender_ == nullptr) {
767 AUDIO_ERR_LOG("AudioDeviceCreateRender failed.");
768 audioManager_->UnloadAdapter(audioManager_, adapterDesc_.adapterName);
769 adapterInited_ = false;
770 return ERR_NOT_STARTED;
771 }
772 AUDIO_INFO_LOG("Create success rendererid: %{public}u desc: %{public}s", renderId_, deviceDesc.desc);
773
774 return 0;
775 }
776
Init(const IAudioSinkAttr & attr)777 int32_t AudioRendererSinkInner::Init(const IAudioSinkAttr &attr)
778 {
779 std::lock_guard<std::mutex> lock(sinkMutex_);
780 attr_ = attr;
781 adapterNameCase_ = attr_.adapterName;
782 AUDIO_INFO_LOG("adapterNameCase_ :%{public}s", adapterNameCase_.c_str());
783 openSpeaker_ = attr_.openMicSpeaker;
784 logMode_ = system::GetIntParameter("persist.multimedia.audiolog.switch", 0);
785 Trace trace("AudioRendererSinkInner::Init " + adapterNameCase_);
786
787 int32_t ret = InitAdapter();
788 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Init adapter failed");
789
790 ret = InitRender();
791 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Init render failed");
792
793 sinkInited_ = true;
794 GetRenderId(sinkId_);
795
796 return SUCCESS;
797 }
798
RenderFrame(char & data,uint64_t len,uint64_t & writeLen)799 int32_t AudioRendererSinkInner::RenderFrame(char &data, uint64_t len, uint64_t &writeLen)
800 {
801 int64_t stamp = ClockTime::GetCurNano();
802 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
803 "Audio Render Handle is nullptr!");
804
805 if (!started_) {
806 AUDIO_WARNING_LOG("AudioRendererSinkInner::RenderFrame invalid state! not started");
807 }
808
809 if (audioMonoState_) {AdjustStereoToMono(&data, len);}
810
811 if (audioBalanceState_) {AdjustAudioBalance(&data, len);}
812
813 CheckUpdateState(&data, len);
814
815 if (switchDeviceMute_) {
816 Trace traceEmpty("AudioRendererSinkInner::RenderFrame::renderEmpty");
817 if (memset_s(reinterpret_cast<void*>(&data), static_cast<size_t>(len), 0,
818 static_cast<size_t>(len)) != EOK) {
819 AUDIO_WARNING_LOG("call memset_s failed");
820 }
821 }
822
823 CheckLatencySignal(reinterpret_cast<uint8_t*>(&data), len);
824
825 BufferDesc buffer = { reinterpret_cast<uint8_t*>(&data), len, len };
826 AudioStreamInfo streamInfo(static_cast<AudioSamplingRate>(attr_.sampleRate), AudioEncodingType::ENCODING_PCM,
827 static_cast<AudioSampleFormat>(attr_.format), static_cast<AudioChannel>(attr_.channel));
828 VolumeTools::DfxOperation(buffer, streamInfo, logUtilsTag_, volumeDataCount_);
829 if (AudioDump::GetInstance().GetVersionType() == DumpFileUtil::BETA_VERSION) {
830 DumpFileUtil::WriteDumpFile(dumpFile_, static_cast<void *>(&data), len);
831 AudioCacheMgr::GetInstance().CacheData(dumpFileName_, static_cast<void *>(&data), len);
832 }
833
834 Trace traceRenderFrame("AudioRendererSinkInner::RenderFrame");
835 int32_t ret = audioRender_->RenderFrame(audioRender_, reinterpret_cast<int8_t*>(&data), static_cast<uint32_t>(len),
836 &writeLen);
837 AudioPerformanceMonitor::GetInstance().RecordTimeStamp(sinkType_, ClockTime::GetCurNano());
838
839 CHECK_AND_RETURN_RET_LOG(ret == 0, ERR_WRITE_FAILED, "RenderFrame failed ret: %{public}x", ret);
840
841 stamp = (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND;
842 int64_t stampThreshold = 50; // 50ms
843 if (logMode_ || stamp >= stampThreshold) {
844 AUDIO_WARNING_LOG("RenderFrame len[%{public}" PRIu64 "] cost[%{public}" PRId64 "]ms", len, stamp);
845 }
846
847 #ifdef FEATURE_POWER_MANAGER
848 if (runningLockManager_) {
849 runningLockManager_->UpdateAppsUidToPowerMgr();
850 }
851 #endif
852
853 return SUCCESS;
854 }
855
CheckUpdateState(char * frame,uint64_t replyBytes)856 void AudioRendererSinkInner::CheckUpdateState(char *frame, uint64_t replyBytes)
857 {
858 if (startUpdate_) {
859 if (renderFrameNum_ == 0) {
860 last10FrameStartTime_ = ClockTime::GetCurNano();
861 }
862 renderFrameNum_++;
863 maxAmplitude_ = UpdateMaxAmplitude(static_cast<ConvertHdiFormat>(attr_.format), frame, replyBytes);
864 if (renderFrameNum_ == GET_MAX_AMPLITUDE_FRAMES_THRESHOLD) {
865 renderFrameNum_ = 0;
866 if (last10FrameStartTime_ > lastGetMaxAmplitudeTime_) {
867 startUpdate_ = false;
868 maxAmplitude_ = 0;
869 }
870 }
871 }
872 }
873
GetMaxAmplitude()874 float AudioRendererSinkInner::GetMaxAmplitude()
875 {
876 lastGetMaxAmplitudeTime_ = ClockTime::GetCurNano();
877 startUpdate_ = true;
878 return maxAmplitude_;
879 }
880
Start(void)881 int32_t AudioRendererSinkInner::Start(void)
882 {
883 std::lock_guard<std::mutex> lock(sinkMutex_);
884 AUDIO_INFO_LOG("sinkName %{public}s, sinkId %{public}u", halName_.c_str(), sinkId_);
885
886 Trace trace("AudioRendererSinkInner::Start");
887 #ifdef FEATURE_POWER_MANAGER
888 AudioXCollie audioXCollie("AudioRendererSinkInner::CreateRunningLock", TIME_OUT_SECONDS);
889 std::shared_ptr<PowerMgr::RunningLock> keepRunningLock;
890 if (runningLockManager_ == nullptr) {
891 std::string lockName = PRIMARY_LOCK_NAME_BASE + halName_;
892 WatchTimeout guard("PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock:Start");
893 keepRunningLock = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock(
894 lockName, PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO);
895 guard.CheckCurrTimeout();
896 if (keepRunningLock) {
897 runningLockManager_ = std::make_shared<AudioRunningLockManager<PowerMgr::RunningLock>> (keepRunningLock);
898 }
899 }
900 if (runningLockManager_ != nullptr) {
901 AUDIO_INFO_LOG("keepRunningLock lock result: %{public}d",
902 runningLockManager_->Lock(RUNNINGLOCK_LOCK_TIMEOUTMS_LASTING)); // -1 for lasting.
903 } else {
904 AUDIO_WARNING_LOG("keepRunningLock is null, playback can not work well!");
905 }
906 audioXCollie.CancelXCollieTimer();
907 #endif
908 dumpFileName_ = halName_ + "_audiosink_" + GetTime() + "_" + std::to_string(attr_.sampleRate) + "_"
909 + std::to_string(attr_.channel) + "_" + std::to_string(attr_.format) + ".pcm";
910 DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileName_, &dumpFile_);
911 logUtilsTag_ = "AudioSink" + halName_;
912
913 InitLatencyMeasurement();
914 if (!started_) {
915 int32_t ret = audioRender_->Start(audioRender_);
916 if (ret != SUCCESS) {
917 AUDIO_ERR_LOG("Start failed!");
918 return ERR_NOT_STARTED;
919 }
920 UpdateSinkState(true);
921 started_ = true;
922 }
923 AudioPerformanceMonitor::GetInstance().RecordTimeStamp(sinkType_, INIT_LASTWRITTEN_TIME);
924 return SUCCESS;
925 }
926
SetVolume(float left,float right)927 int32_t AudioRendererSinkInner::SetVolume(float left, float right)
928 {
929 float volume;
930
931 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
932 "SetVolume failed audioRender_ null");
933 if (halName_ == VOIP_HAL_NAME && switchDeviceMute_ && (abs(left) > FLOAT_EPS || abs(right) > FLOAT_EPS)) {
934 AUDIO_ERR_LOG("Direct voip scene. No need to set volume when switch device and volume is 0");
935 leftVolume_ = left;
936 rightVolume_ = right;
937 return ERR_INVALID_HANDLE;
938 }
939
940 leftVolume_ = left;
941 rightVolume_ = right;
942 if ((abs(leftVolume_) < FLOAT_EPS) && (abs(rightVolume_) > FLOAT_EPS)) {
943 volume = rightVolume_;
944 } else if ((abs(leftVolume_) > FLOAT_EPS) && (abs(rightVolume_) < FLOAT_EPS)) {
945 volume = leftVolume_;
946 } else {
947 volume = (leftVolume_ + rightVolume_) / HALF_FACTOR;
948 }
949
950 int32_t ret = audioRender_->SetVolume(audioRender_, volume);
951 if (ret) {
952 AUDIO_WARNING_LOG("Set volume failed!");
953 }
954
955 return ret;
956 }
957
GetVolume(float & left,float & right)958 int32_t AudioRendererSinkInner::GetVolume(float &left, float &right)
959 {
960 left = leftVolume_;
961 right = rightVolume_;
962 return SUCCESS;
963 }
964
SetVoiceVolume(float volume)965 int32_t AudioRendererSinkInner::SetVoiceVolume(float volume)
966 {
967 Trace trace("AudioRendererSinkInner::SetVoiceVolume");
968 CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, ERR_INVALID_HANDLE,
969 "SetVoiceVolume failed, audioAdapter_ is null");
970 AUDIO_INFO_LOG("Set modem call volume %{public}f", volume);
971 return audioAdapter_->SetVoiceVolume(audioAdapter_, volume);
972 }
973
GetLatency(uint32_t * latency)974 int32_t AudioRendererSinkInner::GetLatency(uint32_t *latency)
975 {
976 Trace trace("AudioRendererSinkInner::GetLatency");
977 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
978 "GetLatency failed audio render null");
979
980 CHECK_AND_RETURN_RET_LOG(latency, ERR_INVALID_PARAM,
981 "GetLatency failed latency null");
982
983 uint32_t hdiLatency;
984 if (audioRender_->GetLatency(audioRender_, &hdiLatency) == 0) {
985 *latency = hdiLatency;
986 return SUCCESS;
987 } else {
988 return ERR_OPERATION_FAILED;
989 }
990 }
991
GetAudioCategory(AudioScene audioScene)992 static AudioCategory GetAudioCategory(AudioScene audioScene)
993 {
994 AudioCategory audioCategory;
995 switch (audioScene) {
996 case AUDIO_SCENE_DEFAULT:
997 audioCategory = AUDIO_IN_MEDIA;
998 break;
999 case AUDIO_SCENE_RINGING:
1000 case AUDIO_SCENE_VOICE_RINGING:
1001 audioCategory = AUDIO_IN_RINGTONE;
1002 break;
1003 case AUDIO_SCENE_PHONE_CALL:
1004 audioCategory = AUDIO_IN_CALL;
1005 break;
1006 case AUDIO_SCENE_PHONE_CHAT:
1007 audioCategory = AUDIO_IN_COMMUNICATION;
1008 break;
1009 default:
1010 audioCategory = AUDIO_IN_MEDIA;
1011 break;
1012 }
1013 AUDIO_DEBUG_LOG("Audio category returned is: %{public}d", audioCategory);
1014
1015 return audioCategory;
1016 }
1017
GetAudioPortPin() const1018 AudioPortPin AudioRendererSinkInner::GetAudioPortPin() const noexcept
1019 {
1020 switch (attr_.deviceType) {
1021 case DEVICE_TYPE_EARPIECE:
1022 return PIN_OUT_EARPIECE;
1023 case DEVICE_TYPE_SPEAKER:
1024 return PIN_OUT_SPEAKER;
1025 case DEVICE_TYPE_WIRED_HEADSET:
1026 return PIN_OUT_HEADSET;
1027 case DEVICE_TYPE_WIRED_HEADPHONES:
1028 return PIN_OUT_HEADPHONE;
1029 case DEVICE_TYPE_BLUETOOTH_SCO:
1030 return PIN_OUT_BLUETOOTH_SCO;
1031 case DEVICE_TYPE_USB_HEADSET:
1032 return PIN_OUT_USB_EXT;
1033 case DEVICE_TYPE_HDMI:
1034 return PIN_OUT_HDMI;
1035 case DEVICE_TYPE_NONE:
1036 return PIN_NONE;
1037 default:
1038 return PIN_OUT_SPEAKER;
1039 }
1040 }
1041
SetOutputPortPin(DeviceType outputDevice,AudioRouteNode & sink)1042 static int32_t SetOutputPortPin(DeviceType outputDevice, AudioRouteNode &sink)
1043 {
1044 int32_t ret = SUCCESS;
1045
1046 switch (outputDevice) {
1047 case DEVICE_TYPE_EARPIECE:
1048 sink.ext.device.type = PIN_OUT_EARPIECE;
1049 sink.ext.device.desc = (char *)"pin_out_earpiece";
1050 break;
1051 case DEVICE_TYPE_SPEAKER:
1052 sink.ext.device.type = PIN_OUT_SPEAKER;
1053 sink.ext.device.desc = (char *)"pin_out_speaker";
1054 break;
1055 case DEVICE_TYPE_WIRED_HEADSET:
1056 sink.ext.device.type = PIN_OUT_HEADSET;
1057 sink.ext.device.desc = (char *)"pin_out_headset";
1058 break;
1059 case DEVICE_TYPE_USB_ARM_HEADSET:
1060 sink.ext.device.type = PIN_OUT_USB_HEADSET;
1061 sink.ext.device.desc = (char *)"pin_out_usb_headset";
1062 break;
1063 case DEVICE_TYPE_USB_HEADSET:
1064 sink.ext.device.type = PIN_OUT_USB_EXT;
1065 sink.ext.device.desc = (char *)"pin_out_usb_ext";
1066 break;
1067 case DEVICE_TYPE_BLUETOOTH_SCO:
1068 sink.ext.device.type = PIN_OUT_BLUETOOTH_SCO;
1069 sink.ext.device.desc = (char *)"pin_out_bluetooth_sco";
1070 break;
1071 case DEVICE_TYPE_BLUETOOTH_A2DP:
1072 sink.ext.device.type = PIN_OUT_BLUETOOTH_A2DP;
1073 sink.ext.device.desc = (char *)"pin_out_bluetooth_a2dp";
1074 break;
1075 case DEVICE_TYPE_HDMI:
1076 sink.ext.device.type = PIN_OUT_HDMI;
1077 sink.ext.device.desc = (char *)"pin_out_hdmi";
1078 break;
1079 case DEVICE_TYPE_NONE:
1080 sink.ext.device.type = PIN_NONE;
1081 sink.ext.device.desc = (char *)"pin_out_none";
1082 break;
1083 default:
1084 ret = ERR_NOT_SUPPORTED;
1085 break;
1086 }
1087
1088 return ret;
1089 }
1090
SetAudioRoute(DeviceType outputDevice,AudioRoute route)1091 int32_t AudioRendererSinkInner::SetAudioRoute(DeviceType outputDevice, AudioRoute route)
1092 {
1093 int64_t stamp = ClockTime::GetCurNano();
1094 CHECK_AND_RETURN_RET_LOG(audioAdapter_ != nullptr, ERR_INVALID_HANDLE, "SetOutputRoutes failed with null adapter");
1095 int32_t ret = audioAdapter_->UpdateAudioRoute(audioAdapter_, &route, &routeHandle_);
1096 stamp = (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND;
1097 AUDIO_WARNING_LOG("deviceType : %{public}d UpdateAudioRoute cost[%{public}" PRId64 "]ms", outputDevice, stamp);
1098 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "UpdateAudioRoute failed");
1099
1100 return SUCCESS;
1101 }
1102
SetOutputRoutes(std::vector<DeviceType> & outputDevices)1103 int32_t AudioRendererSinkInner::SetOutputRoutes(std::vector<DeviceType> &outputDevices)
1104 {
1105 CHECK_AND_RETURN_RET_LOG(!outputDevices.empty() && outputDevices.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT,
1106 ERR_INVALID_PARAM, "Invalid audio devices.");
1107 DeviceType outputDevice = outputDevices.front();
1108 if (outputDevice == currentActiveDevice_ &&
1109 outputDevices.size() == static_cast<uint32_t>(currentDevicesSize_)) {
1110 AUDIO_INFO_LOG("SetOutputRoutes output device not change, type:%{public}d", outputDevice);
1111 return SUCCESS;
1112 }
1113 AudioPortPin outputPortPin = GetAudioPortPin();
1114 std::vector<std::pair<DeviceType, AudioPortPin>> outputDevicesPortPin = {};
1115 for (size_t i = 0; i < outputDevices.size(); i++) {
1116 outputDevicesPortPin.push_back(std::make_pair(outputDevices[i], outputPortPin));
1117 }
1118 return SetOutputRoutes(outputDevicesPortPin);
1119 }
1120
SetOutputRoutes(std::vector<std::pair<DeviceType,AudioPortPin>> & outputDevices)1121 int32_t AudioRendererSinkInner::SetOutputRoutes(std::vector<std::pair<DeviceType, AudioPortPin>> &outputDevices)
1122 {
1123 CHECK_AND_RETURN_RET_LOG(!outputDevices.empty() && outputDevices.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT,
1124 ERR_INVALID_PARAM, "Invalid audio devices.");
1125 DeviceType outputDevice = outputDevices.front().first;
1126 AudioPortPin outputPortPin = outputDevices.front().second;
1127 Trace trace("AudioRendererSinkInner::SetOutputRoutes pin " + std::to_string(outputPortPin) + " device " +
1128 std::to_string(outputDevice));
1129 currentActiveDevice_ = outputDevice;
1130 currentDevicesSize_ = static_cast<int32_t>(outputDevices.size());
1131 SetAudioRouteInfoForEnhanceChain(currentActiveDevice_);
1132
1133 AudioRouteNode source = {};
1134 source.portId = static_cast<int32_t>(0);
1135 source.role = AUDIO_PORT_SOURCE_ROLE;
1136 source.type = AUDIO_PORT_MIX_TYPE;
1137 source.ext.mix.moduleId = static_cast<int32_t>(0);
1138 source.ext.mix.streamId = static_cast<int32_t>(
1139 GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_PRIMARY));
1140 source.ext.device.desc = (char *)"";
1141
1142 int32_t sinksSize = static_cast<int32_t>(outputDevices.size());
1143 AudioRouteNode* sinks = new AudioRouteNode[sinksSize];
1144
1145 for (size_t i = 0; i < outputDevices.size(); i++) {
1146 int32_t ret = SetOutputPortPin(outputDevices[i].first, sinks[i]);
1147 if (ret != SUCCESS) {
1148 delete [] sinks;
1149 AUDIO_ERR_LOG("SetOutputRoutes FAILED: %{public}d", ret);
1150 return ret;
1151 }
1152 outputDevices[i].second = sinks[i].ext.device.type;
1153 AUDIO_INFO_LOG("Output[%{public}zu] PIN is: 0x%{public}X DeviceType is %{public}d", i, outputDevices[i].second,
1154 outputDevices[i].first);
1155 sinks[i].portId = static_cast<int32_t>(audioPort_.portId);
1156 sinks[i].role = AUDIO_PORT_SINK_ROLE;
1157 sinks[i].type = AUDIO_PORT_DEVICE_TYPE;
1158 sinks[i].ext.device.moduleId = static_cast<int32_t>(0);
1159 sinks[i].ext.device.desc = (char *)"";
1160 }
1161
1162 AudioRoute route = {};
1163 route.sources = &source;
1164 route.sourcesLen = 1;
1165 route.sinks = sinks;
1166 route.sinksLen = static_cast<uint32_t>(sinksSize);
1167
1168 int32_t result = SetAudioRoute(outputDevice, route);
1169 if (sinks != nullptr) {
1170 delete [] sinks;
1171 sinks = nullptr;
1172 }
1173 return result;
1174 }
1175
GetAudioScene()1176 int32_t AudioRendererSinkInner::GetAudioScene()
1177 {
1178 return currentAudioScene_;
1179 }
1180
SetAudioScene(AudioScene audioScene,std::vector<DeviceType> & activeDevices)1181 int32_t AudioRendererSinkInner::SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeDevices)
1182 {
1183 CHECK_AND_RETURN_RET_LOG(!activeDevices.empty() && activeDevices.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT,
1184 ERR_INVALID_PARAM, "Invalid audio devices.");
1185 DeviceType activeDevice = activeDevices.front();
1186 CHECK_AND_RETURN_RET_LOG(audioScene >= AUDIO_SCENE_DEFAULT && audioScene < AUDIO_SCENE_MAX,
1187 ERR_INVALID_PARAM, "invalid audioScene");
1188 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
1189 "SetAudioScene failed audio render handle is null!");
1190 if (openSpeaker_) {
1191 AudioPortPin audioSceneOutPort = GetAudioPortPin();
1192 if (halName_ == "usb") {
1193 audioSceneOutPort = PIN_OUT_USB_HEADSET;
1194 } else if (halName_ == "dp") {
1195 audioSceneOutPort = PIN_OUT_DP;
1196 }
1197 AUDIO_DEBUG_LOG("OUTPUT port is %{public}d", audioSceneOutPort);
1198 bool isAudioSceneUpdate = false;
1199 if (audioScene != currentAudioScene_) {
1200 struct AudioSceneDescriptor scene;
1201 scene.scene.id = GetAudioCategory(audioScene);
1202 if (halName_ == DIRECT_HAL_NAME) {
1203 scene.scene.id = AUDIO_DIRECT;
1204 } else if (halName_ == VOIP_HAL_NAME) {
1205 scene.scene.id = AUDIO_IN_COMMUNICATION;
1206 }
1207 scene.desc.pins = audioSceneOutPort;
1208 scene.desc.desc = const_cast<char *>("");
1209 int32_t ret = audioRender_->SelectScene(audioRender_, &scene);
1210 CHECK_AND_RETURN_RET_LOG(ret >= 0, ERR_OPERATION_FAILED,
1211 "Select scene FAILED: %{public}d", ret);
1212 AUDIO_WARNING_LOG("scene: %{public}d, device: %{public}d", audioScene, activeDevice);
1213 currentAudioScene_ = audioScene;
1214 isAudioSceneUpdate = true;
1215 }
1216 if (activeDevices.size() != static_cast<size_t>(currentDevicesSize_) || activeDevice != currentActiveDevice_ ||
1217 (isAudioSceneUpdate &&
1218 (currentAudioScene_ == AUDIO_SCENE_PHONE_CALL || currentAudioScene_ == AUDIO_SCENE_PHONE_CHAT))) {
1219 std::vector<std::pair<DeviceType, AudioPortPin>> activeDevicesPortPin = {};
1220 for (auto device : activeDevices) {
1221 activeDevicesPortPin.push_back(std::make_pair(device, audioSceneOutPort));
1222 }
1223 int32_t ret = SetOutputRoutes(activeDevicesPortPin);
1224 if (ret < 0) {
1225 AUDIO_ERR_LOG("Update route FAILED: %{public}d", ret);
1226 }
1227 currentDevicesSize_ = static_cast<int32_t>(activeDevices.size());
1228 }
1229 }
1230 return SUCCESS;
1231 }
1232
GetTransactionId(uint64_t * transactionId)1233 int32_t AudioRendererSinkInner::GetTransactionId(uint64_t *transactionId)
1234 {
1235 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
1236 "GetTransactionId failed audio render null");
1237 CHECK_AND_RETURN_RET_LOG(transactionId, ERR_INVALID_PARAM,
1238 "GetTransactionId failed transactionId null");
1239
1240 *transactionId = reinterpret_cast<uint64_t>(audioRender_);
1241 return SUCCESS;
1242 }
1243
ReleaseRunningLock()1244 void AudioRendererSinkInner::ReleaseRunningLock()
1245 {
1246 #ifdef FEATURE_POWER_MANAGER
1247 if (runningLockManager_ != nullptr) {
1248 AUDIO_INFO_LOG("keepRunningLock unLock");
1249 std::thread runningLockThread([this] {
1250 runningLockManager_->UnLock();
1251 });
1252 runningLockThread.join();
1253 } else {
1254 AUDIO_WARNING_LOG("keepRunningLock is null, playback can not work well!");
1255 }
1256 #endif
1257 }
1258
Stop(void)1259 int32_t AudioRendererSinkInner::Stop(void)
1260 {
1261 std::lock_guard<std::mutex> lock(sinkMutex_);
1262 AUDIO_INFO_LOG("sinkName %{public}s, sinkId %{public}u", halName_.c_str(), sinkId_);
1263
1264 Trace trace("AudioRendererSinkInner::Stop");
1265
1266 DeinitLatencyMeasurement();
1267
1268 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
1269 "Stop failed audioRender_ null");
1270
1271 if (!started_) {
1272 return SUCCESS;
1273 }
1274
1275 if (halName_ == PRIMARY_HAL_NAME) {
1276 const char keyValueList[] = "primary=stop";
1277 if (audioRender_->SetExtraParams(audioRender_, keyValueList) == 0) {
1278 AUDIO_INFO_LOG("set primary stream stop info to hal");
1279 }
1280 }
1281
1282 int32_t ret = audioRender_->Stop(audioRender_);
1283 UpdateSinkState(false);
1284 if (ret != SUCCESS) {
1285 AUDIO_ERR_LOG("Stop failed!");
1286 return ERR_OPERATION_FAILED;
1287 }
1288 started_ = false;
1289
1290 DumpFileUtil::CloseDumpFile(&dumpFile_);
1291
1292 return SUCCESS;
1293 }
1294
Pause(void)1295 int32_t AudioRendererSinkInner::Pause(void)
1296 {
1297 std::lock_guard<std::mutex> lock(sinkMutex_);
1298 AUDIO_INFO_LOG("sinkName %{public}s", halName_.c_str());
1299
1300 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
1301 "Pause failed audioRender_ null");
1302 CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED,
1303 "Pause invalid state!");
1304
1305 if (!paused_) {
1306 int32_t ret = audioRender_->Pause(audioRender_);
1307 if (!ret) {
1308 paused_ = true;
1309 return SUCCESS;
1310 } else {
1311 AUDIO_ERR_LOG("Pause failed!");
1312 return ERR_OPERATION_FAILED;
1313 }
1314 }
1315
1316 return SUCCESS;
1317 }
1318
Resume(void)1319 int32_t AudioRendererSinkInner::Resume(void)
1320 {
1321 std::lock_guard<std::mutex> lock(sinkMutex_);
1322 AUDIO_INFO_LOG("sinkName %{public}s", halName_.c_str());
1323
1324 CHECK_AND_RETURN_RET_LOG(audioRender_ != nullptr, ERR_INVALID_HANDLE,
1325 "Resume failed audioRender_ null");
1326 CHECK_AND_RETURN_RET_LOG(started_, ERR_OPERATION_FAILED,
1327 "Resume invalid state!");
1328
1329 if (paused_) {
1330 int32_t ret = audioRender_->Resume(audioRender_);
1331 if (!ret) {
1332 paused_ = false;
1333 return SUCCESS;
1334 } else {
1335 AUDIO_ERR_LOG("Resume failed!");
1336 return ERR_OPERATION_FAILED;
1337 }
1338 }
1339 AudioPerformanceMonitor::GetInstance().RecordTimeStamp(sinkType_, INIT_LASTWRITTEN_TIME);
1340 return SUCCESS;
1341 }
1342
Reset(void)1343 int32_t AudioRendererSinkInner::Reset(void)
1344 {
1345 AUDIO_INFO_LOG("sinkName %{public}s", halName_.c_str());
1346
1347 if (started_ && audioRender_ != nullptr) {
1348 int32_t ret = audioRender_->Flush(audioRender_);
1349 if (!ret) {
1350 return SUCCESS;
1351 } else {
1352 AUDIO_ERR_LOG("Reset failed!");
1353 return ERR_OPERATION_FAILED;
1354 }
1355 }
1356
1357 return ERR_OPERATION_FAILED;
1358 }
1359
Flush(void)1360 int32_t AudioRendererSinkInner::Flush(void)
1361 {
1362 AUDIO_INFO_LOG("sinkName %{public}s", halName_.c_str());
1363
1364 if (started_ && audioRender_ != nullptr) {
1365 int32_t ret = audioRender_->Flush(audioRender_);
1366 if (!ret) {
1367 return SUCCESS;
1368 } else {
1369 AUDIO_ERR_LOG("Flush failed!");
1370 return ERR_OPERATION_FAILED;
1371 }
1372 }
1373
1374 return ERR_OPERATION_FAILED;
1375 }
1376
SuspendRenderSink(void)1377 int32_t AudioRendererSinkInner::SuspendRenderSink(void)
1378 {
1379 return SUCCESS;
1380 }
1381
RestoreRenderSink(void)1382 int32_t AudioRendererSinkInner::RestoreRenderSink(void)
1383 {
1384 return SUCCESS;
1385 }
1386
Preload(const std::string & usbInfoStr)1387 int32_t AudioRendererSinkInner::Preload(const std::string &usbInfoStr)
1388 {
1389 CHECK_AND_RETURN_RET_LOG(halName_ == "usb", ERR_INVALID_OPERATION, "Preload only supported for usb");
1390
1391 int32_t ret = UpdateUsbAttrs(usbInfoStr);
1392 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Preload failed when init attr");
1393
1394 ret = InitAdapter();
1395 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Preload failed when init adapter");
1396
1397 ret = InitRender();
1398 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Preload failed when init render");
1399
1400 return SUCCESS;
1401 }
1402
UpdateUsbAttrs(const std::string & usbInfoStr)1403 int32_t AudioRendererSinkInner::UpdateUsbAttrs(const std::string &usbInfoStr)
1404 {
1405 CHECK_AND_RETURN_RET_LOG(usbInfoStr != "", ERR_INVALID_PARAM, "usb info string error");
1406
1407 auto sinkRate_begin = usbInfoStr.find("sink_rate:");
1408 auto sinkRate_end = usbInfoStr.find_first_of(";", sinkRate_begin);
1409 std::string sampleRateStr = usbInfoStr.substr(sinkRate_begin + std::strlen("sink_rate:"),
1410 sinkRate_end - sinkRate_begin - std::strlen("sink_rate:"));
1411 auto sinkFormat_begin = usbInfoStr.find("sink_format:");
1412 auto sinkFormat_end = usbInfoStr.find_first_of(";", sinkFormat_begin);
1413 std::string formatStr = usbInfoStr.substr(sinkFormat_begin + std::strlen("sink_format:"),
1414 sinkFormat_end - sinkFormat_begin - std::strlen("sink_format:"));
1415
1416 // usb default config
1417 CHECK_AND_RETURN_RET_LOG(StringConverter(sampleRateStr, attr_.sampleRate), ERR_INVALID_PARAM,
1418 "convert invalid sampleRate: %{public}s", sampleRateStr.c_str());
1419 attr_.channel = STEREO_CHANNEL_COUNT;
1420 attr_.format = ParseAudioFormat(formatStr);
1421
1422 adapterNameCase_ = "usb";
1423 openSpeaker_ = 0;
1424
1425 return SUCCESS;
1426 }
1427
UpdateDPAttrs(const std::string & dpInfoStr)1428 int32_t AudioRendererSinkInner::UpdateDPAttrs(const std::string &dpInfoStr)
1429 {
1430 CHECK_AND_RETURN_RET_LOG(dpInfoStr != "", ERR_INVALID_PARAM, "usb info string error");
1431
1432 auto sinkRate_begin = dpInfoStr.find("rate=");
1433 auto sinkRate_end = dpInfoStr.find_first_of(" ", sinkRate_begin);
1434 std::string sampleRateStr = dpInfoStr.substr(sinkRate_begin + std::strlen("rate="),
1435 sinkRate_end - sinkRate_begin - std::strlen("rate="));
1436
1437 auto sinkBuffer_begin = dpInfoStr.find("buffer_size=");
1438 auto sinkBuffer_end = dpInfoStr.find_first_of(" ", sinkBuffer_begin);
1439 std::string bufferSize = dpInfoStr.substr(sinkBuffer_begin + std::strlen("buffer_size="),
1440 sinkBuffer_end - sinkBuffer_begin - std::strlen("buffer_size="));
1441
1442 auto sinkChannel_begin = dpInfoStr.find("channels=");
1443 auto sinkChannel_end = dpInfoStr.find_first_of(" ", sinkChannel_begin);
1444 std::string channeltStr = dpInfoStr.substr(sinkChannel_begin + std::strlen("channels="),
1445 sinkChannel_end - sinkChannel_begin - std::strlen("channels="));
1446
1447 auto address_begin = dpInfoStr.find("address=");
1448 auto address_end = dpInfoStr.find_first_of(" ", address_begin);
1449 std::string addressStr = dpInfoStr.substr(address_begin + std::strlen("address="),
1450 address_end - address_begin - std::strlen("address="));
1451
1452 CHECK_AND_RETURN_RET_LOG(StringConverter(sampleRateStr, attr_.sampleRate), ERR_INVALID_PARAM,
1453 "convert invalid sampleRate: %{public}s", sampleRateStr.c_str());
1454 CHECK_AND_RETURN_RET_LOG(StringConverter(channeltStr, attr_.channel), ERR_INVALID_PARAM,
1455 "convert invalid channel: %{public}s", channeltStr.c_str());
1456
1457 attr_.address = addressStr;
1458 uint32_t formatByte = 0;
1459 if (attr_.channel <= 0 || attr_.sampleRate <= 0) {
1460 AUDIO_ERR_LOG("check attr failed channel[%{public}d] sampleRate[%{public}d]", attr_.channel, attr_.sampleRate);
1461 } else {
1462 uint32_t bufferSizeValue = 0;
1463 CHECK_AND_RETURN_RET_LOG(StringConverter(bufferSize, bufferSizeValue), ERR_INVALID_PARAM,
1464 "convert invalid bufferSize: %{public}s", bufferSize.c_str());
1465 formatByte = bufferSizeValue * BUFFER_CALC_1000MS / BUFFER_CALC_20MS
1466 / attr_.channel / attr_.sampleRate;
1467 }
1468
1469 attr_.format = static_cast<HdiAdapterFormat>(ConvertByteToAudioFormat(formatByte));
1470
1471 AUDIO_DEBUG_LOG("UpdateDPAttrs sampleRate %{public}d,format:%{public}d,channelCount:%{public}d,address:%{public}s",
1472 attr_.sampleRate, attr_.format, attr_.channel, addressStr.c_str());
1473
1474 adapterNameCase_ = "dp";
1475 openSpeaker_ = 0;
1476
1477 return SUCCESS;
1478 }
1479
InitAdapter()1480 int32_t AudioRendererSinkInner::InitAdapter()
1481 {
1482 AUDIO_INFO_LOG("Init adapter start sinkName %{public}s", halName_.c_str());
1483
1484 if (adapterInited_) {
1485 AUDIO_INFO_LOG("Adapter already inited");
1486 return SUCCESS;
1487 }
1488
1489 int32_t err = InitAudioManager();
1490 CHECK_AND_RETURN_RET_LOG(err == 0, ERR_NOT_STARTED,
1491 "Init audio manager Fail.");
1492
1493 AudioAdapterDescriptor descs[MAX_AUDIO_ADAPTER_NUM];
1494 uint32_t size = MAX_AUDIO_ADAPTER_NUM;
1495 if (audioManager_ == nullptr) {
1496 AUDIO_ERR_LOG("The audioManager is null");
1497 return ERROR;
1498 }
1499 int32_t ret = audioManager_->GetAllAdapters(audioManager_, (struct AudioAdapterDescriptor *)&descs, &size);
1500 CHECK_AND_RETURN_RET_LOG(size <= MAX_AUDIO_ADAPTER_NUM && size != 0 && ret == 0,
1501 ERR_NOT_STARTED, "Get adapters failed");
1502
1503 enum AudioPortDirection port = PORT_OUT;
1504 int32_t index =
1505 SwitchAdapterRender((struct AudioAdapterDescriptor *)&descs, adapterNameCase_, port, audioPort_, size);
1506 CHECK_AND_RETURN_RET_LOG((index >= 0), ERR_NOT_STARTED, "Switch Adapter failed");
1507
1508 adapterDesc_ = descs[index];
1509 CHECK_AND_RETURN_RET_LOG((audioManager_->LoadAdapter(audioManager_, &adapterDesc_, &audioAdapter_) == SUCCESS),
1510 ERR_NOT_STARTED, "Load Adapter Fail.");
1511
1512 // LCOV_EXCL_START
1513 if (hasAudioParamInfo_) {
1514 SetAudioParameter(audioParamKey_, audioParamCondition_, audioParamValue_);
1515 hasAudioParamInfo_ = false;
1516 }
1517 // LCOV_EXCL_STOP
1518
1519 adapterInited_ = true;
1520
1521 return SUCCESS;
1522 }
1523
InitRender()1524 int32_t AudioRendererSinkInner::InitRender()
1525 {
1526 AUDIO_INFO_LOG("Init render start sinkName %{public}s", halName_.c_str());
1527
1528 Trace trace("AudioRendererSinkInner::InitRender");
1529
1530 if (renderInited_) {
1531 AUDIO_INFO_LOG("Render already inited");
1532 return SUCCESS;
1533 }
1534
1535 CHECK_AND_RETURN_RET_LOG((audioAdapter_ != nullptr), ERR_NOT_STARTED, "Audio device not loaded");
1536
1537 // Initialization port information, can fill through mode and other parameters
1538 CHECK_AND_RETURN_RET_LOG((audioAdapter_->InitAllPorts(audioAdapter_) == SUCCESS),
1539 ERR_NOT_STARTED, "Init ports failed");
1540
1541 int32_t err = CreateRender(audioPort_);
1542 CHECK_AND_RETURN_RET_LOG(err == 0, ERR_NOT_STARTED,
1543 "Create render failed, Audio Port: %{public}d", audioPort_.portId);
1544
1545 if (openSpeaker_) {
1546 int32_t ret = SUCCESS;
1547 std::vector<DeviceType> outputDevices;
1548 if (halName_ == "usb") {
1549 outputDevices.push_back(DEVICE_TYPE_USB_ARM_HEADSET);
1550 ret = SetOutputRoutes(outputDevices);
1551 } else if (halName_ == "dp") {
1552 outputDevices.push_back(DEVICE_TYPE_DP);
1553 ret = SetOutputRoutes(outputDevices);
1554 } else if (halName_ == VOIP_HAL_NAME) {
1555 // voip hal do not need to SetOutputRoute when create render, will SetOutputRoute when start stream
1556 AUDIO_INFO_LOG("voip hal do not need to SetOutputRoute when create render");
1557 } else {
1558 DeviceType type = static_cast<DeviceType>(attr_.deviceType);
1559 if (type == DEVICE_TYPE_INVALID) {
1560 type = DEVICE_TYPE_SPEAKER;
1561 }
1562 outputDevices.push_back(type);
1563 ret = SetOutputRoutes(outputDevices);
1564 }
1565 if (ret < 0) {
1566 AUDIO_WARNING_LOG("Update route FAILED: %{public}d", ret);
1567 }
1568 }
1569
1570 renderInited_ = true;
1571
1572 return SUCCESS;
1573 }
1574
ResetOutputRouteForDisconnect(DeviceType device)1575 void AudioRendererSinkInner::ResetOutputRouteForDisconnect(DeviceType device)
1576 {
1577 if (currentActiveDevice_ == device) {
1578 currentActiveDevice_ = DEVICE_TYPE_NONE;
1579 }
1580 }
1581
InitLatencyMeasurement()1582 void AudioRendererSinkInner::InitLatencyMeasurement()
1583 {
1584 if (!AudioLatencyMeasurement::CheckIfEnabled()) {
1585 return;
1586 }
1587
1588 AUDIO_INFO_LOG("LatencyMeas PrimaryRendererSinkInit");
1589
1590 signalDetectAgent_ = std::make_shared<SignalDetectAgent>();
1591 CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
1592 signalDetectAgent_->sampleFormat_ = attr_.format;
1593 signalDetectAgent_->formatByteSize_ = GetFormatByteSize(attr_.format);
1594 latencyMeasEnabled_ = true;
1595 signalDetected_ = false;
1596 }
1597
DeinitLatencyMeasurement()1598 void AudioRendererSinkInner::DeinitLatencyMeasurement()
1599 {
1600 signalDetectAgent_ = nullptr;
1601 latencyMeasEnabled_ = false;
1602 }
1603
CheckLatencySignal(uint8_t * data,size_t len)1604 void AudioRendererSinkInner::CheckLatencySignal(uint8_t *data, size_t len)
1605 {
1606 if (!latencyMeasEnabled_) {
1607 return;
1608 }
1609 CHECK_AND_RETURN_LOG(signalDetectAgent_ != nullptr, "LatencyMeas signalDetectAgent_ is nullptr");
1610 uint32_t byteSize = static_cast<uint32_t>(GetFormatByteSize(attr_.format));
1611 size_t newlyCheckedTime = len / (attr_.sampleRate / MILLISECOND_PER_SECOND) /
1612 (byteSize * sizeof(uint8_t) * attr_.channel);
1613 detectedTime_ += newlyCheckedTime;
1614 if (detectedTime_ >= MILLISECOND_PER_SECOND && signalDetectAgent_->signalDetected_ &&
1615 !signalDetectAgent_->dspTimestampGot_) {
1616 char value[GET_EXTRA_PARAM_LEN];
1617 AudioParamKey key = NONE;
1618 AudioExtParamKey hdiKey = AudioExtParamKey(key);
1619 std::string condition = "debug_audio_latency_measurement";
1620 int32_t ret = audioAdapter_->GetExtraParams(audioAdapter_, hdiKey,
1621 condition.c_str(), value, GET_EXTRA_PARAM_LEN);
1622 AUDIO_DEBUG_LOG("GetExtraParameter ret:%{public}d", ret);
1623 LatencyMonitor::GetInstance().UpdateDspTime(value);
1624 LatencyMonitor::GetInstance().UpdateSinkOrSourceTime(true,
1625 signalDetectAgent_->lastPeakBufferTime_);
1626 LatencyMonitor::GetInstance().ShowTimestamp(true);
1627 signalDetectAgent_->dspTimestampGot_ = true;
1628 signalDetectAgent_->signalDetected_ = false;
1629 }
1630 signalDetected_ = signalDetectAgent_->CheckAudioData(data, len);
1631 if (signalDetected_) {
1632 AUDIO_INFO_LOG("LatencyMeas primarySink signal detected");
1633 detectedTime_ = 0;
1634 }
1635 }
1636
GetCurDeviceParam(char * keyValueList,size_t len)1637 int32_t AudioRendererSinkInner::GetCurDeviceParam(char *keyValueList, size_t len)
1638 {
1639 int32_t ret = ERROR;
1640 switch (currentActiveDevice_) {
1641 case DEVICE_TYPE_EARPIECE:
1642 ret = snprintf_s(keyValueList, len, len - 1,
1643 "zero_volume=true;routing=1");
1644 break;
1645 case DEVICE_TYPE_SPEAKER:
1646 ret = snprintf_s(keyValueList, len, len - 1,
1647 "zero_volume=true;routing=2");
1648 break;
1649 case DEVICE_TYPE_WIRED_HEADSET:
1650 ret = snprintf_s(keyValueList, len, len - 1,
1651 "zero_volume=true;routing=4");
1652 break;
1653 case DEVICE_TYPE_USB_ARM_HEADSET:
1654 ret = snprintf_s(keyValueList, len, len - 1,
1655 "zero_volume=true;routing=67108864");
1656 break;
1657 case DEVICE_TYPE_USB_HEADSET:
1658 ret = snprintf_s(keyValueList, len, len - 1,
1659 "zero_volume=true;routing=545259520");
1660 break;
1661 case DEVICE_TYPE_BLUETOOTH_SCO:
1662 ret = snprintf_s(keyValueList, len, len - 1,
1663 "zero_volume=true;routing=16");
1664 break;
1665 case DEVICE_TYPE_BLUETOOTH_A2DP:
1666 ret = snprintf_s(keyValueList, len, len - 1,
1667 "zero_volume=true;routing=128");
1668 break;
1669 default:
1670 ret = snprintf_s(keyValueList, len, len - 1,
1671 "zero_volume=true;routing=-100");
1672 break;
1673 }
1674 return ret;
1675 }
1676
WriterSmartPAStatusSysEvent(int32_t status)1677 void AudioRendererSinkInner::WriterSmartPAStatusSysEvent(int32_t status)
1678 {
1679 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1680 Media::MediaMonitor::AUDIO, Media::MediaMonitor::SMARTPA_STATUS,
1681 Media::MediaMonitor::BEHAVIOR_EVENT);
1682 bean->Add("STATUS", status);
1683 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1684 }
1685
SetPaPower(int32_t flag)1686 int32_t AudioRendererSinkInner::SetPaPower(int32_t flag)
1687 {
1688 Trace trace("AudioRendererSinkInner::SetPaPower flag:" + std::to_string(flag));
1689 int32_t ret = ERROR;
1690 char keyValueList[DEVICE_PARAM_MAX_LEN] = {0};
1691 const char keyValueList1[] = "zero_volume=false";
1692
1693 if (flag == 0 && g_paStatus == 1) {
1694 ret = snprintf_s(keyValueList, sizeof(keyValueList), sizeof(keyValueList) - 1,
1695 "zero_volume=true;routing=0");
1696 if (ret > 0 && ret < static_cast<int32_t>(sizeof(keyValueList))) {
1697 CHECK_AND_RETURN_RET(audioRender_ != nullptr, ERROR);
1698 ret = audioRender_->SetExtraParams(audioRender_, keyValueList);
1699 }
1700 if (ret == 0) {
1701 g_paStatus = 0;
1702 WriterSmartPAStatusSysEvent(g_paStatus);
1703 }
1704 return ret;
1705 } else if (flag == 0 && g_paStatus == 0) {
1706 return SUCCESS;
1707 }
1708
1709 AUDIO_INFO_LOG("Get keyValueList %{public}s before get.", keyValueList);
1710 GetCurDeviceParam(keyValueList, DEVICE_PARAM_MAX_LEN);
1711 AUDIO_INFO_LOG("Get keyValueList for openpa: %{public}s", keyValueList);
1712
1713 if (flag == 1 && g_paStatus == 0) {
1714 ret = audioRender_->SetExtraParams(audioRender_, keyValueList);
1715 ret = audioRender_->SetExtraParams(audioRender_, keyValueList1) + ret;
1716 if (ret == 0) {
1717 g_paStatus = 1;
1718 WriterSmartPAStatusSysEvent(g_paStatus);
1719 }
1720 return ret;
1721 } else if (flag == 1 && g_paStatus == 1) {
1722 return SUCCESS;
1723 }
1724
1725 AUDIO_INFO_LOG("receive invalid flag");
1726 return ret;
1727 }
1728
SetPriPaPower()1729 int32_t AudioRendererSinkInner::SetPriPaPower()
1730 {
1731 time_t nowTime = time(nullptr);
1732 int32_t ret = ERROR;
1733 const char keyValueList[] = "primary=start";
1734 double diff = difftime(nowTime, startTime);
1735 if (diff > INTREVAL) {
1736 CHECK_AND_RETURN_RET(audioRender_ != nullptr, ERROR);
1737 ret = audioRender_->SetExtraParams(audioRender_, keyValueList);
1738 if (ret == 0) {
1739 AUDIO_INFO_LOG("set primary stream start info to hal");
1740 }
1741 time(&startTime);
1742 }
1743 return ret;
1744 }
1745
UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],const size_t size)1746 int32_t AudioRendererSinkInner::UpdateAppsUid(const int32_t appsUid[MAX_MIX_CHANNELS],
1747 const size_t size)
1748 {
1749 #ifdef FEATURE_POWER_MANAGER
1750 if (!runningLockManager_) {
1751 return ERROR;
1752 }
1753
1754 return runningLockManager_->UpdateAppsUid(appsUid, appsUid + size);
1755 #endif
1756
1757 return SUCCESS;
1758 }
1759
UpdateAppsUid(const std::vector<int32_t> & appsUid)1760 int32_t AudioRendererSinkInner::UpdateAppsUid(const std::vector<int32_t> &appsUid)
1761 {
1762 #ifdef FEATURE_POWER_MANAGER
1763 if (!runningLockManager_) {
1764 return ERROR;
1765 }
1766
1767 runningLockManager_->UpdateAppsUid(appsUid.cbegin(), appsUid.cend());
1768 runningLockManager_->UpdateAppsUidToPowerMgr();
1769 #endif
1770
1771 return SUCCESS;
1772 }
1773
1774 // LCOV_EXCL_START
SetSinkMuteForSwitchDevice(bool mute)1775 int32_t AudioRendererSinkInner::SetSinkMuteForSwitchDevice(bool mute)
1776 {
1777 std::lock_guard<std::mutex> lock(switchDeviceMutex_);
1778 AUDIO_INFO_LOG("set %{public}s mute %{public}d", halName_.c_str(), mute);
1779
1780 if (mute) {
1781 muteCount_++;
1782 if (switchDeviceMute_) {
1783 AUDIO_INFO_LOG("%{public}s already muted", halName_.c_str());
1784 return SUCCESS;
1785 }
1786 switchDeviceMute_ = true;
1787 if (halName_ == VOIP_HAL_NAME && audioRender_ != nullptr) {
1788 audioRender_->SetVolume(audioRender_, 0.0f);
1789 }
1790 } else {
1791 muteCount_--;
1792 if (muteCount_ > 0) {
1793 AUDIO_WARNING_LOG("%{public}s not all unmuted", halName_.c_str());
1794 return SUCCESS;
1795 }
1796 switchDeviceMute_ = false;
1797 muteCount_ = 0;
1798 if (halName_ == VOIP_HAL_NAME) {
1799 SetVolume(leftVolume_, rightVolume_);
1800 }
1801 }
1802
1803 return SUCCESS;
1804 }
1805
GetRenderId(uint32_t & renderId) const1806 int32_t AudioRendererSinkInner::GetRenderId(uint32_t &renderId) const
1807 {
1808 if (halName_ == "usb") {
1809 renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_USB);
1810 } else if (halName_ == "dp") {
1811 renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_DP);
1812 } else if (halName_ == VOIP_HAL_NAME) {
1813 renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_VOIP);
1814 } else if (halName_ == DIRECT_HAL_NAME) {
1815 renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_DIRECT);
1816 } else {
1817 renderId = GenerateUniqueID(AUDIO_HDI_RENDER_ID_BASE, HDI_RENDER_OFFSET_PRIMARY);
1818 }
1819 return SUCCESS;
1820 }
1821
SetAddress(const std::string & address)1822 void AudioRendererSinkInner::SetAddress(const std::string &address)
1823 {
1824 usbAddress_ = address;
1825 }
1826
SetAudioRouteInfoForEnhanceChain(const DeviceType & outputDevice)1827 int32_t AudioRendererSinkInner::SetAudioRouteInfoForEnhanceChain(const DeviceType &outputDevice)
1828 {
1829 AudioEnhanceChainManager *audioEnhanceChainManager = AudioEnhanceChainManager::GetInstance();
1830 CHECK_AND_RETURN_RET_LOG(audioEnhanceChainManager != nullptr, ERROR, "audioEnhanceChainManager is nullptr");
1831 uint32_t renderId = 0;
1832 int32_t ret = GetRenderId(renderId);
1833 if (ret != SUCCESS) {
1834 AUDIO_WARNING_LOG("GetRenderId failed");
1835 }
1836 if (halName_ == "usb") {
1837 audioEnhanceChainManager->SetOutputDevice(renderId, DEVICE_TYPE_USB_ARM_HEADSET);
1838 } else if (halName_ == "dp") {
1839 audioEnhanceChainManager->SetOutputDevice(renderId, DEVICE_TYPE_DP);
1840 } else {
1841 audioEnhanceChainManager->SetOutputDevice(renderId, outputDevice);
1842 }
1843 return SUCCESS;
1844 }
1845
1846 // UpdateSinkState must be called with AudioRendererSinkInner::sinkMutex_ held
UpdateSinkState(bool started)1847 void AudioRendererSinkInner::UpdateSinkState(bool started)
1848 {
1849 if (callback_) {
1850 callback_->OnAudioSinkStateChange(sinkId_, started);
1851 } else {
1852 AUDIO_WARNING_LOG("AudioSinkCallback is nullptr");
1853 }
1854 }
1855 } // namespace AudioStandard
1856 } // namespace OHOS
1857