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