• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <cinttypes>
17 #include <csignal>
18 #include <fstream>
19 #include <sstream>
20 
21 #include "audio_capturer_source.h"
22 #include "audio_errors.h"
23 #include "audio_renderer_sink.h"
24 #include "iservice_registry.h"
25 #include "audio_log.h"
26 #include "system_ability_definition.h"
27 #include "audio_manager_listener_proxy.h"
28 #include "bluetooth_renderer_sink_intf.h"
29 
30 #include "audio_server.h"
31 
32 extern "C" {
33 #include "renderer_sink_adapter.h"
34 }
35 
36 #define PA
37 #ifdef PA
38 extern "C" {
39     extern int ohos_pa_main(int argc, char *argv[]);
40 }
41 #endif
42 
43 using namespace std;
44 
45 namespace OHOS {
46 namespace AudioStandard {
47 std::map<std::string, std::string> AudioServer::audioParameters;
48 const string DEFAULT_COOKIE_PATH = "/data/data/.pulse_dir/state/cookie";
49 
50 REGISTER_SYSTEM_ABILITY_BY_ID(AudioServer, AUDIO_DISTRIBUTED_SERVICE_ID, true)
51 
52 #ifdef PA
53 constexpr int PA_ARG_COUNT = 1;
54 
paDaemonThread(void * arg)55 void *AudioServer::paDaemonThread(void *arg)
56 {
57     /* Load the mandatory pulseaudio modules at start */
58     char *argv[] = {
59         (char*)"pulseaudio",
60     };
61 
62     AUDIO_INFO_LOG("Calling ohos_pa_main\n");
63     ohos_pa_main(PA_ARG_COUNT, argv);
64     AUDIO_INFO_LOG("Exiting ohos_pa_main\n");
65     exit(-1);
66 }
67 #endif
68 
AudioServer(int32_t systemAbilityId,bool runOnCreate)69 AudioServer::AudioServer(int32_t systemAbilityId, bool runOnCreate)
70     : SystemAbility(systemAbilityId, runOnCreate)
71 {}
72 
OnDump()73 void AudioServer::OnDump()
74 {}
75 
OnStart()76 void AudioServer::OnStart()
77 {
78     AUDIO_DEBUG_LOG("AudioService OnStart");
79     bool res = Publish(this);
80     if (res) {
81         AUDIO_DEBUG_LOG("AudioService OnStart res=%{public}d", res);
82     }
83     AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID);
84 #ifdef PA
85     int32_t ret = pthread_create(&m_paDaemonThread, nullptr, AudioServer::paDaemonThread, nullptr);
86     if (ret != 0) {
87         AUDIO_ERR_LOG("pthread_create failed %d", ret);
88     }
89     AUDIO_INFO_LOG("Created paDaemonThread\n");
90 #endif
91 }
92 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)93 void AudioServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
94 {
95     AUDIO_DEBUG_LOG("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
96     switch (systemAbilityId) {
97         case AUDIO_POLICY_SERVICE_ID:
98             AUDIO_INFO_LOG("OnAddSystemAbility input service start");
99             RegisterPolicyServerDeathRecipient();
100             break;
101         default:
102             AUDIO_ERR_LOG("OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
103             break;
104     }
105 }
106 
OnStop()107 void AudioServer::OnStop()
108 {
109     AUDIO_DEBUG_LOG("AudioService OnStop");
110 }
111 
SetAudioParameter(const std::string & key,const std::string & value)112 void AudioServer::SetAudioParameter(const std::string &key, const std::string &value)
113 {
114     AUDIO_DEBUG_LOG("server: set audio parameter");
115     if (!VerifyClientPermission(MODIFY_AUDIO_SETTINGS_PERMISSION)) {
116         AUDIO_ERR_LOG("SetAudioParameter: MODIFY_AUDIO_SETTINGS permission denied");
117         return;
118     }
119 
120     AudioServer::audioParameters[key] = value;
121 #ifdef PRODUCT_M40
122     AudioRendererSink* audioRendererSinkInstance = AudioRendererSink::GetInstance();
123     if (audioRendererSinkInstance == nullptr) {
124         AUDIO_ERR_LOG("has no valid sink");
125         return;
126     }
127     AudioParamKey parmKey = AudioParamKey::NONE;
128     if (key == "AUDIO_EXT_PARAM_KEY_LOWPOWER") {
129         parmKey = AudioParamKey::PARAM_KEY_LOWPOWER;
130     } else {
131         AUDIO_ERR_LOG("SetAudioParameter: key %{publbic}s is invalid for hdi interface", key.c_str());
132         return;
133     }
134     audioRendererSinkInstance->SetAudioParameter(parmKey, "", value);
135 #endif
136 }
137 
SetAudioParameter(const std::string & networkId,const AudioParamKey key,const std::string & condition,const std::string & value)138 void AudioServer::SetAudioParameter(const std::string& networkId, const AudioParamKey key, const std::string& condition,
139     const std::string& value)
140 {
141     RemoteAudioRendererSink* audioRendererSinkInstance = RemoteAudioRendererSink::GetInstance(networkId.c_str());
142     if (audioRendererSinkInstance == nullptr) {
143         AUDIO_ERR_LOG("has no valid sink");
144         return;
145     }
146 
147     audioRendererSinkInstance->SetAudioParameter(key, condition, value);
148 }
149 
GetAudioParameter(const std::string & key)150 const std::string AudioServer::GetAudioParameter(const std::string &key)
151 {
152     AUDIO_DEBUG_LOG("server: get audio parameter");
153 #ifdef PRODUCT_M40
154     AudioRendererSink* audioRendererSinkInstance = AudioRendererSink::GetInstance();
155     if (audioRendererSinkInstance != nullptr) {
156         AudioParamKey parmKey = AudioParamKey::NONE;
157         if (key == "AUDIO_EXT_PARAM_KEY_LOWPOWER") {
158             parmKey = AudioParamKey::PARAM_KEY_LOWPOWER;
159             return audioRendererSinkInstance->GetAudioParameter(AudioParamKey(parmKey), "");
160         }
161     }
162 #endif
163      if (AudioServer::audioParameters.count(key)) {
164          return AudioServer::audioParameters[key];
165      } else {
166          return "";
167      }
168 }
169 
GetAudioParameter(const std::string & networkId,const AudioParamKey key,const std::string & condition)170 const std::string AudioServer::GetAudioParameter(const std::string& networkId, const AudioParamKey key,
171     const std::string& condition)
172 {
173     RemoteAudioRendererSink* audioRendererSinkInstance = RemoteAudioRendererSink::GetInstance(networkId.c_str());
174     if (audioRendererSinkInstance == nullptr) {
175         AUDIO_ERR_LOG("has no valid sink");
176         return "";
177     }
178     return audioRendererSinkInstance->GetAudioParameter(key, condition);
179 }
180 
RetrieveCookie(int32_t & size)181 const char *AudioServer::RetrieveCookie(int32_t &size)
182 {
183     char *cookieInfo = nullptr;
184     size = 0;
185     std::ifstream cookieFile(DEFAULT_COOKIE_PATH, std::ifstream::binary);
186     if (!cookieFile) {
187         return cookieInfo;
188     }
189 
190     cookieFile.seekg (0, cookieFile.end);
191     size = cookieFile.tellg();
192     cookieFile.seekg (0, cookieFile.beg);
193 
194     if ((size > 0) && (size < PATH_MAX)) {
195         cookieInfo = (char *)malloc(size * sizeof(char));
196         if (cookieInfo == nullptr) {
197             AUDIO_ERR_LOG("AudioServer::RetrieveCookie: No memory");
198             cookieFile.close();
199             return cookieInfo;
200         }
201         AUDIO_DEBUG_LOG("Reading: %{public}d characters...", size);
202         cookieFile.read(cookieInfo, size);
203     }
204     cookieFile.close();
205     return cookieInfo;
206 }
207 
GetTransactionId(DeviceType deviceType,DeviceRole deviceRole)208 uint64_t AudioServer::GetTransactionId(DeviceType deviceType, DeviceRole deviceRole)
209 {
210     uint64_t transactionId = 0;
211     AUDIO_INFO_LOG("GetTransactionId in: device type: %{public}d, device role: %{public}d", deviceType, deviceRole);
212     if (deviceRole != INPUT_DEVICE && deviceRole != OUTPUT_DEVICE) {
213         AUDIO_ERR_LOG("GetTransactionId: error device role");
214         return ERR_INVALID_PARAM;
215     }
216     if (deviceRole == OUTPUT_DEVICE) {
217         struct RendererSinkAdapter *sinkAdapter;
218         int32_t ret = SUCCESS;
219         if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
220             ret = LoadSinkAdapter("a2dp", "LocalDevice", &sinkAdapter);
221         } else {
222             ret = LoadSinkAdapter("primary", "LocalDevice", &sinkAdapter);
223         }
224 
225         if (ret) {
226             AUDIO_ERR_LOG("Load adapter failed");
227             return transactionId;
228         }
229 
230         sinkAdapter->RendererSinkGetTransactionId(&transactionId);
231         UnLoadSinkAdapter(sinkAdapter);
232     } else if (deviceRole == INPUT_DEVICE) {
233         AudioCapturerSource *audioCapturerSourceInstance = AudioCapturerSource::GetInstance();
234         if (audioCapturerSourceInstance) {
235             transactionId = audioCapturerSourceInstance->GetTransactionId();
236         }
237     }
238 
239     AUDIO_INFO_LOG("Transaction Id: %{public}" PRIu64, transactionId);
240     return transactionId;
241 }
242 
GetMaxVolume(AudioVolumeType volumeType)243 int32_t AudioServer::GetMaxVolume(AudioVolumeType volumeType)
244 {
245     AUDIO_DEBUG_LOG("GetMaxVolume server");
246     return MAX_VOLUME;
247 }
248 
GetMinVolume(AudioVolumeType volumeType)249 int32_t AudioServer::GetMinVolume(AudioVolumeType volumeType)
250 {
251     AUDIO_DEBUG_LOG("GetMinVolume server");
252     if (volumeType == STREAM_VOICE_ASSISTANT || volumeType == STREAM_VOICE_CALL) {
253         return (MIN_VOLUME + 1);
254     }
255     return MIN_VOLUME;
256 }
257 
SetMicrophoneMute(bool isMute)258 int32_t AudioServer::SetMicrophoneMute(bool isMute)
259 {
260     int32_t audio_policy_server_id = 1041;
261     int32_t audio_policy_server_Uid = 1005;
262     if (IPCSkeleton::GetCallingUid() != audio_policy_server_id
263         && IPCSkeleton::GetCallingUid() != audio_policy_server_Uid) {
264         return ERR_PERMISSION_DENIED;
265     }
266     AudioCapturerSource *audioCapturerSourceInstance = AudioCapturerSource::GetInstance();
267 
268     if (!audioCapturerSourceInstance->capturerInited_) {
269             AUDIO_INFO_LOG("Capturer is not initialized. Set the flag mute state flag");
270             AudioCapturerSource::micMuteState_ = isMute;
271             return 0;
272     }
273 
274     return audioCapturerSourceInstance->SetMute(isMute);
275 }
276 
IsMicrophoneMute()277 bool AudioServer::IsMicrophoneMute()
278 {
279     int32_t audio_policy_server_id = 1041;
280     int32_t audio_policy_server_Uid = 1005;
281     if (IPCSkeleton::GetCallingUid() != audio_policy_server_id
282         && IPCSkeleton::GetCallingUid() != audio_policy_server_Uid) {
283         return false;
284     }
285     AudioCapturerSource *audioCapturerSourceInstance = AudioCapturerSource::GetInstance();
286     bool isMute = false;
287 
288     if (!audioCapturerSourceInstance->capturerInited_) {
289         AUDIO_INFO_LOG("Capturer is not initialized. Get the mic mute state flag value!");
290         return AudioCapturerSource::micMuteState_;
291     }
292 
293     if (audioCapturerSourceInstance->GetMute(isMute)) {
294         AUDIO_ERR_LOG("GetMute status in capturer returned Error !");
295     }
296 
297     return isMute;
298 }
299 
SetVoiceVolume(float volume)300 int32_t AudioServer::SetVoiceVolume(float volume)
301 {
302     AudioRendererSink *audioRendererSinkInstance = AudioRendererSink::GetInstance();
303 
304     if (audioRendererSinkInstance == nullptr) {
305         AUDIO_WARNING_LOG("Renderer is null.");
306     } else {
307         return audioRendererSinkInstance->SetVoiceVolume(volume);
308     }
309     return ERROR;
310 }
311 
SetAudioScene(AudioScene audioScene,DeviceType activeDevice)312 int32_t AudioServer::SetAudioScene(AudioScene audioScene, DeviceType activeDevice)
313 {
314     AudioCapturerSource *audioCapturerSourceInstance = AudioCapturerSource::GetInstance();
315     AudioRendererSink *audioRendererSinkInstance = AudioRendererSink::GetInstance();
316 
317     if (!audioCapturerSourceInstance->capturerInited_) {
318         AUDIO_WARNING_LOG("Capturer is not initialized.");
319     } else {
320         audioCapturerSourceInstance->SetAudioScene(audioScene, activeDevice);
321     }
322 
323     if (!audioRendererSinkInstance->rendererInited_) {
324         AUDIO_WARNING_LOG("Renderer is not initialized.");
325     } else {
326         audioRendererSinkInstance->SetAudioScene(audioScene, activeDevice);
327     }
328 
329     audioScene_ = audioScene;
330 
331     return SUCCESS;
332 }
333 
UpdateActiveDeviceRoute(DeviceType type,DeviceFlag flag)334 int32_t AudioServer::UpdateActiveDeviceRoute(DeviceType type, DeviceFlag flag)
335 {
336     AUDIO_INFO_LOG("UpdateActiveDeviceRoute deviceType: %{public}d, flag: %{public}d", type, flag);
337     AudioCapturerSource *audioCapturerSourceInstance = AudioCapturerSource::GetInstance();
338     AudioRendererSink *audioRendererSinkInstance = AudioRendererSink::GetInstance();
339 
340     switch (flag) {
341         case DeviceFlag::INPUT_DEVICES_FLAG: {
342             if (audioScene_ != AUDIO_SCENE_DEFAULT) {
343                 audioCapturerSourceInstance->SetAudioScene(audioScene_, type);
344             } else {
345                 audioCapturerSourceInstance->SetInputRoute(type);
346             }
347             break;
348         }
349         case DeviceFlag::OUTPUT_DEVICES_FLAG: {
350             if (audioScene_ != AUDIO_SCENE_DEFAULT) {
351                 audioRendererSinkInstance->SetAudioScene(audioScene_, type);
352             } else {
353                 audioRendererSinkInstance->SetOutputRoute(type);
354             }
355             break;
356         }
357         case DeviceFlag::ALL_DEVICES_FLAG: {
358             if (audioScene_ != AUDIO_SCENE_DEFAULT) {
359                 SetAudioScene(audioScene_, type);
360             } else {
361                 audioCapturerSourceInstance->SetInputRoute(type);
362                 audioRendererSinkInstance->SetOutputRoute(type);
363             }
364             break;
365         }
366         default:
367             break;
368     }
369 
370     return SUCCESS;
371 }
372 
SetAudioMonoState(bool audioMono)373 void AudioServer::SetAudioMonoState(bool audioMono)
374 {
375     AUDIO_INFO_LOG("AudioServer::SetAudioMonoState: audioMono = %{public}s", audioMono? "true": "false");
376 
377     // Set mono for audio_renderer_sink(primary sink)
378     AudioRendererSink *audioRendererSinkInstance = AudioRendererSink::GetInstance();
379     if (!audioRendererSinkInstance->rendererInited_) {
380         AUDIO_WARNING_LOG("Renderer is not initialized.");
381     } else {
382         audioRendererSinkInstance->SetAudioMonoState(audioMono);
383     }
384 
385     // Set mono for bluetooth_renderer_sink
386     BluetoothRendererSinkSetAudioMonoState(audioMono);
387 }
388 
SetAudioBalanceValue(float audioBalance)389 void AudioServer::SetAudioBalanceValue(float audioBalance)
390 {
391     AUDIO_INFO_LOG("AudioServer::SetAudioBalanceValue: audioBalance = %{public}f", audioBalance);
392 
393     // Set balance for audio_renderer_sink(primary sink)
394     AudioRendererSink *audioRendererSinkInstance = AudioRendererSink::GetInstance();
395     if (!audioRendererSinkInstance->rendererInited_) {
396         AUDIO_WARNING_LOG("Renderer is not initialized.");
397     } else {
398         audioRendererSinkInstance->SetAudioBalanceValue(audioBalance);
399     }
400 
401     // Set balance for bluetooth_renderer_sink
402     BluetoothRendererSinkSetAudioBalanceValue(audioBalance);
403 }
404 
NotifyDeviceInfo(std::string networkId,bool connected)405 void AudioServer::NotifyDeviceInfo(std::string networkId, bool connected)
406 {
407     AUDIO_INFO_LOG("notify device info: networkId(%{public}s), connected(%{public}d)", networkId.c_str(), connected);
408     RemoteAudioRendererSink* audioRendererSinkInstance = RemoteAudioRendererSink::GetInstance(networkId.c_str());
409     if (audioRendererSinkInstance != nullptr && connected) {
410         audioRendererSinkInstance->RegisterParameterCallback(this);
411     }
412 }
413 
CheckRemoteDeviceState(std::string networkId,DeviceRole deviceRole,bool isStartDevice)414 int32_t AudioServer::CheckRemoteDeviceState(std::string networkId, DeviceRole deviceRole, bool isStartDevice)
415 {
416     AUDIO_INFO_LOG("CheckRemoteDeviceState: device[%{public}s] deviceRole[%{public}d] isStartDevice[%{public}s]",
417         networkId.c_str(), static_cast<int32_t>(deviceRole), (isStartDevice ? "true" : "false"));
418     RemoteAudioRendererSink* audioRendererSinkInstance = RemoteAudioRendererSink::GetInstance(networkId.c_str());
419     if (audioRendererSinkInstance == nullptr || !audioRendererSinkInstance->rendererInited_) {
420         return ERR_ILLEGAL_STATE;
421     }
422     int32_t ret = SUCCESS;
423     if (isStartDevice) {
424         ret = audioRendererSinkInstance->Start();
425     }
426     return ret;
427 }
428 
OnAudioParameterChange(std::string netWorkId,const AudioParamKey key,const std::string & condition,const std::string value)429 void AudioServer::OnAudioParameterChange(std::string netWorkId, const AudioParamKey key, const std::string& condition,
430     const std::string value)
431 {
432     AUDIO_INFO_LOG("OnAudioParameterChange Callback from networkId: %s", netWorkId.c_str());
433 
434     if (callback_ != nullptr) {
435         callback_->OnAudioParameterChange(netWorkId, key, condition, value);
436     }
437 }
438 
SetParameterCallback(const sptr<IRemoteObject> & object)439 int32_t AudioServer::SetParameterCallback(const sptr<IRemoteObject>& object)
440 {
441     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioServer:set listener object is nullptr");
442 
443     sptr<IStandardAudioServerManagerListener> listener = iface_cast<IStandardAudioServerManagerListener>(object);
444 
445     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioServer: listener obj cast failed");
446 
447     std::shared_ptr<AudioParameterCallback> callback = std::make_shared<AudioManagerListenerCallback>(listener);
448     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to  create cb obj");
449 
450     callback_ = callback;
451     AUDIO_INFO_LOG("AudioServer:: SetParameterCallback  done");
452 
453     return SUCCESS;
454 }
455 
VerifyClientPermission(const std::string & permissionName)456 bool AudioServer::VerifyClientPermission(const std::string &permissionName)
457 {
458     auto callerUid = IPCSkeleton::GetCallingUid();
459     AUDIO_INFO_LOG("AudioServer: ==[%{public}s] [uid:%{public}d]==", permissionName.c_str(), callerUid);
460 
461     // Root users should be whitelisted
462     if (callerUid == ROOT_UID) {
463         AUDIO_INFO_LOG("Root user. Permission GRANTED!!!");
464         return true;
465     }
466 
467     Security::AccessToken::AccessTokenID clientTokenId = IPCSkeleton::GetCallingTokenID();
468     int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(clientTokenId, permissionName);
469     if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
470         AUDIO_ERR_LOG("Permission denied [tid:%{public}d]", clientTokenId);
471         return false;
472     }
473 
474     return true;
475 }
476 
GetDevices(DeviceFlag deviceFlag)477 std::vector<sptr<AudioDeviceDescriptor>> AudioServer::GetDevices(DeviceFlag deviceFlag)
478 {
479     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptor = {};
480     return audioDeviceDescriptor;
481 }
482 
AudioServerDied(pid_t pid)483 void AudioServer::AudioServerDied(pid_t pid)
484 {
485     AUDIO_INFO_LOG("Policy server died: restart pulse audio");
486     _Exit(0);
487 }
488 
RegisterPolicyServerDeathRecipient()489 void AudioServer::RegisterPolicyServerDeathRecipient()
490 {
491     AUDIO_INFO_LOG("Register policy server death recipient");
492     pid_t pid = IPCSkeleton::GetCallingPid();
493     sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(pid);
494     if (deathRecipient_ != nullptr) {
495         auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
496         CHECK_AND_RETURN_LOG(samgr != nullptr, "Failed to obtain system ability manager");
497         sptr<IRemoteObject> object = samgr->GetSystemAbility(OHOS::AUDIO_POLICY_SERVICE_ID);
498         CHECK_AND_RETURN_LOG(object != nullptr, "Policy service unavailable");
499         deathRecipient_->SetNotifyCb(std::bind(&AudioServer::AudioServerDied, this, std::placeholders::_1));
500         bool result = object->AddDeathRecipient(deathRecipient_);
501         if (!result) {
502             AUDIO_ERR_LOG("Failed to add deathRecipient");
503         }
504     }
505 }
506 } // namespace AudioStandard
507 } // namespace OHOS
508