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