• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2025 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 "AudioService"
17 #endif
18 
19 #include "audio_service.h"
20 
21 #include <thread>
22 
23 #include "audio_errors.h"
24 #include "audio_common_log.h"
25 #include "audio_utils.h"
26 #include "policy_handler.h"
27 #include "core_service_handler.h"
28 #include "ipc_stream_in_server.h"
29 #include "common/hdi_adapter_info.h"
30 #include "manager/hdi_adapter_manager.h"
31 #include "source/i_audio_capture_source.h"
32 #include "audio_volume.h"
33 #include "audio_performance_monitor.h"
34 #include "privacy_kit.h"
35 #include "media_monitor_manager.h"
36 #ifdef HAS_FEATURE_INNERCAPTURER
37 #include "playback_capturer_manager.h"
38 #endif
39 #include "audio_resource_service.h"
40 
41 namespace OHOS {
42 namespace AudioStandard {
43 
44 #ifdef SUPPORT_LOW_LATENCY
45 static const int32_t NORMAL_ENDPOINT_RELEASE_DELAY_TIME_MS = 3000; // 3s
46 static const uint32_t A2DP_ENDPOINT_RELEASE_DELAY_TIME = 3000; // 3s
47 static const uint32_t VOIP_ENDPOINT_RELEASE_DELAY_TIME = 200; // 200ms
48 static const uint32_t VOIP_REC_ENDPOINT_RELEASE_DELAY_TIME = 60; // 60ms
49 static const uint32_t A2DP_ENDPOINT_RE_CREATE_RELEASE_DELAY_TIME = 200; // 200ms
50 #endif
51 static const uint32_t BLOCK_HIBERNATE_CALLBACK_IN_MS = 5000; // 5s
52 static const uint32_t RECHECK_SINK_STATE_IN_US = 100000; // 100ms
53 static const int32_t MEDIA_SERVICE_UID = 1013;
54 static const int32_t RENDERER_STREAM_CNT_PER_UID_LIMIT = 40;
55 static const int32_t INVALID_APP_UID = -1;
56 static const int32_t INVALID_APP_CREATED_AUDIO_STREAM_NUM = 0;
57 namespace {
58 static inline const std::unordered_set<SourceType> specialSourceTypeSet_ = {
59     SOURCE_TYPE_PLAYBACK_CAPTURE,
60     SOURCE_TYPE_WAKEUP,
61     SOURCE_TYPE_VIRTUAL_CAPTURE,
62     SOURCE_TYPE_REMOTE_CAST
63 };
64 const size_t MAX_FG_LIST_SIZE = 10;
65 }
66 
GetInstance()67 AudioService *AudioService::GetInstance()
68 {
69     static AudioService AudioService;
70 
71     return &AudioService;
72 }
73 
AudioService()74 AudioService::AudioService()
75 {
76     AUDIO_INFO_LOG("AudioService()");
77 }
78 
~AudioService()79 AudioService::~AudioService()
80 {
81     AUDIO_INFO_LOG("~AudioService()");
82 }
83 
84 #ifdef SUPPORT_LOW_LATENCY
OnProcessRelease(IAudioProcessStream * process,bool isSwitchStream)85 int32_t AudioService::OnProcessRelease(IAudioProcessStream *process, bool isSwitchStream)
86 {
87     std::lock_guard<std::mutex> processListLock(processListMutex_);
88     CHECK_AND_RETURN_RET_LOG(process != nullptr, ERROR, "process is nullptr");
89     bool isFind = false;
90     int32_t ret = ERROR;
91     auto paired = linkedPairedList_.begin();
92     std::string endpointName;
93     bool needRelease = false;
94     int32_t delayTime = NORMAL_ENDPOINT_RELEASE_DELAY_TIME_MS;
95     while (paired != linkedPairedList_.end()) {
96         if ((*paired).first == process) {
97             AUDIO_INFO_LOG("SessionId %{public}u", (*paired).first->GetSessionId());
98             AudioPerformanceMonitor::GetInstance().DeleteSilenceMonitor(process->GetAudioSessionId());
99             auto processConfig = process->GetAudioProcessConfig();
100             if (processConfig.audioMode == AUDIO_MODE_PLAYBACK) {
101                 SetDecMaxRendererStreamCnt();
102                 CleanAppUseNumMap(processConfig.appInfo.appUid);
103             }
104             if (processConfig.capturerInfo.isLoopback || processConfig.rendererInfo.isLoopback) {
105                 SetDecMaxLoopbackStreamCnt(processConfig.audioMode);
106                 DisableLoopback();
107             }
108             if (!isSwitchStream) {
109                 AUDIO_INFO_LOG("is not switch stream, remove from mutedSessions_");
110                 RemoveIdFromMuteControlSet((*paired).first->GetSessionId());
111             }
112             ret = UnlinkProcessToEndpoint((*paired).first, (*paired).second);
113             if ((*paired).second->GetStatus() == AudioEndpoint::EndpointStatus::UNLINKED) {
114                 needRelease = true;
115                 endpointName = (*paired).second->GetEndpointName();
116                 delayTime = GetReleaseDelayTime((*paired).second, isSwitchStream,
117                     processConfig.audioMode == AUDIO_MODE_RECORD);
118             }
119             linkedPairedList_.erase(paired);
120             isFind = true;
121             break;
122         } else {
123             paired++;
124         }
125     }
126     if (isFind) {
127         AUDIO_INFO_LOG("find and release process result %{public}d", ret);
128     } else {
129         AUDIO_INFO_LOG("can not find target process, maybe already released.");
130     }
131     if (needRelease) {
132         ReleaseProcess(endpointName, delayTime);
133     }
134     return SUCCESS;
135 }
136 
ReleaseProcess(const std::string endpointName,const int32_t delayTime)137 void AudioService::ReleaseProcess(const std::string endpointName, const int32_t delayTime)
138 {
139     AUDIO_INFO_LOG("Release endpoint [%{public}s] after %{public}d ms", endpointName.c_str(), delayTime);
140     {
141         std::unique_lock<std::mutex> lock(releaseEndpointMutex_);
142         releasingEndpointSet_.insert(endpointName);
143     }
144     auto releaseMidpointThread = [this, endpointName, delayTime] () {
145         std::unique_lock<std::mutex> processListLock(processListMutex_);
146         CHECK_AND_RETURN_LOG(endpointList_.count(endpointName), "Can't find endpoint %{public}s", endpointName.c_str());
147         if (delayTime != 0) {
148             bool ret = releaseEndpointCV_.wait_for(processListLock, std::chrono::milliseconds(delayTime),
149                 [this, endpointName] {
150                 std::lock_guard<std::mutex> lock(releaseEndpointMutex_);
151                 if (releasingEndpointSet_.count(endpointName)) {
152                     AUDIO_INFO_LOG("Release endpoint %{public}s", endpointName.c_str());
153                     return false;
154                 }
155                 AUDIO_INFO_LOG("No need release endpoint: %{public}s", endpointName.c_str());
156                 return true;
157             });
158 
159             if (ret) {
160                 return;
161             }
162         }
163         this->DelayCallReleaseEndpoint(endpointName);
164     };
165     std::thread releaseEndpointThread(releaseMidpointThread);
166     releaseEndpointThread.detach();
167 }
168 
GetReleaseDelayTime(std::shared_ptr<AudioEndpoint> endpoint,bool isSwitchStream,bool isRecord)169 int32_t AudioService::GetReleaseDelayTime(std::shared_ptr<AudioEndpoint> endpoint, bool isSwitchStream, bool isRecord)
170 {
171     if (endpoint->GetEndpointType() == AudioEndpoint::EndpointType::TYPE_VOIP_MMAP) {
172         return isRecord ? VOIP_REC_ENDPOINT_RELEASE_DELAY_TIME : VOIP_ENDPOINT_RELEASE_DELAY_TIME;
173     }
174     if (endpoint->GetDeviceInfo().deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP) {
175         return NORMAL_ENDPOINT_RELEASE_DELAY_TIME_MS;
176     }
177     // The delay for destruction and reconstruction cannot be set to 0, otherwise there may be a problem:
178     // An endpoint exists at check process, but it may be destroyed immediately - during the re-create process
179     return isSwitchStream ? A2DP_ENDPOINT_RE_CREATE_RELEASE_DELAY_TIME : A2DP_ENDPOINT_RELEASE_DELAY_TIME;
180 }
181 #endif
182 
DisableLoopback()183 void AudioService::DisableLoopback()
184 {
185     HdiAdapterManager &manager = HdiAdapterManager::GetInstance();
186     std::shared_ptr<IDeviceManager> deviceManager = manager.GetDeviceManager(HDI_DEVICE_MANAGER_TYPE_LOCAL);
187     CHECK_AND_RETURN_LOG(deviceManager != nullptr, "local device manager is nullptr!");
188     deviceManager->SetAudioParameter("primary", AudioParamKey::NONE, "", "Karaoke_enable=disable");
189 }
190 
GetIpcStream(const AudioProcessConfig & config,int32_t & ret)191 sptr<IpcStreamInServer> AudioService::GetIpcStream(const AudioProcessConfig &config, int32_t &ret)
192 {
193     Trace trace("AudioService::GetIpcStream");
194 #ifdef HAS_FEATURE_INNERCAPTURER
195     if (!isRegisterCapturerFilterListened_) {
196         AUDIO_INFO_LOG("isRegisterCapturerFilterListened_ is false");
197         PlaybackCapturerManager::GetInstance()->RegisterCapturerFilterListener(this);
198         isRegisterCapturerFilterListened_ = true;
199     }
200 #endif
201     // in plan: GetDeviceInfoForProcess(config) and stream limit check
202     // in plan: call GetProcessDeviceInfo to load inner-cap-sink
203     sptr<IpcStreamInServer> ipcStreamInServer = IpcStreamInServer::Create(config, ret);
204 
205     // in plan: Put playback into list, check if EnableInnerCap is need.
206     if (ipcStreamInServer != nullptr && config.audioMode == AUDIO_MODE_PLAYBACK) {
207         uint32_t sessionId = 0;
208         std::shared_ptr<RendererInServer> renderer = ipcStreamInServer->GetRenderer();
209         if (renderer != nullptr && renderer->GetSessionId(sessionId) == SUCCESS) {
210             InsertRenderer(sessionId, renderer); // for all renderers
211 #ifdef HAS_FEATURE_INNERCAPTURER
212             CheckInnerCapForRenderer(sessionId, renderer);
213 #endif
214             CheckRenderSessionMuteState(sessionId, renderer);
215         }
216     }
217     if (ipcStreamInServer != nullptr && config.audioMode == AUDIO_MODE_RECORD) {
218         uint32_t sessionId = 0;
219         std::shared_ptr<CapturerInServer> capturer = ipcStreamInServer->GetCapturer();
220         if (capturer != nullptr && capturer->GetSessionId(sessionId) == SUCCESS) {
221             InsertCapturer(sessionId, capturer); // for all capturers
222             CheckCaptureSessionMuteState(sessionId, capturer);
223         }
224     }
225 
226     return ipcStreamInServer;
227 }
228 
UpdateMuteControlSet(uint32_t sessionId,bool muteFlag)229 void AudioService::UpdateMuteControlSet(uint32_t sessionId, bool muteFlag)
230 {
231     if (sessionId < MIN_STREAMID || sessionId > MAX_STREAMID) {
232         AUDIO_WARNING_LOG("Invalid sessionid %{public}u", sessionId);
233         return;
234     }
235     std::lock_guard<std::mutex> lock(mutedSessionsMutex_);
236     if (muteFlag) {
237         mutedSessions_.insert(sessionId);
238         return;
239     }
240     if (mutedSessions_.find(sessionId) != mutedSessions_.end()) {
241         mutedSessions_.erase(sessionId);
242     } else {
243         AUDIO_WARNING_LOG("Session id %{public}u not in the set", sessionId);
244     }
245 }
246 
RemoveIdFromMuteControlSet(uint32_t sessionId)247 void AudioService::RemoveIdFromMuteControlSet(uint32_t sessionId)
248 {
249     std::lock_guard<std::mutex> mutedSessionsLock(mutedSessionsMutex_);
250     if (mutedSessions_.find(sessionId) != mutedSessions_.end()) {
251         mutedSessions_.erase(sessionId);
252     } else {
253         AUDIO_WARNING_LOG("Session id %{public}u not in the set", sessionId);
254     }
255 }
256 
CheckRenderSessionMuteState(uint32_t sessionId,std::shared_ptr<RendererInServer> renderer)257 void AudioService::CheckRenderSessionMuteState(uint32_t sessionId, std::shared_ptr<RendererInServer> renderer)
258 {
259     std::unique_lock<std::mutex> mutedSessionsLock(mutedSessionsMutex_);
260     if (mutedSessions_.find(sessionId) != mutedSessions_.end() || IsMuteSwitchStream(sessionId)) {
261         mutedSessionsLock.unlock();
262         AUDIO_INFO_LOG("Session %{public}u is in control", sessionId);
263         renderer->SetNonInterruptMute(true);
264     }
265 }
266 
CheckCaptureSessionMuteState(uint32_t sessionId,std::shared_ptr<CapturerInServer> capturer)267 void AudioService::CheckCaptureSessionMuteState(uint32_t sessionId, std::shared_ptr<CapturerInServer> capturer)
268 {
269     std::unique_lock<std::mutex> mutedSessionsLock(mutedSessionsMutex_);
270     if (mutedSessions_.find(sessionId) != mutedSessions_.end() || IsMuteSwitchStream(sessionId)) {
271         mutedSessionsLock.unlock();
272         AUDIO_INFO_LOG("Session %{public}u is in control", sessionId);
273         capturer->SetNonInterruptMute(true);
274     }
275 }
276 
277 #ifdef SUPPORT_LOW_LATENCY
CheckFastSessionMuteState(uint32_t sessionId,sptr<AudioProcessInServer> process)278 void AudioService::CheckFastSessionMuteState(uint32_t sessionId, sptr<AudioProcessInServer> process)
279 {
280     std::unique_lock<std::mutex> mutedSessionsLock(mutedSessionsMutex_);
281     if (mutedSessions_.find(sessionId) != mutedSessions_.end() || IsMuteSwitchStream(sessionId)) {
282         mutedSessionsLock.unlock();
283         AUDIO_INFO_LOG("Session %{public}u is in control", sessionId);
284         process->SetNonInterruptMute(true);
285     }
286 }
287 #endif
288 
IsMuteSwitchStream(uint32_t sessionId)289 bool AudioService::IsMuteSwitchStream(uint32_t sessionId)
290 {
291     std::lock_guard<std::mutex> muteSwitchStreamLock(muteSwitchStreamSetMutex_);
292     if (muteSwitchStreams_.count(sessionId)) {
293         AUDIO_INFO_LOG("find session %{public}u in muteSwitchStreams_", sessionId);
294         muteSwitchStreams_.erase(sessionId);
295         return true;
296     }
297     return false;
298 }
299 
InsertRenderer(uint32_t sessionId,std::shared_ptr<RendererInServer> renderer)300 void AudioService::InsertRenderer(uint32_t sessionId, std::shared_ptr<RendererInServer> renderer)
301 {
302     std::unique_lock<std::mutex> lock(rendererMapMutex_);
303     AUDIO_INFO_LOG("Insert renderer:%{public}u into map", sessionId);
304     allRendererMap_[sessionId] = renderer;
305 }
306 
SaveForegroundList(std::vector<std::string> list)307 void AudioService::SaveForegroundList(std::vector<std::string> list)
308 {
309     std::lock_guard<std::mutex> lock(foregroundSetMutex_);
310     if (list.size() > MAX_FG_LIST_SIZE) {
311         AUDIO_ERR_LOG("invalid list size %{public}zu", list.size());
312         return;
313     }
314 
315     foregroundSet_.clear();
316     foregroundUidSet_.clear();
317     for (auto &item : list) {
318         AUDIO_WARNING_LOG("Add for hap: %{public}s", item.c_str());
319         foregroundSet_.insert(item);
320     }
321 }
322 
MatchForegroundList(const std::string & bundleName,uint32_t uid)323 bool AudioService::MatchForegroundList(const std::string &bundleName, uint32_t uid)
324 {
325     std::lock_guard<std::mutex> lock(foregroundSetMutex_);
326     if (foregroundSet_.find(bundleName) != foregroundSet_.end()) {
327         AUDIO_WARNING_LOG("find hap %{public}s in list!", bundleName.c_str());
328         if (uid != 0) {
329             foregroundUidSet_.insert(uid);
330         }
331         return true;
332     }
333     return false;
334 }
335 
InForegroundList(uint32_t uid)336 bool AudioService::InForegroundList(uint32_t uid)
337 {
338     std::lock_guard<std::mutex> lock(foregroundSetMutex_);
339     if (foregroundUidSet_.find(uid) != foregroundUidSet_.end()) {
340         AUDIO_INFO_LOG("find hap %{public}d in list!", uid);
341         return true;
342     }
343     return false;
344 }
345 
SaveRenderWhitelist(std::vector<std::string> list)346 void AudioService::SaveRenderWhitelist(std::vector<std::string> list)
347 {
348     std::lock_guard<std::mutex> lock(renderWhitelistMutex_);
349 
350     renderWhitelist_.clear();
351     for (auto &item : list) {
352         AUDIO_INFO_LOG("Add for hap: %{public}s", item.c_str());
353         renderWhitelist_.insert(item);
354     }
355 }
356 
InRenderWhitelist(const std::string bundleName)357 bool AudioService::InRenderWhitelist(const std::string bundleName)
358 {
359     std::lock_guard<std::mutex> lock(renderWhitelistMutex_);
360     if (renderWhitelist_.find(bundleName) != renderWhitelist_.end()) {
361         AUDIO_INFO_LOG("find hap %{public}s in list!", bundleName.c_str());
362         return true;
363     }
364     return false;
365 }
366 
UpdateForegroundState(uint32_t appTokenId,bool isActive)367 bool AudioService::UpdateForegroundState(uint32_t appTokenId, bool isActive)
368 {
369     // UpdateForegroundState 200001000 to active
370     std::string str = "UpdateForegroundState " + std::to_string(appTokenId) + (isActive ? "to active" : "to deactive");
371     Trace trace(str);
372     WatchTimeout guard(str);
373     int32_t res = OHOS::Security::AccessToken::PrivacyKit::SetHapWithFGReminder(appTokenId, isActive);
374     AUDIO_INFO_LOG("res is %{public}d for %{public}s", res, str.c_str());
375     return res;
376 }
377 
DumpForegroundList(std::string & dumpString)378 void AudioService::DumpForegroundList(std::string &dumpString)
379 {
380     std::lock_guard<std::mutex> lock(foregroundSetMutex_);
381     std::stringstream temp;
382     temp << "DumpForegroundList:\n";
383     int32_t index = 0;
384     for (auto item : foregroundSet_) {
385         temp << "    " <<  std::to_string(index++) << ": " <<  item << "\n";
386     }
387     dumpString = temp.str();
388 }
389 
GetStandbyStatus(uint32_t sessionId,bool & isStandby,int64_t & enterStandbyTime)390 int32_t AudioService::GetStandbyStatus(uint32_t sessionId, bool &isStandby, int64_t &enterStandbyTime)
391 {
392     // for normal renderer.
393     std::unique_lock<std::mutex> lockRender(rendererMapMutex_);
394     if (allRendererMap_.count(sessionId)) {
395         std::shared_ptr<RendererInServer> render = allRendererMap_[sessionId].lock();
396         if (render == nullptr) {
397             return ERR_INVALID_PARAM;
398         }
399         return render->GetStandbyStatus(isStandby, enterStandbyTime);
400     }
401     lockRender.unlock();
402 
403     // for fast process.
404 #ifdef SUPPORT_LOW_LATENCY
405     std::unique_lock<std::mutex> lockProcess(processListMutex_);
406     for (auto paired : linkedPairedList_) {
407         sptr<AudioProcessInServer> process = paired.first;
408         if (process->GetSessionId() == sessionId) {
409             return process->GetStandbyStatus(isStandby, enterStandbyTime);
410         }
411     }
412 #endif
413     // not found target sessionId
414     return ERR_INVALID_PARAM;
415 }
416 
RemoveRenderer(uint32_t sessionId,bool isSwitchStream)417 void AudioService::RemoveRenderer(uint32_t sessionId, bool isSwitchStream)
418 {
419     std::unique_lock<std::mutex> lock(rendererMapMutex_);
420     AUDIO_INFO_LOG("Renderer:%{public}u will be removed.", sessionId);
421     if (!allRendererMap_.count(sessionId)) {
422         AUDIO_WARNING_LOG("Renderer in not in map!");
423         return;
424     }
425     allRendererMap_.erase(sessionId);
426     if (!isSwitchStream) {
427         RemoveIdFromMuteControlSet(sessionId);
428     }
429     AudioPerformanceMonitor::GetInstance().DeleteSilenceMonitor(sessionId);
430 }
431 
InsertCapturer(uint32_t sessionId,std::shared_ptr<CapturerInServer> capturer)432 void AudioService::InsertCapturer(uint32_t sessionId, std::shared_ptr<CapturerInServer> capturer)
433 {
434     std::unique_lock<std::mutex> lock(capturerMapMutex_);
435     AUDIO_INFO_LOG("Insert capturer:%{public}u into map", sessionId);
436     allCapturerMap_[sessionId] = capturer;
437 }
438 
RemoveCapturer(uint32_t sessionId,bool isSwitchStream)439 void AudioService::RemoveCapturer(uint32_t sessionId, bool isSwitchStream)
440 {
441     std::unique_lock<std::mutex> lock(capturerMapMutex_);
442     AUDIO_INFO_LOG("Capturer: %{public}u will be removed.", sessionId);
443     if (!allCapturerMap_.count(sessionId)) {
444         AUDIO_WARNING_LOG("Capturer in not in map!");
445         return;
446     }
447     allCapturerMap_.erase(sessionId);
448     {
449         std::unique_lock<std::mutex> muteStatelock(muteStateMapMutex_);
450         muteStateCallbacks_.erase(sessionId);
451     }
452 
453     if (!isSwitchStream) {
454         RemoveIdFromMuteControlSet(sessionId);
455     }
456 }
457 
AddFilteredRender(int32_t innerCapId,std::shared_ptr<RendererInServer> renderer)458 void AudioService::AddFilteredRender(int32_t innerCapId, std::shared_ptr<RendererInServer> renderer)
459 {
460     if (!filteredRendererMap_.count(innerCapId)) {
461         std::vector<std::weak_ptr<RendererInServer>> renders;
462         filteredRendererMap_[innerCapId] = renders;
463     }
464     filteredRendererMap_[innerCapId].push_back(renderer);
465 }
466 
467 #ifdef HAS_FEATURE_INNERCAPTURER
CheckInnerCapForRenderer(uint32_t sessionId,std::shared_ptr<RendererInServer> renderer)468 void AudioService::CheckInnerCapForRenderer(uint32_t sessionId, std::shared_ptr<RendererInServer> renderer)
469 {
470     CHECK_AND_RETURN_LOG(renderer != nullptr, "renderer is null.");
471 
472     std::unique_lock<std::mutex> lock(rendererMapMutex_);
473 
474     // inner-cap not working
475     {
476         std::lock_guard<std::mutex> lock(workingConfigsMutex_);
477         if (workingConfigs_.size() == 0) {
478             return;
479         }
480     }
481     // in plan: check if meet with the workingConfig_
482     std::set<int32_t> captureIds;
483     if (ShouldBeInnerCap(renderer->processConfig_, captureIds)) {
484         for (auto innerCapId : captureIds) {
485             AddFilteredRender(innerCapId, renderer);
486             renderer->EnableInnerCap(innerCapId); // for debug
487         }
488     }
489 }
490 
GetInnerCapFilterPolicy(int32_t innerCapId)491 InnerCapFilterPolicy AudioService::GetInnerCapFilterPolicy(int32_t innerCapId)
492 {
493     if (!workingConfigs_.count(innerCapId)) {
494         AUDIO_ERR_LOG("error, invalid innerCapId");
495         return POLICY_INVALID;
496     }
497     auto usagesSize = workingConfigs_[innerCapId].filterOptions.usages.size();
498     auto pidsSize = workingConfigs_[innerCapId].filterOptions.pids.size();
499     if (usagesSize == 0 && pidsSize == 0) {
500         AUDIO_ERR_LOG("error, invalid usages and pids");
501         return POLICY_INVALID;
502     }
503     if (usagesSize > 0 && pidsSize == 0) {
504         AUDIO_INFO_LOG("usages only");
505         return POLICY_USAGES_ONLY;
506     }
507     return POLICY_USAGES_AND_PIDS;
508 }
509 
510 template<typename T>
isFilterMatched(const std::vector<T> & params,T param,FilterMode mode)511 bool isFilterMatched(const std::vector<T> &params, T param, FilterMode mode)
512 {
513     bool isFound = std::count(params.begin(), params.end(), param) != 0;
514     return (mode == FilterMode::INCLUDE && isFound) || (mode == FilterMode::EXCLUDE && !isFound);
515 }
516 
ShouldBeInnerCap(const AudioProcessConfig & rendererConfig,int32_t innerCapId)517 bool AudioService::ShouldBeInnerCap(const AudioProcessConfig &rendererConfig, int32_t innerCapId)
518 {
519     bool canBeCaptured = rendererConfig.privacyType == AudioPrivacyType::PRIVACY_TYPE_PUBLIC;
520     std::lock_guard<std::mutex> lock(workingConfigsMutex_);
521     if (!canBeCaptured || innerCapId == 0 || !workingConfigs_.count(innerCapId)) {
522         AUDIO_WARNING_LOG("%{public}d privacy is not public!", rendererConfig.appInfo.appPid);
523         return false;
524     }
525     return CheckShouldCap(rendererConfig, innerCapId);
526 }
527 
ShouldBeInnerCap(const AudioProcessConfig & rendererConfig,std::set<int32_t> & beCapIds)528 bool AudioService::ShouldBeInnerCap(const AudioProcessConfig &rendererConfig, std::set<int32_t> &beCapIds)
529 {
530     bool canBeCaptured = rendererConfig.privacyType == AudioPrivacyType::PRIVACY_TYPE_PUBLIC;
531     if (!canBeCaptured) {
532         AUDIO_WARNING_LOG("%{public}d privacy is not public!", rendererConfig.appInfo.appPid);
533         return false;
534     }
535     bool ret = false;
536     std::lock_guard<std::mutex> lock(workingConfigsMutex_);
537     for (auto& filter : workingConfigs_) {
538         if (CheckShouldCap(rendererConfig, filter.first)) {
539             ret = true;
540             beCapIds.insert(filter.first);
541         }
542     }
543     return ret;
544 }
545 
CheckShouldCap(const AudioProcessConfig & rendererConfig,int32_t innerCapId)546 bool AudioService::CheckShouldCap(const AudioProcessConfig &rendererConfig, int32_t innerCapId)
547 {
548     InnerCapFilterPolicy filterPolicy = GetInnerCapFilterPolicy(innerCapId);
549     bool res = false;
550     switch (filterPolicy) {
551         case POLICY_INVALID:
552             return false;
553         case POLICY_USAGES_ONLY:
554             res = isFilterMatched(workingConfigs_[innerCapId].filterOptions.usages,
555                 rendererConfig.rendererInfo.streamUsage, workingConfigs_[innerCapId].filterOptions.usageFilterMode);
556             break;
557         case POLICY_USAGES_AND_PIDS:
558             res = isFilterMatched(workingConfigs_[innerCapId].filterOptions.usages,
559                 rendererConfig.rendererInfo.streamUsage,
560                 workingConfigs_[innerCapId].filterOptions.usageFilterMode) &&
561                 isFilterMatched(workingConfigs_[innerCapId].filterOptions.pids, rendererConfig.appInfo.appPid,
562                 workingConfigs_[innerCapId].filterOptions.pidFilterMode);
563             break;
564         default:
565             break;
566     }
567     AUDIO_INFO_LOG("pid:%{public}d usage:%{public}d result:%{public}s capId:%{public}d",
568         rendererConfig.appInfo.appPid, rendererConfig.rendererInfo.streamUsage, res ? "true" : "false", innerCapId);
569     return res;
570 }
571 #endif
572 
ShouldBeDualTone(const AudioProcessConfig & config)573 bool AudioService::ShouldBeDualTone(const AudioProcessConfig &config)
574 {
575     CHECK_AND_RETURN_RET_LOG(Util::IsRingerOrAlarmerStreamUsage(config.rendererInfo.streamUsage), false,
576         "Wrong usage ,should not be dualtone");
577     AudioDeviceDescriptor deviceInfo(AudioDeviceDescriptor::DEVICE_INFO);
578     bool ret = PolicyHandler::GetInstance().GetProcessDeviceInfo(config, false, deviceInfo);
579     if (!ret) {
580         AUDIO_WARNING_LOG("GetProcessDeviceInfo from audio policy server failed!");
581         return false;
582     }
583     if (config.audioMode != AUDIO_MODE_PLAYBACK) {
584         AUDIO_WARNING_LOG("No playback mode!");
585         return false;
586     }
587     AUDIO_INFO_LOG("Get DeviceInfo from policy server success, deviceType: %{public}d, "
588         "supportLowLatency: %{public}d", deviceInfo.deviceType_, deviceInfo.isLowLatencyDevice_);
589     if (deviceInfo.deviceType_ == DEVICE_TYPE_WIRED_HEADSET || deviceInfo.deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES ||
590         deviceInfo.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP || deviceInfo.deviceType_ == DEVICE_TYPE_USB_HEADSET ||
591         deviceInfo.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET || deviceInfo.deviceType_ == DEVICE_TYPE_REMOTE_CAST ||
592         (deviceInfo.deviceType_ == DEVICE_TYPE_SPEAKER && deviceInfo.networkId_ != std::string(LOCAL_NETWORK_ID)) ||
593         deviceInfo.deviceType_ == DEVICE_TYPE_HEARING_AID) {
594         switch (config.rendererInfo.streamUsage) {
595             case STREAM_USAGE_ALARM:
596             case STREAM_USAGE_VOICE_RINGTONE:
597             case STREAM_USAGE_RINGTONE:
598                 AUDIO_WARNING_LOG("Should DualTone.");
599                 return true;
600             default:
601                 return false;
602         }
603     }
604     return false;
605 }
606 
607 #ifdef HAS_FEATURE_INNERCAPTURER
608 #ifdef SUPPORT_LOW_LATENCY
FilterAllFastProcess()609 void AudioService::FilterAllFastProcess()
610 {
611     std::unique_lock<std::mutex> lock(processListMutex_);
612     if (linkedPairedList_.size() == 0) {
613         return;
614     }
615     for (auto paired : linkedPairedList_) {
616         AudioProcessConfig temp = paired.first->processConfig_;
617         std::set<int32_t> captureIds;
618         if (temp.audioMode == AUDIO_MODE_PLAYBACK && ShouldBeInnerCap(temp, captureIds)) {
619             HandleFastCapture(captureIds, paired.first, paired.second);
620         }
621     }
622 
623     for (auto pair : endpointList_) {
624         if (pair.second->GetDeviceRole() == OUTPUT_DEVICE) {
625             CheckDisableFastInner(pair.second);
626         }
627     }
628 }
629 #endif
630 
CheckDisableFastInner(std::shared_ptr<AudioEndpoint> endpoint)631 int32_t AudioService::CheckDisableFastInner(std::shared_ptr<AudioEndpoint> endpoint)
632 {
633     std::lock_guard<std::mutex> lock(workingConfigsMutex_);
634     for (auto workingConfig : workingConfigs_) {
635         if (!endpoint->ShouldInnerCap(workingConfig.first)) {
636             endpoint->DisableFastInnerCap(workingConfig.first);
637         }
638     }
639     return SUCCESS;
640 }
641 
HandleFastCapture(std::set<int32_t> captureIds,sptr<AudioProcessInServer> audioProcessInServer,std::shared_ptr<AudioEndpoint> audioEndpoint)642 int32_t AudioService::HandleFastCapture(std::set<int32_t> captureIds, sptr<AudioProcessInServer> audioProcessInServer,
643     std::shared_ptr<AudioEndpoint> audioEndpoint)
644 {
645     for (auto captureId : captureIds) {
646         audioProcessInServer->SetInnerCapState(true, captureId);
647         audioEndpoint->EnableFastInnerCap(captureId);
648     }
649     return SUCCESS;
650 }
651 
OnInitInnerCapList(int32_t innerCapId)652 int32_t AudioService::OnInitInnerCapList(int32_t innerCapId)
653 {
654     AUDIO_INFO_LOG("workingInnerCapId_ is %{public}d", innerCapId);
655 #ifdef SUPPORT_LOW_LATENCY
656     FilterAllFastProcess();
657 #endif
658 
659     // strong ref to prevent destruct before unlock
660     std::vector<std::shared_ptr<RendererInServer>> renderers;
661 
662     {
663         std::unique_lock<std::mutex> lock(rendererMapMutex_);
664         for (auto it = allRendererMap_.begin(); it != allRendererMap_.end(); it++) {
665             std::shared_ptr<RendererInServer> renderer = it->second.lock();
666             if (renderer == nullptr) {
667                 AUDIO_WARNING_LOG("Renderer is already released!");
668                 continue;
669             }
670             if (ShouldBeInnerCap(renderer->processConfig_, innerCapId)) {
671                 renderer->EnableInnerCap(innerCapId);
672                 AddFilteredRender(innerCapId, renderer);
673             }
674             renderers.push_back(std::move(renderer));
675         }
676     }
677 
678     return SUCCESS;
679 }
680 
OnUpdateInnerCapList(int32_t innerCapId)681 int32_t AudioService::OnUpdateInnerCapList(int32_t innerCapId)
682 {
683     AUDIO_INFO_LOG("workingInnerCapId_ is %{public}d", innerCapId);
684 
685     std::unique_lock<std::mutex> lock(rendererMapMutex_);
686     if (filteredRendererMap_.count(innerCapId)) {
687         for (size_t i = 0; i < filteredRendererMap_[innerCapId].size(); i++) {
688             std::shared_ptr<RendererInServer> renderer = filteredRendererMap_[innerCapId][i].lock();
689             if (renderer == nullptr) {
690                 AUDIO_WARNING_LOG("Renderer is already released!");
691                 continue;
692             }
693             if (!ShouldBeInnerCap(renderer->processConfig_, innerCapId)) {
694                 renderer->DisableInnerCap(innerCapId);
695             }
696         }
697         filteredRendererMap_.erase(innerCapId);
698     }
699     lock.unlock();
700     // EnableInnerCap will be called twice as it's already in filteredRendererMap_.
701     return OnInitInnerCapList(innerCapId);
702 }
703 #endif
704 
EnableDualToneList(uint32_t sessionId)705 int32_t AudioService::EnableDualToneList(uint32_t sessionId)
706 {
707     workingDualToneId_ = sessionId;
708     AUDIO_INFO_LOG("EnableDualToneList sessionId is %{public}d", sessionId);
709     std::unique_lock<std::mutex> lock(rendererMapMutex_);
710     for (auto it = allRendererMap_.begin(); it != allRendererMap_.end(); it++) {
711         std::shared_ptr<RendererInServer> renderer = it->second.lock();
712         if (renderer == nullptr) {
713             AUDIO_WARNING_LOG("Renderer is already released!");
714             continue;
715         }
716         if (ShouldBeDualTone(renderer->processConfig_)) {
717             renderer->EnableDualTone();
718             filteredDualToneRendererMap_.push_back(renderer);
719         }
720     }
721     return SUCCESS;
722 }
723 
DisableDualToneList(uint32_t sessionId)724 int32_t AudioService::DisableDualToneList(uint32_t sessionId)
725 {
726     AUDIO_INFO_LOG("disable dual tone, sessionId is %{public}d", sessionId);
727     std::unique_lock<std::mutex> lock(rendererMapMutex_);
728     for (size_t i = 0; i < filteredDualToneRendererMap_.size(); i++) {
729         std::shared_ptr<RendererInServer> renderer = filteredDualToneRendererMap_[i].lock();
730         if (renderer == nullptr) {
731             AUDIO_WARNING_LOG("Renderer is already released!");
732             continue;
733         }
734         renderer->DisableDualTone();
735     }
736     filteredDualToneRendererMap_.clear();
737     return SUCCESS;
738 }
739 
740 // Only one session is working at the same time.
OnCapturerFilterChange(uint32_t sessionId,const AudioPlaybackCaptureConfig & newConfig,int32_t innerCapId)741 int32_t AudioService::OnCapturerFilterChange(uint32_t sessionId, const AudioPlaybackCaptureConfig &newConfig,
742     int32_t innerCapId)
743 {
744 #ifdef HAS_FEATURE_INNERCAPTURER
745     Trace trace("AudioService::OnCapturerFilterChange");
746     // in plan:
747     // step 1: if sessionId is not added before, add the sessionId and enbale the filter in allRendererMap_
748     // step 2: if sessionId is already in using, this means the config is changed. Check the filtered renderer before,
749     // call disable inner-cap for those not meet with the new config, than filter all allRendererMap_.
750     bool isOldCap = false;
751     {
752         std::lock_guard<std::mutex> lock(workingConfigsMutex_);
753         if (workingConfigs_.count(innerCapId)) {
754             workingConfigs_[innerCapId] = newConfig;
755             isOldCap = true;
756         } else {
757             workingConfigs_[innerCapId] = newConfig;
758         }
759     }
760     if (isOldCap) {
761         return OnUpdateInnerCapList(innerCapId);
762     } else {
763         return OnInitInnerCapList(innerCapId);
764     }
765     AUDIO_WARNING_LOG("%{public}u is working, comming %{public}u will not work!", innerCapId, sessionId);
766     return ERR_OPERATION_FAILED;
767 #endif
768     return SUCCESS;
769 }
770 
OnCapturerFilterRemove(uint32_t sessionId,int32_t innerCapId)771 int32_t AudioService::OnCapturerFilterRemove(uint32_t sessionId, int32_t innerCapId)
772 {
773 #ifdef HAS_FEATURE_INNERCAPTURER
774     {
775         std::lock_guard<std::mutex> lock(workingConfigsMutex_);
776         if (!workingConfigs_.count(innerCapId)) {
777             AUDIO_WARNING_LOG("%{public}u is working, remove %{public}u will not work!", innerCapId, sessionId);
778             return SUCCESS;
779         }
780         workingConfigs_.erase(innerCapId);
781     }
782 
783 #ifdef SUPPORT_LOW_LATENCY
784     std::unique_lock<std::mutex> lockEndpoint(processListMutex_);
785     for (auto pair : endpointList_) {
786         if (pair.second->GetDeviceRole() == OUTPUT_DEVICE) {
787             pair.second->DisableFastInnerCap(innerCapId);
788         }
789     }
790     lockEndpoint.unlock();
791 #endif
792 
793     // strong ref to prevent destruct before unlock
794     std::vector<std::shared_ptr<RendererInServer>> renderers;
795 
796     {
797         std::lock_guard<std::mutex> lock(rendererMapMutex_);
798         if (filteredRendererMap_.count(innerCapId)) {
799             for (size_t i = 0; i < filteredRendererMap_[innerCapId].size(); i++) {
800                 std::shared_ptr<RendererInServer> renderer = filteredRendererMap_[innerCapId][i].lock();
801                 if (renderer == nullptr) {
802                     AUDIO_WARNING_LOG("Find renderer is already released!");
803                     continue;
804                 }
805                 renderer->DisableInnerCap(innerCapId);
806                 renderers.push_back(std::move(renderer));
807         }
808         AUDIO_INFO_LOG("Filter removed, clear %{public}zu filtered renderer.",
809             filteredRendererMap_[innerCapId].size());
810         filteredRendererMap_.erase(innerCapId);
811         }
812     }
813 #endif
814     return SUCCESS;
815 }
816 
IsEndpointTypeVoip(const AudioProcessConfig & config,AudioDeviceDescriptor & deviceInfo)817 bool AudioService::IsEndpointTypeVoip(const AudioProcessConfig &config, AudioDeviceDescriptor &deviceInfo)
818 {
819     if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
820         config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
821         return config.rendererInfo.originalFlag == AUDIO_FLAG_VOIP_FAST || deviceInfo.networkId_ != LOCAL_NETWORK_ID;
822     }
823 
824     if (config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
825         return config.capturerInfo.originalFlag == AUDIO_FLAG_VOIP_FAST || deviceInfo.networkId_ != LOCAL_NETWORK_ID;
826     }
827     return false;
828 }
829 
830 #ifdef SUPPORT_LOW_LATENCY
GetAudioProcess(const AudioProcessConfig & config)831 sptr<AudioProcessInServer> AudioService::GetAudioProcess(const AudioProcessConfig &config)
832 {
833     Trace trace("AudioService::GetAudioProcess for " + std::to_string(config.appInfo.appPid));
834     AUDIO_INFO_LOG("GetAudioProcess dump %{public}s", ProcessConfig::DumpProcessConfig(config).c_str());
835     AudioStreamInfo audioStreamInfo;
836     AudioDeviceDescriptor deviceInfo = GetDeviceInfoForProcess(config, audioStreamInfo);
837     std::lock_guard<std::mutex> lock(processListMutex_);
838     std::shared_ptr<AudioEndpoint> audioEndpoint = GetAudioEndpointForDevice(deviceInfo, config,
839         audioStreamInfo, IsEndpointTypeVoip(config, deviceInfo));
840     CHECK_AND_RETURN_RET_LOG(audioEndpoint != nullptr, nullptr, "no endpoint found for the process");
841 
842     uint32_t totalSizeInframe = 0;
843     uint32_t spanSizeInframe = 0;
844     audioEndpoint->GetPreferBufferInfo(totalSizeInframe, spanSizeInframe);
845 
846     CHECK_AND_RETURN_RET_LOG(audioStreamInfo.samplingRate > 0, nullptr, "Sample rate in server is invalid.");
847 
848     sptr<AudioProcessInServer> process = AudioProcessInServer::Create(config, this);
849     CHECK_AND_RETURN_RET_LOG(process != nullptr, nullptr, "AudioProcessInServer create failed.");
850     CheckFastSessionMuteState(process->GetSessionId(), process);
851 
852     std::shared_ptr<OHAudioBufferBase> buffer = nullptr;
853     int32_t ret = process->ConfigProcessBuffer(totalSizeInframe, spanSizeInframe, audioStreamInfo, buffer);
854     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, nullptr, "ConfigProcessBuffer failed");
855 
856     ret = LinkProcessToEndpoint(process, audioEndpoint);
857     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, nullptr, "LinkProcessToEndpoint failed");
858     linkedPairedList_.push_back(std::make_pair(process, audioEndpoint));
859 #ifdef HAS_FEATURE_INNERCAPTURER
860     CheckInnerCapForProcess(process, audioEndpoint);
861 #endif
862     return process;
863 }
864 
ResetAudioEndpoint()865 void AudioService::ResetAudioEndpoint()
866 {
867     std::lock_guard<std::mutex> lock(processListMutex_);
868 
869     std::vector<std::string> audioEndpointNames;
870     for (auto paired = linkedPairedList_.begin(); paired != linkedPairedList_.end(); paired++) {
871         if (paired->second->GetEndpointType() == AudioEndpoint::TYPE_MMAP) {
872             // unlink old link
873             if (UnlinkProcessToEndpoint(paired->first, paired->second) != SUCCESS) {
874                 AUDIO_ERR_LOG("Unlink process to old endpoint failed");
875             }
876             audioEndpointNames.push_back(paired->second->GetEndpointName());
877         }
878     }
879 
880     // release old endpoint
881     for (auto &endpointName : audioEndpointNames) {
882         if (endpointList_.count(endpointName) > 0) {
883             endpointList_[endpointName]->Release();
884             AUDIO_INFO_LOG("Erase endpoint %{public}s from endpointList_", endpointName.c_str());
885             endpointList_.erase(endpointName);
886         }
887     }
888 
889     ReLinkProcessToEndpoint();
890 }
891 
ReLinkProcessToEndpoint()892 void AudioService::ReLinkProcessToEndpoint()
893 {
894     using LinkPair = std::pair<sptr<AudioProcessInServer>, std::shared_ptr<AudioEndpoint>>;
895     std::vector<std::vector<LinkPair>::iterator> errorLinkedPaireds;
896     for (auto paired = linkedPairedList_.begin(); paired != linkedPairedList_.end(); paired++) {
897         if (paired->second->GetEndpointType() == AudioEndpoint::TYPE_MMAP) {
898             AUDIO_INFO_LOG("Session id %{public}u", paired->first->GetSessionId());
899 
900             // get new endpoint
901             AudioStreamInfo streamInfo;
902             const AudioProcessConfig &config = paired->first->processConfig_;
903             AudioDeviceDescriptor deviceInfo = GetDeviceInfoForProcess(config, streamInfo, true);
904             std::shared_ptr<AudioEndpoint> audioEndpoint = GetAudioEndpointForDevice(deviceInfo, config,
905                 streamInfo, IsEndpointTypeVoip(config, deviceInfo));
906             if (audioEndpoint == nullptr) {
907                 AUDIO_ERR_LOG("Get new endpoint failed");
908                 errorLinkedPaireds.push_back(paired);
909                 continue;
910             }
911             // link new endpoint
912             if (LinkProcessToEndpoint(paired->first, audioEndpoint) != SUCCESS) {
913                 AUDIO_ERR_LOG("LinkProcessToEndpoint failed");
914                 errorLinkedPaireds.push_back(paired);
915                 continue;
916             }
917             // reset shared_ptr before to new
918             paired->second.reset();
919             paired->second = audioEndpoint;
920 #ifdef HAS_FEATURE_INNERCAPTURER
921             CheckInnerCapForProcess(paired->first, audioEndpoint);
922 #endif
923         }
924     }
925 
926     for (auto &paired : errorLinkedPaireds) {
927         linkedPairedList_.erase(paired);
928     }
929 }
930 
931 #ifdef HAS_FEATURE_INNERCAPTURER
CheckInnerCapForProcess(sptr<AudioProcessInServer> process,std::shared_ptr<AudioEndpoint> endpoint)932 void AudioService::CheckInnerCapForProcess(sptr<AudioProcessInServer> process, std::shared_ptr<AudioEndpoint> endpoint)
933 {
934     Trace trace("AudioService::CheckInnerCapForProcess:" + std::to_string(process->processConfig_.appInfo.appPid));
935     // inner-cap not working
936     std::set<int32_t> captureIds;
937     if (ShouldBeInnerCap(process->processConfig_, captureIds)) {
938         HandleFastCapture(captureIds, process, endpoint);
939     }
940 }
941 #endif
942 
LinkProcessToEndpoint(sptr<AudioProcessInServer> process,std::shared_ptr<AudioEndpoint> endpoint)943 int32_t AudioService::LinkProcessToEndpoint(sptr<AudioProcessInServer> process,
944     std::shared_ptr<AudioEndpoint> endpoint)
945 {
946     int32_t ret = endpoint->LinkProcessStream(process, !GetHibernateState());
947     if (ret != SUCCESS && endpoint->GetLinkedProcessCount() == 0 &&
948         endpointList_.count(endpoint->GetEndpointName())) {
949         std::string endpointToErase = endpoint->GetEndpointName();
950         endpointList_.erase(endpoint->GetEndpointName());
951         AUDIO_ERR_LOG("LinkProcessStream failed, erase endpoint %{public}s", endpointToErase.c_str());
952         return ERR_OPERATION_FAILED;
953     }
954     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "LinkProcessStream to endpoint %{public}s failed",
955         endpoint->GetEndpointName().c_str());
956 
957     ret = process->AddProcessStatusListener(endpoint);
958     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "AddProcessStatusListener failed");
959 
960     std::unique_lock<std::mutex> lock(releaseEndpointMutex_);
961     if (releasingEndpointSet_.count(endpoint->GetEndpointName())) {
962         AUDIO_INFO_LOG("LinkProcessToEndpoint find endpoint is releasing, call break.");
963         releasingEndpointSet_.erase(endpoint->GetEndpointName());
964         releaseEndpointCV_.notify_all();
965     }
966     return SUCCESS;
967 }
968 
UnlinkProcessToEndpoint(sptr<AudioProcessInServer> process,std::shared_ptr<AudioEndpoint> endpoint)969 int32_t AudioService::UnlinkProcessToEndpoint(sptr<AudioProcessInServer> process,
970     std::shared_ptr<AudioEndpoint> endpoint)
971 {
972     int32_t ret = endpoint->UnlinkProcessStream(process);
973     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "UnlinkProcessStream failed");
974 
975     ret = process->RemoveProcessStatusListener(endpoint);
976     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "RemoveProcessStatusListener failed");
977 
978     return SUCCESS;
979 }
980 
DelayCallReleaseEndpoint(std::string endpointName)981 void AudioService::DelayCallReleaseEndpoint(std::string endpointName)
982 {
983     std::lock_guard<std::mutex> lock(releaseEndpointMutex_);
984     if (!releasingEndpointSet_.count(endpointName)) {
985         AUDIO_DEBUG_LOG("Timeout or not need to release: %{public}s", endpointName.c_str());
986         return;
987     }
988     releasingEndpointSet_.erase(endpointName);
989     CHECK_AND_RETURN_LOG(endpointList_.find(endpointName) != endpointList_.end() &&
990         endpointList_[endpointName] != nullptr, "Endpoint %{public}s not available, stop call release",
991         endpointName.c_str());
992     std::shared_ptr<AudioEndpoint> temp = endpointList_[endpointName];
993     if (temp->GetStatus() == AudioEndpoint::EndpointStatus::UNLINKED) {
994         AUDIO_INFO_LOG("%{public}s not in use anymore, call release!", endpointName.c_str());
995         temp->Release();
996         temp = nullptr;
997         endpointList_.erase(endpointName);
998         return;
999     }
1000     AUDIO_WARNING_LOG("%{public}s is not unlinked, stop call release", endpointName.c_str());
1001     return;
1002 }
1003 
GetDeviceInfoForProcess(const AudioProcessConfig & config,AudioStreamInfo & streamInfo,bool isReloadProcess)1004 AudioDeviceDescriptor AudioService::GetDeviceInfoForProcess(const AudioProcessConfig &config,
1005     AudioStreamInfo &streamInfo, bool isReloadProcess)
1006 {
1007     // send the config to AudioPolicyServera and get the device info.
1008     AudioDeviceDescriptor deviceInfo(AudioDeviceDescriptor::DEVICE_INFO);
1009     int32_t ret = CoreServiceHandler::GetInstance().GetProcessDeviceInfoBySessionId(config.originalSessionId,
1010         deviceInfo, streamInfo, isReloadProcess);
1011     if (ret == SUCCESS) {
1012         AUDIO_INFO_LOG("Get DeviceInfo from policy: deviceType:%{public}d, supportLowLatency:%{public}s"
1013             " a2dpOffloadFlag:%{public}d", deviceInfo.deviceType_, (deviceInfo.isLowLatencyDevice_ ? "true" : "false"),
1014             deviceInfo.a2dpOffloadFlag_);
1015         if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
1016             config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION ||
1017             config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
1018             if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) {
1019                 AUDIO_INFO_LOG("VoIP 16K");
1020                 streamInfo = {SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, STEREO, CH_LAYOUT_STEREO};
1021             } else {
1022                 AUDIO_INFO_LOG("VoIP 48K");
1023                 streamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO, CH_LAYOUT_STEREO};
1024             }
1025         } else {
1026             AUDIO_INFO_LOG("Fast stream use format:%{public}d", streamInfo.format);
1027             deviceInfo.deviceName_ = "mmap_device";
1028         }
1029         return deviceInfo;
1030     }
1031 
1032     AUDIO_WARNING_LOG("GetProcessDeviceInfo from audio policy server failed!");
1033     if (config.audioMode == AUDIO_MODE_RECORD) {
1034         deviceInfo.deviceId_ = 1;
1035         deviceInfo.networkId_ = LOCAL_NETWORK_ID;
1036         deviceInfo.deviceRole_ = INPUT_DEVICE;
1037         deviceInfo.deviceType_ = DEVICE_TYPE_MIC;
1038     } else {
1039         deviceInfo.deviceId_ = 6; // 6 for test
1040         deviceInfo.networkId_ = LOCAL_NETWORK_ID;
1041         deviceInfo.deviceRole_ = OUTPUT_DEVICE;
1042         deviceInfo.deviceType_ = DEVICE_TYPE_SPEAKER;
1043     }
1044     streamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO,
1045         CH_LAYOUT_STEREO}; // note: read from xml
1046     deviceInfo.deviceName_ = "mmap_device";
1047     return deviceInfo;
1048 }
1049 
CheckBeforeRecordEndpointCreate(bool isRecord)1050 void AudioService::CheckBeforeRecordEndpointCreate(bool isRecord)
1051 {
1052     // release at once to avoid normal fastsource and voip fastsource existing at the same time
1053     if (isRecord) {
1054         for (auto &item : endpointList_) {
1055             if (item.second->GetAudioMode() == AudioMode::AUDIO_MODE_RECORD) {
1056                 std::string endpointName = item.second->GetEndpointName();
1057                 DelayCallReleaseEndpoint(endpointName);
1058                 AUDIO_INFO_LOG("Release endpoint %{public}s change to now", endpointName.c_str());
1059                 break;
1060             }
1061         }
1062     }
1063 }
1064 
1065 // must be called with processListMutex_ lock hold
GetReuseEndpointType(AudioDeviceDescriptor & deviceInfo,const std::string & deviceKey,AudioStreamInfo & streamInfo)1066 ReuseEndpointType AudioService::GetReuseEndpointType(AudioDeviceDescriptor &deviceInfo,
1067     const std::string &deviceKey, AudioStreamInfo &streamInfo)
1068 {
1069     if (endpointList_.find(deviceKey) == endpointList_.end()) {
1070         return ReuseEndpointType::CREATE_ENDPOINT;
1071     }
1072     bool reuse = streamInfo == endpointList_[deviceKey]->GetAudioStreamInfo();
1073     return reuse ? ReuseEndpointType::REUSE_ENDPOINT : ReuseEndpointType::RECREATE_ENDPOINT;
1074 }
1075 
GetAudioEndpointForDevice(AudioDeviceDescriptor & deviceInfo,const AudioProcessConfig & clientConfig,AudioStreamInfo & streamInfo,bool isVoipStream)1076 std::shared_ptr<AudioEndpoint> AudioService::GetAudioEndpointForDevice(AudioDeviceDescriptor &deviceInfo,
1077     const AudioProcessConfig &clientConfig, AudioStreamInfo &streamInfo, bool isVoipStream)
1078 {
1079     // Create shared stream.
1080     int32_t endpointFlag = isVoipStream ? AUDIO_FLAG_VOIP_FAST : AUDIO_FLAG_MMAP;
1081     std::string deviceKey = AudioEndpoint::GenerateEndpointKey(deviceInfo, endpointFlag);
1082     ReuseEndpointType type = GetReuseEndpointType(deviceInfo, deviceKey, streamInfo);
1083     std::shared_ptr<AudioEndpoint> endpoint = nullptr;
1084 
1085     switch (type) {
1086         case ReuseEndpointType::REUSE_ENDPOINT: {
1087             AUDIO_INFO_LOG("AudioService find endpoint already exist for deviceKey:%{public}s", deviceKey.c_str());
1088             endpoint = endpointList_[deviceKey];
1089             break;
1090         }
1091         case ReuseEndpointType::RECREATE_ENDPOINT: {
1092             std::string endpointName = endpointList_[deviceKey]->GetEndpointName();
1093             AUDIO_INFO_LOG("Release endpoint %{public}s change to now", endpointName.c_str());
1094             DelayCallReleaseEndpoint(endpointName);
1095             [[fallthrough]];
1096         }
1097         case ReuseEndpointType::CREATE_ENDPOINT: {
1098             CheckBeforeRecordEndpointCreate(clientConfig.audioMode == AudioMode::AUDIO_MODE_RECORD);
1099             endpoint = AudioEndpoint::CreateEndpoint(isVoipStream ? AudioEndpoint::TYPE_VOIP_MMAP :
1100                 AudioEndpoint::TYPE_MMAP, endpointFlag, clientConfig, deviceInfo, streamInfo);
1101             CHECK_AND_RETURN_RET_LOG(endpoint != nullptr, nullptr, "Create mmap AudioEndpoint failed.");
1102             AUDIO_INFO_LOG("Add endpoint %{public}s to endpointList_", deviceKey.c_str());
1103             endpointList_[deviceKey] = endpoint;
1104             break;
1105         }
1106         default:
1107             AUDIO_ERR_LOG("Create mmap AudioEndpoint failed.");
1108             break;
1109     }
1110 
1111     return endpoint;
1112 }
1113 #endif
1114 
NotifyStreamVolumeChanged(AudioStreamType streamType,float volume)1115 int32_t AudioService::NotifyStreamVolumeChanged(AudioStreamType streamType, float volume)
1116 {
1117     std::lock_guard<std::mutex> lock(processListMutex_);
1118     int32_t ret = SUCCESS;
1119 #ifdef SUPPORT_LOW_LATENCY
1120     for (auto item : endpointList_) {
1121         if (item.second == nullptr) {
1122             continue;
1123         }
1124         std::string endpointName = item.second->GetEndpointName();
1125         if (endpointName == item.first) {
1126             ret = ret != SUCCESS ? ret : item.second->SetVolume(streamType, volume);
1127         }
1128     }
1129 #endif
1130     UpdateSystemVolume(streamType, volume);
1131     return ret;
1132 }
1133 
Dump(std::string & dumpString)1134 void AudioService::Dump(std::string &dumpString)
1135 {
1136     AUDIO_INFO_LOG("AudioService dump begin");
1137     {
1138         std::lock_guard<std::mutex> lock(workingConfigsMutex_);
1139         for (auto &workingConfig_ : workingConfigs_) {
1140             AppendFormat(dumpString, "InnerCapid: %s  - InnerCap filter: %s\n",
1141             std::to_string(workingConfig_.first).c_str(),
1142             ProcessConfig::DumpInnerCapConfig(workingConfig_.second).c_str());
1143         }
1144     }
1145 #ifdef SUPPORT_LOW_LATENCY
1146     // dump process
1147     for (auto paired : linkedPairedList_) {
1148         paired.first->Dump(dumpString);
1149     }
1150     // dump endpoint
1151     for (auto item : endpointList_) {
1152         AppendFormat(dumpString, "  - Endpoint device id: %s\n", item.first.c_str());
1153         item.second->Dump(dumpString);
1154     }
1155 #endif
1156     // dump voip and direct
1157     {
1158         std::lock_guard<std::mutex> lock(rendererMapMutex_);
1159         for (const auto &item : allRendererMap_) {
1160             std::shared_ptr<RendererInServer> renderer = item.second.lock();
1161             if (renderer) {
1162                 renderer->Dump(dumpString);
1163             }
1164         }
1165     }
1166 
1167     // dump appUseNumMap_ and currentRendererStreamCnt_
1168     {
1169         std::lock_guard<std::mutex> lock(streamLifeCycleMutex_);
1170         AppendFormat(dumpString, " - currentRendererStreamCnt is %d\n", currentRendererStreamCnt_);
1171         for (auto it : appUseNumMap_) {
1172             AppendFormat(dumpString, "  - appUseNumMap_ appUid: %d\n", it.first);
1173             AppendFormat(dumpString, "  - appUseNumMap_ appUid created stream: %d\n", it.second);
1174         }
1175     }
1176     PolicyHandler::GetInstance().Dump(dumpString);
1177     AudioVolume::GetInstance()->Dump(dumpString);
1178 }
1179 
GetMaxAmplitude(bool isOutputDevice)1180 float AudioService::GetMaxAmplitude(bool isOutputDevice)
1181 {
1182 #ifdef SUPPORT_LOW_LATENCY
1183     std::lock_guard<std::mutex> lock(processListMutex_);
1184     if (linkedPairedList_.size() == 0) {
1185         return 0;
1186     }
1187 
1188     float fastAudioMaxAmplitude = 0;
1189     for (auto paired : linkedPairedList_) {
1190         if (isOutputDevice && (paired.second->GetDeviceRole() == OUTPUT_DEVICE)) {
1191             float curFastAudioMaxAmplitude = paired.second->GetMaxAmplitude();
1192             if (curFastAudioMaxAmplitude > fastAudioMaxAmplitude) {
1193                 fastAudioMaxAmplitude = curFastAudioMaxAmplitude;
1194             }
1195         }
1196         if (!isOutputDevice && (paired.second->GetDeviceRole() == INPUT_DEVICE)) {
1197             float curFastAudioMaxAmplitude = paired.second->GetMaxAmplitude();
1198             if (curFastAudioMaxAmplitude > fastAudioMaxAmplitude) {
1199                 fastAudioMaxAmplitude = curFastAudioMaxAmplitude;
1200             }
1201         }
1202     }
1203     return fastAudioMaxAmplitude;
1204 #else
1205     return 0;
1206 #endif
1207 }
1208 
GetRendererBySessionID(const uint32_t & sessionID)1209 std::shared_ptr<RendererInServer> AudioService::GetRendererBySessionID(const uint32_t &sessionID)
1210 {
1211     std::lock_guard<std::mutex> lock(rendererMapMutex_);
1212     if (allRendererMap_.count(sessionID)) {
1213         return allRendererMap_[sessionID].lock();
1214     } else {
1215         return nullptr;
1216     }
1217 }
1218 
GetCapturerBySessionID(const uint32_t & sessionID)1219 std::shared_ptr<CapturerInServer> AudioService::GetCapturerBySessionID(const uint32_t &sessionID)
1220 {
1221     if (allCapturerMap_.count(sessionID)) {
1222         return allCapturerMap_[sessionID].lock();
1223     } else {
1224         return std::shared_ptr<CapturerInServer>();
1225     }
1226 }
1227 
SetNonInterruptMute(const uint32_t sessionId,const bool muteFlag)1228 void AudioService::SetNonInterruptMute(const uint32_t sessionId, const bool muteFlag)
1229 {
1230     AUDIO_INFO_LOG("SessionId: %{public}u, muteFlag: %{public}d", sessionId, muteFlag);
1231     std::unique_lock<std::mutex> rendererLock(rendererMapMutex_);
1232     if (allRendererMap_.count(sessionId)) {
1233         std::shared_ptr<RendererInServer> renderer = allRendererMap_[sessionId].lock();
1234         if (renderer == nullptr) {
1235             AUDIO_ERR_LOG("rendererinserver is null");
1236             rendererLock.unlock();
1237             return;
1238         }
1239         renderer->SetNonInterruptMute(muteFlag);
1240         AUDIO_INFO_LOG("allRendererMap_ has sessionId");
1241         rendererLock.unlock();
1242         return;
1243     }
1244     rendererLock.unlock();
1245     std::unique_lock<std::mutex> capturerLock(capturerMapMutex_);
1246     if (allCapturerMap_.count(sessionId)) {
1247         std::shared_ptr<CapturerInServer> capturer = allCapturerMap_[sessionId].lock();
1248         if (capturer == nullptr) {
1249             AUDIO_ERR_LOG("capturerinserver is null");
1250             return;
1251         }
1252         capturer->SetNonInterruptMute(muteFlag);
1253         AUDIO_INFO_LOG("allCapturerMap_ has sessionId");
1254         return;
1255     }
1256     capturerLock.unlock();
1257     SetNonInterruptMuteForProcess(sessionId, muteFlag);
1258 }
1259 
SetNonInterruptMuteForProcess(const uint32_t sessionId,const bool muteFlag)1260 void AudioService::SetNonInterruptMuteForProcess(const uint32_t sessionId, const bool muteFlag)
1261 {
1262 #ifdef SUPPORT_LOW_LATENCY
1263     std::unique_lock<std::mutex> processListLock(processListMutex_);
1264     for (auto paired : linkedPairedList_) {
1265         if (paired.first == nullptr) {
1266             AUDIO_ERR_LOG("processInServer is nullptr");
1267             return;
1268         }
1269         if (paired.first->GetSessionId() == sessionId) {
1270             AUDIO_INFO_LOG("linkedPairedList_ has sessionId");
1271             paired.first->SetNonInterruptMute(muteFlag);
1272             return;
1273         }
1274     }
1275     processListLock.unlock();
1276 #endif
1277     AUDIO_INFO_LOG("Cannot find sessionId");
1278     // when old stream already released and new stream not create yet
1279     // set muteflag 0 but cannot find sessionId in allRendererMap_, allCapturerMap_ and linkedPairedList_
1280     // need erase it from mutedSessions_ to avoid new stream cannot be set unmute
1281     if (mutedSessions_.count(sessionId) && !muteFlag) {
1282         mutedSessions_.erase(sessionId);
1283     }
1284     // when old stream already released and new stream not create yet
1285     // set muteflag 1 but cannot find sessionId in allRendererMap_, allCapturerMap_ and linkedPairedList_
1286     // this sessionid will not add into mutedSessions_
1287     // so need save it temporarily, when new stream create, check if new stream need mute
1288     // if set muteflag 0 again before new stream create, do not mute it
1289     std::lock_guard<std::mutex> muteSwitchStreamLock(muteSwitchStreamSetMutex_);
1290     if (muteFlag) {
1291         muteSwitchStreams_.insert(sessionId);
1292         AUDIO_INFO_LOG("Insert into muteSwitchStreams_");
1293     } else if (muteSwitchStreams_.count(sessionId)) {
1294         muteSwitchStreams_.erase(sessionId);
1295     }
1296 }
1297 
SetOffloadMode(uint32_t sessionId,int32_t state,bool isAppBack)1298 int32_t AudioService::SetOffloadMode(uint32_t sessionId, int32_t state, bool isAppBack)
1299 {
1300     std::unique_lock<std::mutex> lock(rendererMapMutex_);
1301     if (!allRendererMap_.count(sessionId)) {
1302         AUDIO_WARNING_LOG("Renderer %{public}u is not in map", sessionId);
1303         return ERR_INVALID_INDEX;
1304     }
1305     AUDIO_INFO_LOG("Set offload mode for renderer %{public}u", sessionId);
1306     std::shared_ptr<RendererInServer> renderer = allRendererMap_[sessionId].lock();
1307     if (renderer == nullptr) {
1308         AUDIO_WARNING_LOG("RendererInServer is nullptr");
1309         lock.unlock();
1310         return ERROR;
1311     }
1312     lock.unlock();
1313     int32_t ret = renderer->SetOffloadMode(state, isAppBack);
1314     return ret;
1315 }
1316 
UnsetOffloadMode(uint32_t sessionId)1317 int32_t AudioService::UnsetOffloadMode(uint32_t sessionId)
1318 {
1319     std::unique_lock<std::mutex> lock(rendererMapMutex_);
1320     if (!allRendererMap_.count(sessionId)) {
1321         AUDIO_WARNING_LOG("Renderer %{public}u is not in map", sessionId);
1322         return ERR_INVALID_INDEX;
1323     }
1324     AUDIO_INFO_LOG("Set offload mode for renderer %{public}u", sessionId);
1325     std::shared_ptr<RendererInServer> renderer = allRendererMap_[sessionId].lock();
1326     if (renderer == nullptr) {
1327         AUDIO_WARNING_LOG("RendererInServer is nullptr");
1328         lock.unlock();
1329         return ERROR;
1330     }
1331     int32_t ret = renderer->UnsetOffloadMode();
1332     lock.unlock();
1333     return ret;
1334 }
1335 
UpdateAudioSinkState(uint32_t sinkId,bool started)1336 void AudioService::UpdateAudioSinkState(uint32_t sinkId, bool started)
1337 {
1338     std::unique_lock<std::mutex> lock(allRunningSinksMutex_);
1339     if (started) {
1340         CHECK_AND_RETURN_LOG(allRunningSinks_.find(sinkId) == allRunningSinks_.end(),
1341             "Sink %{public}u already started", sinkId);
1342         allRunningSinks_.insert(sinkId);
1343         AUDIO_INFO_LOG("Sink %{public}u started", sinkId);
1344     } else {
1345         CHECK_AND_RETURN_LOG(allRunningSinks_.find(sinkId) != allRunningSinks_.end(),
1346             "Sink %{public}u already stopped or not started", sinkId);
1347         allRunningSinks_.erase(sinkId);
1348         AUDIO_INFO_LOG("Sink %{public}u stopped", sinkId);
1349         if (allRunningSinks_.empty()) {
1350             allRunningSinksCV_.notify_all();
1351             AUDIO_INFO_LOG("All sinks stop, continue to hibernate");
1352         }
1353     }
1354     return;
1355 }
1356 
CheckHibernateState(bool onHibernate)1357 void AudioService::CheckHibernateState(bool onHibernate)
1358 {
1359     std::unique_lock<std::mutex> lock(allRunningSinksMutex_);
1360     onHibernate_ = onHibernate;
1361     if (onHibernate) {
1362         bool ret = true;
1363         if (allRunningSinks_.empty()) {
1364             // Sleep for 100ms and recheck to avoid another sink start right after first check.
1365             AUDIO_INFO_LOG("No running sinks, sleep for 100ms and check again");
1366             lock.unlock(); // Unlock so that other running sinks can be added
1367             usleep(RECHECK_SINK_STATE_IN_US); // sleep for 100ms
1368             lock.lock();
1369             CHECK_AND_RETURN_LOG(!allRunningSinks_.empty(), "No running sinks, continue to hibernate");
1370         }
1371         AUDIO_INFO_LOG("Wait for all sinks to stop");
1372         ret = allRunningSinksCV_.wait_for(lock, std::chrono::milliseconds(BLOCK_HIBERNATE_CALLBACK_IN_MS),
1373             [this] {return (allRunningSinks_.empty() || !onHibernate_);});
1374         if (!ret) {
1375             AUDIO_ERR_LOG("On hibernate timeout, some sinks still running");
1376         }
1377         return;
1378     } else {
1379         allRunningSinksCV_.notify_all();
1380         AUDIO_INFO_LOG("Wake up from hibernate");
1381     }
1382 }
1383 
GetHibernateState()1384 bool AudioService::GetHibernateState()
1385 {
1386     std::unique_lock<std::mutex> lock(allRunningSinksMutex_);
1387     return onHibernate_;
1388 }
1389 
UpdateSourceType(SourceType sourceType)1390 int32_t AudioService::UpdateSourceType(SourceType sourceType)
1391 {
1392     // specialSourceType need not updateaudioroute
1393     if (specialSourceTypeSet_.count(sourceType) != 0) {
1394         return SUCCESS;
1395     }
1396 
1397     uint32_t id = HdiAdapterManager::GetInstance().GetId(HDI_ID_BASE_CAPTURE, HDI_ID_TYPE_PRIMARY);
1398     std::shared_ptr<IAudioCaptureSource> source = HdiAdapterManager::GetInstance().GetCaptureSource(id);
1399     CHECK_AND_RETURN_RET_LOG(source != nullptr, ERROR, "source is null");
1400 
1401     return source->UpdateSourceType(sourceType);
1402 }
1403 
SetIncMaxRendererStreamCnt(AudioMode audioMode)1404 void AudioService::SetIncMaxRendererStreamCnt(AudioMode audioMode)
1405 {
1406     if (audioMode == AUDIO_MODE_PLAYBACK) {
1407         currentRendererStreamCnt_++;
1408     }
1409 }
1410 
SetDecMaxRendererStreamCnt()1411 void AudioService::SetDecMaxRendererStreamCnt()
1412 {
1413     std::lock_guard<std::mutex> lock(streamLifeCycleMutex_);
1414     currentRendererStreamCnt_--;
1415 }
1416 
SetIncMaxLoopbackStreamCnt(AudioMode audioMode)1417 void AudioService::SetIncMaxLoopbackStreamCnt(AudioMode audioMode)
1418 {
1419     if (audioMode == AUDIO_MODE_PLAYBACK) {
1420         currentLoopbackRendererStreamCnt_++;
1421     } else {
1422         currentLoopbackCapturerStreamCnt_++;
1423     }
1424 }
1425 
GetCurrentLoopbackStreamCnt(AudioMode audioMode)1426 int32_t AudioService::GetCurrentLoopbackStreamCnt(AudioMode audioMode)
1427 {
1428     if (audioMode == AUDIO_MODE_PLAYBACK) {
1429         return currentLoopbackRendererStreamCnt_;
1430     } else {
1431         return currentLoopbackCapturerStreamCnt_;
1432     }
1433 }
1434 
SetDecMaxLoopbackStreamCnt(AudioMode audioMode)1435 void AudioService::SetDecMaxLoopbackStreamCnt(AudioMode audioMode)
1436 {
1437     std::lock_guard<std::mutex> lock(streamLifeCycleMutex_);
1438     if (audioMode == AUDIO_MODE_PLAYBACK) {
1439         currentLoopbackRendererStreamCnt_--;
1440     } else {
1441         currentLoopbackCapturerStreamCnt_--;
1442     }
1443 }
1444 
CleanAppUseNumMap(int32_t appUid)1445 void AudioService::CleanAppUseNumMap(int32_t appUid)
1446 {
1447     std::lock_guard<std::mutex> lock(streamLifeCycleMutex_);
1448     auto appUseNum = appUseNumMap_.find(appUid);
1449     if (appUseNum != appUseNumMap_.end()) {
1450         appUseNumMap_[appUid] = --appUseNum->second;
1451     }
1452 }
1453 
HasBluetoothEndpoint()1454 bool AudioService::HasBluetoothEndpoint()
1455 {
1456 #ifdef SUPPORT_LOW_LATENCY
1457     std::lock_guard<std::mutex> lock(processListMutex_);
1458     return std::any_of(linkedPairedList_.begin(), linkedPairedList_.end(),
1459         [](const auto & linkPair) {
1460             return linkPair.second->GetDeviceInfo().getType() == DEVICE_TYPE_BLUETOOTH_A2DP;
1461         });
1462 #else
1463     return true;
1464 #endif
1465 }
1466 
GetCurrentRendererStreamCnt()1467 int32_t AudioService::GetCurrentRendererStreamCnt()
1468 {
1469     return currentRendererStreamCnt_;
1470 }
1471 
GetAllSinkInputs(std::vector<SinkInput> & sinkInputs)1472 void AudioService::GetAllSinkInputs(std::vector<SinkInput> &sinkInputs)
1473 {
1474     IStreamManager::GetPlaybackManager(PLAYBACK).GetAllSinkInputs(sinkInputs);
1475 }
1476 
SetDefaultAdapterEnable(bool isEnable)1477 void AudioService::SetDefaultAdapterEnable(bool isEnable)
1478 {
1479     isDefaultAdapterEnable_ = isEnable;
1480 }
1481 
GetDefaultAdapterEnable()1482 bool AudioService::GetDefaultAdapterEnable()
1483 {
1484     return isDefaultAdapterEnable_;
1485 }
1486 
1487 // need call with streamLifeCycleMutex_ lock
IsExceedingMaxStreamCntPerUid(int32_t callingUid,int32_t appUid,int32_t maxStreamCntPerUid)1488 bool AudioService::IsExceedingMaxStreamCntPerUid(int32_t callingUid, int32_t appUid,
1489     int32_t maxStreamCntPerUid)
1490 {
1491     if (callingUid != MEDIA_SERVICE_UID) {
1492         appUid = callingUid;
1493     }
1494 
1495     auto appUseNum = appUseNumMap_.find(appUid);
1496     if (appUseNum != appUseNumMap_.end()) {
1497         ++appUseNum->second;
1498     } else {
1499         int32_t initValue = 1;
1500         appUseNumMap_.emplace(appUid, initValue);
1501     }
1502 
1503     if (appUseNumMap_[appUid] >= RENDERER_STREAM_CNT_PER_UID_LIMIT) {
1504         int32_t mostAppUid = INVALID_APP_UID;
1505         int32_t mostAppNum = INVALID_APP_CREATED_AUDIO_STREAM_NUM;
1506         GetCreatedAudioStreamMostUid(mostAppUid, mostAppNum);
1507         std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1508             Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_STREAM_EXHAUSTED_STATS,
1509             Media::MediaMonitor::EventType::FREQUENCY_AGGREGATION_EVENT);
1510         bean->Add("CLIENT_UID", mostAppUid);
1511         bean->Add("TIMES", mostAppNum);
1512         Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1513         AUDIO_WARNING_LOG("Current audio renderer stream num is greater than the renderer stream num limit per uid");
1514     }
1515 
1516     if (appUseNumMap_[appUid] > maxStreamCntPerUid) {
1517         --appUseNumMap_[appUid]; // actual created stream num is stream num decrease one
1518         return true;
1519     }
1520     return false;
1521 }
1522 
GetCreatedAudioStreamMostUid(int32_t & mostAppUid,int32_t & mostAppNum)1523 void AudioService::GetCreatedAudioStreamMostUid(int32_t &mostAppUid, int32_t &mostAppNum)
1524 {
1525     for (auto it = appUseNumMap_.begin(); it != appUseNumMap_.end(); it++) {
1526         if (it->second > mostAppNum) {
1527             mostAppNum = it->second;
1528             mostAppUid = it->first;
1529         }
1530     }
1531     return;
1532 }
1533 
1534 #ifdef HAS_FEATURE_INNERCAPTURER
UnloadModernInnerCapSink(int32_t innerCapId)1535 int32_t AudioService::UnloadModernInnerCapSink(int32_t innerCapId)
1536 {
1537     return PolicyHandler::GetInstance().UnloadModernInnerCapSink(innerCapId);
1538 }
1539 #endif
1540 
RestoreSession(uint32_t sessionId,RestoreInfo restoreInfo)1541 RestoreStatus AudioService::RestoreSession(uint32_t sessionId, RestoreInfo restoreInfo)
1542 {
1543     {
1544         std::lock_guard<std::mutex> lock(rendererMapMutex_);
1545         if (allRendererMap_.find(sessionId) != allRendererMap_.end()) {
1546             std::shared_ptr<RendererInServer> rendererInServer = allRendererMap_[sessionId].lock();
1547             CHECK_AND_RETURN_RET_LOG(rendererInServer != nullptr, RESTORE_ERROR,
1548                 "Session could be released, restore failed");
1549             return rendererInServer->RestoreSession(restoreInfo);
1550         }
1551     }
1552     {
1553         std::lock_guard<std::mutex> lock(capturerMapMutex_);
1554         if (allCapturerMap_.find(sessionId) != allCapturerMap_.end()) {
1555             std::shared_ptr<CapturerInServer> capturerInServer = allCapturerMap_[sessionId].lock();
1556             CHECK_AND_RETURN_RET_LOG(capturerInServer != nullptr, RESTORE_ERROR,
1557                 "Session could be released, restore failed");
1558             return capturerInServer->RestoreSession(restoreInfo);
1559         }
1560     }
1561 #ifdef SUPPORT_LOW_LATENCY
1562     {
1563         std::lock_guard<std::mutex> lock(processListMutex_);
1564         for (auto processEndpointPair : linkedPairedList_) {
1565             if (processEndpointPair.first->GetSessionId() != sessionId) {
1566                 continue;
1567             }
1568             auto audioProcessInServer = processEndpointPair.first;
1569             CHECK_AND_RETURN_RET_LOG(audioProcessInServer != nullptr, RESTORE_ERROR,
1570                 "Session could be released, restore failed");
1571             return audioProcessInServer->RestoreSession(restoreInfo);
1572         }
1573     }
1574 #endif
1575     AUDIO_WARNING_LOG("Session not exists, restore failed");
1576     return RESTORE_ERROR;
1577 }
1578 
SaveAdjustStreamVolumeInfo(float volume,uint32_t sessionId,std::string adjustTime,uint32_t code)1579 void AudioService::SaveAdjustStreamVolumeInfo(float volume, uint32_t sessionId, std::string adjustTime,
1580     uint32_t code)
1581 {
1582     AudioVolume::GetInstance()->SaveAdjustStreamVolumeInfo(volume, sessionId, adjustTime, code);
1583 }
1584 
RegisterMuteStateChangeCallback(uint32_t sessionId,const MuteStateChangeCallbck & callback)1585 void AudioService::RegisterMuteStateChangeCallback(uint32_t sessionId, const MuteStateChangeCallbck &callback)
1586 {
1587     std::unique_lock<std::mutex> lock(muteStateMapMutex_);
1588     if (muteStateCallbacks_.count(sessionId) != 0) {
1589         if (muteStateMap_.count(sessionId) != 0) {
1590             AUDIO_INFO_LOG("session:%{public}u may start again, invoke callback now", sessionId);
1591             bool flag = muteStateMap_[sessionId];
1592             callback(flag);
1593         } else {
1594             AUDIO_WARNING_LOG("session:%{public}u mute state update failed...", sessionId);
1595         }
1596     }
1597     muteStateCallbacks_[sessionId] = callback;
1598 }
1599 
SetSessionMuteState(const uint32_t sessionId,const bool insert,const bool muteFlag)1600 void AudioService::SetSessionMuteState(const uint32_t sessionId, const bool insert, const bool muteFlag)
1601 {
1602     std::unique_lock<std::mutex> lock(muteStateMapMutex_);
1603     if (!insert) {
1604         muteStateMap_.erase(sessionId);
1605     } else {
1606         muteStateMap_[sessionId] = muteFlag;
1607     }
1608 }
1609 
SetLatestMuteState(const uint32_t sessionId,const bool muteFlag)1610 void AudioService::SetLatestMuteState(const uint32_t sessionId, const bool muteFlag)
1611 {
1612     std::unique_lock<std::mutex> lock(muteStateMapMutex_);
1613     if (muteStateCallbacks_.count(sessionId) == 0) {
1614         AUDIO_ERR_LOG("send mute flag to session:%{public}u failed", sessionId);
1615         return;
1616     }
1617     AUDIO_INFO_LOG("session:%{public}u muteflag=%{public}d", sessionId, muteFlag ? 1 : 0);
1618     muteStateCallbacks_[sessionId](muteFlag);
1619 }
1620 
ForceStopAudioStream(StopAudioType audioType)1621 int32_t AudioService::ForceStopAudioStream(StopAudioType audioType)
1622 {
1623     CHECK_AND_RETURN_RET_LOG(audioType >= STOP_ALL && audioType <= STOP_RECORD, ERR_INVALID_PARAM, "Invalid audioType");
1624     AUDIO_INFO_LOG("stop audio stream, type:%{public}d", audioType);
1625     if (audioType == StopAudioType::STOP_ALL || audioType == StopAudioType::STOP_RENDER) {
1626         std::lock_guard<std::mutex> lock(rendererMapMutex_);
1627         for (auto &rendererMap : allRendererMap_) {
1628             std::shared_ptr<RendererInServer> rendererInServer = rendererMap.second.lock();
1629             CHECK_AND_CONTINUE_LOG(rendererInServer != nullptr, "stream could be released, no need to stop");
1630             rendererInServer->StopSession();
1631         }
1632     }
1633     if (audioType == StopAudioType::STOP_ALL || audioType == StopAudioType::STOP_RECORD) {
1634         std::lock_guard<std::mutex> lock(capturerMapMutex_);
1635         for (auto &capturerMap : allCapturerMap_) {
1636             std::shared_ptr<CapturerInServer> capturerInServer = capturerMap.second.lock();
1637             CHECK_AND_CONTINUE_LOG(capturerInServer != nullptr, "stream could be released, no need to stop");
1638             capturerInServer->StopSession();
1639         }
1640     }
1641 #ifdef SUPPORT_LOW_LATENCY
1642     {
1643         std::lock_guard<std::mutex> lock(processListMutex_);
1644         for (auto &[audioProcessInServer, audioEndpoint]: linkedPairedList_) {
1645             CHECK_AND_CONTINUE_LOG(audioProcessInServer && audioEndpoint,
1646                 "stream could be released, no need to stop");
1647             AudioMode audioMode = audioEndpoint->GetAudioMode();
1648             bool isNeedStop = (audioType == StopAudioType::STOP_ALL) ||
1649                 (audioMode == AudioMode::AUDIO_MODE_PLAYBACK && audioType == StopAudioType::STOP_RENDER) ||
1650                 (audioMode == AudioMode::AUDIO_MODE_RECORD && audioType == StopAudioType::STOP_RECORD);
1651             if (isNeedStop) {
1652                 audioProcessInServer->StopSession();
1653             }
1654         }
1655     }
1656 #endif
1657     return SUCCESS;
1658 }
1659 
GetSystemVolume()1660 float AudioService::GetSystemVolume()
1661 {
1662     std::unique_lock<std::mutex> lock(musicOrVoipSystemVolumeMutex_);
1663     return musicOrVoipSystemVolume_;
1664 }
1665 
UpdateSystemVolume(AudioStreamType streamType,float volume)1666 void AudioService::UpdateSystemVolume(AudioStreamType streamType, float volume)
1667 {
1668     AUDIO_INFO_LOG("[WorkgroupInServer] streamType:%{public}d, systemvolume:%{public}f", streamType, volume);
1669     if ((streamType != STREAM_MUSIC) && (streamType != STREAM_VOICE_COMMUNICATION)) {
1670         return;
1671     }
1672     {
1673         std::unique_lock<std::mutex> lock(musicOrVoipSystemVolumeMutex_);
1674         musicOrVoipSystemVolume_ = volume;
1675     }
1676     std::vector<int32_t> pids = AudioResourceService::GetInstance()->GetProcessesOfAudioWorkgroup();
1677     for (int32_t pid : pids) {
1678         RenderersCheckForAudioWorkgroup(pid);
1679     }
1680 }
1681 
RenderersCheckForAudioWorkgroup(int32_t pid)1682 void AudioService::RenderersCheckForAudioWorkgroup(int32_t pid)
1683 {
1684     if (!AudioResourceService::GetInstance()->IsProcessInWorkgroup(pid)) {
1685         return;
1686     }
1687     if (AudioResourceService::GetInstance()->IsProcessHasSystemPermission(pid)) {
1688         return;
1689     }
1690 
1691     std::unordered_map<int32_t, std::unordered_map<int32_t, bool>> allRenderPerProcessMap;
1692     {
1693         std::unique_lock<std::mutex> lock(rendererMapMutex_);
1694         for (auto it = allRendererMap_.begin(); it != allRendererMap_.end(); it++) {
1695             std::shared_ptr<RendererInServer> renderer = it->second.lock();
1696             if (renderer == nullptr) {
1697                 continue;
1698             }
1699             if (renderer->processConfig_.appInfo.appPid != pid) {
1700                 continue;
1701             }
1702             if ((renderer->processConfig_.streamType != STREAM_MUSIC) &&
1703                 (renderer->processConfig_.streamType != STREAM_VOICE_COMMUNICATION)) {
1704                 continue;
1705             }
1706             allRenderPerProcessMap[pid][renderer->processConfig_.originalSessionId]
1707                 = renderer->CollectInfosForWorkgroup(GetSystemVolume());
1708         }
1709     }
1710     // all processes in workgroup
1711     for (const auto &outerPair : allRenderPerProcessMap) {
1712         int32_t pid = outerPair.first;
1713         const auto &innerMap = outerPair.second;
1714         bool isAllowed = false;
1715         // check all renderer info this process
1716         for (const auto &innerPair : innerMap) {
1717             if (innerPair.second) {
1718                 // this process allowed if one renderer running and voiced
1719                 isAllowed = true;
1720                 break;
1721             }
1722         }
1723         AudioResourceService::GetInstance()->WorkgroupRendererMonitor(pid, isAllowed);
1724     }
1725 }
1726 
InitAllDupBuffer(int32_t innerCapId)1727 void AudioService::InitAllDupBuffer(int32_t innerCapId)
1728 {
1729     AUDIO_INFO_LOG("InitAllDupBuffer, innerCapId: %{public}d", innerCapId);
1730 
1731     std::unique_lock<std::mutex> lock(rendererMapMutex_);
1732     if (filteredRendererMap_.count(innerCapId)) {
1733         for (size_t i = 0; i < filteredRendererMap_[innerCapId].size(); i++) {
1734             std::shared_ptr<RendererInServer> renderer = filteredRendererMap_[innerCapId][i].lock();
1735             if (renderer == nullptr) {
1736                 AUDIO_WARNING_LOG("Renderer is already released!");
1737                 continue;
1738             }
1739             if (ShouldBeInnerCap(renderer->processConfig_, innerCapId)) {
1740                 renderer->InitDupBuffer(innerCapId);
1741             }
1742         }
1743     }
1744     lock.unlock();
1745 }
1746 } // namespace AudioStandard
1747 } // namespace OHOS
1748