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 
16 #include "audio_control_manager.h"
17 
18 #include "call_ability_report_proxy.h"
19 #include "call_control_manager.h"
20 #include "call_dialog.h"
21 #include "call_state_processor.h"
22 #include "common_type.h"
23 #include "distributed_call_manager.h"
24 #include "telephony_log_wrapper.h"
25 #include "audio_system_manager.h"
26 #include "audio_routing_manager.h"
27 #include "audio_device_info.h"
28 #include "audio_info.h"
29 #include "voip_call_connection.h"
30 #include "settings_datashare_helper.h"
31 
32 namespace OHOS {
33 namespace Telephony {
34 using namespace AudioStandard;
35 constexpr int32_t DTMF_PLAY_TIME = 30;
36 constexpr int32_t VOICE_TYPE = 0;
37 constexpr int32_t CRS_TYPE = 2;
38 constexpr int32_t CALL_ENDED_PLAY_TIME = 300;
39 
AudioControlManager()40 AudioControlManager::AudioControlManager()
41     : isLocalRingbackNeeded_(false), ring_(nullptr), tone_(nullptr), sound_(nullptr)
42 {}
43 
~AudioControlManager()44 AudioControlManager::~AudioControlManager()
45 {
46     DelayedSingleton<AudioProxy>::GetInstance()->UnsetDeviceChangeCallback();
47     DelayedSingleton<AudioProxy>::GetInstance()->UnsetAudioPreferDeviceChangeCallback();
48     DelayedSingleton<AudioProxy>::GetInstance()->UnsetAudioMicStateChangeCallback();
49 }
50 
Init()51 void AudioControlManager::Init()
52 {
53     DelayedSingleton<AudioDeviceManager>::GetInstance()->Init();
54     DelayedSingleton<AudioSceneProcessor>::GetInstance()->Init();
55 }
56 
UpdateForegroundLiveCall()57 void AudioControlManager::UpdateForegroundLiveCall()
58 {
59     int32_t callId = DelayedSingleton<CallStateProcessor>::GetInstance()->GetAudioForegroundLiveCall();
60     if (callId == INVALID_CALLID) {
61         frontCall_ = nullptr;
62         DelayedSingleton<AudioProxy>::GetInstance()->SetMicrophoneMute(false);
63         TELEPHONY_LOGE("callId is invalid");
64         return;
65     }
66 
67     sptr<CallBase> liveCall = CallObjectManager::GetOneCallObject(callId);
68     if (liveCall == nullptr) {
69         TELEPHONY_LOGE("liveCall is nullptr");
70         return;
71     }
72     if (liveCall->GetTelCallState() == TelCallState::CALL_STATUS_ACTIVE ||
73         liveCall->GetTelCallState() == TelCallState::CALL_STATUS_DIALING ||
74         liveCall->GetTelCallState() == TelCallState::CALL_STATUS_ALERTING) {
75         if (frontCall_ == nullptr) {
76             frontCall_ = liveCall;
77         } else {
78             int32_t frontCallId = frontCall_->GetCallID();
79             int32_t liveCallId = liveCall->GetCallID();
80             if (frontCallId != liveCallId) {
81                 frontCall_ = liveCall;
82             }
83         }
84         bool frontCallMute = frontCall_->IsMuted();
85         bool currentMute = DelayedSingleton<AudioProxy>::GetInstance()->IsMicrophoneMute();
86         if (frontCallMute != currentMute) {
87             SetMute(frontCallMute);
88         }
89     }
90 }
91 
HandleCallStateUpdatedForVoip(sptr<CallBase> & callObjectPtr,TelCallState priorState,TelCallState nextState)92 void AudioControlManager::HandleCallStateUpdatedForVoip(
93     sptr<CallBase> &callObjectPtr, TelCallState priorState, TelCallState nextState)
94 {
95     TELEPHONY_LOGI("control audio for voip start, callId:%{public}d, priorState:%{public}d, nextState:%{public}d",
96         callObjectPtr->GetCallID(), priorState, nextState);
97     if (priorState == TelCallState::CALL_STATUS_INCOMING && nextState == TelCallState::CALL_STATUS_INCOMING) {
98         if (DelayedSingleton<CallObjectManager>::GetInstance()->GetVoipCallNum() == 1) {
99             AudioDevice device = {
100                 .deviceType = AudioDeviceType::DEVICE_EARPIECE,
101                 .address = { 0 },
102             };
103             if (DelayedSingleton<AudioProxy>::GetInstance()->GetPreferredOutputAudioDevice(device) ==
104                 TELEPHONY_SUCCESS) {
105                 DelayedSingleton<AudioDeviceManager>::GetInstance()->SetCurrentAudioDevice(device.deviceType);
106                 TELEPHONY_LOGI("control audio for voip finish, callId:%{public}d", callObjectPtr->GetCallID());
107             } else {
108                 TELEPHONY_LOGE("current audio device nullptr when control audio for voip");
109             }
110         }
111     }
112 }
113 
CallStateUpdated(sptr<CallBase> & callObjectPtr,TelCallState priorState,TelCallState nextState)114 void AudioControlManager::CallStateUpdated(
115     sptr<CallBase> &callObjectPtr, TelCallState priorState, TelCallState nextState)
116 {
117     if (callObjectPtr == nullptr) {
118         TELEPHONY_LOGE("call object nullptr");
119         return;
120     }
121     if (callObjectPtr->GetCallType() == CallType::TYPE_VOIP) {
122         HandleCallStateUpdatedForVoip(callObjectPtr, priorState, nextState);
123         return;
124     }
125     std::lock_guard<std::mutex> lock(mutex_);
126     if (totalCalls_.count(callObjectPtr) == 0) {
127         int32_t callId = callObjectPtr->GetCallID();
128         TelCallState callState = callObjectPtr->GetTelCallState();
129         TELEPHONY_LOGI("add new call, callid:%{public}d , callstate:%{public}d", callId, callState);
130         totalCalls_.insert(callObjectPtr);
131     }
132     HandleCallStateUpdated(callObjectPtr, priorState, nextState);
133     if (nextState == TelCallState::CALL_STATUS_DISCONNECTED && totalCalls_.count(callObjectPtr) > 0) {
134         totalCalls_.erase(callObjectPtr);
135     }
136     UpdateForegroundLiveCall();
137 }
138 
VideoStateUpdated(sptr<CallBase> & callObjectPtr,VideoStateType priorVideoState,VideoStateType nextVideoState)139 void AudioControlManager::VideoStateUpdated(
140     sptr<CallBase> &callObjectPtr, VideoStateType priorVideoState, VideoStateType nextVideoState)
141 {
142     if (callObjectPtr == nullptr) {
143         TELEPHONY_LOGE("call object nullptr");
144         return;
145     }
146     if (callObjectPtr->GetCallType() != CallType::TYPE_IMS) {
147         TELEPHONY_LOGE("other call not need control audio");
148         return;
149     }
150     AudioDevice device = {
151         .deviceType = AudioDeviceType::DEVICE_SPEAKER,
152         .address = { 0 },
153     };
154     AudioDeviceType initDeviceType = GetInitAudioDeviceType();
155     if (callObjectPtr->GetCrsType() == CRS_TYPE) {
156         AudioStandard::AudioRingerMode ringMode = DelayedSingleton<AudioProxy>::GetInstance()->GetRingerMode();
157         if (ringMode != AudioStandard::AudioRingerMode::RINGER_MODE_NORMAL) {
158             if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
159                 initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO) {
160                 device.deviceType = initDeviceType;
161             }
162         }
163         TELEPHONY_LOGI("crs ring tone should be speaker");
164         SetAudioDevice(device);
165         return;
166     }
167     CheckTypeAndSetAudioDevice(callObjectPtr, priorVideoState, nextVideoState, initDeviceType, device);
168 }
169 
CheckTypeAndSetAudioDevice(sptr<CallBase> & callObjectPtr,VideoStateType priorVideoState,VideoStateType nextVideoState,AudioDeviceType & initDeviceType,AudioDevice & device)170 void AudioControlManager::CheckTypeAndSetAudioDevice(sptr<CallBase> &callObjectPtr, VideoStateType priorVideoState,
171     VideoStateType nextVideoState, AudioDeviceType &initDeviceType, AudioDevice &device)
172 {
173     TelCallState telCallState = callObjectPtr->GetTelCallState();
174     if (!IsVideoCall(priorVideoState) && IsVideoCall(nextVideoState) &&
175         (telCallState != TelCallState::CALL_STATUS_INCOMING && telCallState != TelCallState::CALL_STATUS_WAITING)) {
176         if (callObjectPtr->GetOriginalCallType() == VOICE_TYPE &&
177             (telCallState == TelCallState::CALL_STATUS_DIALING || telCallState == TelCallState::CALL_STATUS_ALERTING ||
178             telCallState == TelCallState::CALL_STATUS_DISCONNECTED)) {
179             TELEPHONY_LOGI("before modify set device to EARPIECE, now not set");
180             return;
181         }
182         if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
183             initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO ||
184             initDeviceType == AudioDeviceType::DEVICE_DISTRIBUTED_AUTOMOTIVE) {
185             device.deviceType = initDeviceType;
186         }
187         TELEPHONY_LOGI("set device type, type: %{public}d", static_cast<int32_t>(device.deviceType));
188         SetAudioDevice(device);
189     } else if (!isSetAudioDeviceByUser_ && IsVideoCall(priorVideoState) && !IsVideoCall(nextVideoState)) {
190         device.deviceType = AudioDeviceType::DEVICE_EARPIECE;
191         if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
192             initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO ||
193             initDeviceType == AudioDeviceType::DEVICE_DISTRIBUTED_AUTOMOTIVE) {
194             device.deviceType = initDeviceType;
195         }
196         TELEPHONY_LOGI("set device type, type: %{public}d", static_cast<int32_t>(device.deviceType));
197         SetAudioDevice(device);
198     }
199 }
200 
UpdateDeviceTypeForVideoOrSatelliteCall()201 void AudioControlManager::UpdateDeviceTypeForVideoOrSatelliteCall()
202 {
203     sptr<CallBase> foregroundCall = CallObjectManager::GetForegroundCall();
204     if (foregroundCall == nullptr) {
205         TELEPHONY_LOGE("call object nullptr");
206         return;
207     }
208     if (foregroundCall->GetCallType() != CallType::TYPE_IMS &&
209         foregroundCall->GetCallType() != CallType::TYPE_SATELLITE) {
210         TELEPHONY_LOGE("other call not need control audio");
211         return;
212     }
213     AudioDevice device = {
214         .deviceType = AudioDeviceType::DEVICE_SPEAKER,
215         .address = { 0 },
216     };
217     AudioDeviceType initDeviceType = GetInitAudioDeviceType();
218     if (IsVideoCall(foregroundCall->GetVideoStateType()) ||
219         foregroundCall->GetCallType() == CallType::TYPE_SATELLITE) {
220         if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
221             initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO ||
222             initDeviceType == AudioDeviceType::DEVICE_DISTRIBUTED_AUTOMOTIVE) {
223             device.deviceType = initDeviceType;
224         }
225         TELEPHONY_LOGI("set device type, type: %{public}d", static_cast<int32_t>(device.deviceType));
226         SetAudioDevice(device);
227     }
228 }
229 
UpdateDeviceTypeForCrs()230 void AudioControlManager::UpdateDeviceTypeForCrs()
231 {
232     sptr<CallBase> incomingCall = CallObjectManager::GetOneCallObject(CallRunningState::CALL_RUNNING_STATE_RINGING);
233     if (incomingCall == nullptr) {
234         return;
235     }
236     if (incomingCall->GetCrsType() == CRS_TYPE) {
237         AudioDevice device = {
238             .deviceType = AudioDeviceType::DEVICE_SPEAKER,
239             .address = { 0 },
240         };
241         AudioStandard::AudioRingerMode ringMode = DelayedSingleton<AudioProxy>::GetInstance()->GetRingerMode();
242         if (ringMode != AudioStandard::AudioRingerMode::RINGER_MODE_NORMAL) {
243             AudioDeviceType initDeviceType = GetInitAudioDeviceType();
244             if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
245                 initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO) {
246                 device.deviceType = initDeviceType;
247             }
248         }
249         TELEPHONY_LOGI("crs ring tone should be speaker");
250         SetAudioDevice(device);
251     }
252 }
253 
UpdateDeviceTypeForVideoDialing()254 void AudioControlManager::UpdateDeviceTypeForVideoDialing()
255 {
256     sptr<CallBase> dialingCall = CallObjectManager::GetOneCallObject(CallRunningState::CALL_RUNNING_STATE_DIALING);
257     if (dialingCall == nullptr) {
258         return;
259     }
260     if (dialingCall->GetVideoStateType() == VideoStateType::TYPE_VIDEO) {
261         AudioDevice device = {
262             .deviceType = AudioDeviceType::DEVICE_SPEAKER,
263             .address = { 0 },
264         };
265         AudioDeviceType initDeviceType = GetInitAudioDeviceType();
266         if (initDeviceType == AudioDeviceType::DEVICE_WIRED_HEADSET ||
267             initDeviceType == AudioDeviceType::DEVICE_BLUETOOTH_SCO) {
268             return;
269         }
270         TELEPHONY_LOGI("dialing video call should be speaker");
271         SetAudioDevice(device);
272     }
273 }
274 
IncomingCallActivated(sptr<CallBase> & callObjectPtr)275 void AudioControlManager::IncomingCallActivated(sptr<CallBase> &callObjectPtr) {}
276 
IncomingCallHungUp(sptr<CallBase> & callObjectPtr,bool isSendSms,std::string content)277 void AudioControlManager::IncomingCallHungUp(sptr<CallBase> &callObjectPtr, bool isSendSms, std::string content)
278 {
279     if (callObjectPtr == nullptr) {
280         TELEPHONY_LOGE("call object ptr nullptr");
281         return;
282     }
283     StopWaitingTone();
284 }
285 
HandleCallStateUpdated(sptr<CallBase> & callObjectPtr,TelCallState priorState,TelCallState nextState)286 void AudioControlManager::HandleCallStateUpdated(
287     sptr<CallBase> &callObjectPtr, TelCallState priorState, TelCallState nextState)
288 {
289     if (nextState == TelCallState::CALL_STATUS_ANSWERED) {
290         TELEPHONY_LOGI("user answered, mute ringer instead of release renderer");
291         if (priorState == TelCallState::CALL_STATUS_INCOMING) {
292             DelayedSingleton<CallStateProcessor>::GetInstance()->DeleteCall(callObjectPtr->GetCallID(), priorState);
293         }
294         MuteRinger();
295         return;
296     }
297     HandleNextState(callObjectPtr, nextState);
298     if (priorState == nextState) {
299         TELEPHONY_LOGI("prior state equals next state");
300         return;
301     }
302     HandlePriorState(callObjectPtr, priorState);
303 }
304 
HandleNextState(sptr<CallBase> & callObjectPtr,TelCallState nextState)305 void AudioControlManager::HandleNextState(sptr<CallBase> &callObjectPtr, TelCallState nextState)
306 {
307     AudioEvent event = AudioEvent::UNKNOWN_EVENT;
308     DelayedSingleton<CallStateProcessor>::GetInstance()->AddCall(callObjectPtr->GetCallID(), nextState);
309     switch (nextState) {
310         case TelCallState::CALL_STATUS_DIALING:
311             event = AudioEvent::NEW_DIALING_CALL;
312             audioInterruptState_ = AudioInterruptState::INTERRUPT_STATE_RINGING;
313             break;
314         case TelCallState::CALL_STATUS_ALERTING:
315             event = AudioEvent::NEW_ALERTING_CALL;
316             audioInterruptState_ = AudioInterruptState::INTERRUPT_STATE_RINGING;
317             break;
318         case TelCallState::CALL_STATUS_ACTIVE:
319             HandleNewActiveCall(callObjectPtr);
320             audioInterruptState_ = AudioInterruptState::INTERRUPT_STATE_ACTIVATED;
321             break;
322         case TelCallState::CALL_STATUS_WAITING:
323         case TelCallState::CALL_STATUS_INCOMING:
324             event = AudioEvent::NEW_INCOMING_CALL;
325             audioInterruptState_ = AudioInterruptState::INTERRUPT_STATE_RINGING;
326             break;
327         case TelCallState::CALL_STATUS_DISCONNECTING:
328         case TelCallState::CALL_STATUS_DISCONNECTED:
329             if (isCrsVibrating_) {
330                 DelayedSingleton<AudioProxy>::GetInstance()->StopVibrator();
331                 isCrsVibrating_ = false;
332             }
333             audioInterruptState_ = AudioInterruptState::INTERRUPT_STATE_DEACTIVATED;
334             break;
335         default:
336             break;
337     }
338     if (event == AudioEvent::UNKNOWN_EVENT) {
339         return;
340     }
341     DelayedSingleton<AudioSceneProcessor>::GetInstance()->ProcessEvent(event);
342 }
343 
HandlePriorState(sptr<CallBase> & callObjectPtr,TelCallState priorState)344 void AudioControlManager::HandlePriorState(sptr<CallBase> &callObjectPtr, TelCallState priorState)
345 {
346     AudioEvent event = AudioEvent::UNKNOWN_EVENT;
347     DelayedSingleton<CallStateProcessor>::GetInstance()->DeleteCall(callObjectPtr->GetCallID(), priorState);
348     int32_t stateNumber = DelayedSingleton<CallStateProcessor>::GetInstance()->GetCallNumber(priorState);
349     switch (priorState) {
350         case TelCallState::CALL_STATUS_DIALING:
351             if (stateNumber == EMPTY_VALUE) {
352                 StopRingback(); // should stop ringtone while no more alerting calls
353                 event = AudioEvent::NO_MORE_DIALING_CALL;
354             }
355             break;
356         case TelCallState::CALL_STATUS_ALERTING:
357             if (stateNumber == EMPTY_VALUE) {
358                 StopRingback(); // should stop ringtone while no more alerting calls
359                 event = AudioEvent::NO_MORE_ALERTING_CALL;
360             }
361             break;
362         case TelCallState::CALL_STATUS_INCOMING:
363         case TelCallState::CALL_STATUS_WAITING:
364             ProcessAudioWhenCallActive(callObjectPtr);
365             event = AudioEvent::NO_MORE_INCOMING_CALL;
366             break;
367         case TelCallState::CALL_STATUS_ACTIVE:
368             if (stateNumber == EMPTY_VALUE) {
369                 event = AudioEvent::NO_MORE_ACTIVE_CALL;
370             }
371             StopRingback();
372             break;
373         case TelCallState::CALL_STATUS_HOLDING:
374             if (stateNumber == EMPTY_VALUE) {
375                 event = AudioEvent::NO_MORE_HOLDING_CALL;
376             }
377             break;
378         default:
379             break;
380     }
381     if (event == AudioEvent::UNKNOWN_EVENT) {
382         return;
383     }
384     DelayedSingleton<AudioSceneProcessor>::GetInstance()->ProcessEvent(event);
385 }
386 
ProcessAudioWhenCallActive(sptr<CallBase> & callObjectPtr)387 void AudioControlManager::ProcessAudioWhenCallActive(sptr<CallBase> &callObjectPtr)
388 {
389     if (callObjectPtr->GetCallRunningState() == CallRunningState::CALL_RUNNING_STATE_ACTIVE) {
390         if (isCrsVibrating_) {
391             DelayedSingleton<AudioProxy>::GetInstance()->StopVibrator();
392             isCrsVibrating_ = false;
393         }
394         int ringCallCount = CallObjectManager::GetCallNumByRunningState(CallRunningState::CALL_RUNNING_STATE_RINGING);
395         if ((CallObjectManager::GetCurrentCallNum() - ringCallCount) < MIN_MULITY_CALL_COUNT) {
396             StopSoundtone();
397             PlaySoundtone();
398         }
399         UpdateDeviceTypeForVideoOrSatelliteCall();
400     }
401 }
402 
HandleNewActiveCall(sptr<CallBase> & callObjectPtr)403 void AudioControlManager::HandleNewActiveCall(sptr<CallBase> &callObjectPtr)
404 {
405     CallType callType = callObjectPtr->GetCallType();
406     AudioEvent event = AudioEvent::UNKNOWN_EVENT;
407     switch (callType) {
408         case CallType::TYPE_CS:
409         case CallType::TYPE_SATELLITE:
410             event = AudioEvent::NEW_ACTIVE_CS_CALL;
411             break;
412         case CallType::TYPE_IMS:
413             event = AudioEvent::NEW_ACTIVE_IMS_CALL;
414             break;
415         case CallType::TYPE_OTT:
416             event = AudioEvent::NEW_ACTIVE_OTT_CALL;
417             break;
418         default:
419             break;
420     }
421     if (event == AudioEvent::UNKNOWN_EVENT) {
422         return;
423     }
424     DelayedSingleton<AudioSceneProcessor>::GetInstance()->ProcessEvent(event);
425 }
426 
427 /**
428  * @param device , audio device
429  * usually called by the ui interaction , in purpose of switching to another audio device
430  */
SetAudioDevice(const AudioDevice & device)431 int32_t AudioControlManager::SetAudioDevice(const AudioDevice &device)
432 {
433     return SetAudioDevice(device, false);
434 }
435 
436 /**
437  * @param device , audio device
438  * @param isByUser , call from callui or not
439  * usually called by the ui interaction , in purpose of switching to another audio device
440  */
SetAudioDevice(const AudioDevice & device,bool isByUser)441 int32_t AudioControlManager::SetAudioDevice(const AudioDevice &device, bool isByUser)
442 {
443     TELEPHONY_LOGI("set audio device, type: %{public}d", static_cast<int32_t>(device.deviceType));
444     AudioDeviceType audioDeviceType = AudioDeviceType::DEVICE_UNKNOWN;
445     isSetAudioDeviceByUser_ = isByUser;
446     if (CallObjectManager::HasSatelliteCallExist() && device.deviceType == AudioDeviceType::DEVICE_EARPIECE) {
447         DelayedSingleton<CallDialog>::GetInstance()->DialogConnectExtension("SATELLITE_CALL_NOT_SUPPORT_EARPIECE");
448         return CALL_ERR_AUDIO_SET_AUDIO_DEVICE_FAILED;
449     }
450     switch (device.deviceType) {
451         case AudioDeviceType::DEVICE_SPEAKER:
452         case AudioDeviceType::DEVICE_EARPIECE:
453         case AudioDeviceType::DEVICE_WIRED_HEADSET:
454             audioDeviceType = device.deviceType;
455             break;
456         case AudioDeviceType::DEVICE_DISTRIBUTED_AUTOMOTIVE:
457         case AudioDeviceType::DEVICE_DISTRIBUTED_PHONE:
458         case AudioDeviceType::DEVICE_DISTRIBUTED_PAD:
459             return HandleDistributeAudioDevice(device);
460         case AudioDeviceType::DEVICE_BLUETOOTH_SCO: {
461             std::string address = device.address;
462             std::unique_ptr<AudioStandard::AudioDeviceDescriptor> activeBluetoothDevice =
463                 AudioStandard::AudioRoutingManager::GetInstance()->GetActiveBluetoothDevice();
464             if (address.empty()) {
465                 if (activeBluetoothDevice != nullptr && !activeBluetoothDevice->macAddress_.empty()) {
466                     address = activeBluetoothDevice->macAddress_;
467                 }
468             }
469             AudioSystemManager* audioSystemManager = AudioSystemManager::GetInstance();
470             int32_t ret = audioSystemManager->SetCallDeviceActive(ActiveDeviceType::BLUETOOTH_SCO,
471                 true, address);
472             if (ret != 0) {
473                 TELEPHONY_LOGE("SetCallDeviceActive failed");
474                 return CALL_ERR_AUDIO_SET_AUDIO_DEVICE_FAILED;
475             }
476             audioDeviceType = device.deviceType;
477             break;
478         }
479         default:
480             break;
481     }
482     if (audioDeviceType != AudioDeviceType::DEVICE_UNKNOWN) {
483         if (DelayedSingleton<DistributedCallManager>::GetInstance()->IsDCallDeviceSwitchedOn()) {
484             DelayedSingleton<DistributedCallManager>::GetInstance()->SwitchOffDCallDeviceSync();
485         }
486         if (DelayedSingleton<AudioDeviceManager>::GetInstance()->SwitchDevice(audioDeviceType)) {
487             return TELEPHONY_SUCCESS;
488         }
489     }
490     return CALL_ERR_AUDIO_SET_AUDIO_DEVICE_FAILED;
491 }
492 
HandleDistributeAudioDevice(const AudioDevice & device)493 int32_t AudioControlManager::HandleDistributeAudioDevice(const AudioDevice &device)
494 {
495     if (!DelayedSingleton<DistributedCallManager>::GetInstance()->IsDCallDeviceSwitchedOn()) {
496         if (DelayedSingleton<DistributedCallManager>::GetInstance()->SwitchOnDCallDeviceSync(device)) {
497             return TELEPHONY_SUCCESS;
498         }
499         return CALL_ERR_AUDIO_SET_AUDIO_DEVICE_FAILED;
500     }
501     return TELEPHONY_SUCCESS;
502 }
503 
PlayRingtone()504 bool AudioControlManager::PlayRingtone()
505 {
506     if (!ShouldPlayRingtone()) {
507         TELEPHONY_LOGE("should not play ringtone");
508         return false;
509     }
510     ring_ = std::make_unique<Ring>();
511     if (ring_ == nullptr) {
512         TELEPHONY_LOGE("create ring object failed");
513         return false;
514     }
515     sptr<CallBase> incomingCall = CallObjectManager::GetOneCallObject(CallRunningState::CALL_RUNNING_STATE_RINGING);
516     if (incomingCall == nullptr) {
517         TELEPHONY_LOGE("incomingCall is nullptr");
518         return false;
519     }
520     CallAttributeInfo info;
521     incomingCall->GetCallAttributeBaseInfo(info);
522     AudioStandard::AudioRingerMode ringMode = DelayedSingleton<AudioProxy>::GetInstance()->GetRingerMode();
523     if (incomingCall->GetCrsType() == CRS_TYPE) {
524         if (!isCrsVibrating_ && (ringMode != AudioStandard::AudioRingerMode::RINGER_MODE_SILENT)) {
525             isCrsVibrating_ = (DelayedSingleton<AudioProxy>::GetInstance()->StartVibrator() == TELEPHONY_SUCCESS);
526         }
527         if ((ringMode == AudioStandard::AudioRingerMode::RINGER_MODE_NORMAL) || IsBtOrWireHeadPlugin()) {
528             if (PlaySoundtone()) {
529                 TELEPHONY_LOGI("play soundtone success");
530                 return true;
531             }
532             return false;
533         }
534     }
535     if (ring_->Play(info.accountId) != TELEPHONY_SUCCESS) {
536         TELEPHONY_LOGE("play ringtone failed");
537         return false;
538     }
539     TELEPHONY_LOGI("play ringtone success");
540     return true;
541 }
542 
IsDistributeCallSinkStatus()543 bool AudioControlManager::IsDistributeCallSinkStatus()
544 {
545     std::string dcStatus = "";
546     auto settingHelper = SettingsDataShareHelper::GetInstance();
547     if (settingHelper != nullptr) {
548         OHOS::Uri settingUri(SettingsDataShareHelper::SETTINGS_DATASHARE_URI);
549         settingHelper->Query(settingUri, "distributed_modem_state", dcStatus);
550     }
551     TELEPHONY_LOGI("distributed communication modem status: %{public}s", dcStatus.c_str());
552     if (dcStatus != "1_sink") {
553         return false;
554     }
555     return true;
556 }
557 
PlaySoundtone()558 bool AudioControlManager::PlaySoundtone()
559 {
560     if (IsDistributeCallSinkStatus()) {
561         TELEPHONY_LOGI("distribute call sink status, no need to play sound tone");
562         return true;
563     }
564     if (soundState_ == SoundState::SOUNDING) {
565         TELEPHONY_LOGE("should not play soundTone");
566         return false;
567     }
568     if (sound_ == nullptr) {
569         sound_ = std::make_unique<Sound>();
570         if (sound_ == nullptr) {
571             TELEPHONY_LOGE("create sound object failed");
572             return false;
573         }
574     }
575     if (sound_->Play() != TELEPHONY_SUCCESS) {
576         TELEPHONY_LOGE("play soundtone failed");
577         return false;
578     }
579     TELEPHONY_LOGI("play soundtone success");
580     return true;
581 }
582 
StopSoundtone()583 bool AudioControlManager::StopSoundtone()
584 {
585     if (soundState_ == SoundState::STOPPED) {
586         TELEPHONY_LOGI("soundtone already stopped");
587         return true;
588     }
589     if (sound_ == nullptr) {
590         TELEPHONY_LOGE("sound_ is nullptr");
591         return false;
592     }
593     if (sound_->Stop() != TELEPHONY_SUCCESS) {
594         TELEPHONY_LOGE("stop soundtone failed");
595         return false;
596     }
597     sound_->ReleaseRenderer();
598     TELEPHONY_LOGI("stop soundtone success");
599     return true;
600 }
601 
StopRingtone()602 bool AudioControlManager::StopRingtone()
603 {
604     if (ringState_ == RingState::STOPPED) {
605         TELEPHONY_LOGI("ringtone already stopped");
606         return true;
607     }
608     if (ring_ == nullptr) {
609         TELEPHONY_LOGE("ring_ is nullptr");
610         return false;
611     }
612     if (ring_->Stop() != TELEPHONY_SUCCESS) {
613         TELEPHONY_LOGE("stop ringtone failed");
614         return false;
615     }
616     ring_->ReleaseRenderer();
617     TELEPHONY_LOGI("stop ringtone success");
618     return true;
619 }
620 
621 /**
622  * while audio state changed , maybe need to reinitialize the audio device
623  * in order to get the initialization status of audio device , need to consider varieties of  audio conditions
624  */
GetInitAudioDeviceType() const625 AudioDeviceType AudioControlManager::GetInitAudioDeviceType() const
626 {
627     if (audioInterruptState_ == AudioInterruptState::INTERRUPT_STATE_DEACTIVATED) {
628         return AudioDeviceType::DEVICE_DISABLE;
629     } else {
630         /**
631          * Init audio device type according to the priority in different call state:
632          * In voice call state, bluetooth sco > wired headset > earpiece > speaker
633          * In video call state, bluetooth sco > wired headset > speaker > earpiece
634          */
635         if (AudioDeviceManager::IsDistributedCallConnected()) {
636             return AudioDeviceType::DEVICE_DISTRIBUTED_AUTOMOTIVE;
637         }
638         if (AudioDeviceManager::IsBtActived()) {
639             return AudioDeviceType::DEVICE_BLUETOOTH_SCO;
640         }
641         if (AudioDeviceManager::IsWiredHeadsetConnected()) {
642             return AudioDeviceType::DEVICE_WIRED_HEADSET;
643         }
644         sptr<CallBase> liveCall = CallObjectManager::GetForegroundCall();
645         if (liveCall != nullptr && (liveCall->GetVideoStateType() == VideoStateType::TYPE_VIDEO ||
646             liveCall->GetCallType() == CallType::TYPE_SATELLITE)) {
647             TELEPHONY_LOGI("current video or satellite call speaker is active");
648             return AudioDeviceType::DEVICE_SPEAKER;
649         }
650         if (AudioDeviceManager::IsEarpieceAvailable()) {
651             return AudioDeviceType::DEVICE_EARPIECE;
652         }
653         return AudioDeviceType::DEVICE_SPEAKER;
654     }
655 }
656 
657 /**
658  * @param isMute , mute state
659  * usually called by the ui interaction , mute or unmute microphone
660  */
SetMute(bool isMute)661 int32_t AudioControlManager::SetMute(bool isMute)
662 {
663     bool hasCall = DelayedSingleton<CallControlManager>::GetInstance()->HasCall();
664     if (!hasCall) {
665         TELEPHONY_LOGE("no call exists, set mute failed");
666         return CALL_ERR_AUDIO_SETTING_MUTE_FAILED;
667     }
668     bool enabled = false;
669     if ((DelayedSingleton<CallControlManager>::GetInstance()->HasEmergency(enabled) == TELEPHONY_SUCCESS) && enabled) {
670         isMute = false;
671     }
672     if (!DelayedSingleton<AudioProxy>::GetInstance()->SetMicrophoneMute(isMute)) {
673         TELEPHONY_LOGE("set mute failed");
674         return CALL_ERR_AUDIO_SETTING_MUTE_FAILED;
675     }
676     DelayedSingleton<AudioDeviceManager>::GetInstance()->ReportAudioDeviceInfo();
677     if (frontCall_ == nullptr) {
678         TELEPHONY_LOGE("frontCall_ is nullptr");
679         return TELEPHONY_ERR_LOCAL_PTR_NULL;
680     }
681     bool muted = DelayedSingleton<AudioProxy>::GetInstance()->IsMicrophoneMute();
682     frontCall_->SetMicPhoneState(muted);
683     TELEPHONY_LOGI("SetMute success callId:%{public}d, mute:%{public}d", frontCall_->GetCallID(), muted);
684     return TELEPHONY_SUCCESS;
685 }
686 
MuteRinger()687 int32_t AudioControlManager::MuteRinger()
688 {
689     sptr<CallBase> incomingCall = CallObjectManager::GetOneCallObject(CallRunningState::CALL_RUNNING_STATE_RINGING);
690     if (incomingCall != nullptr) {
691         if (incomingCall->GetCrsType() == CRS_TYPE) {
692             TELEPHONY_LOGI("Mute network ring tone.");
693             MuteNetWorkRingTone();
694         }
695     }
696     SendMuteRingEvent();
697     if (ringState_ == RingState::STOPPED) {
698         TELEPHONY_LOGI("ring already stopped");
699         return TELEPHONY_SUCCESS;
700     }
701     if (ring_ == nullptr) {
702         TELEPHONY_LOGE("ring is nullptr");
703         return CALL_ERR_AUDIO_SETTING_MUTE_FAILED;
704     }
705     if (ring_->SetMute() != TELEPHONY_SUCCESS) {
706         TELEPHONY_LOGE("SetMute fail");
707         return CALL_ERR_AUDIO_SETTING_MUTE_FAILED;
708     }
709     TELEPHONY_LOGI("mute ring success");
710     return TELEPHONY_SUCCESS;
711 }
712 
SendMuteRingEvent()713 void AudioControlManager::SendMuteRingEvent()
714 {
715     CallEventInfo eventInfo;
716     eventInfo.eventId = CallAbilityEventId::EVENT_MUTE_RING;
717     DelayedSingleton<CallAbilityReportProxy>::GetInstance()->CallEventUpdated(eventInfo);
718 }
719 
PlayCallEndedTone(CallEndedType type)720 void AudioControlManager::PlayCallEndedTone(CallEndedType type)
721 {
722     int32_t state;
723     DelayedSingleton<CallControlManager>::GetInstance()->GetVoIPCallState(state);
724     if (state != static_cast<int32_t>(CallStateToApp::CALL_STATE_IDLE)) {
725         TELEPHONY_LOGI("not play callEndTone when has voip call");
726         return;
727     }
728     AudioStandard::AudioRingerMode ringMode = DelayedSingleton<AudioProxy>::GetInstance()->GetRingerMode();
729     if (ringMode != AudioStandard::AudioRingerMode::RINGER_MODE_NORMAL) {
730         TELEPHONY_LOGE("ringer mode is not normal");
731         return;
732     }
733     switch (type) {
734         case CallEndedType::PHONE_IS_BUSY:
735             PlayCallTone(ToneDescriptor::TONE_ENGAGED);
736             break;
737         case CallEndedType::CALL_ENDED_NORMALLY:
738             if (toneState_ == ToneState::TONEING) {
739                 StopCallTone();
740             }
741             TELEPHONY_LOGI("play call ended tone");
742             if (PlayCallTone(ToneDescriptor::TONE_FINISHED) != TELEPHONY_SUCCESS) {
743                 TELEPHONY_LOGE("play call ended tone failed");
744                 return;
745             }
746             toneState_ = ToneState::CALLENDED;
747             std::this_thread::sleep_for(std::chrono::milliseconds(CALL_ENDED_PLAY_TIME));
748             toneState_ = ToneState::TONEING;
749             if (StopCallTone() != TELEPHONY_SUCCESS) {
750                 TELEPHONY_LOGE("stop call ended tone failed");
751                 return;
752             }
753             break;
754         case CallEndedType::UNKNOWN:
755             PlayCallTone(ToneDescriptor::TONE_UNKNOWN);
756             break;
757         case CallEndedType::INVALID_NUMBER:
758             PlayCallTone(ToneDescriptor::TONE_INVALID_NUMBER);
759             break;
760         default:
761             break;
762     }
763 }
764 
GetCallList()765 std::set<sptr<CallBase>> AudioControlManager::GetCallList()
766 {
767     std::lock_guard<std::mutex> lock(mutex_);
768     return totalCalls_;
769 }
770 
GetCurrentActiveCall()771 sptr<CallBase> AudioControlManager::GetCurrentActiveCall()
772 {
773     int32_t callId = DelayedSingleton<CallStateProcessor>::GetInstance()->GetCurrentActiveCall();
774     if (callId != INVALID_CALLID) {
775         return GetCallBase(callId);
776     }
777     return nullptr;
778 }
779 
GetCallBase(int32_t callId)780 sptr<CallBase> AudioControlManager::GetCallBase(int32_t callId)
781 {
782     sptr<CallBase> callBase = nullptr;
783     std::lock_guard<std::mutex> lock(mutex_);
784     for (auto &call : totalCalls_) {
785         if (call->GetCallID() == callId) {
786             callBase = call;
787             break;
788         }
789     }
790     return callBase;
791 }
792 
IsEmergencyCallExists()793 bool AudioControlManager::IsEmergencyCallExists()
794 {
795     std::lock_guard<std::mutex> lock(mutex_);
796     for (auto call : totalCalls_) {
797         if (call->GetEmergencyState()) {
798             return true;
799         }
800     }
801     return false;
802 }
803 
IsSatelliteExists()804 bool AudioControlManager::IsSatelliteExists()
805 {
806     std::lock_guard<std::mutex> lock(mutex_);
807     for (auto call : totalCalls_) {
808         if (call->GetCallType() == CallType::TYPE_SATELLITE) {
809             return true;
810         }
811     }
812     return false;
813 }
814 
GetAudioInterruptState()815 AudioInterruptState AudioControlManager::GetAudioInterruptState()
816 {
817     return audioInterruptState_;
818 }
819 
SetVolumeAudible()820 void AudioControlManager::SetVolumeAudible()
821 {
822     DelayedSingleton<AudioProxy>::GetInstance()->SetVolumeAudible();
823 }
824 
SetRingState(RingState state)825 void AudioControlManager::SetRingState(RingState state)
826 {
827     ringState_ = state;
828 }
829 
SetSoundState(SoundState state)830 void AudioControlManager::SetSoundState(SoundState state)
831 {
832     soundState_ = state;
833 }
834 
SetToneState(ToneState state)835 void AudioControlManager::SetToneState(ToneState state)
836 {
837     std::lock_guard<std::recursive_mutex> lock(toneStateLock_);
838     toneState_ = state;
839 }
840 
SetLocalRingbackNeeded(bool isNeeded)841 void AudioControlManager::SetLocalRingbackNeeded(bool isNeeded)
842 {
843     if (isLocalRingbackNeeded_ && !isNeeded) {
844         StopRingback();
845     }
846     isLocalRingbackNeeded_ = isNeeded;
847 }
848 
IsNumberAllowed(const std::string & phoneNum)849 bool AudioControlManager::IsNumberAllowed(const std::string &phoneNum)
850 {
851     // check whether the phone number is allowed or not , should not ring if number is not allowed
852     return true;
853 }
854 
ShouldPlayRingtone() const855 bool AudioControlManager::ShouldPlayRingtone() const
856 {
857     auto processor = DelayedSingleton<CallStateProcessor>::GetInstance();
858     int32_t alertingCallNum = processor->GetCallNumber(TelCallState::CALL_STATUS_ALERTING);
859     int32_t incomingCallNum = processor->GetCallNumber(TelCallState::CALL_STATUS_INCOMING);
860     if (incomingCallNum == EMPTY_VALUE || alertingCallNum > EMPTY_VALUE || ringState_ == RingState::RINGING
861         || (soundState_ == SoundState::SOUNDING && CallObjectManager::HasIncomingCallCrsType())) {
862         return false;
863     }
864     return true;
865 }
866 
IsAudioActivated() const867 bool AudioControlManager::IsAudioActivated() const
868 {
869     return audioInterruptState_ == AudioInterruptState::INTERRUPT_STATE_ACTIVATED ||
870         audioInterruptState_ == AudioInterruptState::INTERRUPT_STATE_RINGING;
871 }
872 
PlayCallTone(ToneDescriptor type)873 int32_t AudioControlManager::PlayCallTone(ToneDescriptor type)
874 {
875     std::lock_guard<std::recursive_mutex> lock(toneStateLock_);
876     if (toneState_ == ToneState::TONEING) {
877         TELEPHONY_LOGE("should not play callTone");
878         return CALL_ERR_AUDIO_TONE_PLAY_FAILED;
879     }
880     toneState_ = ToneState::TONEING;
881     tone_ = std::make_unique<Tone>(type);
882     if (tone_ == nullptr) {
883         TELEPHONY_LOGE("create tone failed");
884         return TELEPHONY_ERR_LOCAL_PTR_NULL;
885     }
886     if (tone_->Play() != TELEPHONY_SUCCESS) {
887         TELEPHONY_LOGE("play calltone failed");
888         return CALL_ERR_AUDIO_TONE_PLAY_FAILED;
889     }
890     TELEPHONY_LOGI("play calltone success");
891     return TELEPHONY_SUCCESS;
892 }
893 
StopCallTone()894 int32_t AudioControlManager::StopCallTone()
895 {
896     std::lock_guard<std::recursive_mutex> lock(toneStateLock_);
897     if (toneState_ == ToneState::STOPPED) {
898         TELEPHONY_LOGI("tone is already stopped");
899         return TELEPHONY_SUCCESS;
900     }
901     if (toneState_ == ToneState::CALLENDED) {
902         TELEPHONY_LOGE("call ended tone is running");
903         return CALL_ERR_AUDIO_TONE_STOP_FAILED;
904     }
905     if (tone_ == nullptr) {
906         TELEPHONY_LOGE("tone_ is nullptr");
907         return TELEPHONY_ERR_LOCAL_PTR_NULL;
908     }
909     if (tone_->Stop() != TELEPHONY_SUCCESS) {
910         TELEPHONY_LOGE("stop calltone failed");
911         return CALL_ERR_AUDIO_TONE_STOP_FAILED;
912     }
913     tone_->ReleaseRenderer();
914     toneState_ = ToneState::STOPPED;
915     TELEPHONY_LOGI("stop call tone success");
916     return TELEPHONY_SUCCESS;
917 }
918 
IsTonePlaying()919 bool AudioControlManager::IsTonePlaying()
920 {
921     std::lock_guard<std::recursive_mutex> lock(toneStateLock_);
922     return toneState_ == ToneState::TONEING;
923 }
924 
IsCurrentRinging() const925 bool AudioControlManager::IsCurrentRinging() const
926 {
927     return ringState_ == RingState::RINGING;
928 }
929 
PlayRingback()930 int32_t AudioControlManager::PlayRingback()
931 {
932     if (!isLocalRingbackNeeded_) {
933         return CALL_ERR_AUDIO_TONE_PLAY_FAILED;
934     }
935     return PlayCallTone(ToneDescriptor::TONE_RINGBACK);
936 }
937 
StopRingback()938 int32_t AudioControlManager::StopRingback()
939 {
940     return StopCallTone();
941 }
942 
PlayWaitingTone()943 int32_t AudioControlManager::PlayWaitingTone()
944 {
945     return PlayCallTone(ToneDescriptor::TONE_WAITING);
946 }
947 
StopWaitingTone()948 int32_t AudioControlManager::StopWaitingTone()
949 {
950     if (tone_ != nullptr && tone_->getCurrentToneType() == ToneDescriptor::TONE_WAITING) {
951         return StopCallTone();
952     }
953     return TELEPHONY_SUCCESS;
954 }
955 
PlayDtmfTone(char str)956 int32_t AudioControlManager::PlayDtmfTone(char str)
957 {
958     ToneDescriptor dtmfTone = Tone::ConvertDigitToTone(str);
959     std::unique_ptr<Tone> tone = std::make_unique<Tone>(dtmfTone);
960     if (tone == nullptr) {
961         TELEPHONY_LOGE("create dtmf tone failed");
962         return TELEPHONY_ERR_LOCAL_PTR_NULL;
963     }
964     if (tone->Play() != TELEPHONY_SUCCESS) {
965         TELEPHONY_LOGE("play dtmftone failed");
966         return CALL_ERR_AUDIO_TONE_PLAY_FAILED;
967     }
968     TELEPHONY_LOGI("play dtmftone success");
969     std::this_thread::sleep_for(std::chrono::milliseconds(DTMF_PLAY_TIME));
970     if (tone->Stop() != TELEPHONY_SUCCESS) {
971         TELEPHONY_LOGE("stop dtmftone failed");
972         return CALL_ERR_AUDIO_TONE_STOP_FAILED;
973     }
974     tone->ReleaseRenderer();
975     TELEPHONY_LOGI("stop dtmf tone success");
976     return TELEPHONY_SUCCESS;
977 }
978 
StopDtmfTone()979 int32_t AudioControlManager::StopDtmfTone()
980 {
981     return StopCallTone();
982 }
983 
OnPostDialNextChar(char str)984 int32_t AudioControlManager::OnPostDialNextChar(char str)
985 {
986     int32_t result = PlayDtmfTone(str);
987     if (result != TELEPHONY_SUCCESS) {
988         return result;
989     }
990     return TELEPHONY_SUCCESS;
991 }
992 
NewCallCreated(sptr<CallBase> & callObjectPtr)993 void AudioControlManager::NewCallCreated(sptr<CallBase> &callObjectPtr) {}
994 
CallDestroyed(const DisconnectedDetails & details)995 void AudioControlManager::CallDestroyed(const DisconnectedDetails &details) {}
996 
IsSoundPlaying()997 bool AudioControlManager::IsSoundPlaying()
998 {
999     return soundState_ == SoundState::SOUNDING;
1000 }
1001 
MuteNetWorkRingTone()1002 void AudioControlManager::MuteNetWorkRingTone()
1003 {
1004     bool result =
1005         DelayedSingleton<AudioProxy>::GetInstance()->SetAudioScene(AudioStandard::AudioScene::AUDIO_SCENE_DEFAULT);
1006     TELEPHONY_LOGI("Set volume mute, result: %{public}d", result);
1007     if (isCrsVibrating_) {
1008         DelayedSingleton<AudioProxy>::GetInstance()->StopVibrator();
1009         isCrsVibrating_ = false;
1010     }
1011 }
1012 
IsVideoCall(VideoStateType videoState)1013 bool AudioControlManager::IsVideoCall(VideoStateType videoState)
1014 {
1015     return videoState == VideoStateType::TYPE_SEND_ONLY || videoState == VideoStateType::TYPE_RECEIVE_ONLY ||
1016            videoState == VideoStateType::TYPE_VIDEO;
1017 }
1018 
IsBtOrWireHeadPlugin()1019 bool AudioControlManager::IsBtOrWireHeadPlugin()
1020 {
1021     return AudioDeviceManager::IsBtActived() || AudioDeviceManager::IsWiredHeadsetConnected();
1022 }
1023 } // namespace Telephony
1024 } // namespace OHOS