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