1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef LOG_TAG
16 #define LOG_TAG "AudioServer"
17 #endif
18
19 #include "audio_server.h"
20
21 #include <cinttypes>
22 #include <codecvt>
23 #include <csignal>
24 #include <fstream>
25 #include <sstream>
26 #include <thread>
27 #include <unordered_map>
28 #include <vector>
29 #include <dlfcn.h>
30 #include <format>
31
32 #include "bundle_mgr_interface.h"
33 #include "bundle_mgr_proxy.h"
34 #include "iservice_registry.h"
35 #include "system_ability_definition.h"
36 #include "hisysevent.h"
37 #include "parameters.h"
38
39 #include "audio_capturer_source.h"
40 #include "fast_audio_capturer_source.h"
41 #include "audio_errors.h"
42 #include "audio_service_log.h"
43 #include "audio_asr.h"
44 #include "audio_manager_listener_proxy.h"
45 #include "audio_service.h"
46 #include "audio_schedule.h"
47 #include "audio_info.h"
48 #include "audio_utils.h"
49 #include "i_audio_capturer_source.h"
50 #include "i_audio_renderer_sink.h"
51 #include "audio_renderer_sink.h"
52 #include "i_standard_audio_server_manager_listener.h"
53 #include "playback_capturer_manager.h"
54 #include "config/audio_param_parser.h"
55 #include "media_monitor_manager.h"
56
57 #define PA
58 #ifdef PA
59 extern "C" {
60 extern int ohos_pa_main(int argc, char *argv[]);
61 }
62 #endif
63
64 using namespace std;
65
66 namespace OHOS {
67 namespace AudioStandard {
68
69 constexpr int32_t SYSTEM_STATUS_START = 1;
70 constexpr int32_t SYSTEM_STATUS_STOP = 0;
71 constexpr int32_t SYSTEM_PROCESS_TYPE = 1;
72 uint32_t AudioServer::paDaemonTid_;
73 std::map<std::string, std::string> AudioServer::audioParameters;
74 std::unordered_map<std::string, std::unordered_map<std::string, std::set<std::string>>> AudioServer::audioParameterKeys;
75 const string DEFAULT_COOKIE_PATH = "/data/data/.pulse_dir/state/cookie";
76 const std::string CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
77 constexpr const char *TEL_SATELLITE_SUPPORT = "const.telephony.satellite.supported";
78 const std::string SATEMODEM_PARAMETER = "usedmodem=satemodem";
79 const std::string PCM_DUMP_KEY = "PCM_DUMP";
80 constexpr int32_t UID_FOUNDATION_SA = 5523;
81 const unsigned int TIME_OUT_SECONDS = 10;
82 const unsigned int SCHEDULE_REPORT_TIME_OUT_SECONDS = 2;
83 static const int32_t INVALID_APP_UID = -1;
84 static const int32_t INVALID_APP_CREATED_AUDIO_STREAM_NUM = -1;
85 static const std::vector<StreamUsage> STREAMS_NEED_VERIFY_SYSTEM_PERMISSION = {
86 STREAM_USAGE_SYSTEM,
87 STREAM_USAGE_DTMF,
88 STREAM_USAGE_ENFORCED_TONE,
89 STREAM_USAGE_ULTRASONIC,
90 STREAM_USAGE_VOICE_MODEM_COMMUNICATION
91 };
92 static const int32_t MODERN_INNER_API_VERSION = 12;
93 const int32_t API_VERSION_REMAINDER = 1000;
94 static constexpr int32_t VM_MANAGER_UID = 7700;
95 static const int32_t FAST_DUMPINFO_LEN = 2;
96 static const int32_t BUNDLENAME_LENGTH_LIMIT = 1024;
97 constexpr int32_t UID_CAMERA = 1047;
98 constexpr int32_t MAX_RENDERER_STREAM_CNT_PER_UID = 40;
99 const int32_t DEFAULT_MAX_RENDERER_INSTANCES = 128;
100 static const std::set<int32_t> RECORD_CHECK_FORWARD_LIST = {
101 VM_MANAGER_UID,
102 UID_CAMERA
103 };
104 // using pass-in appInfo for uids:
105 constexpr int32_t UID_MEDIA_SA = 1013;
106
107 const std::set<int32_t> RECORD_PASS_APPINFO_LIST = {
108 UID_MEDIA_SA
109 };
110
111 const std::set<SourceType> VALID_SOURCE_TYPE = {
112 SOURCE_TYPE_MIC,
113 SOURCE_TYPE_VOICE_RECOGNITION,
114 SOURCE_TYPE_PLAYBACK_CAPTURE,
115 SOURCE_TYPE_WAKEUP,
116 SOURCE_TYPE_VOICE_CALL,
117 SOURCE_TYPE_VOICE_COMMUNICATION,
118 SOURCE_TYPE_ULTRASONIC,
119 SOURCE_TYPE_VIRTUAL_CAPTURE,
120 SOURCE_TYPE_VOICE_MESSAGE,
121 SOURCE_TYPE_REMOTE_CAST,
122 SOURCE_TYPE_VOICE_TRANSCRIPTION,
123 SOURCE_TYPE_CAMCORDER
124 };
125
126
127 static constexpr unsigned int GET_BUNDLE_TIME_OUT_SECONDS = 10;
128
129 static const std::map<std::string, AsrAecMode> AEC_MODE_MAP = {
130 {"BYPASS", AsrAecMode::BYPASS},
131 {"STANDARD", AsrAecMode::STANDARD}
132 };
133
134 static const std::map<AsrAecMode, std::string> AEC_MODE_MAP_VERSE = {
135 {AsrAecMode::BYPASS, "BYPASS"},
136 {AsrAecMode::STANDARD, "STANDARD"}
137 };
138
139 static const std::map<std::string, AsrNoiseSuppressionMode> NS_MODE_MAP = {
140 {"BYPASS", AsrNoiseSuppressionMode::BYPASS},
141 {"STANDARD", AsrNoiseSuppressionMode::STANDARD},
142 {"NEAR_FIELD", AsrNoiseSuppressionMode::NEAR_FIELD},
143 {"FAR_FIELD", AsrNoiseSuppressionMode::FAR_FIELD}
144 };
145
146 static const std::map<AsrNoiseSuppressionMode, std::string> NS_MODE_MAP_VERSE = {
147 {AsrNoiseSuppressionMode::BYPASS, "BYPASS"},
148 {AsrNoiseSuppressionMode::STANDARD, "STANDARD"},
149 {AsrNoiseSuppressionMode::NEAR_FIELD, "NEAR_FIELD"},
150 {AsrNoiseSuppressionMode::FAR_FIELD, "FAR_FIELD"}
151 };
152
153 static const std::map<std::string, AsrWhisperDetectionMode> WHISPER_DETECTION_MODE_MAP = {
154 {"BYPASS", AsrWhisperDetectionMode::BYPASS},
155 {"STANDARD", AsrWhisperDetectionMode::STANDARD},
156 };
157
158 static const std::map<AsrWhisperDetectionMode, std::string> WHISPER_DETECTION_MODE_MAP_VERSE = {
159 {AsrWhisperDetectionMode::BYPASS, "BYPASS"},
160 {AsrWhisperDetectionMode::STANDARD, "STANDARD"},
161 };
162
163 static const std::map<std::string, AsrVoiceControlMode> VC_MODE_MAP = {
164 {"audio2voicetx", AsrVoiceControlMode::AUDIO_2_VOICETX},
165 {"audiomix2voicetx", AsrVoiceControlMode::AUDIO_MIX_2_VOICETX},
166 {"audio2voicetxex", AsrVoiceControlMode::AUDIO_2_VOICE_TX_EX},
167 {"audiomix2voicetxex", AsrVoiceControlMode::AUDIO_MIX_2_VOICE_TX_EX},
168 };
169
170 static const std::map<AsrVoiceControlMode, std::string> VC_MODE_MAP_VERSE = {
171 {AsrVoiceControlMode::AUDIO_2_VOICETX, "audio2voicetx"},
172 {AsrVoiceControlMode::AUDIO_MIX_2_VOICETX, "audiomix2voicetx"},
173 {AsrVoiceControlMode::AUDIO_2_VOICE_TX_EX, "audio2voicetxex"},
174 {AsrVoiceControlMode::AUDIO_MIX_2_VOICE_TX_EX, "audiomix2voicetxex"},
175 };
176
177 static const std::map<std::string, AsrVoiceMuteMode> VM_MODE_MAP = {
178 {"output_mute", AsrVoiceMuteMode::OUTPUT_MUTE},
179 {"input_mute", AsrVoiceMuteMode::INPUT_MUTE},
180 {"mute_tts", AsrVoiceMuteMode::TTS_MUTE},
181 {"mute_call", AsrVoiceMuteMode::CALL_MUTE},
182 {"ouput_mute_ex", AsrVoiceMuteMode::OUTPUT_MUTE_EX},
183 };
184
185 static const std::map<AsrVoiceMuteMode, std::string> VM_MODE_MAP_VERSE = {
186 {AsrVoiceMuteMode::OUTPUT_MUTE, "output_mute"},
187 {AsrVoiceMuteMode::INPUT_MUTE, "input_mute"},
188 {AsrVoiceMuteMode::TTS_MUTE, "mute_tts"},
189 {AsrVoiceMuteMode::CALL_MUTE, "mute_call"},
190 {AsrVoiceMuteMode::OUTPUT_MUTE_EX, "ouput_mute_ex"},
191 };
192
193 static const std::map<std::string, bool> RES_MAP = {
194 {"true", true},
195 {"false", false},
196 };
197
198 static const std::map<bool, std::string> RES_MAP_VERSE = {
199 {true, "true"},
200 {false, "false"},
201 };
202
IsNeedVerifyPermission(const StreamUsage streamUsage)203 static bool IsNeedVerifyPermission(const StreamUsage streamUsage)
204 {
205 for (const auto& item : STREAMS_NEED_VERIFY_SYSTEM_PERMISSION) {
206 if (streamUsage == item) {
207 return true;
208 }
209 }
210 return false;
211 }
212
213 class CapturerStateOb final : public ICapturerStateCallback {
214 public:
CapturerStateOb(std::function<void(bool, int32_t)> callback)215 explicit CapturerStateOb(std::function<void(bool, int32_t)> callback) : callback_(callback)
216 {
217 num_ = count_.fetch_add(1, std::memory_order_relaxed);
218 }
219
220 ~CapturerStateOb() override final
221 {
222 count_.fetch_sub(1, std::memory_order_relaxed);
223 }
224
225 void OnCapturerState(bool isActive) override final
226 {
227 callback_(isActive, num_);
228 }
229
230 private:
231 static inline std::atomic<int32_t> count_ = 0;
232 int32_t num_;
233
234 // callback to audioserver
235 std::function<void(bool, int32_t)> callback_;
236 };
237
splitString(const std::string& str, const std::string& pattern)238 std::vector<std::string> splitString(const std::string& str, const std::string& pattern)
239 {
240 std::vector<std::string> res;
241 if (str == "")
242 return res;
243 std::string strs = str + pattern;
244 size_t pos = strs.find(pattern);
245
246 while (pos != strs.npos) {
247 std::string temp = strs.substr(0, pos);
248 res.push_back(temp);
249 strs = strs.substr(pos + 1, strs.size());
250 pos = strs.find(pattern);
251 }
252 return res;
253 }
254
255 REGISTER_SYSTEM_ABILITY_BY_ID(AudioServer, AUDIO_DISTRIBUTED_SERVICE_ID, true)
256
257 #ifdef PA
258 constexpr int PA_ARG_COUNT = 1;
259
paDaemonThread(void *arg)260 void *AudioServer::paDaemonThread(void *arg)
261 {
262 /* Load the mandatory pulseaudio modules at start */
263 char *argv[] = {
264 (char*)"pulseaudio",
265 };
266 paDaemonTid_ = static_cast<uint32_t>(gettid());
267 AUDIO_INFO_LOG("Calling ohos_pa_main\n");
268 ohos_pa_main(PA_ARG_COUNT, argv);
269 AUDIO_INFO_LOG("Exiting ohos_pa_main\n");
270 exit(-1);
271 }
272 #endif
273
AudioServer(int32_t systemAbilityId, bool runOnCreate)274 AudioServer::AudioServer(int32_t systemAbilityId, bool runOnCreate)
275 : SystemAbility(systemAbilityId, runOnCreate),
276 audioEffectServer_(std::make_unique<AudioEffectServer>()) {}
277
OnDump()278 void AudioServer::OnDump() {}
279
Dump(int32_t fd, const std::vector<std::u16string> &args)280 int32_t AudioServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
281 {
282 AUDIO_INFO_LOG("Dump Process Invoked");
283 if (args.size() == FAST_DUMPINFO_LEN && args[0] == u"-fb") {
284 std::string bundleName = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(args[1]);
285 std::string result = GetAudioParameter(CHECK_FAST_BLOCK_PREFIX + bundleName);
286 std::string dumpString = "check fast list :bundle name is" + bundleName + " result is " + result + "\n";
287 return write(fd, dumpString.c_str(), dumpString.size());
288 }
289 std::queue<std::u16string> argQue;
290 for (decltype(args.size()) index = 0; index < args.size(); ++index) {
291 argQue.push(args[index]);
292 }
293 std::string dumpString;
294
295 AudioServerDump dumpObj;
296 int32_t res = dumpObj.Initialize();
297 CHECK_AND_RETURN_RET_LOG(res == AUDIO_DUMP_SUCCESS, AUDIO_DUMP_INIT_ERR,
298 "Audio Service Dump Not initialised\n");
299 dumpObj.AudioDataDump(dumpString, argQue);
300 return write(fd, dumpString.c_str(), dumpString.size());
301 }
302
InitMaxRendererStreamCntPerUid()303 void AudioServer::InitMaxRendererStreamCntPerUid()
304 {
305 bool result = GetSysPara("const.multimedia.audio.stream_cnt_uid", maxRendererStreamCntPerUid_);
306 if (!result || maxRendererStreamCntPerUid_ <= 0) {
307 maxRendererStreamCntPerUid_ = MAX_RENDERER_STREAM_CNT_PER_UID;
308 }
309 }
310
OnStart()311 void AudioServer::OnStart()
312 {
313 AUDIO_INFO_LOG("OnStart uid:%{public}d", getuid());
314 InitMaxRendererStreamCntPerUid();
315 AudioInnerCall::GetInstance()->RegisterAudioServer(this);
316 bool res = Publish(this);
317 if (!res) {
318 AUDIO_ERR_LOG("start err");
319 WriteServiceStartupError();
320 }
321 int32_t fastControlFlag = 0;
322 GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag);
323 if (fastControlFlag == 1) {
324 isFastControlled_ = true;
325 }
326 AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID);
327 AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
328 AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
329 #ifdef PA
330 int32_t ret = pthread_create(&m_paDaemonThread, nullptr, AudioServer::paDaemonThread, nullptr);
331 pthread_setname_np(m_paDaemonThread, "OS_PaDaemon");
332 if (ret != 0) {
333 AUDIO_ERR_LOG("pthread_create failed %d", ret);
334 WriteServiceStartupError();
335 }
336 AUDIO_DEBUG_LOG("Created paDaemonThread\n");
337 #endif
338
339 RegisterAudioCapturerSourceCallback();
340
341 std::unique_ptr<AudioParamParser> audioParamParser = make_unique<AudioParamParser>();
342 if (audioParamParser == nullptr) {
343 WriteServiceStartupError();
344 }
345 CHECK_AND_RETURN_LOG(audioParamParser != nullptr, "Failed to create audio extra parameters parser");
346 if (audioParamParser->LoadConfiguration(audioParameterKeys)) {
347 AUDIO_INFO_LOG("Audio extra parameters load configuration successfully.");
348 }
349 }
350
WriteServiceStartupError()351 void AudioServer::WriteServiceStartupError()
352 {
353 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
354 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_SERVICE_STARTUP_ERROR,
355 Media::MediaMonitor::FAULT_EVENT);
356 bean->Add("SERVICE_ID", static_cast<int32_t>(Media::MediaMonitor::AUDIO_SERVER_ID));
357 bean->Add("ERROR_CODE", static_cast<int32_t>(Media::MediaMonitor::AUDIO_SERVER));
358 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
359 }
360
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)361 void AudioServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
362 {
363 AUDIO_DEBUG_LOG("systemAbilityId:%{public}d", systemAbilityId);
364 switch (systemAbilityId) {
365 case AUDIO_POLICY_SERVICE_ID:
366 AUDIO_INFO_LOG("input service start");
367 RegisterPolicyServerDeathRecipient();
368 break;
369 case RES_SCHED_SYS_ABILITY_ID:
370 AUDIO_INFO_LOG("ressched service start");
371 OnAddResSchedService(getpid());
372 break;
373 case MEMORY_MANAGER_SA_ID:
374 NotifyProcessStatus(true);
375 break;
376 default:
377 AUDIO_ERR_LOG("unhandled sysabilityId:%{public}d", systemAbilityId);
378 break;
379 }
380 }
381
NotifyProcessStatus(bool isStart)382 void AudioServer::NotifyProcessStatus(bool isStart)
383 {
384 int pid = getpid();
385 void *libMemMgrClientHandle = dlopen("libmemmgrclient.z.so", RTLD_NOW);
386 if (!libMemMgrClientHandle) {
387 AUDIO_ERR_LOG("dlopen libmemmgrclient library failed");
388 return;
389 }
390 void *notifyProcessStatusFunc = dlsym(libMemMgrClientHandle, "notify_process_status");
391 if (!notifyProcessStatusFunc) {
392 AUDIO_ERR_LOG("dlsm notify_process_status failed");
393 dlclose(libMemMgrClientHandle);
394 return;
395 }
396 auto notifyProcessStatus = reinterpret_cast<int(*)(int, int, int, int)>(notifyProcessStatusFunc);
397 if (isStart) {
398 AUDIO_ERR_LOG("notify to memmgr when audio_server is started");
399 // 1 indicates the service is started
400 notifyProcessStatus(pid, SYSTEM_PROCESS_TYPE, SYSTEM_STATUS_START, AUDIO_DISTRIBUTED_SERVICE_ID);
401 } else {
402 AUDIO_ERR_LOG("notify to memmgr when audio_server is stopped");
403 // 0 indicates the service is stopped
404 notifyProcessStatus(pid, SYSTEM_PROCESS_TYPE, SYSTEM_STATUS_STOP, AUDIO_DISTRIBUTED_SERVICE_ID);
405 }
406 dlclose(libMemMgrClientHandle);
407 }
408
OnStop()409 void AudioServer::OnStop()
410 {
411 AUDIO_DEBUG_LOG("OnStop");
412 NotifyProcessStatus(false);
413 }
414
SetPcmDumpParameter(const std::vector<std::pair<std::string, std::string>> ¶ms)415 bool AudioServer::SetPcmDumpParameter(const std::vector<std::pair<std::string, std::string>> ¶ms)
416 {
417 bool ret = VerifyClientPermission(DUMP_AUDIO_PERMISSION);
418 CHECK_AND_RETURN_RET_LOG(ret, false, "set audiodump parameters failed: no permission.");
419 int32_t res = Media::MediaMonitor::MediaMonitorManager::GetInstance().SetMediaParameters(params);
420 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, false, "MediaMonitor SetMediaParameters failed.");
421 return true;
422 }
423
SetExtraParameters(const std::string& key, const std::vector<std::pair<std::string, std::string>>& kvpairs)424 int32_t AudioServer::SetExtraParameters(const std::string& key,
425 const std::vector<std::pair<std::string, std::string>>& kvpairs)
426 {
427 bool ret = PermissionUtil::VerifySystemPermission();
428 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "set extra parameters failed: not system app.");
429 ret = VerifyClientPermission(MODIFY_AUDIO_SETTINGS_PERMISSION);
430 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED, "set extra parameters failed: no permission.");
431
432 if (key == PCM_DUMP_KEY) {
433 ret = SetPcmDumpParameter(kvpairs);
434 CHECK_AND_RETURN_RET_LOG(ret, ERROR, "set audiodump parameters failed");
435 return SUCCESS;
436 }
437
438 if (audioParameterKeys.empty()) {
439 AUDIO_ERR_LOG("audio extra parameters mainKey and subKey is empty");
440 return ERROR;
441 }
442
443 auto mainKeyIt = audioParameterKeys.find(key);
444 if (mainKeyIt == audioParameterKeys.end()) {
445 return ERR_INVALID_PARAM;
446 }
447
448 std::unordered_map<std::string, std::set<std::string>> subKeyMap = mainKeyIt->second;
449 std::string value;
450 bool match = true;
451 for (auto it = kvpairs.begin(); it != kvpairs.end(); it++) {
452 auto subKeyIt = subKeyMap.find(it->first);
453 if (subKeyIt != subKeyMap.end()) {
454 value += it->first + "=" + it->second + ";";
455 if (it->first == "unprocess_audio_effect") {
456 int appUid = IPCSkeleton::GetCallingUid();
457 AUDIO_INFO_LOG("add unprocess UID [%{public}d]", appUid);
458 IStreamManager::GetRecorderManager().AddUnprocessStream(appUid);
459 continue;
460 }
461 auto valueIter = subKeyIt->second.find("effect");
462 if (valueIter != subKeyIt->second.end()) {
463 RecognizeAudioEffectType(key, it->first, it->second);
464 }
465 } else {
466 match = false;
467 break;
468 }
469 }
470 if (!match) { return ERR_INVALID_PARAM; }
471
472 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
473 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
474 audioRendererSinkInstance->SetAudioParameter(AudioParamKey::NONE, "", value);
475 return SUCCESS;
476 }
477
SetAudioParameter(const std::string &key, const std::string &value)478 void AudioServer::SetAudioParameter(const std::string &key, const std::string &value)
479 {
480 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
481 AudioXCollie audioXCollie("AudioServer::SetAudioParameter", TIME_OUT_SECONDS);
482 AUDIO_DEBUG_LOG("server: set audio parameter");
483 if (key != "AUDIO_EXT_PARAM_KEY_A2DP_OFFLOAD_CONFIG") {
484 bool ret = VerifyClientPermission(MODIFY_AUDIO_SETTINGS_PERMISSION);
485 CHECK_AND_RETURN_LOG(ret, "MODIFY_AUDIO_SETTINGS permission denied");
486 } else {
487 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "A2dp offload modify audio settings permission denied");
488 }
489
490 AudioServer::audioParameters[key] = value;
491
492 // send it to hal
493 AudioParamKey parmKey = AudioParamKey::NONE;
494 if (key == "A2dpSuspended") {
495 parmKey = AudioParamKey::A2DP_SUSPEND_STATE;
496 IAudioRendererSink* bluetoothSinkInstance = IAudioRendererSink::GetInstance("a2dp", "");
497 CHECK_AND_RETURN_LOG(bluetoothSinkInstance != nullptr, "has no valid sink");
498 std::string renderValue = key + "=" + value + ";";
499 bluetoothSinkInstance->SetAudioParameter(parmKey, "", renderValue);
500 return;
501 }
502
503 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
504 CHECK_AND_RETURN_LOG(audioRendererSinkInstance != nullptr, "has no valid sink");
505
506 if (key == "AUDIO_EXT_PARAM_KEY_LOWPOWER") {
507 parmKey = AudioParamKey::PARAM_KEY_LOWPOWER;
508 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::AUDIO, "SMARTPA_LOWPOWER",
509 HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "STATE", value == "SmartPA_lowpower=on" ? 1 : 0);
510 } else if (key == "bt_headset_nrec") {
511 parmKey = AudioParamKey::BT_HEADSET_NREC;
512 } else if (key == "bt_wbs") {
513 parmKey = AudioParamKey::BT_WBS;
514 } else if (key == "AUDIO_EXT_PARAM_KEY_A2DP_OFFLOAD_CONFIG") {
515 parmKey = AudioParamKey::A2DP_OFFLOAD_STATE;
516 std::string value_new = "a2dpOffloadConfig=" + value;
517 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value_new);
518 return;
519 } else if (key == "mmi") {
520 parmKey = AudioParamKey::MMI;
521 } else if (key == "perf_info") {
522 parmKey = AudioParamKey::PERF_INFO;
523 } else {
524 AUDIO_ERR_LOG("key %{public}s is invalid for hdi interface", key.c_str());
525 return;
526 }
527 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
528 }
529
SetAsrAecMode(AsrAecMode asrAecMode)530 int32_t AudioServer::SetAsrAecMode(AsrAecMode asrAecMode)
531 {
532 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
533 "Check playback permission failed, no system permission");
534 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
535 std::string key = "asr_aec_mode";
536 std::string value = key + "=";
537 std::string keyAec = "ASR_AEC";
538 std::string valueAec = "";
539
540 auto it = AEC_MODE_MAP_VERSE.find(asrAecMode);
541 if (it != AEC_MODE_MAP_VERSE.end()) {
542 value = key + "=" + it->second;
543 if (it->second == "STANDARD") {
544 valueAec = "ASR_AEC=ON";
545 } else {
546 valueAec = "ASR_AEC=OFF";
547 }
548 } else {
549 AUDIO_ERR_LOG("get value failed.");
550 return ERR_INVALID_PARAM;
551 }
552 AudioServer::audioParameters[key] = value;
553 AudioServer::audioParameters[keyAec] = valueAec;
554 AudioParamKey parmKey = AudioParamKey::NONE;
555 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
556 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
557 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
558 audioRendererSinkInstance->SetAudioParameter(parmKey, "", valueAec);
559 return 0;
560 }
561
GetAsrAecMode(AsrAecMode& asrAecMode)562 int32_t AudioServer::GetAsrAecMode(AsrAecMode& asrAecMode)
563 {
564 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
565 "Check playback permission failed, no system permission");
566 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
567 std::string key = "asr_aec_mode";
568 std::string keyAec = "ASR_AEC";
569 AudioParamKey parmKey = AudioParamKey::NONE;
570 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
571 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
572 std::string asrAecModeSink = audioRendererSinkInstance->GetAudioParameter(parmKey, key);
573 auto it = AudioServer::audioParameters.find(key);
574 if (it != AudioServer::audioParameters.end()) {
575 asrAecModeSink = it->second;
576 } else {
577 // if asr_aec_mode null, return ASR_AEC.
578 // if asr_aec_mode null and ASR_AEC null, return err.
579 auto itAec = AudioServer::audioParameters.find(keyAec);
580 std::string asrAecSink = itAec->second;
581 if (asrAecSink == "ASR_AEC=ON") {
582 asrAecMode = AsrAecMode::STANDARD;
583 } else if (asrAecSink == "ASR_AEC=OFF") {
584 asrAecMode = AsrAecMode::BYPASS;
585 } else {
586 AUDIO_ERR_LOG("get value failed.");
587 return ERR_INVALID_PARAM;
588 }
589 return 0;
590 }
591
592 std::vector<std::string> resMode = splitString(asrAecModeSink, "=");
593 const int32_t resSize = 2;
594 std::string modeString = "";
595 if (resMode.size() == resSize) {
596 modeString = resMode[1];
597 auto it = AEC_MODE_MAP.find(modeString);
598 if (it != AEC_MODE_MAP.end()) {
599 asrAecMode = it->second;
600 } else {
601 AUDIO_ERR_LOG("get value failed.");
602 return ERR_INVALID_PARAM;
603 }
604 } else {
605 AUDIO_ERR_LOG("get value failed.");
606 return ERR_INVALID_PARAM;
607 }
608 return 0;
609 }
610
SuspendRenderSink(const std::string &sinkName)611 int32_t AudioServer::SuspendRenderSink(const std::string &sinkName)
612 {
613 if (!PermissionUtil::VerifyIsAudio()) {
614 AUDIO_ERR_LOG("not audio calling!");
615 return ERR_OPERATION_FAILED;
616 }
617 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance(sinkName.c_str(), "");
618 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
619 return audioRendererSinkInstance->SuspendRenderSink();
620 }
621
RestoreRenderSink(const std::string &sinkName)622 int32_t AudioServer::RestoreRenderSink(const std::string &sinkName)
623 {
624 if (!PermissionUtil::VerifyIsAudio()) {
625 AUDIO_ERR_LOG("not audio calling!");
626 return ERR_OPERATION_FAILED;
627 }
628 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance(sinkName.c_str(), "");
629 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
630 return audioRendererSinkInstance->RestoreRenderSink();
631 }
632
SetAsrNoiseSuppressionMode(AsrNoiseSuppressionMode asrNoiseSuppressionMode)633 int32_t AudioServer::SetAsrNoiseSuppressionMode(AsrNoiseSuppressionMode asrNoiseSuppressionMode)
634 {
635 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
636 "Check playback permission failed, no system permission");
637 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
638 std::string key = "asr_ns_mode";
639 std::string value = key + "=";
640
641 auto it = NS_MODE_MAP_VERSE.find(asrNoiseSuppressionMode);
642 if (it != NS_MODE_MAP_VERSE.end()) {
643 value = key + "=" + it->second;
644 } else {
645 AUDIO_ERR_LOG("get value failed.");
646 return ERR_INVALID_PARAM;
647 }
648 AudioServer::audioParameters[key] = value;
649 AudioParamKey parmKey = AudioParamKey::NONE;
650 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
651 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
652 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
653 return 0;
654 }
655
GetAsrNoiseSuppressionMode(AsrNoiseSuppressionMode& asrNoiseSuppressionMode)656 int32_t AudioServer::GetAsrNoiseSuppressionMode(AsrNoiseSuppressionMode& asrNoiseSuppressionMode)
657 {
658 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
659 "Check playback permission failed, no system permission");
660 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
661 std::string key = "asr_ns_mode";
662 AudioParamKey parmKey = AudioParamKey::NONE;
663 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
664 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
665 std::string asrNoiseSuppressionModeSink = audioRendererSinkInstance->GetAudioParameter(parmKey, key);
666 auto it = AudioServer::audioParameters.find(key);
667 if (it != AudioServer::audioParameters.end()) {
668 asrNoiseSuppressionModeSink = it->second;
669 } else {
670 AUDIO_ERR_LOG("get value failed.");
671 return ERR_INVALID_PARAM;
672 }
673
674 std::vector<std::string> resMode = splitString(asrNoiseSuppressionModeSink, "=");
675 const int32_t resSize = 2;
676 std::string modeString = "";
677 if (resMode.size() == resSize) {
678 modeString = resMode[1];
679 auto it = NS_MODE_MAP.find(modeString);
680 if (it != NS_MODE_MAP.end()) {
681 asrNoiseSuppressionMode = it->second;
682 } else {
683 AUDIO_ERR_LOG("get value failed.");
684 return ERR_INVALID_PARAM;
685 }
686 } else {
687 AUDIO_ERR_LOG("get value failed.");
688 return ERR_INVALID_PARAM;
689 }
690 return 0;
691 }
692
SetAsrWhisperDetectionMode(AsrWhisperDetectionMode asrWhisperDetectionMode)693 int32_t AudioServer::SetAsrWhisperDetectionMode(AsrWhisperDetectionMode asrWhisperDetectionMode)
694 {
695 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
696 "Check playback permission failed, no system permission");
697 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
698 std::string key = "asr_wd_mode";
699 std::string value = key + "=";
700
701 auto it = WHISPER_DETECTION_MODE_MAP_VERSE.find(asrWhisperDetectionMode);
702 if (it != WHISPER_DETECTION_MODE_MAP_VERSE.end()) {
703 value = key + "=" + it->second;
704 } else {
705 AUDIO_ERR_LOG("get value failed.");
706 return ERR_INVALID_PARAM;
707 }
708 AudioServer::audioParameters[key] = value;
709 AudioParamKey parmKey = AudioParamKey::NONE;
710 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
711 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
712 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
713 return 0;
714 }
715
GetAsrWhisperDetectionMode(AsrWhisperDetectionMode& asrWhisperDetectionMode)716 int32_t AudioServer::GetAsrWhisperDetectionMode(AsrWhisperDetectionMode& asrWhisperDetectionMode)
717 {
718 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
719 "Check playback permission failed, no system permission");
720 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
721 std::string key = "asr_wd_mode";
722 AudioParamKey parmKey = AudioParamKey::NONE;
723 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
724 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
725 std::string asrWhisperDetectionModeSink = audioRendererSinkInstance->GetAudioParameter(parmKey, key);
726 auto it = AudioServer::audioParameters.find(key);
727 if (it != AudioServer::audioParameters.end()) {
728 asrWhisperDetectionModeSink = it->second;
729 } else {
730 AUDIO_ERR_LOG("get value failed.");
731 return ERR_INVALID_PARAM;
732 }
733
734 std::vector<std::string> resMode = splitString(asrWhisperDetectionModeSink, "=");
735 const int32_t resSize = 2;
736 std::string modeString = "";
737 if (resMode.size() == resSize) {
738 modeString = resMode[1];
739 auto it = WHISPER_DETECTION_MODE_MAP.find(modeString);
740 if (it != WHISPER_DETECTION_MODE_MAP.end()) {
741 asrWhisperDetectionMode = it->second;
742 } else {
743 AUDIO_ERR_LOG("get value failed.");
744 return ERR_INVALID_PARAM;
745 }
746 } else {
747 AUDIO_ERR_LOG("get value failed.");
748 return ERR_INVALID_PARAM;
749 }
750 return 0;
751 }
752
SetAsrVoiceControlMode(AsrVoiceControlMode asrVoiceControlMode, bool on)753 int32_t AudioServer::SetAsrVoiceControlMode(AsrVoiceControlMode asrVoiceControlMode, bool on)
754 {
755 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
756 "Check playback permission failed, no system permission");
757 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
758 std::string key = "avcm";
759 std::string value = key + "=";
760
761 auto it = VC_MODE_MAP_VERSE.find(asrVoiceControlMode);
762 auto res = RES_MAP_VERSE.find(on);
763 if ((it != VC_MODE_MAP_VERSE.end()) && (res != RES_MAP_VERSE.end())) {
764 value = it->second + "=" + res->second;
765 } else {
766 AUDIO_ERR_LOG("get value failed.");
767 return ERR_INVALID_PARAM;
768 }
769 AudioServer::audioParameters[key] = value;
770 AudioParamKey parmKey = AudioParamKey::NONE;
771 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
772 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
773 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
774 return 0;
775 }
776
SetAsrVoiceMuteMode(AsrVoiceMuteMode asrVoiceMuteMode, bool on)777 int32_t AudioServer::SetAsrVoiceMuteMode(AsrVoiceMuteMode asrVoiceMuteMode, bool on)
778 {
779 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
780 "Check playback permission failed, no system permission");
781 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
782 std::string key = "avmm";
783 std::string value = key + "=";
784
785 auto it = VM_MODE_MAP_VERSE.find(asrVoiceMuteMode);
786 auto res = RES_MAP_VERSE.find(on);
787 if ((it != VM_MODE_MAP_VERSE.end()) && (res != RES_MAP_VERSE.end())) {
788 value = it->second + "=" + res->second;
789 } else {
790 AUDIO_ERR_LOG("get value failed.");
791 return ERR_INVALID_PARAM;
792 }
793 AudioServer::audioParameters[key] = value;
794 AudioParamKey parmKey = AudioParamKey::NONE;
795 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
796 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
797 audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
798 return 0;
799 }
800
IsWhispering()801 int32_t AudioServer::IsWhispering()
802 {
803 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_SYSTEM_PERMISSION_DENIED,
804 "Check playback permission failed, no system permission");
805 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
806 std::string key = "asr_is_whisper";
807 AudioParamKey parmKey = AudioParamKey::NONE;
808 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
809 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
810
811 std::string isWhisperSink = audioRendererSinkInstance->GetAudioParameter(parmKey, key);
812 int32_t whisperRes = 0;
813 if (isWhisperSink == "TRUE") {
814 whisperRes = 1;
815 }
816 return whisperRes;
817 }
818
SetAudioParameter(const std::string& networkId, const AudioParamKey key, const std::string& condition, const std::string& value)819 void AudioServer::SetAudioParameter(const std::string& networkId, const AudioParamKey key, const std::string& condition,
820 const std::string& value)
821 {
822 int32_t callingUid = IPCSkeleton::GetCallingUid();
823 bool ret = VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
824 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio() || ret, "refused for %{public}d", callingUid);
825 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("remote", networkId.c_str());
826 CHECK_AND_RETURN_LOG(audioRendererSinkInstance != nullptr, "has no valid sink");
827
828 audioRendererSinkInstance->SetAudioParameter(key, condition, value);
829 }
830
GetPcmDumpParameter(const std::vector<std::string> &subKeys, std::vector<std::pair<std::string, std::string>> &result)831 bool AudioServer::GetPcmDumpParameter(const std::vector<std::string> &subKeys,
832 std::vector<std::pair<std::string, std::string>> &result)
833 {
834 bool ret = VerifyClientPermission(DUMP_AUDIO_PERMISSION);
835 CHECK_AND_RETURN_RET_LOG(ret, false, "get audiodump parameters no permission");
836 int32_t res = Media::MediaMonitor::MediaMonitorManager::GetInstance().GetMediaParameters(subKeys, result);
837 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, false, "MediaMonitor GetMediaParameters failed");
838 return true;
839 }
840
GetExtraParameters(const std::string &mainKey, const std::vector<std::string> &subKeys, std::vector<std::pair<std::string, std::string>> &result)841 int32_t AudioServer::GetExtraParameters(const std::string &mainKey,
842 const std::vector<std::string> &subKeys, std::vector<std::pair<std::string, std::string>> &result)
843 {
844 if (mainKey == PCM_DUMP_KEY) {
845 bool ret = GetPcmDumpParameter(subKeys, result);
846 CHECK_AND_RETURN_RET_LOG(ret, ERROR, "get audiodump parameters failed");
847 return SUCCESS;
848 }
849
850 if (audioParameterKeys.empty()) {
851 AUDIO_ERR_LOG("audio extra parameters mainKey and subKey is empty");
852 return ERROR;
853 }
854
855 auto mainKeyIt = audioParameterKeys.find(mainKey);
856 if (mainKeyIt == audioParameterKeys.end()) {
857 return ERR_INVALID_PARAM;
858 }
859
860 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
861 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
862 std::unordered_map<std::string, std::set<std::string>> subKeyMap = mainKeyIt->second;
863 if (subKeys.empty()) {
864 for (auto it = subKeyMap.begin(); it != subKeyMap.end(); it++) {
865 std::string value = audioRendererSinkInstance->GetAudioParameter(AudioParamKey::NONE, it->first);
866 result.emplace_back(std::make_pair(it->first, value));
867 }
868 return SUCCESS;
869 }
870
871 bool match = true;
872 for (auto it = subKeys.begin(); it != subKeys.end(); it++) {
873 auto subKeyIt = subKeyMap.find(*it);
874 if (subKeyIt != subKeyMap.end()) {
875 std::string value = audioRendererSinkInstance->GetAudioParameter(AudioParamKey::NONE, *it);
876 result.emplace_back(std::make_pair(*it, value));
877 } else {
878 match = false;
879 break;
880 }
881 }
882 if (!match) {
883 result.clear();
884 return ERR_INVALID_PARAM;
885 }
886 return SUCCESS;
887 }
888
CheckAndPrintStacktrace(const std::string &key)889 bool AudioServer::CheckAndPrintStacktrace(const std::string &key)
890 {
891 AUDIO_WARNING_LOG("Start handle forced xcollie event for key %{public}s", key.c_str());
892 if (key == "dump_pulseaudio_stacktrace") {
893 AudioXCollie audioXCollie("AudioServer::PrintStackTrace", 1);
894 sleep(2); // sleep 2 seconds to dump stacktrace
895 return true;
896 } else if (key == "recovery_audio_server") {
897 AudioXCollie audioXCollie("AudioServer::Kill", 1, nullptr, nullptr, AUDIO_XCOLLIE_FLAG_RECOVERY);
898 sleep(2); // sleep 2 seconds to dump stacktrace
899 return true;
900 } else if (key == "dump_pa_stacktrace_and_kill") {
901 AudioXCollie audioXCollie("AudioServer::PrintStackTraceAndKill", 1, nullptr, nullptr,
902 AUDIO_XCOLLIE_FLAG_LOG | AUDIO_XCOLLIE_FLAG_RECOVERY);
903 sleep(2); // sleep 2 seconds to dump stacktrace
904 return true;
905 }
906 return false;
907 }
908
GetAudioParameter(const std::string &key)909 const std::string AudioServer::GetAudioParameter(const std::string &key)
910 {
911 if (IPCSkeleton::GetCallingUid() == MEDIA_SERVICE_UID && CheckAndPrintStacktrace(key) == true) {
912 return "";
913 }
914 std::lock_guard<std::mutex> lockSet(audioParameterMutex_);
915 AudioXCollie audioXCollie("GetAudioParameter", TIME_OUT_SECONDS);
916
917 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
918 if (audioRendererSinkInstance != nullptr) {
919 AudioParamKey parmKey = AudioParamKey::NONE;
920 if (key == "AUDIO_EXT_PARAM_KEY_LOWPOWER") {
921 parmKey = AudioParamKey::PARAM_KEY_LOWPOWER;
922 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey(parmKey), "");
923 }
924 if (key == "need_change_usb_device") {
925 parmKey = AudioParamKey::USB_DEVICE;
926 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey(parmKey), "need_change_usb_device");
927 }
928 if (key == "getSmartPAPOWER" || key == "show_RealTime_ChipModel") {
929 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey::NONE, key);
930 }
931 if (key == "perf_info") {
932 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey::PERF_INFO, key);
933 }
934 if (key.size() < BUNDLENAME_LENGTH_LIMIT && key.size() > CHECK_FAST_BLOCK_PREFIX.size() &&
935 key.substr(0, CHECK_FAST_BLOCK_PREFIX.size()) == CHECK_FAST_BLOCK_PREFIX) {
936 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey::NONE, key);
937 }
938
939 const std::string mmiPre = "mmi_";
940 if (key.size() > mmiPre.size()) {
941 if (key.substr(0, mmiPre.size()) == mmiPre) {
942 parmKey = AudioParamKey::MMI;
943 return audioRendererSinkInstance->GetAudioParameter(AudioParamKey(parmKey),
944 key.substr(mmiPre.size(), key.size() - mmiPre.size()));
945 }
946 }
947 }
948
949 if (AudioServer::audioParameters.count(key)) {
950 return AudioServer::audioParameters[key];
951 } else {
952 return "";
953 }
954 }
955
GetDPParameter(const std::string &condition)956 const std::string AudioServer::GetDPParameter(const std::string &condition)
957 {
958 IAudioRendererSink *dpAudioRendererSinkInstance = IAudioRendererSink::GetInstance("dp", "");
959 CHECK_AND_RETURN_RET_LOG(dpAudioRendererSinkInstance != nullptr, "", "get dp instance failed");
960
961 return dpAudioRendererSinkInstance->GetAudioParameter(AudioParamKey::GET_DP_DEVICE_INFO, condition);
962 }
963
GetUsbParameter()964 const std::string AudioServer::GetUsbParameter()
965 {
966 IAudioRendererSink *usbAudioRendererSinkInstance = IAudioRendererSink::GetInstance("usb", "");
967 IAudioCapturerSource *usbAudioCapturerSinkInstance = IAudioCapturerSource::GetInstance("usb", "");
968 if (usbAudioRendererSinkInstance != nullptr && usbAudioCapturerSinkInstance != nullptr) {
969 std::string usbInfoStr =
970 usbAudioRendererSinkInstance->GetAudioParameter(AudioParamKey::USB_DEVICE, "get_usb_info");
971 // Preload usb sink and source, make pa load module faster to avoid blocking client write
972 usbAudioRendererSinkInstance->Preload(usbInfoStr);
973 usbAudioCapturerSinkInstance->Preload(usbInfoStr);
974 return usbInfoStr;
975 }
976 return "";
977 }
978
GetAudioParameter(const std::string& networkId, const AudioParamKey key, const std::string& condition)979 const std::string AudioServer::GetAudioParameter(const std::string& networkId, const AudioParamKey key,
980 const std::string& condition)
981 {
982 int32_t callingUid = IPCSkeleton::GetCallingUid();
983 bool ret = VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
984 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio() || ret, "", "refused for %{public}d", callingUid);
985
986 if (networkId == LOCAL_NETWORK_ID) {
987 AudioXCollie audioXCollie("GetAudioParameter", TIME_OUT_SECONDS);
988 if (key == AudioParamKey::USB_DEVICE) {
989 return GetUsbParameter();
990 }
991 if (key == AudioParamKey::GET_DP_DEVICE_INFO) {
992 return GetDPParameter(condition);
993 }
994 } else {
995 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("remote", networkId.c_str());
996 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, "", "has no valid sink");
997 return audioRendererSinkInstance->GetAudioParameter(key, condition);
998 }
999 return "";
1000 }
1001
GetTransactionId(DeviceType deviceType, DeviceRole deviceRole)1002 uint64_t AudioServer::GetTransactionId(DeviceType deviceType, DeviceRole deviceRole)
1003 {
1004 uint64_t transactionId = 0;
1005 AUDIO_DEBUG_LOG("device type: %{public}d, device role: %{public}d", deviceType, deviceRole);
1006 if (deviceRole != INPUT_DEVICE && deviceRole != OUTPUT_DEVICE) {
1007 AUDIO_ERR_LOG("AudioServer::GetTransactionId: error device role");
1008 return ERR_INVALID_PARAM;
1009 }
1010 if (deviceRole == INPUT_DEVICE) {
1011 AudioCapturerSource *audioCapturerSourceInstance;
1012 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
1013 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("usb");
1014 } else {
1015 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("primary");
1016 }
1017 if (audioCapturerSourceInstance) {
1018 transactionId = audioCapturerSourceInstance->GetTransactionId();
1019 }
1020 return transactionId;
1021 }
1022
1023 // deviceRole OUTPUT_DEVICE
1024 IAudioRendererSink *iRendererInstance = nullptr;
1025 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1026 iRendererInstance = IAudioRendererSink::GetInstance("a2dp", "");
1027 } else if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
1028 iRendererInstance = IAudioRendererSink::GetInstance("usb", "");
1029 } else {
1030 iRendererInstance = IAudioRendererSink::GetInstance("primary", "");
1031 }
1032
1033 int32_t ret = ERROR;
1034 if (iRendererInstance != nullptr) {
1035 ret = iRendererInstance->GetTransactionId(&transactionId);
1036 }
1037
1038 CHECK_AND_RETURN_RET_LOG(!ret, transactionId, "Get transactionId failed.");
1039
1040 AUDIO_DEBUG_LOG("Transaction Id: %{public}" PRIu64, transactionId);
1041 return transactionId;
1042 }
1043
LoadAudioEffectLibraries(const std::vector<Library> libraries, const std::vector<Effect> effects, std::vector<Effect>& successEffectList)1044 bool AudioServer::LoadAudioEffectLibraries(const std::vector<Library> libraries, const std::vector<Effect> effects,
1045 std::vector<Effect>& successEffectList)
1046 {
1047 int32_t callingUid = IPCSkeleton::GetCallingUid();
1048 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), false, "LoadAudioEffectLibraries refused for %{public}d",
1049 callingUid);
1050 bool loadSuccess = audioEffectServer_->LoadAudioEffects(libraries, effects, successEffectList);
1051 if (!loadSuccess) {
1052 AUDIO_WARNING_LOG("Load audio effect failed, please check log");
1053 }
1054 return loadSuccess;
1055 }
1056
SetMicrophoneMute(bool isMute)1057 int32_t AudioServer::SetMicrophoneMute(bool isMute)
1058 {
1059 int32_t callingUid = IPCSkeleton::GetCallingUid();
1060 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_PERMISSION_DENIED, "refused for %{public}d",
1061 callingUid);
1062
1063 std::vector<IAudioCapturerSource *> allSourcesInstance;
1064 IAudioCapturerSource::GetAllInstance(allSourcesInstance);
1065 for (auto it = allSourcesInstance.begin(); it != allSourcesInstance.end(); ++it) {
1066 (*it)->SetMute(isMute);
1067 }
1068
1069 int32_t ret = SetMicrophoneMuteForEnhanceChain(isMute);
1070 if (ret != SUCCESS) {
1071 AUDIO_WARNING_LOG("SetMicrophoneMuteForEnhanceChain failed.");
1072 }
1073 return SUCCESS;
1074 }
1075
SetVoiceVolume(float volume)1076 int32_t AudioServer::SetVoiceVolume(float volume)
1077 {
1078 int32_t callingUid = IPCSkeleton::GetCallingUid();
1079 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d",
1080 callingUid);
1081 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1082
1083 if (audioRendererSinkInstance == nullptr) {
1084 AUDIO_WARNING_LOG("Renderer is null.");
1085 } else {
1086 return audioRendererSinkInstance->SetVoiceVolume(volume);
1087 }
1088 return ERROR;
1089 }
1090
OffloadSetVolume(float volume)1091 int32_t AudioServer::OffloadSetVolume(float volume)
1092 {
1093 int32_t callingUid = IPCSkeleton::GetCallingUid();
1094 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1095 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("offload", "");
1096
1097 if (audioRendererSinkInstance == nullptr) {
1098 AUDIO_ERR_LOG("Renderer is null.");
1099 return ERROR;
1100 }
1101 return audioRendererSinkInstance->SetVolume(volume, volume);
1102 }
1103
SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeOutputDevices, DeviceType activeInputDevice, BluetoothOffloadState a2dpOffloadFlag)1104 int32_t AudioServer::SetAudioScene(AudioScene audioScene, std::vector<DeviceType> &activeOutputDevices,
1105 DeviceType activeInputDevice, BluetoothOffloadState a2dpOffloadFlag)
1106 {
1107 std::lock_guard<std::mutex> lock(audioSceneMutex_);
1108
1109 DeviceType activeOutputDevice = activeOutputDevices.front();
1110 int32_t callingUid = IPCSkeleton::GetCallingUid();
1111 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1112 AudioXCollie audioXCollie("AudioServer::SetAudioScene", TIME_OUT_SECONDS);
1113 AudioCapturerSource *audioCapturerSourceInstance;
1114 IAudioRendererSink *audioRendererSinkInstance;
1115 if (activeOutputDevice == DEVICE_TYPE_USB_ARM_HEADSET) {
1116 audioRendererSinkInstance = IAudioRendererSink::GetInstance("usb", "");
1117 } else {
1118 audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1119 }
1120 if (activeInputDevice == DEVICE_TYPE_USB_ARM_HEADSET) {
1121 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("usb");
1122 } else {
1123 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("primary");
1124 }
1125
1126 if (audioCapturerSourceInstance == nullptr || !audioCapturerSourceInstance->IsInited()) {
1127 AUDIO_WARNING_LOG("Capturer is not initialized.");
1128 } else {
1129 audioCapturerSourceInstance->SetAudioScene(audioScene, activeInputDevice);
1130 }
1131
1132 if (audioRendererSinkInstance == nullptr || !audioRendererSinkInstance->IsInited()) {
1133 AUDIO_WARNING_LOG("Renderer is not initialized.");
1134 } else {
1135 if (activeOutputDevice == DEVICE_TYPE_BLUETOOTH_A2DP && a2dpOffloadFlag != A2DP_OFFLOAD) {
1136 activeOutputDevices[0] = DEVICE_TYPE_NONE;
1137 }
1138 audioRendererSinkInstance->SetAudioScene(audioScene, activeOutputDevices);
1139 }
1140
1141 audioScene_ = audioScene;
1142 return SUCCESS;
1143 }
1144
SetIORoutes(std::vector<std::pair<DeviceType, DeviceFlag>> &activeDevices, BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)1145 int32_t AudioServer::SetIORoutes(std::vector<std::pair<DeviceType, DeviceFlag>> &activeDevices,
1146 BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)
1147 {
1148 CHECK_AND_RETURN_RET_LOG(!activeDevices.empty() && activeDevices.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT,
1149 ERR_INVALID_PARAM, "Invalid audio devices.");
1150 DeviceType type = activeDevices.front().first;
1151 DeviceFlag flag = activeDevices.front().second;
1152
1153 std::vector<DeviceType> deviceTypes;
1154 for (auto activeDevice : activeDevices) {
1155 AUDIO_INFO_LOG("SetIORoutes device type:%{public}d", activeDevice.first);
1156 deviceTypes.push_back(activeDevice.first);
1157 }
1158 AUDIO_INFO_LOG("SetIORoutes 1st deviceType: %{public}d, flag: %{public}d deviceName:%{public}s",
1159 type, flag, deviceName.c_str());
1160 int32_t ret = SetIORoutes(type, flag, deviceTypes, a2dpOffloadFlag, deviceName);
1161 return ret;
1162 }
1163
SetIORoutes(DeviceType type, DeviceFlag flag, std::vector<DeviceType> deviceTypes, BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)1164 int32_t AudioServer::SetIORoutes(DeviceType type, DeviceFlag flag, std::vector<DeviceType> deviceTypes,
1165 BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)
1166 {
1167 IAudioCapturerSource *audioCapturerSourceInstance;
1168 IAudioRendererSink *audioRendererSinkInstance;
1169 if (type == DEVICE_TYPE_USB_ARM_HEADSET) {
1170 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("usb");
1171 audioRendererSinkInstance = IAudioRendererSink::GetInstance("usb", "");
1172 } else {
1173 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("primary");
1174 audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1175 if (!audioCapturerSourceInstance->IsInited()) {
1176 audioCapturerSourceInstance = FastAudioCapturerSource::GetInstance();
1177 }
1178 if (type == DEVICE_TYPE_BLUETOOTH_A2DP && a2dpOffloadFlag != A2DP_OFFLOAD &&
1179 deviceTypes.size() == 1 && deviceTypes[0] == DEVICE_TYPE_BLUETOOTH_A2DP) {
1180 deviceTypes[0] = DEVICE_TYPE_NONE;
1181 }
1182 }
1183 CHECK_AND_RETURN_RET_LOG(audioCapturerSourceInstance != nullptr && audioRendererSinkInstance != nullptr,
1184 ERR_INVALID_PARAM, "SetIORoutes failed for null instance!");
1185
1186 std::lock_guard<std::mutex> lock(audioSceneMutex_);
1187 if (flag == DeviceFlag::INPUT_DEVICES_FLAG) {
1188 if (audioScene_ != AUDIO_SCENE_DEFAULT) {
1189 audioCapturerSourceInstance->SetAudioScene(audioScene_, type, deviceName);
1190 } else {
1191 audioCapturerSourceInstance->SetInputRoute(type, deviceName);
1192 }
1193 } else if (flag == DeviceFlag::OUTPUT_DEVICES_FLAG) {
1194 if (audioScene_ != AUDIO_SCENE_DEFAULT) {
1195 audioRendererSinkInstance->SetAudioScene(audioScene_, deviceTypes);
1196 } else {
1197 audioRendererSinkInstance->SetOutputRoutes(deviceTypes);
1198 }
1199 PolicyHandler::GetInstance().SetActiveOutputDevice(type);
1200 } else if (flag == DeviceFlag::ALL_DEVICES_FLAG) {
1201 if (audioScene_ != AUDIO_SCENE_DEFAULT) {
1202 audioCapturerSourceInstance->SetAudioScene(audioScene_, type, deviceName);
1203 audioRendererSinkInstance->SetAudioScene(audioScene_, deviceTypes);
1204 } else {
1205 audioCapturerSourceInstance->SetInputRoute(type, deviceName);
1206 audioRendererSinkInstance->SetOutputRoutes(deviceTypes);
1207 }
1208 PolicyHandler::GetInstance().SetActiveOutputDevice(type);
1209 } else {
1210 AUDIO_ERR_LOG("SetIORoutes invalid device flag");
1211 return ERR_INVALID_PARAM;
1212 }
1213 return SUCCESS;
1214 }
1215
UpdateActiveDeviceRoute(DeviceType type, DeviceFlag flag, BluetoothOffloadState a2dpOffloadFlag)1216 int32_t AudioServer::UpdateActiveDeviceRoute(DeviceType type, DeviceFlag flag, BluetoothOffloadState a2dpOffloadFlag)
1217 {
1218 int32_t callingUid = IPCSkeleton::GetCallingUid();
1219 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1220
1221 std::vector<std::pair<DeviceType, DeviceFlag>> activeDevices;
1222 activeDevices.push_back(make_pair(type, flag));
1223 return UpdateActiveDevicesRoute(activeDevices, a2dpOffloadFlag);
1224 }
1225
UpdateActiveDevicesRoute(std::vector<std::pair<DeviceType, DeviceFlag>> &activeDevices, BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)1226 int32_t AudioServer::UpdateActiveDevicesRoute(std::vector<std::pair<DeviceType, DeviceFlag>> &activeDevices,
1227 BluetoothOffloadState a2dpOffloadFlag, const std::string &deviceName)
1228 {
1229 int32_t callingUid = IPCSkeleton::GetCallingUid();
1230 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1231 return SetIORoutes(activeDevices, a2dpOffloadFlag, deviceName);
1232 }
1233
SetAudioMonoState(bool audioMono)1234 void AudioServer::SetAudioMonoState(bool audioMono)
1235 {
1236 AUDIO_INFO_LOG("AudioMonoState = [%{public}s]", audioMono ? "true": "false");
1237 int32_t callingUid = IPCSkeleton::GetCallingUid();
1238 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "refused for %{public}d", callingUid);
1239 // Set mono for audio_renderer_sink (primary)
1240 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1241 if (audioRendererSinkInstance != nullptr) {
1242 audioRendererSinkInstance->SetAudioMonoState(audioMono);
1243 } else {
1244 AUDIO_ERR_LOG("AudioServer::SetAudioBalanceValue: primary = null");
1245 }
1246
1247 // Set mono for bluetooth_renderer_sink (a2dp)
1248 IAudioRendererSink *a2dpIAudioRendererSink = IAudioRendererSink::GetInstance("a2dp", "");
1249 if (a2dpIAudioRendererSink != nullptr) {
1250 a2dpIAudioRendererSink->SetAudioMonoState(audioMono);
1251 } else {
1252 AUDIO_ERR_LOG("AudioServer::SetAudioBalanceValue: a2dp = null");
1253 }
1254
1255 // Set mono for offload_audio_renderer_sink (offload)
1256 IAudioRendererSink *offloadIAudioRendererSink = IAudioRendererSink::GetInstance("offload", "");
1257 if (offloadIAudioRendererSink != nullptr) {
1258 offloadIAudioRendererSink->SetAudioMonoState(audioMono);
1259 } else {
1260 AUDIO_ERR_LOG("AudioServer::SetAudioBalanceValue: offload = null");
1261 }
1262
1263 // Set mono for audio_renderer_sink (direct)
1264 IAudioRendererSink *directRenderSink = AudioRendererSink::GetInstance("direct");
1265 if (directRenderSink != nullptr) {
1266 directRenderSink->SetAudioMonoState(audioMono);
1267 } else {
1268 AUDIO_WARNING_LOG("direct = null");
1269 }
1270
1271 // Set mono for audio_renderer_sink (voip)
1272 IAudioRendererSink *voipRenderSink = AudioRendererSink::GetInstance("voip");
1273 if (voipRenderSink != nullptr) {
1274 voipRenderSink->SetAudioMonoState(audioMono);
1275 } else {
1276 AUDIO_WARNING_LOG("voip = null");
1277 }
1278 }
1279
SetAudioBalanceValue(float audioBalance)1280 void AudioServer::SetAudioBalanceValue(float audioBalance)
1281 {
1282 AUDIO_INFO_LOG("AudioBalanceValue = [%{public}f]", audioBalance);
1283 int32_t callingUid = IPCSkeleton::GetCallingUid();
1284 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "refused for %{public}d", callingUid);
1285 CHECK_AND_RETURN_LOG(audioBalance >= -1.0f && audioBalance <= 1.0f,
1286 "audioBalance value %{public}f is out of range [-1.0, 1.0]", audioBalance);
1287
1288 // Set balance for audio_renderer_sink (primary)
1289 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1290 if (audioRendererSinkInstance != nullptr) {
1291 audioRendererSinkInstance->SetAudioBalanceValue(audioBalance);
1292 } else {
1293 AUDIO_WARNING_LOG("primary = null");
1294 }
1295
1296 // Set balance for bluetooth_renderer_sink (a2dp)
1297 IAudioRendererSink *a2dpIAudioRendererSink = IAudioRendererSink::GetInstance("a2dp", "");
1298 if (a2dpIAudioRendererSink != nullptr) {
1299 a2dpIAudioRendererSink->SetAudioBalanceValue(audioBalance);
1300 } else {
1301 AUDIO_WARNING_LOG("a2dp = null");
1302 }
1303
1304 // Set balance for offload_audio_renderer_sink (offload)
1305 IAudioRendererSink *offloadIAudioRendererSink = IAudioRendererSink::GetInstance("offload", "");
1306 if (offloadIAudioRendererSink != nullptr) {
1307 offloadIAudioRendererSink->SetAudioBalanceValue(audioBalance);
1308 } else {
1309 AUDIO_WARNING_LOG("offload = null");
1310 }
1311
1312 // Set balance for audio_renderer_sink (direct)
1313 IAudioRendererSink *directRenderSink = AudioRendererSink::GetInstance("direct");
1314 if (directRenderSink != nullptr) {
1315 directRenderSink->SetAudioBalanceValue(audioBalance);
1316 } else {
1317 AUDIO_WARNING_LOG("direct = null");
1318 }
1319
1320 // Set balance for audio_renderer_sink (voip)
1321 IAudioRendererSink *voipRenderSink = AudioRendererSink::GetInstance("voip");
1322 if (voipRenderSink != nullptr) {
1323 voipRenderSink->SetAudioBalanceValue(audioBalance);
1324 } else {
1325 AUDIO_WARNING_LOG("voip = null");
1326 }
1327 }
1328
NotifyDeviceInfo(std::string networkId, bool connected)1329 void AudioServer::NotifyDeviceInfo(std::string networkId, bool connected)
1330 {
1331 int32_t callingUid = IPCSkeleton::GetCallingUid();
1332 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "refused for %{public}d", callingUid);
1333 AUDIO_INFO_LOG("notify device info: networkId(%{public}s), connected(%{public}d)",
1334 GetEncryptStr(networkId).c_str(), connected);
1335 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance("remote", networkId.c_str());
1336 if (audioRendererSinkInstance != nullptr && connected) {
1337 audioRendererSinkInstance->RegisterParameterCallback(this);
1338 }
1339 }
1340
IsParamEnabled(std::string key, bool &isEnabled)1341 inline bool IsParamEnabled(std::string key, bool &isEnabled)
1342 {
1343 int32_t policyFlag = 0;
1344 if (GetSysPara(key.c_str(), policyFlag) && policyFlag == 1) {
1345 isEnabled = true;
1346 return true;
1347 }
1348 isEnabled = false;
1349 return false;
1350 }
1351
RegiestPolicyProvider(const sptr<IRemoteObject> &object)1352 int32_t AudioServer::RegiestPolicyProvider(const sptr<IRemoteObject> &object)
1353 {
1354 int32_t callingUid = IPCSkeleton::GetCallingUid();
1355 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1356 sptr<IPolicyProviderIpc> policyProvider = iface_cast<IPolicyProviderIpc>(object);
1357 CHECK_AND_RETURN_RET_LOG(policyProvider != nullptr, ERR_INVALID_PARAM,
1358 "policyProvider obj cast failed");
1359 bool ret = PolicyHandler::GetInstance().ConfigPolicyProvider(policyProvider);
1360 CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED, "ConfigPolicyProvider failed!");
1361 return SUCCESS;
1362 }
1363
GetHapBuildApiVersion(int32_t callerUid)1364 int32_t AudioServer::GetHapBuildApiVersion(int32_t callerUid)
1365 {
1366 AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName",
1367 GET_BUNDLE_TIME_OUT_SECONDS);
1368 std::string bundleName {""};
1369 AppExecFwk::BundleInfo bundleInfo;
1370 auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1371 CHECK_AND_RETURN_RET_LOG(saManager != nullptr, 0, "failed: saManager is nullptr");
1372
1373 sptr<IRemoteObject> remoteObject = saManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1374 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, 0, "failed: remoteObject is nullptr");
1375
1376 sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1377 CHECK_AND_RETURN_RET_LOG(bundleMgrProxy != nullptr, 0, "failed: bundleMgrProxy is nullptr");
1378
1379 bundleMgrProxy->GetNameForUid(callerUid, bundleName);
1380 bundleMgrProxy->GetBundleInfoV9(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT |
1381 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES |
1382 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION |
1383 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO |
1384 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_HASH_VALUE,
1385 bundleInfo,
1386 AppExecFwk::Constants::ALL_USERID);
1387 int32_t hapApiVersion = bundleInfo.applicationInfo.apiTargetVersion % API_VERSION_REMAINDER;
1388 AUDIO_INFO_LOG("callerUid %{public}d, version %{public}d", callerUid, hapApiVersion);
1389 return hapApiVersion;
1390 }
1391
ResetRecordConfig(AudioProcessConfig &config)1392 void AudioServer::ResetRecordConfig(AudioProcessConfig &config)
1393 {
1394 if (config.capturerInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE) {
1395 config.isInnerCapturer = true;
1396 config.innerCapMode = LEGACY_INNER_CAP;
1397 if (PermissionUtil::VerifyPermission(CAPTURE_PLAYBACK_PERMISSION, IPCSkeleton::GetCallingTokenID())) {
1398 AUDIO_INFO_LOG("CAPTURE_PLAYBACK permission granted");
1399 config.innerCapMode = MODERN_INNER_CAP;
1400 } else if (config.callerUid == MEDIA_SERVICE_UID || config.callerUid == VASSISTANT_UID) {
1401 config.innerCapMode = MODERN_INNER_CAP;
1402 } else if (GetHapBuildApiVersion(config.callerUid) >= MODERN_INNER_API_VERSION) { // check build api-version
1403 config.innerCapMode = LEGACY_MUTE_CAP;
1404 }
1405 AUDIO_INFO_LOG("callerUid %{public}d, innerCapMode %{public}d", config.callerUid, config.innerCapMode);
1406 } else {
1407 AUDIO_INFO_LOG("CAPTURE_PLAYBACK permission denied");
1408 config.isInnerCapturer = false;
1409 }
1410 #ifdef AUDIO_BUILD_VARIANT_ROOT
1411 if (config.callerUid == ROOT_UID) {
1412 config.innerCapMode = MODERN_INNER_CAP;
1413 }
1414 #endif
1415 if (config.capturerInfo.sourceType == SourceType::SOURCE_TYPE_WAKEUP) {
1416 config.isWakeupCapturer = true;
1417 } else {
1418 config.isWakeupCapturer = false;
1419 }
1420 }
1421
ResetProcessConfig(const AudioProcessConfig &config)1422 AudioProcessConfig AudioServer::ResetProcessConfig(const AudioProcessConfig &config)
1423 {
1424 AudioProcessConfig resetConfig(config);
1425
1426 int32_t callerUid = IPCSkeleton::GetCallingUid();
1427 int32_t callerPid = IPCSkeleton::GetCallingPid();
1428
1429 resetConfig.callerUid = callerUid;
1430
1431 // client pid uid check.
1432 if (RECORD_PASS_APPINFO_LIST.count(callerUid)) {
1433 AUDIO_INFO_LOG("Create process for %{public}d, clientUid:%{public}d.", callerUid, config.appInfo.appUid);
1434 } else if (RECORD_CHECK_FORWARD_LIST.count(callerUid)) {
1435 AUDIO_INFO_LOG("Check forward calling for uid:%{public}d", callerUid);
1436 resetConfig.appInfo.appTokenId = IPCSkeleton::GetFirstTokenID();
1437 resetConfig.appInfo.appFullTokenId = IPCSkeleton::GetFirstFullTokenID();
1438 } else {
1439 AUDIO_INFO_LOG("Use true client appInfo instead for pid:%{public}d uid:%{public}d", callerPid, callerUid);
1440 resetConfig.appInfo.appPid = callerPid;
1441 resetConfig.appInfo.appUid = callerUid;
1442 resetConfig.appInfo.appTokenId = IPCSkeleton::GetCallingTokenID();
1443 resetConfig.appInfo.appFullTokenId = IPCSkeleton::GetCallingFullTokenID();
1444 }
1445
1446 if (resetConfig.audioMode == AUDIO_MODE_RECORD) {
1447 ResetRecordConfig(resetConfig);
1448 }
1449 return resetConfig;
1450 }
1451
CheckStreamInfoFormat(const AudioProcessConfig &config)1452 bool AudioServer::CheckStreamInfoFormat(const AudioProcessConfig &config)
1453 {
1454 if (NotContain(AUDIO_SUPPORTED_SAMPLING_RATES, config.streamInfo.samplingRate)) {
1455 AUDIO_ERR_LOG("Check format failed invalid samplingRate:%{public}d", config.streamInfo.samplingRate);
1456 return false;
1457 }
1458
1459 if (NotContain(AUDIO_SUPPORTED_FORMATS, config.streamInfo.format)) {
1460 AUDIO_ERR_LOG("Check format failed invalid format:%{public}d", config.streamInfo.format);
1461 return false;
1462 }
1463
1464 if (NotContain(AUDIO_SUPPORTED_ENCODING_TYPES, config.streamInfo.encoding)) {
1465 AUDIO_ERR_LOG("Check format failed invalid encoding:%{public}d", config.streamInfo.encoding);
1466 return false;
1467 }
1468
1469 // both renderer and capturer check RENDERER_SUPPORTED_CHANNELLAYOUTS, should we rename it?
1470 if (NotContain(RENDERER_SUPPORTED_CHANNELLAYOUTS, config.streamInfo.channelLayout)) {
1471 AUDIO_ERR_LOG("Check format failed invalid channelLayout:%{public}" PRId64".", config.streamInfo.channelLayout);
1472 return false;
1473 }
1474
1475 if (config.audioMode == AUDIO_MODE_PLAYBACK && NotContain(RENDERER_SUPPORTED_CHANNELS,
1476 config.streamInfo.channels)) {
1477 AUDIO_ERR_LOG("Check format failed invalid renderer channels:%{public}d", config.streamInfo.channels);
1478 return false;
1479 }
1480
1481 if (config.audioMode == AUDIO_MODE_RECORD && NotContain(CAPTURER_SUPPORTED_CHANNELS, config.streamInfo.channels)) {
1482 AUDIO_ERR_LOG("Check format failed invalid capturer channels:%{public}d", config.streamInfo.channels);
1483 return false;
1484 }
1485
1486 return true;
1487 }
1488
CheckRendererFormat(const AudioProcessConfig &config)1489 bool AudioServer::CheckRendererFormat(const AudioProcessConfig &config)
1490 {
1491 if (NotContain(AUDIO_SUPPORTED_STREAM_USAGES, config.rendererInfo.streamUsage)) {
1492 AUDIO_ERR_LOG("Check format failed invalid streamUsage:%{public}d", config.rendererInfo.streamUsage);
1493 return false;
1494 }
1495 return true;
1496 }
1497
CheckRecorderFormat(const AudioProcessConfig &config)1498 bool AudioServer::CheckRecorderFormat(const AudioProcessConfig &config)
1499 {
1500 if (NotContain(AUDIO_SUPPORTED_SOURCE_TYPES, config.capturerInfo.sourceType)) {
1501 AUDIO_ERR_LOG("Check format failed invalid sourceType:%{public}d", config.capturerInfo.sourceType);
1502 return false;
1503 }
1504 if (config.capturerInfo.capturerFlags != AUDIO_FLAG_NORMAL && NotContain(AUDIO_FAST_STREAM_SUPPORTED_SOURCE_TYPES,
1505 config.capturerInfo.sourceType)) {
1506 AUDIO_ERR_LOG("Check format failed invalid fast sourceType:%{public}d", config.capturerInfo.sourceType);
1507 return false;
1508 }
1509 return true;
1510 }
1511
CheckConfigFormat(const AudioProcessConfig &config)1512 bool AudioServer::CheckConfigFormat(const AudioProcessConfig &config)
1513 {
1514 if (!CheckStreamInfoFormat(config)) {
1515 return false;
1516 }
1517 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1518 return CheckRendererFormat(config);
1519 }
1520
1521 if (config.audioMode == AUDIO_MODE_RECORD) {
1522 return CheckRecorderFormat(config);
1523 }
1524
1525 AUDIO_ERR_LOG("Check format failed invalid mode.");
1526 return false;
1527 }
1528
GetBundleNameFromUid(int32_t uid)1529 const std::string AudioServer::GetBundleNameFromUid(int32_t uid)
1530 {
1531 AudioXCollie audioXCollie("AudioServer::GetBundleNameFromUid",
1532 GET_BUNDLE_TIME_OUT_SECONDS);
1533 std::string bundleName {""};
1534 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1535 CHECK_AND_RETURN_RET_LOG(systemAbilityManager != nullptr, "", "systemAbilityManager is nullptr");
1536
1537 sptr<IRemoteObject> remoteObject = systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1538 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, "", "remoteObject is nullptr");
1539
1540 sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1541 CHECK_AND_RETURN_RET_LOG(bundleMgrProxy != nullptr, "", "bundleMgrProxy is nullptr");
1542
1543 bundleMgrProxy->GetNameForUid(uid, bundleName);
1544
1545 return bundleName;
1546 }
1547
IsFastBlocked(int32_t uid)1548 bool AudioServer::IsFastBlocked(int32_t uid)
1549 {
1550 std::string bundleName = GetBundleNameFromUid(uid);
1551 std::string result = GetAudioParameter(CHECK_FAST_BLOCK_PREFIX + bundleName);
1552 return result == "true";
1553 }
1554
SendRendererCreateErrorInfo(const StreamUsage &sreamUsage, const int32_t &errorCode)1555 void AudioServer::SendRendererCreateErrorInfo(const StreamUsage &sreamUsage,
1556 const int32_t &errorCode)
1557 {
1558 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1559 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_STREAM_CREATE_ERROR_STATS,
1560 Media::MediaMonitor::FREQUENCY_AGGREGATION_EVENT);
1561 bean->Add("IS_PLAYBACK", 1);
1562 bean->Add("CLIENT_UID", static_cast<int32_t>(getuid()));
1563 bean->Add("STREAM_TYPE", sreamUsage);
1564 bean->Add("ERROR_CODE", errorCode);
1565 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1566 }
1567
CheckParam(const AudioProcessConfig &config)1568 int32_t AudioServer::CheckParam(const AudioProcessConfig &config)
1569 {
1570 ContentType contentType = config.rendererInfo.contentType;
1571 if (contentType < CONTENT_TYPE_UNKNOWN || contentType > CONTENT_TYPE_ULTRASONIC) {
1572 SendRendererCreateErrorInfo(config.rendererInfo.streamUsage,
1573 ERR_INVALID_PARAM);
1574 AUDIO_ERR_LOG("Invalid content type");
1575 return ERR_INVALID_PARAM;
1576 }
1577
1578 StreamUsage streamUsage = config.rendererInfo.streamUsage;
1579 if (streamUsage < STREAM_USAGE_UNKNOWN || streamUsage > STREAM_USAGE_MAX) {
1580 SendRendererCreateErrorInfo(config.rendererInfo.streamUsage,
1581 ERR_INVALID_PARAM);
1582 AUDIO_ERR_LOG("Invalid stream usage");
1583 return ERR_INVALID_PARAM;
1584 }
1585
1586 if (contentType == CONTENT_TYPE_ULTRASONIC || IsNeedVerifyPermission(streamUsage)) {
1587 if (!PermissionUtil::VerifySystemPermission()) {
1588 SendRendererCreateErrorInfo(config.rendererInfo.streamUsage,
1589 ERR_PERMISSION_DENIED);
1590 AUDIO_ERR_LOG("CreateAudioRenderer failed! CONTENT_TYPE_ULTRASONIC or STREAM_USAGE_SYSTEM or "\
1591 "STREAM_USAGE_VOICE_MODEM_COMMUNICATION: No system permission");
1592 return ERR_PERMISSION_DENIED;
1593 }
1594 }
1595 return SUCCESS;
1596 }
1597
CheckMaxRendererInstances()1598 int32_t AudioServer::CheckMaxRendererInstances()
1599 {
1600 int32_t maxRendererInstances = PolicyHandler::GetInstance().GetMaxRendererInstances();
1601 if (maxRendererInstances <= 0) {
1602 maxRendererInstances = DEFAULT_MAX_RENDERER_INSTANCES;
1603 }
1604
1605 if (AudioService::GetInstance()->GetCurrentRendererStreamCnt() >= maxRendererInstances) {
1606 int32_t mostAppUid = INVALID_APP_UID;
1607 int32_t mostAppNum = INVALID_APP_CREATED_AUDIO_STREAM_NUM;
1608 AudioService::GetInstance()->GetCreatedAudioStreamMostUid(mostAppUid, mostAppNum);
1609 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1610 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_STREAM_EXHAUSTED_STATS,
1611 Media::MediaMonitor::EventType::FREQUENCY_AGGREGATION_EVENT);
1612 bean->Add("CLIENT_UID", mostAppUid);
1613 bean->Add("TIMES", mostAppNum);
1614 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1615 AUDIO_ERR_LOG("Current audio renderer stream num is greater than the maximum num of configured instances");
1616 return ERR_EXCEED_MAX_STREAM_CNT;
1617 }
1618 return SUCCESS;
1619 }
1620
CreateAudioStream(const AudioProcessConfig &config, int32_t callingUid)1621 sptr<IRemoteObject> AudioServer::CreateAudioStream(const AudioProcessConfig &config, int32_t callingUid)
1622 {
1623 int32_t appUid = config.appInfo.appUid;
1624 if (callingUid != MEDIA_SERVICE_UID) {
1625 appUid = callingUid;
1626 }
1627 if (IsNormalIpcStream(config) || (isFastControlled_ && IsFastBlocked(config.appInfo.appUid))) {
1628 AUDIO_INFO_LOG("Create normal ipc stream, isFastControlled: %{public}d", isFastControlled_);
1629 int32_t ret = 0;
1630 sptr<IpcStreamInServer> ipcStream = AudioService::GetInstance()->GetIpcStream(config, ret);
1631 if (ipcStream == nullptr) {
1632 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1633 AudioService::GetInstance()->CleanUpStream(appUid, false);
1634 }
1635 AUDIO_ERR_LOG("GetIpcStream failed.");
1636 return nullptr;
1637 }
1638 AudioService::GetInstance()->SetIncMaxRendererStreamCnt(config.audioMode);
1639 sptr<IRemoteObject> remoteObject= ipcStream->AsObject();
1640 return remoteObject;
1641 }
1642
1643 sptr<IAudioProcess> process = AudioService::GetInstance()->GetAudioProcess(config);
1644 if (process == nullptr) {
1645 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1646 AudioService::GetInstance()->CleanUpStream(appUid, false);
1647 }
1648 AUDIO_ERR_LOG("GetAudioProcess failed.");
1649 return nullptr;
1650 }
1651 AudioService::GetInstance()->SetIncMaxRendererStreamCnt(config.audioMode);
1652 sptr<IRemoteObject> remoteObject= process->AsObject();
1653 return remoteObject;
1654 }
1655
CreateAudioProcess(const AudioProcessConfig &config, int32_t &errorCode)1656 sptr<IRemoteObject> AudioServer::CreateAudioProcess(const AudioProcessConfig &config, int32_t &errorCode)
1657 {
1658 Trace trace("AudioServer::CreateAudioProcess");
1659 AudioProcessConfig resetConfig = ResetProcessConfig(config);
1660 CHECK_AND_RETURN_RET_LOG(CheckConfigFormat(resetConfig), nullptr, "AudioProcessConfig format is wrong, please check"
1661 ":%{public}s", ProcessConfig::DumpProcessConfig(resetConfig).c_str());
1662 CHECK_AND_RETURN_RET_LOG(PermissionChecker(resetConfig), nullptr, "Create audio process failed, no permission");
1663
1664 std::lock_guard<std::mutex> lock(streamLifeCycleMutex_);
1665 int32_t ret = CheckParam(config);
1666 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, nullptr, "Check params failed");
1667 int32_t callingUid = IPCSkeleton::GetCallingUid();
1668 if (resetConfig.audioMode == AUDIO_MODE_PLAYBACK) {
1669 errorCode = CheckMaxRendererInstances();
1670 if (errorCode != SUCCESS) {
1671 return nullptr;
1672 }
1673 if (AudioService::GetInstance()->IsExceedingMaxStreamCntPerUid(callingUid, resetConfig.appInfo.appUid,
1674 maxRendererStreamCntPerUid_)) {
1675 errorCode = ERR_EXCEED_MAX_STREAM_CNT_PER_UID;
1676 AUDIO_ERR_LOG("Current audio renderer stream num exceeds maxRendererStreamCntPerUid");
1677 return nullptr;
1678 }
1679 }
1680
1681 if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION && callingUid == UID_FOUNDATION_SA
1682 && config.rendererInfo.isSatellite) {
1683 bool isSupportSate = OHOS::system::GetBoolParameter(TEL_SATELLITE_SUPPORT, false);
1684 CHECK_AND_RETURN_RET_LOG(isSupportSate, nullptr, "Do not support satellite");
1685 IAudioRendererSink* audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
1686 audioRendererSinkInstance->SetAudioParameter(AudioParamKey::NONE, "", SATEMODEM_PARAMETER);
1687 }
1688 #ifdef FEATURE_APPGALLERY
1689 PolicyHandler::GetInstance().GetAndSaveClientType(resetConfig.appInfo.appUid,
1690 GetBundleNameFromUid(resetConfig.appInfo.appUid));
1691 #endif
1692
1693 return CreateAudioStream(resetConfig, callingUid);
1694 }
1695
IsNormalIpcStream(const AudioProcessConfig &config) const1696 bool AudioServer::IsNormalIpcStream(const AudioProcessConfig &config) const
1697 {
1698 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1699 return config.rendererInfo.rendererFlags == AUDIO_FLAG_NORMAL ||
1700 config.rendererInfo.rendererFlags == AUDIO_FLAG_VOIP_DIRECT;
1701 } else if (config.audioMode == AUDIO_MODE_RECORD) {
1702 return config.capturerInfo.capturerFlags == AUDIO_FLAG_NORMAL;
1703 }
1704
1705 return false;
1706 }
1707
CheckRemoteDeviceState(std::string networkId, DeviceRole deviceRole, bool isStartDevice)1708 int32_t AudioServer::CheckRemoteDeviceState(std::string networkId, DeviceRole deviceRole, bool isStartDevice)
1709 {
1710 AUDIO_INFO_LOG("CheckRemoteDeviceState: device[%{public}s] deviceRole[%{public}d] isStartDevice[%{public}s]",
1711 GetEncryptStr(networkId).c_str(), static_cast<int32_t>(deviceRole), (isStartDevice ? "true" : "false"));
1712
1713 int32_t callingUid = IPCSkeleton::GetCallingUid();
1714 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1715 CHECK_AND_RETURN_RET(isStartDevice, SUCCESS);
1716
1717 int32_t ret = SUCCESS;
1718 switch (deviceRole) {
1719 case OUTPUT_DEVICE:
1720 {
1721 IAudioRendererSink* rendererInstance = IAudioRendererSink::GetInstance("remote", networkId.c_str());
1722 if (rendererInstance == nullptr || !rendererInstance->IsInited()) {
1723 AUDIO_ERR_LOG("Remote renderer[%{public}s] is uninit.", networkId.c_str());
1724 return ERR_ILLEGAL_STATE;
1725 }
1726 ret = rendererInstance->Start();
1727 break;
1728 }
1729 case INPUT_DEVICE:
1730 {
1731 IAudioCapturerSource *capturerInstance = IAudioCapturerSource::GetInstance("remote", networkId.c_str());
1732 if (capturerInstance == nullptr || !capturerInstance->IsInited()) {
1733 AUDIO_ERR_LOG("Remote capturer[%{public}s] is uninit.", networkId.c_str());
1734 return ERR_ILLEGAL_STATE;
1735 }
1736 ret = capturerInstance->Start();
1737 break;
1738 }
1739 default:
1740 AUDIO_ERR_LOG("Remote device role %{public}d is not supported.", deviceRole);
1741 return ERR_NOT_SUPPORTED;
1742 }
1743 if (ret != SUCCESS) {
1744 AUDIO_ERR_LOG("Check remote device[%{public}s] fail, ret %{public}d.", networkId.c_str(), ret);
1745 }
1746 return ret;
1747 }
1748
OnAudioSinkParamChange(const std::string &netWorkId, const AudioParamKey key, const std::string &condition, const std::string &value)1749 void AudioServer::OnAudioSinkParamChange(const std::string &netWorkId, const AudioParamKey key,
1750 const std::string &condition, const std::string &value)
1751 {
1752 std::shared_ptr<AudioParameterCallback> callback = nullptr;
1753 {
1754 std::lock_guard<std::mutex> lockSet(audioParamCbMtx_);
1755 AUDIO_INFO_LOG("OnAudioSinkParamChange Callback from networkId: %s", netWorkId.c_str());
1756 CHECK_AND_RETURN_LOG(audioParamCb_ != nullptr, "OnAudioSinkParamChange: audio param allback is null.");
1757 callback = audioParamCb_;
1758 }
1759 callback->OnAudioParameterChange(netWorkId, key, condition, value);
1760 }
1761
OnAudioSourceParamChange(const std::string &netWorkId, const AudioParamKey key, const std::string &condition, const std::string &value)1762 void AudioServer::OnAudioSourceParamChange(const std::string &netWorkId, const AudioParamKey key,
1763 const std::string &condition, const std::string &value)
1764 {
1765 std::shared_ptr<AudioParameterCallback> callback = nullptr;
1766 {
1767 std::lock_guard<std::mutex> lockSet(audioParamCbMtx_);
1768 AUDIO_INFO_LOG("OnAudioSourceParamChange Callback from networkId: %s", netWorkId.c_str());
1769 CHECK_AND_RETURN_LOG(audioParamCb_ != nullptr, "OnAudioSourceParamChange: audio param allback is null.");
1770 callback = audioParamCb_;
1771 }
1772 callback->OnAudioParameterChange(netWorkId, key, condition, value);
1773 }
1774
OnWakeupClose()1775 void AudioServer::OnWakeupClose()
1776 {
1777 AUDIO_INFO_LOG("OnWakeupClose Callback start");
1778 std::shared_ptr<WakeUpSourceCallback> callback = nullptr;
1779 {
1780 std::lock_guard<std::mutex> lockSet(setWakeupCloseCallbackMutex_);
1781 CHECK_AND_RETURN_LOG(wakeupCallback_ != nullptr, "OnWakeupClose callback is nullptr.");
1782 callback = wakeupCallback_;
1783 }
1784 callback->OnWakeupClose();
1785 }
1786
OnCapturerState(bool isActive, int32_t num)1787 void AudioServer::OnCapturerState(bool isActive, int32_t num)
1788 {
1789 AUDIO_DEBUG_LOG("OnCapturerState Callback start");
1790 std::shared_ptr<WakeUpSourceCallback> callback = nullptr;
1791 {
1792 std::lock_guard<std::mutex> lockSet(setWakeupCloseCallbackMutex_);
1793 callback = wakeupCallback_;
1794 }
1795
1796 // Ensure that the send callback is not executed concurrently
1797 std::lock_guard<std::mutex> lockCb(onCapturerStateCbMutex_);
1798
1799 uint64_t previousStateFlag;
1800 uint64_t currentStateFlag;
1801 if (isActive) {
1802 uint64_t tempFlag = static_cast<uint64_t>(1) << num;
1803 previousStateFlag = capturerStateFlag_.fetch_or(tempFlag);
1804 currentStateFlag = previousStateFlag | tempFlag;
1805 } else {
1806 uint64_t tempFlag = ~(static_cast<uint64_t>(1) << num);
1807 previousStateFlag = capturerStateFlag_.fetch_and(tempFlag);
1808 currentStateFlag = previousStateFlag & tempFlag;
1809 }
1810 bool previousState = previousStateFlag;
1811 bool currentState = currentStateFlag;
1812
1813 if (previousState == currentState) {
1814 // state not change, need not trigger callback
1815 return;
1816 }
1817
1818 CHECK_AND_RETURN_LOG(callback != nullptr, "OnCapturerState callback is nullptr.");
1819 Trace traceCb("callbackToIntelligentVoice");
1820 int64_t stamp = ClockTime::GetCurNano();
1821 callback->OnCapturerState(isActive);
1822 stamp = (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND;
1823 AUDIO_INFO_LOG("isActive:%{public}d num:%{public}d cb cost[%{public}" PRId64 "]", isActive, num, stamp);
1824 }
1825
SetParameterCallback(const sptr<IRemoteObject>& object)1826 int32_t AudioServer::SetParameterCallback(const sptr<IRemoteObject>& object)
1827 {
1828 int32_t callingUid = IPCSkeleton::GetCallingUid();
1829 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
1830 std::lock_guard<std::mutex> lock(audioParamCbMtx_);
1831 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioServer:set listener object is nullptr");
1832
1833 sptr<IStandardAudioServerManagerListener> listener = iface_cast<IStandardAudioServerManagerListener>(object);
1834
1835 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioServer: listener obj cast failed");
1836
1837 std::shared_ptr<AudioParameterCallback> callback = std::make_shared<AudioManagerListenerCallback>(listener);
1838 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
1839
1840 audioParamCb_ = callback;
1841 AUDIO_INFO_LOG("AudioServer:: SetParameterCallback done");
1842
1843 return SUCCESS;
1844 }
1845
SetWakeupSourceCallback(const sptr<IRemoteObject>& object)1846 int32_t AudioServer::SetWakeupSourceCallback(const sptr<IRemoteObject>& object)
1847 {
1848 int32_t callingUid = IPCSkeleton::GetCallingUid();
1849 CHECK_AND_RETURN_RET_LOG(callingUid == INTELL_VOICE_SERVICR_UID, false,
1850 "SetWakeupSourceCallback refused for %{public}d", callingUid);
1851
1852 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
1853 "SetWakeupCloseCallback set listener object is nullptr");
1854
1855 sptr<IStandardAudioServerManagerListener> listener = iface_cast<IStandardAudioServerManagerListener>(object);
1856
1857 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM,
1858 "SetWakeupCloseCallback listener obj cast failed");
1859
1860 std::shared_ptr<AudioManagerListenerCallback> wakeupCallback
1861 = std::make_shared<AudioManagerListenerCallback>(listener);
1862 CHECK_AND_RETURN_RET_LOG(wakeupCallback != nullptr, ERR_INVALID_PARAM,
1863 "SetWakeupCloseCallback failed to create cb obj");
1864
1865 {
1866 std::lock_guard<std::mutex> lockSet(setWakeupCloseCallbackMutex_);
1867 wakeupCallback_ = wakeupCallback;
1868 }
1869
1870 std::thread([this, wakeupCallback] {
1871 std::lock_guard<std::mutex> lockCb(onCapturerStateCbMutex_);
1872 wakeupCallback->TrigerFirstOnCapturerStateCallback(capturerStateFlag_);
1873 }).detach();
1874
1875 AUDIO_INFO_LOG("SetWakeupCloseCallback done");
1876
1877 return SUCCESS;
1878 }
1879
VerifyClientPermission(const std::string &permissionName, Security::AccessToken::AccessTokenID tokenId)1880 bool AudioServer::VerifyClientPermission(const std::string &permissionName,
1881 Security::AccessToken::AccessTokenID tokenId)
1882 {
1883 auto callerUid = IPCSkeleton::GetCallingUid();
1884 AUDIO_INFO_LOG("[%{public}s] for uid:%{public}d tokenId:%{public}u", permissionName.c_str(), callerUid, tokenId);
1885
1886 #ifdef AUDIO_BUILD_VARIANT_ROOT
1887 // Root users should be whitelisted
1888 if (callerUid == ROOT_UID) {
1889 AUDIO_INFO_LOG("Root user. Permission GRANTED!!!");
1890 return true;
1891 }
1892 #endif
1893 Security::AccessToken::AccessTokenID clientTokenId = tokenId;
1894 if (clientTokenId == Security::AccessToken::INVALID_TOKENID) {
1895 clientTokenId = IPCSkeleton::GetCallingTokenID();
1896 }
1897 int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(clientTokenId, permissionName);
1898 CHECK_AND_RETURN_RET_LOG(res == Security::AccessToken::PermissionState::PERMISSION_GRANTED,
1899 false, "Permission denied [tid:%{public}d]", clientTokenId);
1900
1901 return true;
1902 }
1903
PermissionChecker(const AudioProcessConfig &config)1904 bool AudioServer::PermissionChecker(const AudioProcessConfig &config)
1905 {
1906 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1907 return CheckPlaybackPermission(config);
1908 }
1909
1910 if (config.audioMode == AUDIO_MODE_RECORD) {
1911 return CheckRecorderPermission(config);
1912 }
1913
1914 AUDIO_ERR_LOG("Check failed invalid mode.");
1915 return false;
1916 }
1917
CheckPlaybackPermission(const AudioProcessConfig &config)1918 bool AudioServer::CheckPlaybackPermission(const AudioProcessConfig &config)
1919 {
1920 StreamUsage streamUsage = config.rendererInfo.streamUsage;
1921
1922 bool needVerifyPermission = false;
1923 for (const auto& item : STREAMS_NEED_VERIFY_SYSTEM_PERMISSION) {
1924 if (streamUsage == item) {
1925 needVerifyPermission = true;
1926 break;
1927 }
1928 }
1929 if (needVerifyPermission == false) {
1930 return true;
1931 }
1932 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), false,
1933 "Check playback permission failed, no system permission");
1934 return true;
1935 }
1936
CheckRecorderPermission(const AudioProcessConfig &config)1937 bool AudioServer::CheckRecorderPermission(const AudioProcessConfig &config)
1938 {
1939 Security::AccessToken::AccessTokenID tokenId = config.appInfo.appTokenId;
1940 uint64_t fullTokenId = config.appInfo.appFullTokenId;
1941 SourceType sourceType = config.capturerInfo.sourceType;
1942 CHECK_AND_RETURN_RET_LOG(VALID_SOURCE_TYPE.count(sourceType), false, "invalid source type:%{public}d", sourceType);
1943
1944 #ifdef AUDIO_BUILD_VARIANT_ROOT
1945 int32_t appUid = config.appInfo.appUid;
1946 if (appUid == ROOT_UID) {
1947 return true;
1948 }
1949 #endif
1950
1951 AUDIO_INFO_LOG("check for uid:%{public}d source type:%{public}d", config.callerUid, sourceType);
1952
1953 if (sourceType == SOURCE_TYPE_VOICE_CALL) {
1954 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1955 CHECK_AND_RETURN_RET_LOG(hasSystemPermission, false, "VOICE_CALL failed: no system permission.");
1956
1957 bool res = CheckVoiceCallRecorderPermission(tokenId);
1958 return res;
1959 }
1960
1961 if (sourceType == SOURCE_TYPE_REMOTE_CAST) {
1962 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1963 CHECK_AND_RETURN_RET_LOG(hasSystemPermission, false,
1964 "Create source remote cast failed: no system permission.");
1965
1966 bool hasCastAudioOutputPermission = VerifyClientPermission(CAST_AUDIO_OUTPUT_PERMISSION, tokenId);
1967 CHECK_AND_RETURN_RET_LOG(hasCastAudioOutputPermission, false, "No cast audio output permission");
1968 return true;
1969 }
1970
1971 if (sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE && config.innerCapMode == MODERN_INNER_CAP) {
1972 AUDIO_INFO_LOG("modern inner-cap source, no need to check.");
1973 return true;
1974 }
1975
1976 // All record streams should be checked for MICROPHONE_PERMISSION
1977 bool res = VerifyClientPermission(MICROPHONE_PERMISSION, tokenId);
1978 CHECK_AND_RETURN_RET_LOG(res, false, "Check record permission failed: No permission.");
1979
1980 if (sourceType == SOURCE_TYPE_WAKEUP) {
1981 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1982 bool hasIntelVoicePermission = VerifyClientPermission(MANAGE_INTELLIGENT_VOICE_PERMISSION, tokenId);
1983 CHECK_AND_RETURN_RET_LOG(hasSystemPermission && hasIntelVoicePermission, false,
1984 "Create wakeup record stream failed: no permission.");
1985 return true;
1986 }
1987
1988 if (PermissionUtil::NeedVerifyBackgroundCapture(config.callerUid, sourceType) &&
1989 !PermissionUtil::VerifyBackgroundCapture(tokenId, fullTokenId)) {
1990 AUDIO_ERR_LOG("VerifyBackgroundCapture failed uid:%{public}d", config.callerUid);
1991 return false;
1992 }
1993
1994 return true;
1995 }
1996
CheckVoiceCallRecorderPermission(Security::AccessToken::AccessTokenID tokenId)1997 bool AudioServer::CheckVoiceCallRecorderPermission(Security::AccessToken::AccessTokenID tokenId)
1998 {
1999 bool hasRecordVoiceCallPermission = VerifyClientPermission(RECORD_VOICE_CALL_PERMISSION, tokenId);
2000 CHECK_AND_RETURN_RET_LOG(hasRecordVoiceCallPermission, false, "No permission");
2001 return true;
2002 }
2003
AudioServerDied(pid_t pid, pid_t uid)2004 void AudioServer::AudioServerDied(pid_t pid, pid_t uid)
2005 {
2006 AUDIO_INFO_LOG("Policy server died: restart pulse audio");
2007 _Exit(0);
2008 }
2009
RegisterPolicyServerDeathRecipient()2010 void AudioServer::RegisterPolicyServerDeathRecipient()
2011 {
2012 AUDIO_INFO_LOG("Register policy server death recipient");
2013 pid_t pid = IPCSkeleton::GetCallingPid();
2014 pid_t uid = IPCSkeleton::GetCallingUid();
2015 sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(pid, uid);
2016 if (deathRecipient_ != nullptr) {
2017 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2018 CHECK_AND_RETURN_LOG(samgr != nullptr, "Failed to obtain system ability manager");
2019 sptr<IRemoteObject> object = samgr->GetSystemAbility(OHOS::AUDIO_POLICY_SERVICE_ID);
2020 CHECK_AND_RETURN_LOG(object != nullptr, "Policy service unavailable");
2021 deathRecipient_->SetNotifyCb([this] (pid_t pid, pid_t uid) { this->AudioServerDied(pid, uid); });
2022 bool result = object->AddDeathRecipient(deathRecipient_);
2023 if (!result) {
2024 AUDIO_ERR_LOG("Failed to add deathRecipient");
2025 }
2026 }
2027 }
2028
RequestThreadPriority(uint32_t tid, string bundleName)2029 void AudioServer::RequestThreadPriority(uint32_t tid, string bundleName)
2030 {
2031 AUDIO_INFO_LOG("RequestThreadPriority tid: %{public}u", tid);
2032
2033 int32_t pid = IPCSkeleton::GetCallingPid();
2034 AudioXCollie audioXCollie("AudioServer::ScheduleReportData", SCHEDULE_REPORT_TIME_OUT_SECONDS);
2035 ScheduleReportData(pid, tid, bundleName.c_str());
2036 }
2037
CreatePlaybackCapturerManager()2038 bool AudioServer::CreatePlaybackCapturerManager()
2039 {
2040 if (!PermissionUtil::VerifyIsAudio()) {
2041 AUDIO_ERR_LOG("not audio calling!");
2042 return false;
2043 }
2044 std::vector<int32_t> usage;
2045 PlaybackCapturerManager *playbackCapturerMgr = PlaybackCapturerManager::GetInstance();
2046 playbackCapturerMgr->SetSupportStreamUsage(usage);
2047 return true;
2048 }
2049
SetSupportStreamUsage(std::vector<int32_t> usage)2050 int32_t AudioServer::SetSupportStreamUsage(std::vector<int32_t> usage)
2051 {
2052 AUDIO_INFO_LOG("SetSupportStreamUsage with usage num:%{public}zu", usage.size());
2053
2054 if (!PermissionUtil::VerifyIsAudio()) {
2055 AUDIO_ERR_LOG("not audio calling!");
2056 return ERR_OPERATION_FAILED;
2057 }
2058 PlaybackCapturerManager *playbackCapturerMgr = PlaybackCapturerManager::GetInstance();
2059 playbackCapturerMgr->SetSupportStreamUsage(usage);
2060 return SUCCESS;
2061 }
2062
RegisterAudioCapturerSourceCallback()2063 void AudioServer::RegisterAudioCapturerSourceCallback()
2064 {
2065 IAudioCapturerSource* audioCapturerSourceWakeupInstance =
2066 IAudioCapturerSource::GetInstance("primary", nullptr, SOURCE_TYPE_WAKEUP);
2067 if (audioCapturerSourceWakeupInstance != nullptr) {
2068 audioCapturerSourceWakeupInstance->RegisterWakeupCloseCallback(this);
2069 }
2070
2071 IAudioCapturerSource* primaryAudioCapturerSourceInstance =
2072 IAudioCapturerSource::GetInstance("primary", nullptr, SOURCE_TYPE_MIC);
2073 IAudioCapturerSource *usbAudioCapturerSinkInstance = IAudioCapturerSource::GetInstance("usb", "");
2074 IAudioCapturerSource *fastAudioCapturerSourceInstance = FastAudioCapturerSource::GetInstance();
2075 IAudioCapturerSource *voipFastAudioCapturerSourceInstance = FastAudioCapturerSource::GetVoipInstance();
2076
2077 for (auto audioCapturerSourceInstance : {
2078 primaryAudioCapturerSourceInstance,
2079 usbAudioCapturerSinkInstance,
2080 fastAudioCapturerSourceInstance,
2081 voipFastAudioCapturerSourceInstance
2082 }) {
2083 if (audioCapturerSourceInstance != nullptr) {
2084 audioCapturerSourceInstance->RegisterAudioCapturerSourceCallback(make_unique<CapturerStateOb>(
2085 [this] (bool isActive, int32_t num) {
2086 this->OnCapturerState(isActive, num);
2087 }));
2088 }
2089 }
2090 }
2091
SetCaptureSilentState(bool state)2092 int32_t AudioServer::SetCaptureSilentState(bool state)
2093 {
2094 if (!PermissionUtil::VerifyIsAudio()) {
2095 AUDIO_ERR_LOG("not audio calling!");
2096 return ERR_OPERATION_FAILED;
2097 }
2098
2099 PlaybackCapturerManager *playbackCapturerMgr = PlaybackCapturerManager::GetInstance();
2100 playbackCapturerMgr->SetCaptureSilentState(state);
2101 return SUCCESS;
2102 }
2103
NotifyStreamVolumeChanged(AudioStreamType streamType, float volume)2104 int32_t AudioServer::NotifyStreamVolumeChanged(AudioStreamType streamType, float volume)
2105 {
2106 int32_t callingUid = IPCSkeleton::GetCallingUid();
2107 if (!PermissionUtil::VerifyIsAudio()) {
2108 AUDIO_ERR_LOG("NotifyStreamVolumeChanged refused for %{public}d", callingUid);
2109 return ERR_NOT_SUPPORTED;
2110 }
2111
2112 SetSystemVolumeToEffect(streamType, volume);
2113
2114 int32_t ret = AudioService::GetInstance()->NotifyStreamVolumeChanged(streamType, volume);
2115 if (ret != SUCCESS) {
2116 AUDIO_WARNING_LOG("NotifyStreamVolumeChanged failed");
2117 }
2118 ret = SetVolumeInfoForEnhanceChain(streamType);
2119 if (ret != SUCCESS) {
2120 AUDIO_WARNING_LOG("SetVolumeInfoForEnhanceChain failed");
2121 }
2122 return SUCCESS;
2123 }
2124
ResetRouteForDisconnect(DeviceType type)2125 int32_t AudioServer::ResetRouteForDisconnect(DeviceType type)
2126 {
2127 int32_t callingUid = IPCSkeleton::GetCallingUid();
2128 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
2129
2130 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
2131 if (audioRendererSinkInstance == nullptr) {
2132 AUDIO_ERR_LOG("audioRendererSinkInstance is null!");
2133 return ERROR;
2134 }
2135 audioRendererSinkInstance->ResetOutputRouteForDisconnect(type);
2136
2137 // todo reset capturer
2138
2139 return SUCCESS;
2140 }
2141
GetMaxAmplitude(bool isOutputDevice, int32_t deviceType)2142 float AudioServer::GetMaxAmplitude(bool isOutputDevice, int32_t deviceType)
2143 {
2144 int32_t callingUid = IPCSkeleton::GetCallingUid();
2145 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), 0, "GetMaxAmplitude refused for %{public}d", callingUid);
2146
2147 float fastMaxAmplitude = AudioService::GetInstance()->GetMaxAmplitude(isOutputDevice);
2148 if (isOutputDevice) {
2149 IAudioRendererSink *iRendererInstance = nullptr;
2150 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
2151 iRendererInstance = IAudioRendererSink::GetInstance("a2dp", "");
2152 } else if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
2153 iRendererInstance = IAudioRendererSink::GetInstance("usb", "");
2154 } else {
2155 iRendererInstance = IAudioRendererSink::GetInstance("primary", "");
2156 }
2157 if (iRendererInstance != nullptr) {
2158 float normalMaxAmplitude = iRendererInstance->GetMaxAmplitude();
2159 return (normalMaxAmplitude > fastMaxAmplitude) ? normalMaxAmplitude : fastMaxAmplitude;
2160 }
2161 } else {
2162 AudioCapturerSource *audioCapturerSourceInstance;
2163 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
2164 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("usb");
2165 } else {
2166 audioCapturerSourceInstance = AudioCapturerSource::GetInstance("primary");
2167 }
2168 if (audioCapturerSourceInstance != nullptr) {
2169 float normalMaxAmplitude = audioCapturerSourceInstance->GetMaxAmplitude();
2170 return (normalMaxAmplitude > fastMaxAmplitude) ? normalMaxAmplitude : fastMaxAmplitude;
2171 }
2172 }
2173
2174 return 0;
2175 }
2176
ResetAudioEndpoint()2177 void AudioServer::ResetAudioEndpoint()
2178 {
2179 int32_t callingUid = IPCSkeleton::GetCallingUid();
2180 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "Refused for %{public}d", callingUid);
2181 AudioService::GetInstance()->ResetAudioEndpoint();
2182 }
2183
UpdateLatencyTimestamp(std::string ×tamp, bool isRenderer)2184 void AudioServer::UpdateLatencyTimestamp(std::string ×tamp, bool isRenderer)
2185 {
2186 if (isRenderer) {
2187 LatencyMonitor::GetInstance().UpdateClientTime(true, timestamp);
2188 } else {
2189 LatencyMonitor::GetInstance().UpdateClientTime(false, timestamp);
2190 LatencyMonitor::GetInstance().ShowTimestamp(false);
2191 }
2192 }
2193
UpdateDualToneState(bool enable, int32_t sessionId)2194 int32_t AudioServer::UpdateDualToneState(bool enable, int32_t sessionId)
2195 {
2196 int32_t callingUid = IPCSkeleton::GetCallingUid();
2197 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid);
2198
2199 if (enable) {
2200 return AudioService::GetInstance()->EnableDualToneList(static_cast<uint32_t>(sessionId));
2201 } else {
2202 return AudioService::GetInstance()->DisableDualToneList(static_cast<uint32_t>(sessionId));
2203 }
2204 }
2205
SetSinkRenderEmpty(const std::string &devceClass, int32_t durationUs)2206 int32_t AudioServer::SetSinkRenderEmpty(const std::string &devceClass, int32_t durationUs)
2207 {
2208 if (durationUs <= 0) {
2209 return SUCCESS;
2210 }
2211 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance("primary", "");
2212 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
2213
2214 return audioRendererSinkInstance->SetRenderEmpty(durationUs);
2215 }
2216
SetSinkMuteForSwitchDevice(const std::string &devceClass, int32_t durationUs, bool mute)2217 int32_t AudioServer::SetSinkMuteForSwitchDevice(const std::string &devceClass, int32_t durationUs, bool mute)
2218 {
2219 int32_t callingUid = IPCSkeleton::GetCallingUid();
2220 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_PERMISSION_DENIED, "refused for %{public}d",
2221 callingUid);
2222
2223 if (durationUs <= 0) {
2224 return SUCCESS;
2225 }
2226
2227 IAudioRendererSink *audioRendererSinkInstance = IAudioRendererSink::GetInstance(devceClass.c_str(), "");
2228 CHECK_AND_RETURN_RET_LOG(audioRendererSinkInstance != nullptr, ERROR, "has no valid sink");
2229 return audioRendererSinkInstance->SetSinkMuteForSwitchDevice(mute);
2230 }
2231
UpdateSessionConnectionState(const int32_t &sessionId, const int32_t &state)2232 void AudioServer::UpdateSessionConnectionState(const int32_t &sessionId, const int32_t &state)
2233 {
2234 AUDIO_INFO_LOG("Server get sessionID: %{public}d, state: %{public}d", sessionId, state);
2235 int32_t callingUid = IPCSkeleton::GetCallingUid();
2236 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(),
2237 "Update session connection state refused for %{public}d", callingUid);
2238 std::shared_ptr<RendererInServer> renderer =
2239 AudioService::GetInstance()->GetRendererBySessionID(static_cast<uint32_t>(sessionId));
2240
2241 if (renderer == nullptr) {
2242 AUDIO_ERR_LOG("No render in server has sessionID");
2243 return;
2244 }
2245 renderer->OnDataLinkConnectionUpdate(static_cast<IOperation>(state));
2246 }
2247
SetNonInterruptMute(const uint32_t sessionId, const bool muteFlag)2248 void AudioServer::SetNonInterruptMute(const uint32_t sessionId, const bool muteFlag)
2249 {
2250 AUDIO_INFO_LOG("sessionId_: %{public}u, muteFlag: %{public}d", sessionId, muteFlag);
2251 int32_t callingUid = IPCSkeleton::GetCallingUid();
2252 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "Refused for %{public}d", callingUid);
2253 AudioService::GetInstance()->SetNonInterruptMute(sessionId, muteFlag);
2254 }
2255
RestoreSession(const int32_t &sessionID, bool isOutput)2256 void AudioServer::RestoreSession(const int32_t &sessionID, bool isOutput)
2257 {
2258 AUDIO_INFO_LOG("restore output: %{public}d, sessionID: %{public}d", isOutput, sessionID);
2259 int32_t callingUid = IPCSkeleton::GetCallingUid();
2260 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(),
2261 "Update session connection state refused for %{public}d", callingUid);
2262 if (isOutput) {
2263 std::shared_ptr<RendererInServer> renderer =
2264 AudioService::GetInstance()->GetRendererBySessionID(static_cast<uint32_t>(sessionID));
2265 if (renderer == nullptr) {
2266 AUDIO_ERR_LOG("No render in server has sessionID");
2267 return;
2268 }
2269 renderer->RestoreSession();
2270 } else {
2271 std::shared_ptr<CapturerInServer> capturer =
2272 AudioService::GetInstance()->GetCapturerBySessionID(static_cast<uint32_t>(sessionID));
2273 if (capturer == nullptr) {
2274 AUDIO_ERR_LOG("No capturer in server has sessionID");
2275 return;
2276 }
2277 capturer->RestoreSession();
2278 }
2279 }
2280
SetOffloadMode(uint32_t sessionId, int32_t state, bool isAppBack)2281 int32_t AudioServer::SetOffloadMode(uint32_t sessionId, int32_t state, bool isAppBack)
2282 {
2283 int32_t callingUid = IPCSkeleton::GetCallingUid();
2284 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d",
2285 callingUid);
2286 return AudioService::GetInstance()->SetOffloadMode(sessionId, state, isAppBack);
2287 }
2288
UnsetOffloadMode(uint32_t sessionId)2289 int32_t AudioServer::UnsetOffloadMode(uint32_t sessionId)
2290 {
2291 int32_t callingUid = IPCSkeleton::GetCallingUid();
2292 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d",
2293 callingUid);
2294 return AudioService::GetInstance()->UnsetOffloadMode(sessionId);
2295 }
2296
SetHibernateEndpointRelease(const bool &isHibernate)2297 void AudioServer::SetHibernateEndpointRelease(const bool &isHibernate)
2298 {
2299 int32_t callingUid = IPCSkeleton::GetCallingUid();
2300 CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "refused for %{public}d", callingUid);
2301 AudioService::GetInstance()->SetHibernateEndpointRelease(isHibernate);
2302 }
2303 } // namespace AudioStandard
2304 } // namespace OHOS
2305