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