diff --git a/frameworks/innerkitsimpl/audioadapter/include/pulse_audio_service_adapter_impl.h b/frameworks/innerkitsimpl/audioadapter/include/pulse_audio_service_adapter_impl.h index 5d98492c4daccdcfa765827832773ac5bcc7e9f9..a0055de0f72822950d131d9c879afdf2372491a9 100644 --- a/frameworks/innerkitsimpl/audioadapter/include/pulse_audio_service_adapter_impl.h +++ b/frameworks/innerkitsimpl/audioadapter/include/pulse_audio_service_adapter_impl.h @@ -16,24 +16,19 @@ #ifndef ST_PULSEAUDIO_AUDIO_SERVICE_ADAPTER_H #define ST_PULSEAUDIO_AUDIO_SERVICE_ADAPTER_H -#ifdef __cplusplus -extern "C" { -#endif #include -#ifdef __cplusplus -} -#endif + #include "audio_service_adapter.h" namespace OHOS { namespace AudioStandard { class PulseAudioServiceAdapterImpl : public AudioServiceAdapter { public: - PulseAudioServiceAdapterImpl(AudioServiceAdapterCallback *cb); + PulseAudioServiceAdapterImpl(std::unique_ptr &cb); ~PulseAudioServiceAdapterImpl(); bool Connect() override; - int32_t OpenAudioPort(char *audioPortName, std::string moduleArgs) override; + int32_t OpenAudioPort(std::string audioPortName, std::string moduleArgs) override; int32_t CloseAudioPort(int32_t audioHandleIndex) override; int32_t SetDefaultSink(std::string name) override; int32_t SetDefaultSource(std::string name) override; diff --git a/frameworks/innerkitsimpl/audioadapter/src/pulse_audio_service_adapter_impl.cpp b/frameworks/innerkitsimpl/audioadapter/src/pulse_audio_service_adapter_impl.cpp index 0ba7feac0b7f9bea3861d94a01343c759cffa7ba..a484238761d8a9bbc338f9ef7d23edb532827cf6 100644 --- a/frameworks/innerkitsimpl/audioadapter/src/pulse_audio_service_adapter_impl.cpp +++ b/frameworks/innerkitsimpl/audioadapter/src/pulse_audio_service_adapter_impl.cpp @@ -24,19 +24,19 @@ namespace OHOS { namespace AudioStandard { -static AudioServiceAdapterCallback *mAudioServiceAdapterCallback; +static std::unique_ptr mAudioServiceAdapterCallback; AudioServiceAdapter::~AudioServiceAdapter() = default; PulseAudioServiceAdapterImpl::~PulseAudioServiceAdapterImpl() = default; -std::unique_ptr AudioServiceAdapter::CreateAudioAdapter(AudioServiceAdapterCallback *cb) +std::unique_ptr AudioServiceAdapter::CreateAudioAdapter(std::unique_ptr cb) { return std::make_unique(cb); } -PulseAudioServiceAdapterImpl::PulseAudioServiceAdapterImpl(AudioServiceAdapterCallback *cb) +PulseAudioServiceAdapterImpl::PulseAudioServiceAdapterImpl(std::unique_ptr &cb) { - mAudioServiceAdapterCallback = cb; + mAudioServiceAdapterCallback = std::move(cb); } bool PulseAudioServiceAdapterImpl::Connect() @@ -88,7 +88,7 @@ bool PulseAudioServiceAdapterImpl::ConnectToPulseAudio() userData->thiz = this; if (mContext != NULL) { - pa_context_disconnect (mContext); + pa_context_disconnect(mContext); pa_context_set_state_callback(mContext, NULL, NULL); pa_context_set_subscribe_callback(mContext, NULL, NULL); pa_context_unref(mContext); @@ -124,13 +124,13 @@ Fail: return false; } -int32_t PulseAudioServiceAdapterImpl::OpenAudioPort(char *audioPortName, std::string moduleArgs) +int32_t PulseAudioServiceAdapterImpl::OpenAudioPort(std::string audioPortName, std::string moduleArgs) { std::unique_ptr userData = std::make_unique(); userData->thiz = this; pa_threaded_mainloop_lock(mMainLoop); - pa_operation *operation = pa_context_load_module(mContext, audioPortName, moduleArgs.c_str(), PaModuleLoadCb, + pa_operation *operation = pa_context_load_module(mContext, audioPortName.c_str(), moduleArgs.c_str(), PaModuleLoadCb, reinterpret_cast(userData.get())); if (operation == NULL) { MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] pa_context_load_module returned nullptr"); @@ -385,7 +385,7 @@ void PulseAudioServiceAdapterImpl::PaGetSinkInputInfoMuteStatusCb(pa_context *c, PulseAudioServiceAdapterImpl *thiz = userData->thiz; if (eol < 0) { - MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %s", + MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %{public}s", pa_strerror(pa_context_errno(c))); return; } @@ -423,7 +423,7 @@ void PulseAudioServiceAdapterImpl::PaGetSinkInputInfoMuteCb(pa_context *c, const PulseAudioServiceAdapterImpl *thiz = userData->thiz; if (eol < 0) { - MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %s", + MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %{public}s", pa_strerror(pa_context_errno(c))); return; } @@ -495,7 +495,7 @@ void PulseAudioServiceAdapterImpl::PaModuleLoadCb(pa_context *c, uint32_t idx, v { UserData *userData = reinterpret_cast(userdata); if (idx == PA_INVALID_INDEX) { - MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failure: %s", pa_strerror(pa_context_errno(c))); + MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failure: %{public}s", pa_strerror(pa_context_errno(c))); userData->idx = PA_INVALID_INDEX; } else { userData->idx = idx; @@ -514,7 +514,7 @@ void PulseAudioServiceAdapterImpl::PaGetSinkInputInfoVolumeCb(pa_context *c, con MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] GetSinkInputInfoVolumeCb"); if (eol < 0) { delete userData; - MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %s", + MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %{public}s", pa_strerror(pa_context_errno(c))); return; } @@ -566,7 +566,7 @@ void PulseAudioServiceAdapterImpl::PaGetSinkInputInfoCorkStatusCb(pa_context *c, PulseAudioServiceAdapterImpl *thiz = userData->thiz; if (eol < 0) { - MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %s", + MEDIA_ERR_LOG("[PulseAudioServiceAdapterImpl] Failed to get sink input information: %{public}s", pa_strerror(pa_context_errno(c))); return; } diff --git a/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink_intf.h b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink_intf.h index 6219e31c01d434f185db1352e3ce26f34d30c203..90500d15753f6bc36876461d53d3c4215088daa7 100644 --- a/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink_intf.h +++ b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink_intf.h @@ -27,13 +27,13 @@ typedef struct { float volume; } AudioSinkAttr; -int32_t AudioRendererSinkInit(AudioSinkAttr *); +int32_t AudioRendererSinkInit(AudioSinkAttr *attr); void AudioRendererSinkDeInit(void); int32_t AudioRendererSinkStart(void); int32_t AudioRendererSinkStop(void); -int32_t AudioRendererRenderFrame(char*, uint64_t, uint64_t*); +int32_t AudioRendererRenderFrame(char *data, uint64_t len, uint64_t *writeLen); int32_t AudioRendererSinkSetVolume(float, float); -int32_t AudioRendererSinkGetLatency(uint32_t *); +int32_t AudioRendererSinkGetLatency(uint32_t *latency); #ifdef __cplusplus } #endif diff --git a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp index 340cb3952c5d3688efc43f5714a981bfe1fb0246..3c9b89fc5679dee0249448fb4c1173654e1236b5 100644 --- a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp +++ b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp @@ -55,7 +55,7 @@ AudioRendererSink::~AudioRendererSink() DeInit(); } -AudioRendererSink* AudioRendererSink::GetInstance() +AudioRendererSink *AudioRendererSink::GetInstance() { static AudioRendererSink audioRenderer_; @@ -119,7 +119,7 @@ static int32_t SwitchAdapter(struct AudioAdapterDescriptor *descs, const char *a continue; } if (!strcmp(desc->adapterName, adapterNameCase)) { - for (uint32_t port = 0; ((desc != nullptr) && (port < desc->portNum)); port++) { + for (uint32_t port = 0; port < desc->portNum; port++) { // Only find out the port of out in the sound card if (desc->ports[port].dir == portFlag) { *renderPort = desc->ports[port]; @@ -465,7 +465,7 @@ extern "C" { using namespace OHOS::AudioStandard; -AudioRendererSink* g_audioRendrSinkInstance = AudioRendererSink::GetInstance(); +AudioRendererSink *g_audioRendrSinkInstance = AudioRendererSink::GetInstance(); int32_t AudioRendererSinkInit(AudioSinkAttr *attr) { diff --git a/frameworks/innerkitsimpl/common/include/media_info.h b/frameworks/innerkitsimpl/common/include/media_info.h deleted file mode 100755 index 55193c649b6b3ad83c72ddbf0b7be250f05de10b..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/common/include/media_info.h +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @addtogroup MultiMedia_MediaCommon - * @{ - * - * @brief Provides data types and media formats required for recording and playing audio and videos. - * - * - * @since 1.0 - * @version 1.0 - */ - -/** - * @file media_info.h - * - * @brief Declares the media_info class and provides various audio, video, and codec types. - * - * - * @since 1.0 - * @version 1.0 - */ - -#ifndef MEDIA_INFO_H -#define MEDIA_INFO_H -#include - -/** - * Indicates the constant quality mode. In this mode, the bit rate is not limited to guarantee the image quality to - * the largest extent. - */ -const int BITRATE_MODE_CQ = 0; - -/** - * Indicates the variable bit rate mode. In this mode, the codec dynamically adjusts the output bit rate based on - * the image complexity. The codec increases the bit rate if the image is complex and decreases the bit rate if the - * image is simple. - */ -const int BITRATE_MODE_VBR = 1; - -/** Indicates the constant bit rate mode. In this mode, the codec keeps the output bit rate as constant as possible. */ -const int BITRATE_MODE_CBR = 2; - -/** Indicates the ARGB8888 color format. */ -const int32_t COLOR_FORMAT_ARGB8888_32BIT = 16; - -/** Indicates the YUV420SP color format. */ -const int32_t COLOR_FORMAT_YUV420SP = 21; - -/** Indicates that the current frame is an Instantaneous Decoder Refresh (IDR) frame. */ -const std::string KEY_IS_SYNC_FRAME = "is-sync-frame"; - -/** Indicates the frame timestamp. */ -const std::string KEY_TIME_US = "timeUs"; - -/** - * @brief Enumerates audio source types. - * - * @since 1.0 - * @version 1.0 - */ -typedef enum { - /** Invalid audio source */ - AUDIO_SOURCE_INVALID = -1, - /** Default audio source */ - AUDIO_SOURCE_DEFAULT = 0, - /** Microphone */ - AUDIO_MIC = 1, - /** Uplink voice */ - AUDIO_VOICE_UPLINK = 2, - /** Downlink voice */ - AUDIO_VOICE_DOWNLINK = 3, - /** Voice call */ - AUDIO_VOICE_CALL = 4, - /** Camcorder */ - AUDIO_CAMCORDER = 5, - /** Voice recognition */ - AUDIO_VOICE_RECOGNITION = 6, - /** Voice communication */ - AUDIO_VOICE_COMMUNICATION = 7, - /** Remote submix */ - AUDIO_REMOTE_SUBMIX = 8, - /** Unprocessed audio */ - AUDIO_UNPROCESSED = 9, - /** Voice performance */ - AUDIO_VOICE_PERFORMANCE = 10, - /** Echo reference */ - AUDIO_ECHO_REFERENCE = 1997, - /** Radio tuner */ - AUDIO_RADIO_TUNER = 1998, - /** Hotword */ - AUDIO_HOTWORD = 1999, - /** Extended remote submix */ - AUDIO_REMOTE_SUBMIX_EXTEND = 10007, -} AudioSourceType; - -/** - * @brief Defines the audio Device Descriptor. - * - * @since 1.0 - * @version 1.0 - */ -typedef struct { - /** Device name */ - std::string deviceName; - /** Type of the audio input source */ - AudioSourceType inputSourceType; - /** Bits 31-24: reserved bits; bits 23-16: mode ID; bits 15-8: device ID; bits 7-0: channel ID */ - uint32_t deviceId; -} AudioDeviceDesc; - -/** - * @brief Enumerates audio stream types. - * - * @since 1.0 - * @version 1.0 - */ -typedef enum { - /** Default audio stream type */ - TYPE_DEFAULT = -1, - /** Media */ - TYPE_MEDIA = 0, - /** Voice call */ - TYPE_VOICE_COMMUNICATION = 1, - /** System sound */ - TYPE_SYSTEM = 2, - /** Ringtone */ - TYPE_RING = 3, - /** Music */ - TYPE_MUSIC = 4, - /** Alarm */ - TYPE_ALARM = 5, - /** Notification */ - TYPE_NOTIFICATION = 6, - /** Bluetooth Synchronous Connection-Oriented (SCO) */ - TYPE_BLUETOOTH_SCO = 7, - /** Enforced audible */ - TYPE_ENFORCED_AUDIBLE = 8, - /** Dual-tone multi-frequency (DTMF) */ - TYPE_DTMF = 9, - /** Text-To-Speech (TTS) */ - TYPE_TTS = 10, - /** Accessibility */ - TYPE_ACCESSIBILITY = 11, -} AudioStreamType; - -/** - * @brief Enumerates video codec formats. - * - * @since 1.0 - * @version 1.0 - */ -typedef enum { - /** Default format */ - VIDEO_DEFAULT = 0, - /** H.264 */ - H264 = 2, - /** High Efficiency Video Coding (HEVC) */ - HEVC = 5, -} VideoCodecFormat; - -/** - * @brief Enumerates audio codec formats. - * - * @since 1.0 - * @version 1.0 - */ -typedef enum { - /** Default format */ - AUDIO_DEFAULT = 0, - /** Advanced Audio Coding Low Complexity (AAC-LC) */ - AAC_LC = 1, - /** High-Efficiency Advanced Audio Coding (AAC-HE), previously known as AAC+ or aacPlus v1 */ - AAC_HE_V1 = 2, - /** AAC++ or aacPlus v2 */ - AAC_HE_V2 = 3, - /** Advanced Audio Coding Low Delay (AAC-LD) */ - AAC_LD = 4, - /** Advanced Audio Coding Enhanced Low Delay (AAC-ELD) */ - AAC_ELD = 5, - /** Invalid value */ - FORMAT_BUTT, -} AudioCodecFormat; - -/** - * @brief Enumerates audio bit widths. - * - * @since 1.0 - * @version 1.0 - */ -typedef enum { - /** 8-bit width */ - BIT_WIDTH_8 = 8, - /** 16-bit width */ - BIT_WIDTH_16 = 16, - /** 24-bit width */ - BIT_WIDTH_24 = 24, - /** Invalid value */ - BIT_WIDTH_BUTT, -} AudioBitWidth; -#endif // MEDIA_INFO_H diff --git a/frameworks/innerkitsimpl/pulseaudio/include/ltdl.h b/frameworks/innerkitsimpl/pulseaudio/include/ltdl.h index 9ce4b7d3ea355c1df5f3a3581c70c5a515f2ff23..e77d6958f0fb0ec5b693b148a1256935652a4cea 100644 --- a/frameworks/innerkitsimpl/pulseaudio/include/ltdl.h +++ b/frameworks/innerkitsimpl/pulseaudio/include/ltdl.h @@ -19,10 +19,10 @@ #include -typedef void* lt_dlhandle; +typedef void *lt_dlhandle; const char *lt_dlerror(void); -const char* lt_dlgetsearchpath(); +const char *lt_dlgetsearchpath(); int lt_dlclose(lt_dlhandle handle); lt_dlhandle lt_dlopenext(const char *filename); -void* lt_dlsym(lt_dlhandle handle, const char *symbol); +void *lt_dlsym(lt_dlhandle handle, const char *symbol); diff --git a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/hdi_source.c b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/hdi_source.c index 30b3eeef3c198c599cac2a31497383774c7df410..83286f80b4e69f74381b0b6c5db684c3f99a91a3 100644 --- a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/hdi_source.c +++ b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/hdi_source.c @@ -335,7 +335,7 @@ static int pa_set_source_properties(pa_module *m, pa_modargs *ma, pa_sample_spec return 0; } -pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver) { +pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char *driver) { struct userdata *u = NULL; pa_sample_spec ss; char *thread_name = NULL; diff --git a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_sink.c b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_sink.c index f47aa9ed2fa57d4186563edcf4f75a1bed39db3a..8ffca663c40aef25ba3cc0b0578fc956a23e72b4 100644 --- a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_sink.c +++ b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_sink.c @@ -21,7 +21,7 @@ #include #include -pa_sink* PaHdiSinkNew(pa_module *m, pa_modargs *ma, const char *driver); +pa_sink *PaHdiSinkNew(pa_module *m, pa_modargs *ma, const char *driver); void PaHdiSinkFree(pa_sink *s); PA_MODULE_AUTHOR("OpenHarmony"); diff --git a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_source.c b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_source.c index 4e8760c937f138f9ad2e11f8f5130fffe858de00..b77a74ff061cd4ace224aaa2e395c6da03861895 100644 --- a/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_source.c +++ b/frameworks/innerkitsimpl/pulseaudio/src/modules/hdi/module_hdi_source.c @@ -17,14 +17,12 @@ #include #endif -#include - #include #include #include #include -pa_source* pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver); +pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char *driver); void pa_hdi_source_free(pa_source *s); @@ -91,7 +89,7 @@ int pa__get_n_used(pa_module *m) return pa_source_linked_by(source); } -void pa__done(pa_module*m) +void pa__done(pa_module *m) { pa_source *source = NULL; diff --git a/frameworks/innerkitsimpl/pulseaudio/src/pulsecore/ltdl-stub.c b/frameworks/innerkitsimpl/pulseaudio/src/pulsecore/ltdl-stub.c index ce239ab9b8ef4a8b822326f58214da872cc3ab67..5c41c8154b95bd3a9d39e029842dd0369940dafc 100644 --- a/frameworks/innerkitsimpl/pulseaudio/src/pulsecore/ltdl-stub.c +++ b/frameworks/innerkitsimpl/pulseaudio/src/pulsecore/ltdl-stub.c @@ -20,28 +20,33 @@ #define SYSTEM_LIB_PATH "/system/lib/" -lt_dlhandle lt_dlopenext(const char *filename) { +lt_dlhandle lt_dlopenext(const char *filename) +{ pa_assert(filename); return (dlopen(filename, RTLD_NOW)); } -void* lt_dlsym(lt_dlhandle handle, const char *symbol) { +void *lt_dlsym(lt_dlhandle handle, const char *symbol) +{ pa_assert(handle); pa_assert(symbol); return (dlsym(handle, symbol)); } -int lt_dlclose(lt_dlhandle handle) { +int lt_dlclose(lt_dlhandle handle) +{ pa_assert(handle); return (dlclose(handle)); } -const char *lt_dlerror(void) { +const char *lt_dlerror(void) +{ return dlerror(); } -const char* lt_dlgetsearchpath() { - const char* path = SYSTEM_LIB_PATH; +const char *lt_dlgetsearchpath() +{ + const char *path = SYSTEM_LIB_PATH; return path; } diff --git a/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/include/audio_policy_test.h b/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/include/audio_policy_test.h index c93f2b0e9a689e25a964c303b797a1ff0442788a..20e525f1e26283b937be0f9d49a591ae8496cc18 100644 --- a/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/include/audio_policy_test.h +++ b/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/include/audio_policy_test.h @@ -30,9 +30,9 @@ struct PolicyParam { AudioStreamType streamType; AudioRingerMode ringerMode; ActiveDeviceType actDeviceType; - AudioDeviceDescriptor::DeviceType deviceType; - AudioDeviceDescriptor::DeviceFlag deviceFlag; - AudioDeviceDescriptor::DeviceRole deviceRole; + DeviceType deviceType; + DeviceFlag deviceFlag; + DeviceRole deviceRole; bool active; bool mute; string key; diff --git a/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/src/audio_policy_test.cpp b/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/src/audio_policy_test.cpp index 1aba9b58c7714918364215a073161660bf8e00bd..23d0bed64f9dc9a7d81062c37e34f8c038412e0b 100644 --- a/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/src/audio_policy_test.cpp +++ b/frameworks/innerkitsimpl/test/moduletest/audiopolicy/1.0/src/audio_policy_test.cpp @@ -138,14 +138,14 @@ const PolicyParam AUDIO_PARAMS[] = { const PolicyParam DEVICES_PARAMS[] = { { - .deviceType = AudioDeviceDescriptor::MIC, - .deviceFlag = AudioDeviceDescriptor::DeviceFlag::INPUT_DEVICES_FLAG, - .deviceRole = AudioDeviceDescriptor::DeviceRole::INPUT_DEVICE + .deviceType = DEVICE_TYPE_MIC, + .deviceFlag = INPUT_DEVICES_FLAG, + .deviceRole = INPUT_DEVICE }, { - .deviceType = AudioDeviceDescriptor::SPEAKER, - .deviceFlag = AudioDeviceDescriptor::DeviceFlag::OUTPUT_DEVICES_FLAG, - .deviceRole = AudioDeviceDescriptor::DeviceRole::OUTPUT_DEVICE + .deviceType = DEVICE_TYPE_SPEAKER, + .deviceFlag = OUTPUT_DEVICES_FLAG, + .deviceRole = OUTPUT_DEVICE } }; } // namespace @@ -448,9 +448,9 @@ class AudioPolicyGetDevicesTest : public AudioPolicyTest {}; HWTEST_P(AudioPolicyGetDevicesTest, GetDevices, TestSize.Level1) { PolicyParam params = GetParam(); - AudioDeviceDescriptor::DeviceFlag deviceFlag = params.deviceFlag; - AudioDeviceDescriptor::DeviceType deviceType = params.deviceType; - AudioDeviceDescriptor::DeviceRole deviceRole = params.deviceRole; + DeviceFlag deviceFlag = params.deviceFlag; + DeviceType deviceType = params.deviceType; + DeviceRole deviceRole = params.deviceRole; vector> audioDeviceDescriptors = AudioSystemManager::GetInstance()->GetDevices(deviceFlag); sptr audioDeviceDescriptor = audioDeviceDescriptors[0]; diff --git a/frameworks/kitsimpl/audio_capturer/src/audio_capturer_napi.cpp b/frameworks/kitsimpl/audio_capturer/src/audio_capturer_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbc3f20c962d8b2678253fe9bb4d95f61b6fd61a --- /dev/null +++ b/frameworks/kitsimpl/audio_capturer/src/audio_capturer_napi.cpp @@ -0,0 +1,588 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audio_capturer_napi.h" +#include "audio_manager_napi.h" +#include "audio_parameters_napi.h" +#include "hilog/log.h" + +#include "securec.h" + +using namespace std; +using OHOS::HiviewDFX::HiLog; +using OHOS::HiviewDFX::HiLogLabel; + +namespace OHOS { +namespace AudioStandard { +napi_ref AudioCapturerNapi::sConstructor_ = nullptr; +std::unique_ptr AudioCapturerNapi::sAudioParameters_ = nullptr; + +namespace { + const int ARGS_ONE = 1; + const int ARGS_TWO = 2; + + const int PARAM0 = 0; + const int PARAM1 = 1; + + const int ERROR = -1; + const int SUCCESS = 0; + + constexpr HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "AudioCapturerNapi"}; +} + +AudioCapturerNapi::AudioCapturerNapi() + : audioCapturer_(nullptr), env_(nullptr), wrapper_(nullptr) {} + +AudioCapturerNapi::~AudioCapturerNapi() +{ + if (wrapper_ != nullptr) { + napi_delete_reference(env_, wrapper_); + } +} + +void AudioCapturerNapi::Destructor(napi_env env, void *nativeObject, void *finalize_hint) +{ + if (nativeObject != nullptr) { + auto obj = static_cast(nativeObject); + delete obj; + } +} + +napi_value AudioCapturerNapi::Init(napi_env env, napi_value exports) +{ + napi_status status; + napi_value constructor; + napi_value result = nullptr; + const int32_t refCount = 1; + napi_get_undefined(env, &result); + + napi_property_descriptor audio_capturer_properties[] = { + DECLARE_NAPI_FUNCTION("setParams", SetParams), + DECLARE_NAPI_FUNCTION("getParams", GetParams), + DECLARE_NAPI_FUNCTION("start", Start), + DECLARE_NAPI_FUNCTION("read", Read), + DECLARE_NAPI_FUNCTION("getAudioTime", GetAudioTime), + DECLARE_NAPI_FUNCTION("stop", Stop), + DECLARE_NAPI_FUNCTION("release", Release), + DECLARE_NAPI_FUNCTION("getBufferSize", GetBufferSize) + }; + + napi_property_descriptor static_prop[] = { + DECLARE_NAPI_STATIC_FUNCTION("createAudioCapturer", CreateAudioCapturer) + }; + + status = napi_define_class(env, AUDIO_CAPTURER_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Construct, nullptr, + sizeof(audio_capturer_properties) / sizeof(audio_capturer_properties[PARAM0]), + audio_capturer_properties, &constructor); + if (status != napi_ok) { + return result; + } + + status = napi_create_reference(env, constructor, refCount, &sConstructor_); + if (status == napi_ok) { + status = napi_set_named_property(env, exports, AUDIO_CAPTURER_NAPI_CLASS_NAME.c_str(), constructor); + if (status == napi_ok) { + status = napi_define_properties(env, exports, + sizeof(static_prop) / sizeof(static_prop[PARAM0]), static_prop); + if (status == napi_ok) { + return exports; + } + } + } + + HiLog::Error(LABEL, "Failure in AudioCapturerNapi::Init()"); + + return result; +} + +static int32_t GetAudioStreamType(napi_env env, napi_value value) +{ + napi_status status; + int32_t streamType = AudioStreamType::STREAM_DEFAULT; + + status = napi_get_value_int32(env, value, &streamType); + if (status == napi_ok) { + switch (streamType) { + case AudioManagerNapi::RINGTONE: + streamType = AudioStreamType::STREAM_RING; + break; + case AudioManagerNapi::MEDIA: + case AudioManagerNapi::VOICE_ASSISTANT: + streamType = AudioStreamType::STREAM_MUSIC; + break; + case AudioManagerNapi::VOICE_CALL: + streamType = AudioStreamType::STREAM_VOICE_CALL; + break; + default: + streamType = AudioStreamType::STREAM_MUSIC; + break; + } + } + + return streamType; +} + +napi_value AudioCapturerNapi::Construct(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value jsThis = nullptr; + napi_value result = nullptr; + size_t argCount = 1; + napi_value args[1] = {0}; + + napi_get_undefined(env, &result); + status = napi_get_cb_info(env, info, &argCount, args, &jsThis, nullptr); + if (status != napi_ok) { + return result; + } + + int32_t streamType = GetAudioStreamType(env, args[0]); + HiLog::Info(LABEL, "AudioCapturerNapi: Audio stream type: %{public}d", streamType); + if (streamType != AudioStreamType::STREAM_DEFAULT) { + unique_ptr obj = make_unique(); + if (obj != nullptr) { + obj->env_ = env; + obj->audioCapturer_ + = AudioCapturer::Create(static_cast(streamType)); + obj->contentType_ = CONTENT_TYPE_MUSIC; + obj->streamUsage_ = STREAM_USAGE_MEDIA; + obj->deviceRole_ = INPUT_DEVICE; + obj->deviceType_ = DEVICE_TYPE_MIC; + status = napi_wrap(env, jsThis, static_cast(obj.get()), + AudioCapturerNapi::Destructor, nullptr, &(obj->wrapper_)); + if (status == napi_ok) { + obj.release(); + return jsThis; + } + } + } + + HiLog::Error(LABEL, "Failed in AudioCapturerNapi::Construct()!"); + + return result; +} + +napi_value AudioCapturerNapi::CreateAudioCapturer(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value constructor; + size_t argCount = 1; + napi_value args[1] = {0}; + + status = napi_get_cb_info(env, info, &argCount, args, nullptr, nullptr); + if (status != napi_ok || argCount != 1) { + HiLog::Error(LABEL, "Invalid arguments!"); + return nullptr; + } + + status = napi_get_reference_value(env, sConstructor_, &constructor); + if (status == napi_ok) { + status = napi_new_instance(env, constructor, argCount, args, &result); + if (status == napi_ok) { + return result; + } + } + + HiLog::Error(LABEL, "Create audio capturer failed"); + napi_get_undefined(env, &result); + + return result; +} + +int32_t AudioCapturerNapi::SetAudioParameters(napi_env env, napi_value arg) +{ + int32_t format; + int32_t channels; + int32_t samplingRate; + int32_t encoding; + int32_t contentType = static_cast(CONTENT_TYPE_MUSIC); + int32_t usage = static_cast(STREAM_USAGE_MEDIA); + int32_t deviceRole = static_cast(DEVICE_TYPE_MIC); + int32_t deviceType = static_cast(INPUT_DEVICE); + + napi_value property; + + if ((napi_get_named_property(env, arg, "format", &property) != napi_ok) + || napi_get_value_int32(env, property, &format) != napi_ok) { + HiLog::Error(LABEL, "Could not get the format argument!"); + return ERROR; + } + + if ((napi_get_named_property(env, arg, "channels", &property) != napi_ok) + || napi_get_value_int32(env, property, &channels) != napi_ok) { + HiLog::Error(LABEL, "Could not get the channels argument!"); + return ERROR; + } + + if ((napi_get_named_property(env, arg, "samplingRate", &property) != napi_ok) + || napi_get_value_int32(env, property, &samplingRate) != napi_ok) { + HiLog::Error(LABEL, "Could not get the samplingRate argument!"); + return ERROR; + } + + if ((napi_get_named_property(env, arg, "encoding", &property) != napi_ok) + || napi_get_value_int32(env, property, &encoding) != napi_ok) { + HiLog::Error(LABEL, "Could not get the encoding argument!"); + return ERROR; + } + + if ((napi_get_named_property(env, arg, "contentType", &property) != napi_ok) + || napi_get_value_int32(env, property, &contentType) != napi_ok) { + HiLog::Error(LABEL, "Could not get the contentType argument, set existing values"); + contentType = this->contentType_; + } + + if ((napi_get_named_property(env, arg, "usage", &property) != napi_ok) + || napi_get_value_int32(env, property, &usage) != napi_ok) { + HiLog::Error(LABEL, "Could not get the usage argument, set existing value"); + usage = this->streamUsage_; + } + + if ((napi_get_named_property(env, arg, "deviceRole", &property) != napi_ok) + || napi_get_value_int32(env, property, &deviceRole) != napi_ok) { + HiLog::Error(LABEL, "Could not get the device role argument, set existing value"); + deviceRole = this->deviceRole_; + } + + if ((napi_get_named_property(env, arg, "deviceType", &property) != napi_ok) + || napi_get_value_int32(env, property, &deviceType) != napi_ok) { + HiLog::Error(LABEL, "Could not get the device type argument, set existing value"); + deviceType = this->deviceType_; + } + + if (sAudioParameters_) { + sAudioParameters_.reset(); + } + + sAudioParameters_ = std::make_unique(); + sAudioParameters_->format = static_cast(format); + sAudioParameters_->channels = static_cast(channels); + sAudioParameters_->samplingRate = static_cast(samplingRate); + sAudioParameters_->encoding = static_cast(encoding); + sAudioParameters_->contentType = static_cast(contentType); + sAudioParameters_->usage = static_cast(usage); + sAudioParameters_->deviceRole = static_cast(deviceRole); + sAudioParameters_->deviceType = static_cast(deviceType); + + return SUCCESS; +} + +napi_value AudioCapturerNapi::SetParams(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + size_t argc = ARGS_ONE; + napi_value argv[ARGS_ONE] = {0}; + napi_get_undefined(env, &result); + + status = napi_get_cb_info(env, info, &argc, argv, &jsThis, nullptr); + if ((status != napi_ok) || (jsThis == nullptr) || (argc > ARGS_ONE)) { + HiLog::Error(LABEL, "Set params invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Set params failed!"); + return result; + } + + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[PARAM0], &valueType); + if (valueType != napi_object) { + HiLog::Error(LABEL, "invalid parameter type!"); + return result; + } + + int32_t ret = capturerNapi->SetAudioParameters(env, argv[PARAM0]); + if (ret == SUCCESS) { + AudioCapturerParams capturerParams; + capturerParams.audioSampleFormat = sAudioParameters_->format; + capturerParams.samplingRate = sAudioParameters_->samplingRate; + capturerParams.audioChannel = sAudioParameters_->channels; + capturerParams.audioEncoding = sAudioParameters_->encoding; + capturerNapi->contentType_ = sAudioParameters_->contentType; + capturerNapi->streamUsage_ = sAudioParameters_->usage; + capturerNapi->deviceRole_ = sAudioParameters_->deviceRole; + capturerNapi->deviceType_ = sAudioParameters_->deviceType; + capturerNapi->audioCapturer_->SetParams(capturerParams); + + HiLog::Info(LABEL, "Set params success"); + } + + return result; +} + +napi_value AudioCapturerNapi::GetParams(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get params invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer get params failed!"); + return result; + } + + AudioCapturerParams capturerParams; + if (capturerNapi->audioCapturer_->GetParams(capturerParams) == 0) { + unique_ptr audioParams = make_unique(); + audioParams->format = capturerParams.audioSampleFormat; + audioParams->samplingRate = capturerParams.samplingRate; + audioParams->channels = capturerParams.audioChannel; + audioParams->encoding = capturerParams.audioEncoding; + audioParams->contentType = capturerNapi->contentType_; + audioParams->usage = capturerNapi->streamUsage_; + audioParams->deviceRole = capturerNapi->deviceRole_; + audioParams->deviceType = capturerNapi->deviceType_; + + result = AudioParametersNapi::CreateAudioParametersWrapper(env, audioParams); + } + + return result; +} + +napi_value AudioCapturerNapi::Start(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Start invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer start failed!"); + return result; + } + + bool isStarted = capturerNapi->audioCapturer_->Start(); + napi_get_boolean(env, isStarted, &result); + + return result; +} + +napi_value AudioCapturerNapi::Read(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + size_t argc = ARGS_TWO; + napi_value argv[ARGS_TWO] = {0}; + napi_get_undefined(env, &result); + + status = napi_get_cb_info(env, info, &argc, argv, &jsThis, nullptr); + if ((status != napi_ok) || (jsThis == nullptr) || (argc != ARGS_TWO)) { + HiLog::Error(LABEL, "Read invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer read failed!"); + return result; + } + + uint32_t userSize = 0; + bool isBlocking = false; + + for (size_t i = PARAM0; i < argc; i++) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + + if ((i == PARAM0) && (valueType == napi_number)) { + napi_get_value_uint32(env, argv[i], &userSize); + if (userSize <= 0) { + return result; + } + } else if ((i == PARAM1) && (valueType == napi_boolean)) { + napi_get_value_bool(env, argv[i], &isBlocking); + } else { + HiLog::Error(LABEL, "Capturer read invalid param!"); + return result; + } + } + + uint8_t *buffer = (uint8_t *)malloc(userSize); + if (!buffer) { + HiLog::Error(LABEL, "Capturer read buffer allocation failed"); + return result; + } + + size_t bytesRead = 0; + while (bytesRead < userSize) { + int32_t len = capturerNapi->audioCapturer_->Read(*(buffer + bytesRead), userSize - bytesRead, isBlocking); + if (len >= 0) { + bytesRead += len; + } else { + bytesRead = len; + break; + } + } + + if (bytesRead > 0) { + uint8_t *native = nullptr; + napi_value arrayBuffer = nullptr; + napi_create_arraybuffer(env, bytesRead, reinterpret_cast(&native), &arrayBuffer); + if (!memcpy_s(native, bytesRead, buffer, bytesRead)) { + free(buffer); + HiLog::Info(LABEL, "Capturer read success"); + return arrayBuffer; + } + } + + free(buffer); + + return result; +} + +napi_value AudioCapturerNapi::GetAudioTime(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get audio time invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer release failed!"); + return result; + } + + Timestamp timestamp; + if (capturerNapi->audioCapturer_->GetAudioTime(timestamp, Timestamp::Timestampbase::MONOTONIC)) { + const uint64_t secToNanosecond = 1000000000; + uint64_t time = timestamp.time.tv_nsec + timestamp.time.tv_sec * secToNanosecond; + napi_create_int64(env, time, &result); + } + + return result; +} + +napi_value AudioCapturerNapi::Stop(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Stop invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer stop failed!"); + return result; + } + + bool isStopped = capturerNapi->audioCapturer_->Stop(); + napi_get_boolean(env, isStopped, &result); + + return result; +} + +napi_value AudioCapturerNapi::Release(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Release invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer release failed!"); + return result; + } + + bool isReleased = capturerNapi->audioCapturer_->Release(); + napi_get_boolean(env, isReleased, &result); + + return result; +} + +napi_value AudioCapturerNapi::GetBufferSize(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + napi_value jsThis = nullptr; + napi_get_undefined(env, &result); + + size_t argCount = 0; + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get buffer size invalid arguments"); + return result; + } + + AudioCapturerNapi *capturerNapi = nullptr; + status = napi_unwrap(env, jsThis, reinterpret_cast(&capturerNapi)); + if (status != napi_ok || (capturerNapi == nullptr)) { + HiLog::Error(LABEL, "Capturer release failed!"); + return result; + } + + size_t bufferSize; + int32_t ret = capturerNapi->audioCapturer_->GetBufferSize(bufferSize); + if (ret == SUCCESS) { + HiLog::Info(LABEL, "Capturer get buffer success"); + napi_create_int32(env, bufferSize, &result); + } + + return result; +} +} +} \ No newline at end of file diff --git a/frameworks/kitsimpl/audio_capturer/src/audio_parameters_napi.cpp b/frameworks/kitsimpl/audio_capturer/src/audio_parameters_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9355aa5f65b6ad4a6b69c8c95b2218f46177ffc --- /dev/null +++ b/frameworks/kitsimpl/audio_capturer/src/audio_parameters_napi.cpp @@ -0,0 +1,917 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audio_parameters_napi.h" +#include "hilog/log.h" + +using namespace std; +using OHOS::HiviewDFX::HiLog; +using OHOS::HiviewDFX::HiLogLabel; + +namespace OHOS { +namespace AudioStandard { +napi_ref AudioParametersNapi::sConstructor_ = nullptr; +unique_ptr AudioParametersNapi::sAudioParameters_ = nullptr; + +napi_ref AudioParametersNapi::sampleFormat_ = nullptr; +napi_ref AudioParametersNapi::audioChannel_ = nullptr; +napi_ref AudioParametersNapi::samplingRate_ = nullptr; +napi_ref AudioParametersNapi::encodingType_ = nullptr; +napi_ref AudioParametersNapi::contentType_ = nullptr; +napi_ref AudioParametersNapi::streamUsage_ = nullptr; +napi_ref AudioParametersNapi::deviceRole_ = nullptr; +napi_ref AudioParametersNapi::deviceType_ = nullptr; + +namespace { + constexpr HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "AudioParametersNapi"}; +} + +AudioParametersNapi::AudioParametersNapi() + : env_(nullptr), wrapper_(nullptr) { +} + +AudioParametersNapi::~AudioParametersNapi() +{ + if (wrapper_ != nullptr) { + napi_delete_reference(env_, wrapper_); + } + audioParameters_ = nullptr; +} + +void AudioParametersNapi::Destructor(napi_env env, void *nativeObject, void *finalize_hint) +{ + if (nativeObject != nullptr) { + auto obj = static_cast(nativeObject); + delete obj; + } +} + +napi_status AudioParametersNapi::AddNamedProperty(napi_env env, napi_value object, + const std::string name, int32_t enumValue) +{ + napi_status status; + napi_value enumNapiValue; + + status = napi_create_int32(env, enumValue, &enumNapiValue); + if (status == napi_ok) { + status = napi_set_named_property(env, object, name.c_str(), enumNapiValue); + } + + return status; +} + +napi_value AudioParametersNapi::CreateAudioSampleFormatObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: sampleFormatMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &sampleFormat_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateAudioSampleFormatObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateAudioChannelObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: audioChannelMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &audioChannel_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateAudioChannelObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateSamplingRateObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: samplingRateMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &samplingRate_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateSamplingRateObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateEncodingTypeObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: encodingTypeMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &encodingType_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateEncodingTypeObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateContentTypeObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: contentTypeMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &contentType_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateContentTypeObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateStreamUsageObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: streamUsageMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &streamUsage_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateStreamUsageObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateDeviceRoleObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: deviceRoleMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &deviceRole_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateDeviceRoleObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::CreateDeviceTypeObject(napi_env env) +{ + napi_value result = nullptr; + napi_status status; + std::string propName; + + status = napi_create_object(env, &result); + if (status == napi_ok) { + for (auto &iter: deviceTypeMap) { + propName = iter.first; + status = AddNamedProperty(env, result, propName, iter.second); + if (status != napi_ok) { + HiLog::Error(LABEL, "Failed to add named prop!"); + break; + } + propName.clear(); + } + if (status == napi_ok) { + status = napi_create_reference(env, result, REFERENCE_CREATION_COUNT, &deviceType_); + if (status == napi_ok) { + return result; + } + } + } + HiLog::Error(LABEL, "CreateDeviceRoleObject is Failed!"); + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::Init(napi_env env, napi_value exports) +{ + HiLog::Info(LABEL, "AudioParametersNapi::Init()"); + napi_status status; + napi_value constructor; + napi_value result = nullptr; + napi_get_undefined(env, &result); + + napi_property_descriptor audio_parameters_properties[] = { + DECLARE_NAPI_GETTER_SETTER("format", GetAudioSampleFormat, SetAudioSampleFormat), + DECLARE_NAPI_GETTER_SETTER("channels", GetAudioChannel, SetAudioChannel), + DECLARE_NAPI_GETTER_SETTER("samplingRate", GetAudioSamplingRate, SetAudioSamplingRate), + DECLARE_NAPI_GETTER_SETTER("encoding", GetAudioEncodingType, SetAudioEncodingType), + DECLARE_NAPI_GETTER_SETTER("contentType", GetContentType, SetContentType), + DECLARE_NAPI_GETTER_SETTER("usage", GetStreamUsage, SetStreamUsage), + DECLARE_NAPI_GETTER_SETTER("deviceRole", GetDeviceRole, SetDeviceRole), + DECLARE_NAPI_GETTER_SETTER("deviceType", GetDeviceType, SetDeviceType) + }; + + napi_property_descriptor static_prop[] = { + DECLARE_NAPI_PROPERTY("AudioSampleFormat", CreateAudioSampleFormatObject(env)), + DECLARE_NAPI_PROPERTY("AudioChannel", CreateAudioChannelObject(env)), + DECLARE_NAPI_PROPERTY("AudioSamplingRate", CreateSamplingRateObject(env)), + DECLARE_NAPI_PROPERTY("AudioEncodingType", CreateEncodingTypeObject(env)), + DECLARE_NAPI_PROPERTY("ContentType", CreateContentTypeObject(env)), + DECLARE_NAPI_PROPERTY("StreamUsage", CreateStreamUsageObject(env)), + DECLARE_NAPI_PROPERTY("DeviceRole", CreateDeviceRoleObject(env)), + DECLARE_NAPI_PROPERTY("DeviceType", CreateDeviceTypeObject(env)) + }; + + status = napi_define_class(env, AUDIO_PARAMETERS_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Construct, + nullptr, sizeof(audio_parameters_properties) / sizeof(audio_parameters_properties[0]), + audio_parameters_properties, &constructor); + if (status != napi_ok) { + return result; + } + + status = napi_create_reference(env, constructor, REFERENCE_CREATION_COUNT, &sConstructor_); + if (status == napi_ok) { + status = napi_set_named_property(env, exports, AUDIO_PARAMETERS_NAPI_CLASS_NAME.c_str(), + constructor); + if (status == napi_ok) { + status = napi_define_properties(env, exports, + sizeof(static_prop) / sizeof(static_prop[0]), static_prop); + if (status == napi_ok) { + return exports; + } + } + } + HiLog::Error(LABEL, "Failure in AudioParametersNapi::Init()"); + + return result; +} + +napi_value AudioParametersNapi::Construct(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value jsThis = nullptr; + size_t argCount = 0; + + status = napi_get_cb_info(env, info, &argCount, nullptr, &jsThis, nullptr); + if (status == napi_ok) { + unique_ptr obj = make_unique(); + if (obj != nullptr) { + obj->env_ = env; + obj->audioParameters_ = move(sAudioParameters_); + status = napi_wrap(env, jsThis, static_cast(obj.get()), + AudioParametersNapi::Destructor, nullptr, &(obj->wrapper_)); + if (status == napi_ok) { + obj.release(); + return jsThis; + } + } + } + HiLog::Error(LABEL, "Failed in AudioParametersNapi::Construct()!"); + napi_get_undefined(env, &jsThis); + + return jsThis; +} + +napi_value AudioParametersNapi::CreateAudioParametersWrapper(napi_env env, unique_ptr &audioParameters) +{ + napi_status status; + napi_value result = nullptr; + napi_value constructor; + + if (audioParameters != nullptr) { + status = napi_get_reference_value(env, sConstructor_, &constructor); + if (status == napi_ok) { + sAudioParameters_ = move(audioParameters); + status = napi_new_instance(env, constructor, 0, nullptr, &result); + sAudioParameters_.release(); + if (status == napi_ok) { + return result; + } + } + HiLog::Error(LABEL, "Failed in CreateAudioParametersWrapper, %{public}d", status); + } + + napi_get_undefined(env, &result); + + return result; +} + +napi_value AudioParametersNapi::GetAudioSampleFormat(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + AudioSampleFormat audioSampleFormat; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get audio sample format fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + audioSampleFormat = audioParametersNapi->audioParameters_->format; + status = napi_create_int32(env, audioSampleFormat, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetAudioSampleFormat(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t audioSampleFormat; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set sample format fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set sample format fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &audioSampleFormat); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->format = static_cast(audioSampleFormat); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetAudioChannel(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + AudioChannel audioChannel; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get audio channels fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + audioChannel = audioParametersNapi->audioParameters_->channels; + status = napi_create_int32(env, audioChannel, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetAudioChannel(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t audioChannel; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set audio channel fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set audio channel fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &audioChannel); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->channels = static_cast(audioChannel); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetAudioSamplingRate(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + AudioSamplingRate samplingRate; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get sampling rate fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + samplingRate = audioParametersNapi->audioParameters_->samplingRate; + status = napi_create_int32(env, samplingRate, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetAudioSamplingRate(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t samplingRate; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set sampling rate fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set sampling rate fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &samplingRate); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->samplingRate = static_cast(samplingRate); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetAudioEncodingType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + AudioEncodingType encodingType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get encoding type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + encodingType = audioParametersNapi->audioParameters_->encoding; + status = napi_create_int32(env, encodingType, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetAudioEncodingType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t encodingType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set audio encoding type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set audio encoding type fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &encodingType); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->encoding = static_cast(encodingType); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetContentType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + ContentType contentType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get content type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + contentType = audioParametersNapi->audioParameters_->contentType; + status = napi_create_int32(env, contentType, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetContentType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t contentType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set content type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set content type fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &contentType); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->contentType = static_cast(contentType); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetStreamUsage(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + StreamUsage usage; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get stream usage fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + usage = audioParametersNapi->audioParameters_->usage; + status = napi_create_int32(env, usage, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetStreamUsage(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t usage; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set stream usage fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set stream usage fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &usage); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->usage = static_cast(usage); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetDeviceRole(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + DeviceRole deviceRole; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get device role fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + deviceRole = audioParametersNapi->audioParameters_->deviceRole; + status = napi_create_int32(env, deviceRole, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetDeviceRole(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t deviceRole; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set device role fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set device role fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &deviceRole); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->deviceRole = static_cast(deviceRole); + } + + return jsResult; +} + +napi_value AudioParametersNapi::GetDeviceType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 0; + napi_value jsThis = nullptr; + DeviceType deviceType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, nullptr, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr) { + HiLog::Error(LABEL, "Get device type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + deviceType = audioParametersNapi->audioParameters_->deviceType; + HiLog::Info(LABEL, "get device type: %d", deviceType); + status = napi_create_int32(env, deviceType, &jsResult); + if (status == napi_ok) { + return jsResult; + } + } + + return jsResult; +} + +napi_value AudioParametersNapi::SetDeviceType(napi_env env, napi_callback_info info) +{ + napi_status status; + AudioParametersNapi *audioParametersNapi = nullptr; + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_value jsThis = nullptr; + int32_t deviceType; + napi_value jsResult = nullptr; + napi_get_undefined(env, &jsResult); + + status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr); + if (status != napi_ok || jsThis == nullptr || args[0] == nullptr) { + HiLog::Error(LABEL, "set device type fail to napi_get_cb_info"); + return jsResult; + } + + status = napi_unwrap(env, jsThis, (void **)&audioParametersNapi); + if (status == napi_ok) { + napi_valuetype valueType = napi_undefined; + if (napi_typeof(env, args[0], &valueType) != napi_ok || valueType != napi_number) { + HiLog::Error(LABEL, "set device type fail: wrong data type"); + return jsResult; + } + } + + status = napi_get_value_int32(env, args[0], &deviceType); + if (status == napi_ok) { + audioParametersNapi->audioParameters_->deviceType = static_cast(deviceType); + HiLog::Info(LABEL, "set device type: %d", audioParametersNapi->audioParameters_->deviceType); + } + + return jsResult; +} +} +} \ No newline at end of file diff --git a/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp b/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp index 02d7d6e7a46abf0163c30c1e825908555c03fb58..63e1daf4a4e7ff34749685e78917e934c69475ee 100644 --- a/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp +++ b/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp @@ -136,7 +136,7 @@ napi_value AudioDeviceDescriptorNapi::GetDeviceRole(napi_env env, napi_callback_ AudioDeviceDescriptorNapi* deviceDescriptor = nullptr; size_t argc = 0; napi_value thisVar = nullptr; - AudioDeviceDescriptor::DeviceRole deviceRole; + DeviceRole deviceRole; napi_value jsResult = nullptr; napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); @@ -158,7 +158,7 @@ napi_value AudioDeviceDescriptorNapi::GetDeviceType(napi_env env, napi_callback_ napi_status status; size_t argc = 0; napi_value thisVar = nullptr; - AudioDeviceDescriptor::DeviceType deviceType; + DeviceType deviceType; napi_value jsResult = nullptr; AudioDeviceDescriptorNapi* deviceDescriptor = nullptr; diff --git a/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp b/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp index e67cc4fff746e599880a8475ffc10c1868d4ceaa..f89b0dc77afb58d97aa8f789fc7d8e346ea892f2 100644 --- a/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp +++ b/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp @@ -13,8 +13,10 @@ * limitations under the License. */ -#include "audio_manager_napi.h" +#include "audio_capturer_napi.h" #include "audio_device_descriptor_napi.h" +#include "audio_manager_napi.h" +#include "audio_parameters_napi.h" #include "hilog/log.h" using namespace std; @@ -175,7 +177,7 @@ napi_value AudioManagerNapi::CreateAudioVolumeTypeObject(napi_env env) status = napi_create_object(env, &result); if (status == napi_ok) { - for (int i = AudioManagerNapi::RINGTONE; i <= AudioManagerNapi::MEDIA; i++) { + for (int i = AudioManagerNapi::RINGTONE; i <= AudioManagerNapi::VOICE_ASSISTANT; i++) { switch (i) { case AudioManagerNapi::RINGTONE: propName = "RINGTONE"; @@ -183,6 +185,12 @@ napi_value AudioManagerNapi::CreateAudioVolumeTypeObject(napi_env env) case AudioManagerNapi::MEDIA: propName = "MEDIA"; break; + case AudioManagerNapi::VOICE_CALL: + propName = "VOICE_CALL"; + break; + case AudioManagerNapi::VOICE_ASSISTANT: + propName = "VOICE_ASSISTANT"; + break; default: HiLog::Error(LABEL, "Invalid prop!"); continue; @@ -216,15 +224,15 @@ napi_value AudioManagerNapi::CreateDeviceFlagObject(napi_env env) status = napi_create_object(env, &result); if (status == napi_ok) { - for (int i = AudioDeviceDescriptor::DEVICE_FLAG_NONE + 1; i < AudioDeviceDescriptor::DEVICE_FLAG_MAX; i++) { + for (int i = DEVICE_FLAG_NONE + 1; i < DEVICE_FLAG_MAX; i++) { switch (i) { - case AudioDeviceDescriptor::OUTPUT_DEVICES_FLAG: + case OUTPUT_DEVICES_FLAG: propName = "OUTPUT_DEVICES_FLAG"; break; - case AudioDeviceDescriptor::INPUT_DEVICES_FLAG: + case INPUT_DEVICES_FLAG: propName = "INPUT_DEVICES_FLAG"; break; - case AudioDeviceDescriptor::ALL_DEVICES_FLAG: + case ALL_DEVICES_FLAG: propName = "ALL_DEVICES_FLAG"; break; default: @@ -260,12 +268,12 @@ napi_value AudioManagerNapi::CreateDeviceRoleObject(napi_env env) status = napi_create_object(env, &result); if (status == napi_ok) { - for (int i = AudioDeviceDescriptor::DEVICE_ROLE_NONE + 1; i < AudioDeviceDescriptor::DEVICE_ROLE_MAX; i++) { + for (int i = DEVICE_ROLE_NONE + 1; i < DEVICE_ROLE_MAX; i++) { switch (i) { - case AudioDeviceDescriptor::INPUT_DEVICE: + case INPUT_DEVICE: propName = "INPUT_DEVICE"; break; - case AudioDeviceDescriptor::OUTPUT_DEVICE: + case OUTPUT_DEVICE: propName = "OUTPUT_DEVICE"; break; default: @@ -301,27 +309,27 @@ napi_value AudioManagerNapi::CreateDeviceTypeObject(napi_env env) status = napi_create_object(env, &result); if (status == napi_ok) { - for (int i = AudioDeviceDescriptor::DEVICE_TYPE_NONE + 1; i < AudioDeviceDescriptor::DEVICE_TYPE_MAX; i++) { + for (int i = DEVICE_TYPE_NONE + 1; i < DEVICE_TYPE_MAX; i++) { switch (i) { - case AudioDeviceDescriptor::INVALID: + case DEVICE_TYPE_INVALID: propName = "INVALID"; break; - case AudioDeviceDescriptor::EARPIECE: + case DEVICE_TYPE_EARPIECE: propName = "EARPIECE"; break; - case AudioDeviceDescriptor::SPEAKER: + case DEVICE_TYPE_SPEAKER: propName = "SPEAKER"; break; - case AudioDeviceDescriptor::WIRED_HEADSET: + case DEVICE_TYPE_WIRED_HEADSET: propName = "WIRED_HEADSET"; break; - case AudioDeviceDescriptor::BLUETOOTH_SCO: + case DEVICE_TYPE_BLUETOOTH_SCO: propName = "BLUETOOTH_SCO"; break; - case AudioDeviceDescriptor::BLUETOOTH_A2DP: + case DEVICE_TYPE_BLUETOOTH_A2DP: propName = "BLUETOOTH_A2DP"; break; - case AudioDeviceDescriptor::MIC: + case DEVICE_TYPE_MIC: propName = "MIC"; break; default: @@ -1639,7 +1647,7 @@ napi_value AudioManagerNapi::GetDevices(napi_env env, napi_callback_info info) [](napi_env env, void *data) { auto context = static_cast(data); context->deviceDescriptors = context->objectInfo->audioMngr_->GetDevices( - static_cast(context->deviceFlag)); + static_cast(context->deviceFlag)); context->status = 0; }, GetDevicesAsyncCallbackComplete, static_cast(asyncContext.get()), &asyncContext->work); @@ -1662,6 +1670,9 @@ static napi_value Init(napi_env env, napi_value exports) { AudioManagerNapi::Init(env, exports); AudioDeviceDescriptorNapi::Init(env, exports); + AudioCapturerNapi::Init(env, exports); + AudioParametersNapi::Init(env, exports); + return exports; } diff --git a/interfaces/innerkits/native/audioadapter/include/audio_service_adapter.h b/interfaces/innerkits/native/audioadapter/include/audio_service_adapter.h index e1ae1b1dee018b0703e0a8c8d9c01e2520d86aa8..8a11dc7b9a6f3d008287de7ddccd47df208db399 100644 --- a/interfaces/innerkits/native/audioadapter/include/audio_service_adapter.h +++ b/interfaces/innerkits/native/audioadapter/include/audio_service_adapter.h @@ -33,6 +33,8 @@ public: * @return Returns volume level in float */ virtual float OnGetVolumeCb(std::string streamType) = 0; + + virtual ~AudioServiceAdapterCallback() {}; }; class AudioServiceAdapter { @@ -43,7 +45,7 @@ public: * @param cb callback reference for AudioServiceAdapterCallback class * @return Returns instance of class that extends AudioServiceAdapter */ - static std::unique_ptr CreateAudioAdapter(AudioServiceAdapterCallback *cb); + static std::unique_ptr CreateAudioAdapter(std::unique_ptr cb); /** * @brief Connect to underlining audio server @@ -62,7 +64,7 @@ public: * @return Returns module index if module loaded sucessfully; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t OpenAudioPort(char *audioPortName, std::string moduleArgs) = 0; + virtual int32_t OpenAudioPort(std::string audioPortName, std::string moduleArgs) = 0; /** * @brief closes/unloads the audio modules loaded. diff --git a/interfaces/innerkits/native/audiocommon/include/audio_info.h b/interfaces/innerkits/native/audiocommon/include/audio_info.h index 3a9a6583e313b44c0289270658d168651a53e87d..143988c3eeb409ad335b46bd56023669e15229cf 100644 --- a/interfaces/innerkits/native/audiocommon/include/audio_info.h +++ b/interfaces/innerkits/native/audiocommon/include/audio_info.h @@ -24,6 +24,87 @@ namespace OHOS { namespace AudioStandard { +enum DeviceFlag { + /** + * Device flag none. + */ + DEVICE_FLAG_NONE = -1, + /** + * Indicates all output audio devices. + */ + OUTPUT_DEVICES_FLAG = 1, + /** + * Indicates all input audio devices. + */ + INPUT_DEVICES_FLAG = 2, + /** + * Indicates all audio devices. + */ + ALL_DEVICES_FLAG = 3, + /** + * Device flag max count. + */ + DEVICE_FLAG_MAX +}; + +enum DeviceRole { + /** + * Device role none. + */ + DEVICE_ROLE_NONE = -1, + /** + * Input device role. + */ + INPUT_DEVICE = 1, + /** + * Output device role. + */ + OUTPUT_DEVICE = 2, + /** + * Device role max count. + */ + DEVICE_ROLE_MAX +}; + +enum DeviceType { + /** + * Indicates device type none. + */ + DEVICE_TYPE_NONE = -1, + /** + * Indicates invalid device + */ + DEVICE_TYPE_INVALID = 0, + /** + * Indicates earpiece + */ + DEVICE_TYPE_EARPIECE = 1, + /** + * Indicates a speaker built in a device. + */ + DEVICE_TYPE_SPEAKER = 2, + /** + * Indicates a headset, which is the combination of a pair of headphones and a microphone. + */ + DEVICE_TYPE_WIRED_HEADSET = 3, + /** + * Indicates a Bluetooth device used for telephony. + */ + DEVICE_TYPE_BLUETOOTH_SCO = 7, + /** + * Indicates a Bluetooth device supporting the Advanced Audio Distribution Profile (A2DP). + */ + DEVICE_TYPE_BLUETOOTH_A2DP = 8, + /** + * Indicates a microphone built in a device. + */ + DEVICE_TYPE_MIC = 15, + /** + * Indicates device type max count. + */ + DEVICE_TYPE_MAX +}; + enum ActiveDeviceType { ACTIVE_DEVICE_TYPE_NONE = -1, SPEAKER = 2, @@ -37,53 +118,57 @@ enum AudioStreamType { */ STREAM_DEFAULT = -1, /** - * Indicates audio streams media. + * Indicates audio streams for system sounds. */ - STREAM_MEDIA = 0, + STREAM_SYSTEM = 0, /** - * Indicates audio streams of voices in calls. + * Indicates audio streams for music playback. */ - STREAM_VOICE_CALL = 1, + STREAM_MUSIC = 1, /** - * Indicates audio streams for system sounds. + * Indicates audio streams for ringtones. */ - STREAM_SYSTEM = 2, + STREAM_RING = 2, /** - * Indicates audio streams for ringtones. + * Indicates audio streams media. */ - STREAM_RING = 3, + STREAM_MEDIA = 3, /** - * Indicates audio streams for music playback. + * Indicates audio streams of voices in calls. */ - STREAM_MUSIC = 4, + STREAM_VOICE_CALL = 4, + /** + * Indicates Audio streams for voice assistant + */ + VOICE_ASSISTANT = 5, /** * Indicates audio streams for alarms. */ - STREAM_ALARM = 5, + STREAM_ALARM = 6, /** * Indicates audio streams for notifications. */ - STREAM_NOTIFICATION = 6, + STREAM_NOTIFICATION = 7, /** * Indicates audio streams for voice calls routed through a connected Bluetooth device. */ - STREAM_BLUETOOTH_SCO = 7, + STREAM_BLUETOOTH_SCO = 8, /** * Indicates audio streams for enforced audible. */ - STREAM_ENFORCED_AUDIBLE = 8, + STREAM_ENFORCED_AUDIBLE = 9, /** * Indicates audio streams for dual-tone multi-frequency (DTMF) tones. */ - STREAM_DTMF = 9, + STREAM_DTMF = 10, /** * Indicates audio streams exclusively transmitted through the speaker (text-to-speech) of a device. */ - STREAM_TTS = 10, + STREAM_TTS = 11, /** * Indicates audio streams used for prompts in terms of accessibility. */ - STREAM_ACCESSIBILITY = 11 + STREAM_ACCESSIBILITY = 12 }; enum AudioEncodingType { @@ -171,6 +256,38 @@ struct AudioStreamParams { uint8_t channels; }; +/** +* Enumerates the audio content type. +*/ +enum ContentType { + CONTENT_TYPE_UNKNOWN = 0, + CONTENT_TYPE_SPEECH = 1, + CONTENT_TYPE_MUSIC = 2, + CONTENT_TYPE_MOVIE = 3, + CONTENT_TYPE_SONIFICATION = 4, +}; + +/** +* Enumerates the stream usage. +*/ +enum StreamUsage { + STREAM_USAGE_UNKNOWN = 0, + STREAM_USAGE_MEDIA = 1, + STREAM_USAGE_VOICE_COMMUNICATION = 2, + STREAM_USAGE_NOTIFICATION_RINGTONE = 3, +}; + +struct AudioParameters { + AudioSampleFormat format; + AudioChannel channels; + AudioSamplingRate samplingRate; + AudioEncodingType encoding; + ContentType contentType; + StreamUsage usage; + DeviceRole deviceRole; + DeviceType deviceType; +}; + // Supported audio parameters for both renderer and capturer const std::vector AUDIO_SUPPORTED_FORMATS { SAMPLE_U8, diff --git a/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h b/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h index ac16359ef0c9dda57952709dcd6d7ce76eb8969e..7cc47e7991416016e1930befaac7cdcffbeb93c5 100644 --- a/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h +++ b/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h @@ -27,87 +27,6 @@ class AudioDeviceDescriptor; class AudioDeviceDescriptor : public Parcelable { friend class AudioSystemManager; public: -enum DeviceFlag { - /** - * Device flag none. - */ - DEVICE_FLAG_NONE = -1, - /** - * Indicates all output audio devices. - */ - OUTPUT_DEVICES_FLAG = 1, - /** - * Indicates all input audio devices. - */ - INPUT_DEVICES_FLAG = 2, - /** - * Indicates all audio devices. - */ - ALL_DEVICES_FLAG = 3, - /** - * Device flag max count. - */ - DEVICE_FLAG_MAX -}; - -enum DeviceRole { - /** - * Device role none. - */ - DEVICE_ROLE_NONE = -1, - /** - * Input device role. - */ - INPUT_DEVICE = 1, - /** - * Output device role. - */ - OUTPUT_DEVICE = 2, - /** - * Device role max count. - */ - DEVICE_ROLE_MAX -}; - -enum DeviceType { - /** - * Indicates device type none. - */ - DEVICE_TYPE_NONE = -1, - /** - * Indicates invalid device - */ - INVALID = 0, - /** - * Indicates earpiece - */ - EARPIECE = 1, - /** - * Indicates a speaker built in a device. - */ - SPEAKER = 2, - /** - * Indicates a headset, which is the combination of a pair of headphones and a microphone. - */ - WIRED_HEADSET = 3, - /** - * Indicates a Bluetooth device used for telephony. - */ - BLUETOOTH_SCO = 7, - /** - * Indicates a Bluetooth device supporting the Advanced Audio Distribution Profile (A2DP). - */ - BLUETOOTH_A2DP = 8, - /** - * Indicates a microphone built in a device. - */ - MIC = 15, - /** - * Indicates device type max count. - */ - DEVICE_TYPE_MAX -}; - DeviceType getType(); DeviceRole getRole(); DeviceType deviceType_; @@ -115,7 +34,7 @@ enum DeviceType { AudioDeviceDescriptor(); virtual ~AudioDeviceDescriptor(); bool Marshalling(Parcel &parcel) const override; - static AudioDeviceDescriptor* Unmarshalling(Parcel &parcel); + static AudioDeviceDescriptor *Unmarshalling(Parcel &parcel); }; /** @@ -125,49 +44,66 @@ enum DeviceType { class AudioSystemManager { public: -enum AudioVolumeType { + enum AudioVolumeType { /** - * Indicates audio streams of voices in calls. + * Indicates audio streams default. */ - STREAM_VOICE_CALL = 1, + STREAM_DEFAULT = -1, /** * Indicates audio streams for system sounds. */ - STREAM_SYSTEM = 2, + STREAM_SYSTEM = 0, + /** + * Indicates audio streams for music playback. + */ + STREAM_MUSIC = 1, /** * Indicates audio streams for ringtones. */ - STREAM_RING = 3, + STREAM_RING = 2, /** - * Indicates audio streams for music playback. + * Indicates audio streams media. */ - STREAM_MUSIC = 4, + STREAM_MEDIA = 3, + /** + * Indicates audio streams of voices in calls. + */ + STREAM_VOICE_CALL = 4, + /** + * Indicates Audio streams for voice assistant + */ + VOICE_ASSISTANT = 5, /** * Indicates audio streams for alarms. */ - STREAM_ALARM = 5, + STREAM_ALARM = 6, /** * Indicates audio streams for notifications. */ - STREAM_NOTIFICATION = 6, + STREAM_NOTIFICATION = 7, /** * Indicates audio streams for voice calls routed through a connected Bluetooth device. */ - STREAM_BLUETOOTH_SCO = 7, + STREAM_BLUETOOTH_SCO = 8, + /** + * Indicates audio streams for enforced audible. + */ + STREAM_ENFORCED_AUDIBLE = 9, /** * Indicates audio streams for dual-tone multi-frequency (DTMF) tones. */ - STREAM_DTMF = 8, + STREAM_DTMF = 10, /** * Indicates audio streams exclusively transmitted through the speaker (text-to-speech) of a device. */ - STREAM_TTS = 9, + STREAM_TTS = 11, /** * Indicates audio streams used for prompts in terms of accessibility. */ - STREAM_ACCESSIBILITY = 10 + STREAM_ACCESSIBILITY = 12 }; - static AudioSystemManager* GetInstance(); + + static AudioSystemManager *GetInstance(); static float MapVolumeToHDI(int32_t volume); static int32_t MapVolumeFromHDI(float volume); int32_t SetVolume(AudioSystemManager::AudioVolumeType volumeType, int32_t volume) const; @@ -178,7 +114,7 @@ enum AudioVolumeType { bool IsStreamMute(AudioSystemManager::AudioVolumeType volumeType) const; int32_t SetMicrophoneMute(bool isMute) const; bool IsMicrophoneMute(void) const; - std::vector> GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) const; + std::vector> GetDevices(DeviceFlag deviceFlag) const; const std::string GetAudioParameter(const std::string key) const; void SetAudioParameter(const std::string key, const std::string value) const; int32_t SetDeviceActive(ActiveDeviceType deviceType, bool flag) const; diff --git a/interfaces/innerkits/native/audiopolicy/include/audio_policy_manager.h b/interfaces/innerkits/native/audiopolicy/include/audio_policy_manager.h index 3386122b3412ca5b93d0264af4a141486750cc4a..b80178690e47a738296357c47669c0afb1e68915 100644 --- a/interfaces/innerkits/native/audiopolicy/include/audio_policy_manager.h +++ b/interfaces/innerkits/native/audiopolicy/include/audio_policy_manager.h @@ -22,7 +22,7 @@ namespace OHOS { namespace AudioStandard { -using InternalDeviceType = AudioDeviceDescriptor::DeviceType; +using InternalDeviceType = DeviceType; class AudioPolicyManager { public: diff --git a/interfaces/innerkits/native/audiosession/include/audio_session.h b/interfaces/innerkits/native/audiosession/include/audio_session.h index 08b32e9b00bc9e41dce56bd702203cc2e8064326..50c9c58e998841d88723b01a7653033191ce4711 100644 --- a/interfaces/innerkits/native/audiosession/include/audio_session.h +++ b/interfaces/innerkits/native/audiosession/include/audio_session.h @@ -33,18 +33,18 @@ class AudioSession : public AudioServiceClient { public: uint32_t GetSessionID(); - AudioDevDescriptor* GetActiveAudioSinkDevice(uint32_t sessionID); - AudioDevDescriptor* GetActiveAudioSourceDevice(uint32_t sessionID); + AudioDevDescriptor *GetActiveAudioSinkDevice(uint32_t sessionID); + AudioDevDescriptor *GetActiveAudioSourceDevice(uint32_t sessionID); - bool SetActiveAudioSinkDevice(uint32_t sessionID, const AudioDevDescriptor& audioDesc); - bool SetActiveAudioSourceDevice(uint32_t sessionID, const AudioDevDescriptor& audioDesc); + bool SetActiveAudioSinkDevice(uint32_t sessionID, const AudioDevDescriptor &audioDesc); + bool SetActiveAudioSourceDevice(uint32_t sessionID, const AudioDevDescriptor &audioDesc); float GetAudioStreamVolume(uint32_t sessionID); float GetAudioDeviceVolume(uint32_t sessionID); bool SetAudioStreamVolume(uint32_t sessionID, float volume); bool SetAudioDeviceVolume(uint32_t sessionID, float volume); private: - AudioSession* CreateSession(SessionType eSession); + AudioSession *CreateSession(SessionType eSession); }; } // namespace AudioStandard } // namespace OHOS diff --git a/interfaces/kits/js/audio_capturer/include/audio_capturer_napi.h b/interfaces/kits/js/audio_capturer/include/audio_capturer_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..f853674754ba3196558f2c0b84ffed0240193489 --- /dev/null +++ b/interfaces/kits/js/audio_capturer/include/audio_capturer_napi.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AUDIO_CAPTURER_NAPI_H_ +#define AUDIO_CAPTURER_NAPI_H_ + +#include + +#include "audio_capturer.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AudioStandard { +static const std::string AUDIO_CAPTURER_NAPI_CLASS_NAME = "AudioCapturer"; + +class AudioCapturerNapi { +public: + AudioCapturerNapi(); + ~AudioCapturerNapi(); + + static napi_value Init(napi_env env, napi_value exports); +private: + static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); + static napi_value Construct(napi_env env, napi_callback_info info); + static napi_value CreateAudioCapturer(napi_env env, napi_callback_info info); + static napi_value SetParams(napi_env env, napi_callback_info info); + static napi_value GetParams(napi_env env, napi_callback_info info); + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value Read(napi_env env, napi_callback_info info); + static napi_value GetAudioTime(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static napi_value Release(napi_env env, napi_callback_info info); + static napi_value GetBufferSize(napi_env env, napi_callback_info info); + + static napi_ref sConstructor_; + static std::unique_ptr sAudioParameters_; + + int32_t SetAudioParameters(napi_env env, napi_value arg); + + std::unique_ptr audioCapturer_; + ContentType contentType_; + StreamUsage streamUsage_; + DeviceRole deviceRole_; + DeviceType deviceType_; + napi_env env_; + napi_ref wrapper_; +}; +} +} +#endif /* AUDIO_CAPTURER_NAPI_H_ */ \ No newline at end of file diff --git a/interfaces/kits/js/audio_capturer/include/audio_parameters_napi.h b/interfaces/kits/js/audio_capturer/include/audio_parameters_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..78e8472403ac633cd798cb7c6d68c090a86f5758 --- /dev/null +++ b/interfaces/kits/js/audio_capturer/include/audio_parameters_napi.h @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AUDIO_PARAMETERS_NAPI_H_ +#define AUDIO_PARAMETERS_NAPI_H_ + +#include +#include + +#include "audio_info.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AudioStandard { +static const std::string AUDIO_PARAMETERS_NAPI_CLASS_NAME = "AudioParameters"; + +static const std::int32_t REFERENCE_CREATION_COUNT = 1; + +static const std::map sampleFormatMap = { + {"SAMPLE_U8", SAMPLE_U8}, + {"SAMPLE_S16LE", SAMPLE_S16LE}, + {"SAMPLE_S24LE", SAMPLE_S24LE}, + {"SAMPLE_S32LE", SAMPLE_S32LE}, + {"INVALID_WIDTH", INVALID_WIDTH} +}; + +static const std::map audioChannelMap = { + {"MONO", MONO}, + {"STEREO", STEREO} +}; + +static const std::map samplingRateMap = { + {"SAMPLE_RATE_8000", SAMPLE_RATE_8000}, + {"SAMPLE_RATE_11025", SAMPLE_RATE_11025}, + {"SAMPLE_RATE_12000", SAMPLE_RATE_12000}, + {"SAMPLE_RATE_16000", SAMPLE_RATE_16000}, + {"SAMPLE_RATE_22050", SAMPLE_RATE_22050}, + {"SAMPLE_RATE_24000", SAMPLE_RATE_24000}, + {"SAMPLE_RATE_32000", SAMPLE_RATE_32000}, + {"SAMPLE_RATE_44100", SAMPLE_RATE_44100}, + {"SAMPLE_RATE_48000", SAMPLE_RATE_48000}, + {"SAMPLE_RATE_64000", SAMPLE_RATE_64000}, + {"SAMPLE_RATE_96000", SAMPLE_RATE_96000} +}; + +static const std::map encodingTypeMap = { + {"ENCODING_PCM", ENCODING_PCM}, + {"ENCODING_AAC", ENCODING_AAC}, + {"ENCODING_INVALID", ENCODING_INVALID} +}; + +static const std::map contentTypeMap = { + {"CONTENT_TYPE_UNKNOWN", CONTENT_TYPE_UNKNOWN}, + {"CONTENT_TYPE_SPEECH", CONTENT_TYPE_SPEECH}, + {"CONTENT_TYPE_MUSIC", CONTENT_TYPE_MUSIC}, + {"CONTENT_TYPE_MOVIE", CONTENT_TYPE_MOVIE}, + {"CONTENT_TYPE_SONIFICATION", CONTENT_TYPE_SONIFICATION} +}; + +static const std::map streamUsageMap = { + {"STREAM_USAGE_UNKNOWN", STREAM_USAGE_UNKNOWN}, + {"STREAM_USAGE_MEDIA", STREAM_USAGE_MEDIA}, + {"STREAM_USAGE_VOICE_COMMUNICATION", STREAM_USAGE_VOICE_COMMUNICATION}, + {"STREAM_USAGE_NOTIFICATION_RINGTONE", STREAM_USAGE_NOTIFICATION_RINGTONE} +}; + +static const std::map deviceRoleMap = { + {"DEVICE_ROLE_NONE", DEVICE_ROLE_NONE}, + {"INPUT_DEVICE", INPUT_DEVICE}, + {"OUTPUT_DEVICE", OUTPUT_DEVICE}, + {"DEVICE_ROLE_MAX", DEVICE_ROLE_MAX} +}; + +static const std::map deviceTypeMap = { + {"NONE", DEVICE_TYPE_NONE}, + {"INVALID", DEVICE_TYPE_INVALID}, + {"EARPIECE", DEVICE_TYPE_EARPIECE}, + {"SPEAKER", DEVICE_TYPE_SPEAKER}, + {"WIRED_HEADSET", DEVICE_TYPE_WIRED_HEADSET}, + {"BLUETOOTH_SCO", DEVICE_TYPE_BLUETOOTH_SCO}, + {"BLUETOOTH_A2DP", DEVICE_TYPE_BLUETOOTH_A2DP}, + {"MIC", DEVICE_TYPE_MIC}, + {"MAX", DEVICE_TYPE_MAX}, +}; + +class AudioParametersNapi { +public: + AudioParametersNapi(); + ~AudioParametersNapi(); + + static napi_value Init(napi_env env, napi_value exports); + static napi_value CreateAudioParametersWrapper(napi_env env, std::unique_ptr &audioParameters); + +private: + static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); + static napi_value Construct(napi_env env, napi_callback_info info); + static napi_value GetAudioSampleFormat(napi_env env, napi_callback_info info); + static napi_value SetAudioSampleFormat(napi_env env, napi_callback_info info); + static napi_value GetAudioChannel(napi_env env, napi_callback_info info); + static napi_value SetAudioChannel(napi_env env, napi_callback_info info); + static napi_value GetAudioSamplingRate(napi_env env, napi_callback_info info); + static napi_value SetAudioSamplingRate(napi_env env, napi_callback_info info); + static napi_value GetAudioEncodingType(napi_env env, napi_callback_info info); + static napi_value SetAudioEncodingType(napi_env env, napi_callback_info info); + static napi_value GetContentType(napi_env env, napi_callback_info info); + static napi_value SetContentType(napi_env env, napi_callback_info info); + static napi_value GetStreamUsage(napi_env env, napi_callback_info info); + static napi_value SetStreamUsage(napi_env env, napi_callback_info info); + static napi_value GetDeviceRole(napi_env env, napi_callback_info info); + static napi_value SetDeviceRole(napi_env env, napi_callback_info info); + static napi_value GetDeviceType(napi_env env, napi_callback_info info); + static napi_value SetDeviceType(napi_env env, napi_callback_info info); + + static napi_status AddNamedProperty(napi_env env, napi_value object, const std::string name, int32_t enumValue); + static napi_value CreateAudioSampleFormatObject(napi_env env); + static napi_value CreateAudioChannelObject(napi_env env); + static napi_value CreateSamplingRateObject(napi_env env); + static napi_value CreateEncodingTypeObject(napi_env env); + static napi_value CreateContentTypeObject(napi_env env); + static napi_value CreateStreamUsageObject(napi_env env); + static napi_value CreateDeviceRoleObject(napi_env env); + static napi_value CreateDeviceTypeObject(napi_env env); + + static napi_ref sConstructor_; + static napi_ref sampleFormat_; + static napi_ref audioChannel_; + static napi_ref samplingRate_; + static napi_ref encodingType_; + static napi_ref contentType_; + static napi_ref streamUsage_; + static napi_ref deviceRole_; + static napi_ref deviceType_; + + static std::unique_ptr sAudioParameters_; + + std::unique_ptr audioParameters_; + napi_env env_; + napi_ref wrapper_; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif /* AUDIO_PARAMETERS_NAPI_H_ */ \ No newline at end of file diff --git a/interfaces/kits/js/audio_manager/@ohos.multimedia.audio.d.ts b/interfaces/kits/js/audio_manager/@ohos.multimedia.audio.d.ts index 683c676801635a2078236fed32402efcf2152d4b..3e61c5b55eb671826648282e07a489103d2ff3df 100644 --- a/interfaces/kits/js/audio_manager/@ohos.multimedia.audio.d.ts +++ b/interfaces/kits/js/audio_manager/@ohos.multimedia.audio.d.ts @@ -30,6 +30,13 @@ declare namespace audio { */ function getAudioManager(): AudioManager; + /** + * Obtains an AudioCapturer instance. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + function createAudioCapturer(volumeType: AudioVolumeType): AudioCapturer; + /** * Enumerates audio stream types. * @devices @@ -44,6 +51,14 @@ declare namespace audio { * Audio streams for media purpose */ MEDIA = 3, + /** + * Audio streams for voice calls + */ + VOICE_CALL = 4, + /** + * Audio stream for voice assistant + */ + VOICE_ASSISTANT = 5, } /** @@ -150,6 +165,71 @@ declare namespace audio { RINGER_MODE_NORMAL, } + /** + * Enumerates the sample format. + */ + enum AudioSampleFormat { + SAMPLE_U8 = 1, + SAMPLE_S16LE = 2, + SAMPLE_S24LE = 3, + SAMPLE_S32LE = 4, + INVALID_WIDTH = -1 + }; + + /** + * Enumerates the audio channel. + */ + enum AudioChannel { + MONO = 1, + STEREO + }; + + /** + * Enumerates the audio sampling rate. + */ + enum AudioSamplingRate { + SAMPLE_RATE_8000 = 8000, + SAMPLE_RATE_11025 = 11025, + SAMPLE_RATE_12000 = 12000, + SAMPLE_RATE_16000 = 16000, + SAMPLE_RATE_22050 = 22050, + SAMPLE_RATE_24000 = 24000, + SAMPLE_RATE_32000 = 32000, + SAMPLE_RATE_44100 = 44100, + SAMPLE_RATE_48000 = 48000, + SAMPLE_RATE_64000 = 64000, + SAMPLE_RATE_96000 = 96000 + }; + + /** + * Enumerates the audio encoding type. + */ + enum AudioEncodingType { + ENCODING_PCM = 0, + ENCODING_INVALID + }; + + /** + * Enumerates the audio content type. + */ + enum ContentType { + CONTENT_TYPE_UNKNOWN = 0, + CONTENT_TYPE_SPEECH = 1, + CONTENT_TYPE_MUSIC = 2, + CONTENT_TYPE_MOVIE = 3, + CONTENT_TYPE_SONIFICATION = 4, + } + + /** + * Enumerates the stream usage. + */ + enum StreamUsage { + STREAM_USAGE_UNKNOWN = 0, + STREAM_USAGE_MEDIA = 1, + STREAM_USAGE_VOICE_COMMUNICATION = 2, + STREAM_USAGE_NOTIFICATION_RINGTONE = 3, + } + /** * Manages audio volume and audio device information. * @devices @@ -368,6 +448,119 @@ declare namespace audio { readonly deviceType: DeviceType; } + /** + * Provides functions for applications to manage audio capturing. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + interface AudioCapturer { + /** + * Sets audio capture parameters. + * If set parameters is not called explicitly, then 16Khz sampling rate, mono channel and PCM_S16_LE format will be set by default. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + setParams(params: AudioParameters): void; + + /** + * Obtains audio capture parameters. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + getParams(): AudioParameters; + + /** + * Starts audio capturing. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + start(): boolean; + + /** + * Capture audio data. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + read(size: number, isBlockingRead: boolean): ArrayBuffer; + + /** + * Obtains the current timestamp. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + getAudioTime(): number; + + /** + * Stops audio capturing. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + stop(): boolean; + + /** + * Releases a capture resources. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + release(): boolean; + + /** + * Obtains a reasonable minimum buffer size for capturer, however, the capturer can + * accept other read sizes as well. + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + getBufferSize(): number; + } + + /** + * Structure for audio parameters + * @devices + * @sysCap SystemCapability.Multimedia.Audio + */ + interface AudioParameters { + /** + * Audio sample format + * @devices + */ + format: AudioSampleFormat; + /** + * Audio channels + * @devices + */ + channels: AudioChannel; + /** + * Audio sampling rate + * @devices + */ + samplingRate: AudioSamplingRate; + /** + * Audio encoding type + * @devices + */ + encoding: AudioEncodingType; + /** + * Audio content type + * @devices + */ + contentType: ContentType; + /** + * Audio stream usage + * @devices + */ + usage: StreamUsage; + /** + * Audio device role + * @devices + */ + deviceRole: DeviceRole; + /** + * Audio device type + * @devices + */ + deviceType: DeviceType; + } + /** * A queue of AudioDeviceDescriptor, which is read-only. * @devices diff --git a/interfaces/kits/js/audio_manager/BUILD.gn b/interfaces/kits/js/audio_manager/BUILD.gn index 8d7b6d58165ad128a904bf065358475396a0fa2c..9d5591cc40c497c17bff0b0d7efa334bc4c3eb02 100644 --- a/interfaces/kits/js/audio_manager/BUILD.gn +++ b/interfaces/kits/js/audio_manager/BUILD.gn @@ -16,42 +16,41 @@ import("//build/ohos/ace/ace.gni") js_declaration("audio_js") { part_name = "multimedia_audio_standard" - sources = [ - "./@ohos.multimedia.audio.d.ts", - ] + sources = [ "./@ohos.multimedia.audio.d.ts" ] } ohos_copy("audio_declaration") { - sources = [ - "./@ohos.multimedia.audio.d.ts", - ] + sources = [ "./@ohos.multimedia.audio.d.ts" ] outputs = [ target_out_dir + "/$target_name/" ] module_source_dir = target_out_dir + "/$target_name" module_install_name = "" } ohos_shared_library("audio") { - include_dirs = [ - "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_manager/include", - ] - - sources = [ - "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp", - "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp" - ] - - deps = [ - "//foundation/ace/napi:ace_napi", - "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiomanager:audio_client", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils" - ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] - - relative_install_dir = "module/multimedia" - part_name = "multimedia_audio_standard" - subsystem_name = "multimedia" + include_dirs = [ + "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_manager/include", + "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_capturer/include", + "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiocommon/include", + ] + + sources = [ + "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_capturer/src/audio_capturer_napi.cpp", + "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_capturer/src/audio_parameters_napi.cpp", + "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_manager/src/audio_device_descriptor_napi.cpp", + "//foundation/multimedia/audio_standard/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp", + ] + + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/ace/napi:ace_napi", + "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiocapturer:audio_capturer", + "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiomanager:audio_client", + "//utils/native/base:utils", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + relative_install_dir = "module/multimedia" + part_name = "multimedia_audio_standard" + subsystem_name = "multimedia" } diff --git a/interfaces/kits/js/audio_manager/include/audio_manager_napi.h b/interfaces/kits/js/audio_manager/include/audio_manager_napi.h index 4a0f34303ffb871f69cb1b4329af3c37d13d8088..85b1635367fb288954e1e574009e7dbbd8e402b1 100644 --- a/interfaces/kits/js/audio_manager/include/audio_manager_napi.h +++ b/interfaces/kits/js/audio_manager/include/audio_manager_napi.h @@ -33,7 +33,9 @@ public: enum AudioVolumeType { RINGTONE = 2, - MEDIA = 3 + MEDIA = 3, + VOICE_CALL = 4, + VOICE_ASSISTANT = 5 }; enum AudioRingMode { diff --git a/ohos.build b/ohos.build index 771f3372d2b90ee6dedf059d5ab61c4e09a17b8b..bbd3ea50dcd1137c3dedbbd11f40ba60112299ff 100644 --- a/ohos.build +++ b/ohos.build @@ -72,9 +72,14 @@ "header": { "header_files": [ "audio_manager_napi.h", - "audio_device_descriptor_napi.h" + "audio_device_descriptor_napi.h", + "audio_capturer_napi.h", + "audio_parameters_napi.h" ], - "header_base": "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_manager/include" + "header_base": [ + "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_manager/include", + "//foundation/multimedia/audio_standard/interfaces/kits/js/audio_capturer/include" + ] } } ], diff --git a/services/etc/pulseaudio.cfg b/services/etc/pulseaudio.cfg index 37bcc11a231ad343634e28bd87aadc4ec0538d04..230628c3097c9d1320cae2743bce03ff713474ed 100644 --- a/services/etc/pulseaudio.cfg +++ b/services/etc/pulseaudio.cfg @@ -6,8 +6,14 @@ "mkdir /data/data/.pulse_dir", "chmod 777 /data/data/.pulse_dir", "chown system shell /data/data/.pulse_dir", - "export PULSE_STATE_PATH /data/data/.pulse_dir", - "export PULSE_RUNTIME_PATH /data/data/.pulse_dir", + "mkdir /data/data/.pulse_dir/runtime", + "chmod 777 /data/data/.pulse_dir/runtime", + "chown system shell /data/data/.pulse_dir/runtime", + "mkdir /data/data/.pulse_dir/state", + "chmod 777 /data/data/.pulse_dir/state", + "chown system shell /data/data/.pulse_dir/state", + "export PULSE_STATE_PATH /data/data/.pulse_dir/state", + "export PULSE_RUNTIME_PATH /data/data/.pulse_dir/runtime", "start pulseaudio", "exec /system/bin/sleep 4", "trigger audio_policy_start" diff --git a/services/include/audio_manager_base.h b/services/include/audio_manager_base.h index 6ff4f1027dcc3d599d15fe1e614afa4f54f66d2a..129d6c94df07c1e5e3fe30293693a0f4f62c4a41 100644 --- a/services/include/audio_manager_base.h +++ b/services/include/audio_manager_base.h @@ -60,7 +60,7 @@ public: * * @return Returns the array of audio device descriptor. */ - virtual std::vector> GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) = 0; + virtual std::vector> GetDevices(DeviceFlag deviceFlag) = 0; /** * Set Audio Parameter. diff --git a/services/include/client/audio_manager_proxy.h b/services/include/client/audio_manager_proxy.h index ac19fc4322fbd441ba6c2edb9956e359a7b10ca2..ab80313d6214dbccaa4e79d48f57471f2318e4bf 100644 --- a/services/include/client/audio_manager_proxy.h +++ b/services/include/client/audio_manager_proxy.h @@ -30,7 +30,7 @@ public: int32_t GetMinVolume(AudioSystemManager::AudioVolumeType volumeType) override; int32_t SetMicrophoneMute(bool isMute) override; bool IsMicrophoneMute() override; - std::vector> GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) override; + std::vector> GetDevices(DeviceFlag deviceFlag) override; const std::string GetAudioParameter(const std::string key) override; void SetAudioParameter(const std::string key, const std::string value) override; private: diff --git a/services/include/client/audio_service_client.h b/services/include/client/audio_service_client.h index 20dda2af1201eda15a3e23db35e822fa8ba9cdb7..c51e13b79ae97a4a9d93e6f02343ace086d53cef 100644 --- a/services/include/client/audio_service_client.h +++ b/services/include/client/audio_service_client.h @@ -81,6 +81,10 @@ public: class AudioServiceClient { public: + static constexpr char PA_RUNTIME_DIR[] = "/data/data/.pulse_dir/runtime"; + static constexpr char PA_STATE_DIR[] = "/data/data/.pulse_dir/state"; + static constexpr char PA_HOME_DIR[] = "/data/data/.pulse_dir/state"; + AudioServiceClient(); virtual ~AudioServiceClient(); @@ -206,7 +210,7 @@ public: * @param audioParams will be filled up with stream audio parameters * @return Returns {@code 0} if success; returns {@code -1} otherwise. */ - int32_t GetAudioStreamParams(AudioStreamParams& audioParams); + int32_t GetAudioStreamParams(AudioStreamParams &audioParams); /** * Provides the minimum buffer size required for this audio stream @@ -294,7 +298,7 @@ private: std::mutex mtx; AudioCache acache; - const void* internalReadBuffer; + const void *internalReadBuffer; size_t internalRdBufLen; size_t internalRdBufIndex; int32_t streamCmdStatus; @@ -356,6 +360,8 @@ private: // Resets PA audio client and free up resources if any with this API void ResetPAAudioClient(); + // For setting some environment variables required while running from hap + void SetEnv(); // Callbacks to be implemented static void PAStreamStateCb(pa_stream *stream, void *userdata); diff --git a/services/include/server/audio_server.h b/services/include/server/audio_server.h index b9407f66d587bb23288ac684a205f9edb5e10a4c..755b109772437830a8e50935acb002dcbb6e0d66 100644 --- a/services/include/server/audio_server.h +++ b/services/include/server/audio_server.h @@ -39,7 +39,7 @@ public: int32_t GetMinVolume(AudioSystemManager::AudioVolumeType volumeType) override; int32_t SetMicrophoneMute(bool isMute) override; bool IsMicrophoneMute() override; - std::vector> GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) override; + std::vector> GetDevices(DeviceFlag deviceFlag) override; static void* paDaemonThread(void* arg); void SetAudioParameter(const std::string key, const std::string value) override; const std::string GetAudioParameter(const std::string key) override; diff --git a/services/src/audio_policy/server/service/include/audio_policy_service.h b/services/src/audio_policy/server/service/include/audio_policy_service.h index 3ffb3b1911e3f6003c788e011eb72526c336f88e..fb85c6db063effaf1ed7dc94de5e6e565f56c6b5 100644 --- a/services/src/audio_policy/server/service/include/audio_policy_service.h +++ b/services/src/audio_policy/server/service/include/audio_policy_service.h @@ -64,9 +64,9 @@ public: AudioRingerMode GetRingerMode() const; // Parser callbacks - void OnAudioPortAvailable(std::shared_ptr portInfo); + void OnAudioPortAvailable(std::unique_ptr portInfo); - void OnAudioPortPinAvailable(std::shared_ptr portInfo); + void OnAudioPortPinAvailable(std::unique_ptr portInfo); void OnDefaultOutputPortPin(InternalDeviceType device); @@ -86,10 +86,10 @@ private: std::list& GetActiveDevicesList(InternalDeviceType deviceType) { switch (deviceType) { - case InternalDeviceType::SPEAKER: - case InternalDeviceType::BLUETOOTH_SCO: + case InternalDeviceType::DEVICE_TYPE_SPEAKER: + case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: return mActiveOutputDevices; - case InternalDeviceType::MIC: + case InternalDeviceType::DEVICE_TYPE_MIC: return mActiveInputDevices; default: return mActiveOutputDevices; // Default case return Output device diff --git a/services/src/audio_policy/server/service/include/common/audio_config.h b/services/src/audio_policy/server/service/include/common/audio_config.h index 64660be35c6d546c1567129f670004322f9c730b..fca11ce95d88420d55b0902447fdf6768e1f4126 100644 --- a/services/src/audio_policy/server/service/include/common/audio_config.h +++ b/services/src/audio_policy/server/service/include/common/audio_config.h @@ -47,12 +47,12 @@ enum PortType { class PortInfo { public: PortType type; - char* name; - char* role; - char* rate; - char* channels; - char* buffer_size; - char* fileName; + char *name; + char *role; + char *rate; + char *channels; + char *buffer_size; + char *fileName; PortInfo() : type(TYPE_AUDIO_PORT_INVALID), @@ -91,7 +91,7 @@ public: struct AudioPortPinInfo : public PortInfo { public: - char* pinType; + char *pinType; AudioPortPinInfo() : pinType(nullptr) { diff --git a/services/src/audio_policy/server/service/include/config/xml_parser.h b/services/src/audio_policy/server/service/include/config/xml_parser.h index 5ac727d5ebbee46091bf19555926f58eb1506710..c0be16ab37403a36cbe1b501148cc5054e31baeb 100644 --- a/services/src/audio_policy/server/service/include/config/xml_parser.h +++ b/services/src/audio_policy/server/service/include/config/xml_parser.h @@ -16,14 +16,8 @@ #ifndef ST_XML_PARSER_H #define ST_XML_PARSER_H -#ifdef __cplusplus -extern "C" { -#endif #include #include -#ifdef __cplusplus -} -#endif #include "audio_config.h" #include "iport_observer.h" @@ -39,7 +33,7 @@ public: bool Parse() final; void Destroy() final; - explicit XMLParser(IPortObserver& observer) + explicit XMLParser(IPortObserver &observer) : mPortObserver(observer), mDoc(nullptr) { @@ -50,17 +44,17 @@ public: Destroy(); } private: - bool ParseInternal(xmlNode* node); - NodeName GetNodeNameAsInt(xmlNode* node); - void ParseBuiltInDevices(xmlNode* node); - void ParseDefaultOutputDevice(xmlNode* node); - void ParseDefaultInputDevice(xmlNode* node); - void ParseAudioPorts(xmlNode* node); - void ParseAudioPortPins(xmlNode* node); - InternalDeviceType GetDeviceType(xmlChar *device); - - IPortObserver& mPortObserver; - xmlDoc* mDoc; + bool ParseInternal(xmlNode *node); + NodeName GetNodeNameAsInt(xmlNode *node); + void ParseBuiltInDevices(xmlNode *node); + void ParseDefaultOutputDevice(xmlNode *node); + void ParseDefaultInputDevice(xmlNode *node); + void ParseAudioPorts(xmlNode *node); + void ParseAudioPortPins(xmlNode *node); + InternalDeviceType GetDeviceType(xmlChar &device); + + IPortObserver &mPortObserver; + xmlDoc *mDoc; }; } // namespace AudioStandard } // namespace OHOS diff --git a/services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h b/services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h index 51f36771d4d23fad446ca1dfa674cae5ac54f0ff..9a1dcbc1b3c79bef075f6986c92e22442574f62c 100644 --- a/services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h +++ b/services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h @@ -42,7 +42,7 @@ public: virtual bool IsStreamActive(AudioStreamType streamType) = 0; - virtual AudioIOHandle OpenAudioPort(std::shared_ptr audioPortInfo) = 0; + virtual AudioIOHandle OpenAudioPort(std::unique_ptr &audioPortInfo) = 0; virtual int32_t CloseAudioPort(AudioIOHandle ioHandle) = 0; diff --git a/services/src/audio_policy/server/service/include/interface/iport_observer.h b/services/src/audio_policy/server/service/include/interface/iport_observer.h index 8e53159172ca006fa0ae6c495b88ca6f0bf8d869..f6b98fdf48a68aa0ae3654ef475c2ea57d201f09 100644 --- a/services/src/audio_policy/server/service/include/interface/iport_observer.h +++ b/services/src/audio_policy/server/service/include/interface/iport_observer.h @@ -23,8 +23,8 @@ namespace OHOS { namespace AudioStandard { class IPortObserver { public: - virtual void OnAudioPortAvailable(std::shared_ptr portInfo) = 0; - virtual void OnAudioPortPinAvailable(std::shared_ptr portInfo) = 0; + virtual void OnAudioPortAvailable(std::unique_ptr portInfo) = 0; + virtual void OnAudioPortPinAvailable(std::unique_ptr portInfo) = 0; virtual void OnDefaultOutputPortPin(InternalDeviceType device) = 0; virtual void OnDefaultInputPortPin(InternalDeviceType device) = 0; }; diff --git a/services/src/audio_policy/server/service/include/manager/audio_adapter_manager.h b/services/src/audio_policy/server/service/include/manager/audio_adapter_manager.h index 97cb41663c1e7a39a874e545c7c2a3bed6a6451f..09bd731981b491024daee17696c8c19fefec4a53 100644 --- a/services/src/audio_policy/server/service/include/manager/audio_adapter_manager.h +++ b/services/src/audio_policy/server/service/include/manager/audio_adapter_manager.h @@ -58,7 +58,7 @@ public: bool IsStreamActive(AudioStreamType streamType); - AudioIOHandle OpenAudioPort(std::shared_ptr audioPortInfo); + AudioIOHandle OpenAudioPort(std::unique_ptr &audioPortInfo); int32_t CloseAudioPort(AudioIOHandle ioHandle); @@ -68,6 +68,8 @@ public: AudioRingerMode GetRingerMode(void); + virtual ~AudioAdapterManager() {} + private: struct UserData { AudioAdapterManager *thiz; @@ -86,10 +88,8 @@ private: mVolumeMap[STREAM_RING] = MAX_VOLUME; } - virtual ~AudioAdapterManager() {} - bool ConnectToPulseAudio(void); - std::string GetModuleArgs(std::shared_ptr audioPortInfo); + std::string GetModuleArgs(std::unique_ptr &audioPortInfo); std::string GetStreamNameByStreamType(AudioStreamType streamType); AudioStreamType GetStreamIDByType(std::string streamType); bool InitAudioPolicyKvStore(bool& isFirstBoot); @@ -107,6 +107,32 @@ private: std::unique_ptr mAudioPolicyKvStore; friend class PolicyCallbackImpl; }; + +class PolicyCallbackImpl : public AudioServiceAdapterCallback { +public: + explicit PolicyCallbackImpl(std::unique_ptr &audioAdapterManager) + { + audioAdapterManager_ = std::move(audioAdapterManager); + } + + ~PolicyCallbackImpl() + { + audioAdapterManager_ = nullptr; + } + + float OnGetVolumeCb(std::string streamType) + { + if (audioAdapterManager_->mRingerMode != RINGER_MODE_NORMAL) { + if (!streamType.compare("ring")) { + return AudioAdapterManager::MIN_VOLUME; + } + } + AudioStreamType streamID = audioAdapterManager_->GetStreamIDByType(streamType); + return audioAdapterManager_->mVolumeMap[streamID]; + } +private: + std::unique_ptr audioAdapterManager_; +}; } // namespace AudioStandard } // namespace OHOS #endif // ST_PULSEAUDIO_ADAPTER_MANAGER_H diff --git a/services/src/audio_policy/server/service/src/audio_policy_service.cpp b/services/src/audio_policy/server/service/src/audio_policy_service.cpp index a704fb3eeaedbf790110ff4279b961eb2f9a4129..af320de2468f0dbefeaef73d303d8998f69dc061 100644 --- a/services/src/audio_policy/server/service/src/audio_policy_service.cpp +++ b/services/src/audio_policy/server/service/src/audio_policy_service.cpp @@ -71,13 +71,13 @@ std::string AudioPolicyService::GetPortName(InternalDeviceType deviceType) { std::string portName = PORT_NONE; switch (deviceType) { - case InternalDeviceType::BLUETOOTH_SCO: + case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: portName = BLUEZ_SINK; break; - case InternalDeviceType::SPEAKER: + case InternalDeviceType::DEVICE_TYPE_SPEAKER: portName = HDI_SINK; break; - case InternalDeviceType::MIC: + case InternalDeviceType::DEVICE_TYPE_MIC: portName = HDI_SOURCE; break; default: @@ -150,8 +150,8 @@ bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType) const bool result = false; switch (deviceType) { - case InternalDeviceType::SPEAKER: - case InternalDeviceType::BLUETOOTH_SCO: + case InternalDeviceType::DEVICE_TYPE_SPEAKER: + case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: for (list::const_iterator iter = mActiveOutputDevices.begin(); iter != mActiveOutputDevices.end(); ++iter) { if (*iter == deviceType) { @@ -179,14 +179,14 @@ AudioRingerMode AudioPolicyService::GetRingerMode() const // Parser callbacks -void AudioPolicyService::OnAudioPortAvailable(shared_ptr portInfo) +void AudioPolicyService::OnAudioPortAvailable(unique_ptr portInfo) { AudioIOHandle ioHandle = mAudioPolicyManager.OpenAudioPort(portInfo); mIOHandles[portInfo->name] = ioHandle; return; } -void AudioPolicyService::OnAudioPortPinAvailable(shared_ptr portInfo) +void AudioPolicyService::OnAudioPortPinAvailable(unique_ptr portInfo) { return; } @@ -214,13 +214,13 @@ AudioIOHandle AudioPolicyService::GetAudioIOHandle(InternalDeviceType deviceType { AudioIOHandle ioHandle; switch (deviceType) { - case InternalDeviceType::SPEAKER: + case InternalDeviceType::DEVICE_TYPE_SPEAKER: ioHandle = mIOHandles[HDI_SINK]; break; - case InternalDeviceType::BLUETOOTH_SCO: + case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: ioHandle = mIOHandles[BLUEZ_SINK]; break; - case InternalDeviceType::MIC: + case InternalDeviceType::DEVICE_TYPE_MIC: ioHandle = mIOHandles[HDI_SOURCE]; break; default: diff --git a/services/src/audio_policy/server/service/src/config/xml_parser.cpp b/services/src/audio_policy/server/service/src/config/xml_parser.cpp index a76bcf85ed56b8180b58ac9cadffa7ccba98f842..a024f85a6d30fedb42c90ee1b7d2dfe3c08c79bf 100644 --- a/services/src/audio_policy/server/service/src/config/xml_parser.cpp +++ b/services/src/audio_policy/server/service/src/config/xml_parser.cpp @@ -32,7 +32,7 @@ bool XMLParser::LoadConfiguration() bool XMLParser::Parse() { - xmlNode* root = xmlDocGetRootElement(mDoc); + xmlNode *root = xmlDocGetRootElement(mDoc); if (root == NULL) { MEDIA_ERR_LOG("xmlDocGetRootElement Failed"); return false; @@ -52,9 +52,9 @@ void XMLParser::Destroy() return; } -bool XMLParser::ParseInternal(xmlNode* node) +bool XMLParser::ParseInternal(xmlNode *node) { - xmlNode* currNode = node; + xmlNode *currNode = node; for (; currNode; currNode = currNode->next) { if (XML_ELEMENT_NODE == currNode->type) { switch (GetNodeNameAsInt(currNode)) { @@ -83,7 +83,7 @@ bool XMLParser::ParseInternal(xmlNode* node) return true; } -NodeName XMLParser::GetNodeNameAsInt(xmlNode* node) +NodeName XMLParser::GetNodeNameAsInt(xmlNode *node) { if (!xmlStrcmp(node->name, reinterpret_cast("BuiltInDevices"))) return BUILT_IN_DEVICES; @@ -103,11 +103,11 @@ NodeName XMLParser::GetNodeNameAsInt(xmlNode* node) return UNKNOWN; } -void XMLParser::ParseBuiltInDevices(xmlNode* node) +void XMLParser::ParseBuiltInDevices(xmlNode *node) { while (node) { - xmlNode* child = node->children; - xmlChar* device = xmlNodeGetContent(child); + xmlNode *child = node->children; + xmlChar *device = xmlNodeGetContent(child); if (device != NULL) { MEDIA_DEBUG_LOG("Trigger Cb"); @@ -118,39 +118,39 @@ void XMLParser::ParseBuiltInDevices(xmlNode* node) return; } -void XMLParser::ParseDefaultOutputDevice(xmlNode* node) +void XMLParser::ParseDefaultOutputDevice(xmlNode *node) { - xmlNode* child = node->children; - xmlChar* device = xmlNodeGetContent(child); + xmlNode *child = node->children; + xmlChar *device = xmlNodeGetContent(child); if (device != NULL) { MEDIA_DEBUG_LOG("DefaultOutputDevice %{public}s", device); - mPortObserver.OnDefaultOutputPortPin(GetDeviceType(device)); + mPortObserver.OnDefaultOutputPortPin(GetDeviceType(*device)); } return; } -void XMLParser::ParseDefaultInputDevice(xmlNode* node) +void XMLParser::ParseDefaultInputDevice(xmlNode *node) { - xmlNode* child = node->children; - xmlChar* device = xmlNodeGetContent(child); + xmlNode *child = node->children; + xmlChar *device = xmlNodeGetContent(child); MEDIA_DEBUG_LOG("DefaultInputDevice"); if (device != NULL) { MEDIA_DEBUG_LOG("DefaultInputDevice %{public}s", device); - mPortObserver.OnDefaultInputPortPin(GetDeviceType(device)); + mPortObserver.OnDefaultInputPortPin(GetDeviceType(*device)); } return; } -void XMLParser::ParseAudioPorts(xmlNode* node) +void XMLParser::ParseAudioPorts(xmlNode *node) { - xmlNode* child = node->xmlChildrenNode; + xmlNode *child = node->xmlChildrenNode; for (; child; child = child->next) { if (!xmlStrcmp(child->name, reinterpret_cast("AudioPort"))) { - std::shared_ptr portInfo = std::make_shared(); + std::unique_ptr portInfo = std::make_unique(); portInfo->type = TYPE_AUDIO_PORT; if (xmlHasProp(child, reinterpret_cast(const_cast("role")))) { @@ -189,20 +189,20 @@ void XMLParser::ParseAudioPorts(xmlNode* node) reinterpret_cast(const_cast("file")))); } - mPortObserver.OnAudioPortAvailable(portInfo); + mPortObserver.OnAudioPortAvailable(std::move(portInfo)); } } return; } -void XMLParser::ParseAudioPortPins(xmlNode* node) +void XMLParser::ParseAudioPortPins(xmlNode *node) { - xmlNode* child = node->xmlChildrenNode; + xmlNode *child = node->xmlChildrenNode; for (; child; child = child->next) { if (!xmlStrcmp(child->name, reinterpret_cast("AudioPortPin"))) { - std::shared_ptr portInfo = std::make_shared(); + std::unique_ptr portInfo = std::make_unique(); portInfo->type = TYPE_AUDIO_PORT_PIN; if (xmlHasProp(child, reinterpret_cast(const_cast("role")))) @@ -220,19 +220,19 @@ void XMLParser::ParseAudioPortPins(xmlNode* node) MEDIA_INFO_LOG("AudioPort:Role: %s, Name: %s, Type: %s", portInfo->role, portInfo->name, portInfo->pinType); - mPortObserver.OnAudioPortPinAvailable(portInfo); + mPortObserver.OnAudioPortPinAvailable(std::move(portInfo)); } } return; } -InternalDeviceType XMLParser::GetDeviceType(xmlChar *device) +InternalDeviceType XMLParser::GetDeviceType(xmlChar &device) { - if (!xmlStrcmp(device, reinterpret_cast("Speaker"))) - return InternalDeviceType::SPEAKER; - if (!xmlStrcmp(device, reinterpret_cast("Built-In Mic"))) - return InternalDeviceType::MIC; + if (!xmlStrcmp(&device, reinterpret_cast("Speaker"))) + return InternalDeviceType::DEVICE_TYPE_SPEAKER; + if (!xmlStrcmp(&device, reinterpret_cast("Built-In Mic"))) + return InternalDeviceType::DEVICE_TYPE_MIC; return InternalDeviceType::DEVICE_TYPE_NONE; } diff --git a/services/src/audio_policy/server/service/src/manager/audio_adapter_manager.cpp b/services/src/audio_policy/server/service/src/manager/audio_adapter_manager.cpp index 960db0ca6b8a50708354ef451e34edf4f05d5f64..1f26add40e85e4ab4afb0d5a7b4acad2b8c381ec 100644 --- a/services/src/audio_policy/server/service/src/manager/audio_adapter_manager.cpp +++ b/services/src/audio_policy/server/service/src/manager/audio_adapter_manager.cpp @@ -22,31 +22,11 @@ namespace OHOS { namespace AudioStandard { -class PolicyCallbackImpl : public AudioServiceAdapterCallback { -public: - explicit PolicyCallbackImpl(AudioAdapterManager *audioAdapterManager) - { - audioAdapterManager_ = audioAdapterManager; - } - - float OnGetVolumeCb(std::string streamType) - { - if (audioAdapterManager_->mRingerMode != RINGER_MODE_NORMAL) { - if (!streamType.compare("ring")) { - return AudioAdapterManager::MIN_VOLUME; - } - } - AudioStreamType streamID = audioAdapterManager_->GetStreamIDByType(streamType); - return audioAdapterManager_->mVolumeMap[streamID]; - } -private: - AudioAdapterManager *audioAdapterManager_; -}; - bool AudioAdapterManager::Init() { - PolicyCallbackImpl *policyCallbackImpl = new PolicyCallbackImpl(this); - mAudioServiceAdapter = AudioServiceAdapter::CreateAudioAdapter(policyCallbackImpl); + std::unique_ptr audioAdapterManager(this); + std::unique_ptr policyCallbackImpl = std::make_unique(audioAdapterManager); + mAudioServiceAdapter = AudioServiceAdapter::CreateAudioAdapter(std::move(policyCallbackImpl)); bool result = mAudioServiceAdapter->Connect(); if (!result) { MEDIA_ERR_LOG("[AudioAdapterManager] Error in connecting audio adapter"); @@ -100,15 +80,16 @@ bool AudioAdapterManager::IsStreamActive(AudioStreamType streamType) bool result = mAudioServiceAdapter->IsStreamActive(streamType); return result; } + int32_t AudioAdapterManager::SetDeviceActive(AudioIOHandle ioHandle, InternalDeviceType deviceType, std::string name, bool active) { switch (deviceType) { - case InternalDeviceType::SPEAKER: - case InternalDeviceType::BLUETOOTH_SCO: { + case InternalDeviceType::DEVICE_TYPE_SPEAKER: + case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: { return mAudioServiceAdapter->SetDefaultSink(name); } - case InternalDeviceType::MIC: { + case InternalDeviceType::DEVICE_TYPE_MIC: { return mAudioServiceAdapter->SetDefaultSource(name); } default: @@ -136,7 +117,7 @@ AudioRingerMode AudioAdapterManager::GetRingerMode() return mRingerMode; } -AudioIOHandle AudioAdapterManager::OpenAudioPort(std::shared_ptr audioPortInfo) +AudioIOHandle AudioAdapterManager::OpenAudioPort(std::unique_ptr &audioPortInfo) { std::string moduleArgs = GetModuleArgs(audioPortInfo); MEDIA_INFO_LOG("[AudioAdapterManager] load-module %{public}s %{public}s", audioPortInfo->name, moduleArgs.c_str()); @@ -161,7 +142,7 @@ int32_t AudioAdapterManager::CloseAudioPort(AudioIOHandle ioHandle) } // Private Members -std::string AudioAdapterManager::GetModuleArgs(std::shared_ptr audioPortInfo) +std::string AudioAdapterManager::GetModuleArgs(std::unique_ptr &audioPortInfo) { std::string args; diff --git a/services/src/client/audio_manager_proxy.cpp b/services/src/client/audio_manager_proxy.cpp index 56ea189463fe0b38617e08e6a41823c5cc1b10c3..86c00f3633ff8167f27e06781d56a3b2f3a2acb0 100644 --- a/services/src/client/audio_manager_proxy.cpp +++ b/services/src/client/audio_manager_proxy.cpp @@ -87,7 +87,7 @@ bool AudioManagerProxy::IsMicrophoneMute() return isMute; } -std::vector> AudioManagerProxy::GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) +std::vector> AudioManagerProxy::GetDevices(DeviceFlag deviceFlag) { MessageParcel data; MessageParcel reply; diff --git a/services/src/client/audio_service_client.cpp b/services/src/client/audio_service_client.cpp index 55df63b41385bc90017744995ee0245ab15e499e..4780d7eac2c5a41b9156c6b5caefd24a821e0b2a 100644 --- a/services/src/client/audio_service_client.cpp +++ b/services/src/client/audio_service_client.cpp @@ -17,6 +17,8 @@ #include "media_log.h" #include "securec.h" +#include "unistd.h" + using namespace std; namespace OHOS { @@ -27,24 +29,30 @@ AudioCapturerCallbacks::~AudioCapturerCallbacks() = default; const uint64_t LATENCY_IN_MSEC = 200UL; #define CHECK_AND_RETURN_IFINVALID(expr) \ +do { \ if (!(expr)) { \ return AUDIO_CLIENT_ERR; \ - } + } \ +} while (false) #define CHECK_PA_STATUS_RET_IF_FAIL(mainLoop, context, paStream, error) \ +do { \ if (!context || !paStream || !mainLoop \ - || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context)) \ - || !PA_STREAM_IS_GOOD(pa_stream_get_state(paStream))) { \ - return error; \ - } + || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context)) \ + || !PA_STREAM_IS_GOOD(pa_stream_get_state(paStream))) { \ + return error; \ + } \ +} while (false) #define CHECK_PA_STATUS_FOR_WRITE(mainLoop, context, paStream, pError, retVal) \ +do { \ if (!context || !paStream || !mainLoop \ - || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context)) \ - || !PA_STREAM_IS_GOOD(pa_stream_get_state(paStream))) { \ - pError = pa_context_errno(context); \ - return retVal; \ - } + || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context)) \ + || !PA_STREAM_IS_GOOD(pa_stream_get_state(paStream))) { \ + pError = pa_context_errno(context); \ + return retVal; \ + } \ +} while (false) AudioStreamParams AudioServiceClient::ConvertFromPAAudioParams(pa_sample_spec paSampleSpec) { @@ -84,19 +92,19 @@ pa_sample_spec AudioServiceClient::ConvertToPAAudioParams(AudioStreamParams audi switch ((AudioSampleFormat)audioParams.format) { case SAMPLE_U8: - paSampleSpec.format = (pa_sample_format_t) PA_SAMPLE_U8; + paSampleSpec.format = (pa_sample_format_t)PA_SAMPLE_U8; break; case SAMPLE_S16LE: - paSampleSpec.format = (pa_sample_format_t) PA_SAMPLE_S16LE; + paSampleSpec.format = (pa_sample_format_t)PA_SAMPLE_S16LE; break; case SAMPLE_S24LE: - paSampleSpec.format = (pa_sample_format_t) PA_SAMPLE_S24LE; + paSampleSpec.format = (pa_sample_format_t)PA_SAMPLE_S24LE; break; case SAMPLE_S32LE: - paSampleSpec.format = (pa_sample_format_t) PA_SAMPLE_S32LE; + paSampleSpec.format = (pa_sample_format_t)PA_SAMPLE_S32LE; break; default: - paSampleSpec.format = (pa_sample_format_t) PA_SAMPLE_INVALID; + paSampleSpec.format = (pa_sample_format_t)PA_SAMPLE_INVALID; break; } @@ -119,7 +127,7 @@ static size_t AlignToAudioFrameSize(size_t l, const pa_sample_spec &ss) void AudioServiceClient::PAStreamCmdSuccessCb(pa_stream *stream, int32_t success, void *userdata) { AudioServiceClient *asClient = (AudioServiceClient *)userdata; - pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *) asClient->mainLoop; + pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *)asClient->mainLoop; asClient->streamCmdStatus = success; pa_threaded_mainloop_signal(mainLoop, 0); @@ -127,7 +135,7 @@ void AudioServiceClient::PAStreamCmdSuccessCb(pa_stream *stream, int32_t success void AudioServiceClient::PAStreamRequestCb(pa_stream *stream, size_t length, void *userdata) { - pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *) userdata; + pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *)userdata; pa_threaded_mainloop_signal(mainLoop, 0); } @@ -139,15 +147,14 @@ void AudioServiceClient::PAStreamUnderFlowCb(pa_stream *stream, void *userdata) void AudioServiceClient::PAStreamLatencyUpdateCb(pa_stream *stream, void *userdata) { - pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *) userdata; - MEDIA_INFO_LOG("Inside latency update callback"); + pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *)userdata; pa_threaded_mainloop_signal(mainLoop, 0); } void AudioServiceClient::PAStreamStateCb(pa_stream *stream, void *userdata) { AudioServiceClient *asClient = (AudioServiceClient *)userdata; - pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *) asClient->mainLoop; + pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *)asClient->mainLoop; if (asClient->mAudioRendererCallbacks) asClient->mAudioRendererCallbacks->OnStreamStateChangeCb(); @@ -170,7 +177,7 @@ void AudioServiceClient::PAStreamStateCb(pa_stream *stream, void *userdata) void AudioServiceClient::PAContextStateCb(pa_context *context, void *userdata) { - pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *) userdata; + pa_threaded_mainloop *mainLoop = (pa_threaded_mainloop *)userdata; MEDIA_INFO_LOG("Current Context State: %d", pa_context_get_state(context)); @@ -290,11 +297,35 @@ AudioServiceClient::~AudioServiceClient() ResetPAAudioClient(); } +void AudioServiceClient::SetEnv() +{ + int ret = 0; + const char *env_home_pa = getenv("HOME"); + if (!env_home_pa) { + ret = setenv("HOME", PA_HOME_DIR, 1); + MEDIA_INFO_LOG("set env HOME: %{public}d", ret); + } + + const char *env_runtime_pa = getenv("PULSE_RUNTIME_PATH"); + if (!env_runtime_pa) { + ret = setenv("PULSE_RUNTIME_PATH", PA_RUNTIME_DIR, 1); + MEDIA_INFO_LOG("set env PULSE_RUNTIME_DIR: %{public}d", ret); + } + + const char *env_state_pa = getenv("PULSE_STATE_PATH"); + if (!env_state_pa) { + ret = setenv("PULSE_STATE_PATH", PA_STATE_DIR, 1); + MEDIA_INFO_LOG("set env PULSE_STATE_PATH: %{public}d", ret); + } +} + int32_t AudioServiceClient::Initialize(ASClientType eClientType) { int error = PA_ERR_INTERNAL; eAudioClientType = eClientType; + SetEnv(); + mainLoop = pa_threaded_mainloop_new(); if (mainLoop == NULL) return AUDIO_CLIENT_INIT_ERR; @@ -315,7 +346,7 @@ int32_t AudioServiceClient::Initialize(ASClientType eClientType) if (pa_context_connect(context, NULL, PA_CONTEXT_NOFAIL, NULL) < 0) { error = pa_context_errno(context); - MEDIA_ERR_LOG("context connect error: %{public}d", error); + MEDIA_ERR_LOG("context connect error: %{public}s", pa_strerror(error)); ResetPAAudioClient(); return AUDIO_CLIENT_INIT_ERR; } @@ -339,7 +370,7 @@ int32_t AudioServiceClient::Initialize(ASClientType eClientType) if (!PA_CONTEXT_IS_GOOD(state)) { error = pa_context_errno(context); - MEDIA_ERR_LOG("context bad state error: %{public}d", error); + MEDIA_ERR_LOG("context bad state error: %{public}s", pa_strerror(error)); pa_threaded_mainloop_unlock(mainLoop); ResetPAAudioClient(); return AUDIO_CLIENT_INIT_ERR; @@ -508,11 +539,11 @@ int32_t AudioServiceClient::CreateStream(AudioStreamParams audioParams, AudioStr } pa_proplist_free(propList); - pa_stream_set_state_callback(paStream, PAStreamStateCb, (void *) this); + pa_stream_set_state_callback(paStream, PAStreamStateCb, (void *)this); pa_stream_set_write_callback(paStream, PAStreamRequestCb, mainLoop); pa_stream_set_read_callback(paStream, PAStreamRequestCb, mainLoop); pa_stream_set_latency_update_callback(paStream, PAStreamLatencyUpdateCb, mainLoop); - pa_stream_set_underflow_callback(paStream, PAStreamUnderFlowCb, (void *) this); + pa_stream_set_underflow_callback(paStream, PAStreamUnderFlowCb, (void *)this); pa_threaded_mainloop_unlock(mainLoop); @@ -555,7 +586,7 @@ int32_t AudioServiceClient::StartStream() } streamCmdStatus = 0; - operation = pa_stream_cork(paStream, 0, PAStreamCmdSuccessCb, (void *) this); + operation = pa_stream_cork(paStream, 0, PAStreamCmdSuccessCb, (void *)this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mainLoop); @@ -593,7 +624,7 @@ int32_t AudioServiceClient::StopStream() } streamCmdStatus = 0; - operation = pa_stream_cork(paStream, 1, PAStreamCmdSuccessCb, (void *) this); + operation = pa_stream_cork(paStream, 1, PAStreamCmdSuccessCb, (void *)this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mainLoop); @@ -627,7 +658,7 @@ int32_t AudioServiceClient::FlushStream() } streamCmdStatus = 0; - operation = pa_stream_flush(paStream, PAStreamCmdSuccessCb, (void *) this); + operation = pa_stream_flush(paStream, PAStreamCmdSuccessCb, (void *)this); if (operation == NULL) { MEDIA_ERR_LOG("Stream Flush Operation Failed"); pa_threaded_mainloop_unlock(mainLoop); @@ -681,7 +712,7 @@ int32_t AudioServiceClient::DrainStream() } streamCmdStatus = 0; - operation = pa_stream_drain(paStream, PAStreamCmdSuccessCb, (void *) this); + operation = pa_stream_drain(paStream, PAStreamCmdSuccessCb, (void *)this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mainLoop); @@ -864,7 +895,7 @@ size_t AudioServiceClient::WriteStream(const StreamBuffer &stream, int32_t &pErr int32_t AudioServiceClient::UpdateReadBuffer(uint8_t *buffer, size_t &length, size_t &readSize) { size_t l = (internalRdBufLen < length) ? internalRdBufLen : length; - if (memcpy_s(buffer, length, (const uint8_t*) internalReadBuffer + internalRdBufIndex, l)) { + if (memcpy_s(buffer, length, (const uint8_t*)internalReadBuffer + internalRdBufIndex, l)) { MEDIA_ERR_LOG("Update read buffer failed"); return AUDIO_CLIENT_READ_STREAM_ERR; } @@ -880,7 +911,7 @@ int32_t AudioServiceClient::UpdateReadBuffer(uint8_t *buffer, size_t &length, si internalRdBufLen = 0; internalRdBufIndex = 0; if (retVal < 0) { - MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %d", retVal); + MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %{public}d", retVal); return AUDIO_CLIENT_READ_STREAM_ERR; } } @@ -901,7 +932,7 @@ int32_t AudioServiceClient::ReadStream(StreamBuffer &stream, bool isBlocking) while (!internalReadBuffer) { int retVal = pa_stream_peek(paStream, &internalReadBuffer, &internalRdBufLen); if (retVal < 0) { - MEDIA_ERR_LOG("pa_stream_peek failed, retVal: %d", retVal); + MEDIA_ERR_LOG("pa_stream_peek failed, retVal: %{public}d", retVal); pa_threaded_mainloop_unlock(mainLoop); return AUDIO_CLIENT_READ_STREAM_ERR; } @@ -916,7 +947,7 @@ int32_t AudioServiceClient::ReadStream(StreamBuffer &stream, bool isBlocking) } else if (!internalReadBuffer) { retVal = pa_stream_drop(paStream); if (retVal < 0) { - MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %d", retVal); + MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %{public}d", retVal); pa_threaded_mainloop_unlock(mainLoop); return AUDIO_CLIENT_READ_STREAM_ERR; } @@ -954,11 +985,11 @@ int32_t AudioServiceClient::GetMinimumBufferSize(size_t &minBufferSize) } if (eAudioClientType == AUDIO_SERVICE_CLIENT_PLAYBACK) { - minBufferSize = (size_t) MINIMUM_BUFFER_SIZE; + minBufferSize = (size_t)MINIMUM_BUFFER_SIZE; } if (eAudioClientType == AUDIO_SERVICE_CLIENT_RECORD) { - minBufferSize = (size_t) bufferAttr->fragsize; + minBufferSize = (size_t)bufferAttr->fragsize; } MEDIA_INFO_LOG("buffer size: %zu", minBufferSize); @@ -978,11 +1009,11 @@ int32_t AudioServiceClient::GetMinimumFrameCount(uint32_t &frameCount) } if (eAudioClientType == AUDIO_SERVICE_CLIENT_PLAYBACK) { - minBufferSize = (size_t) MINIMUM_BUFFER_SIZE; + minBufferSize = (size_t)MINIMUM_BUFFER_SIZE; } if (eAudioClientType == AUDIO_SERVICE_CLIENT_RECORD) { - minBufferSize = (size_t) bufferAttr->fragsize; + minBufferSize = (size_t)bufferAttr->fragsize; } uint32_t bytesPerSample = pa_frame_size(&sampleSpec); @@ -1095,13 +1126,13 @@ int32_t AudioServiceClient::GetAudioLatency(uint64_t &latency) void AudioServiceClient::RegisterAudioRendererCallbacks(const AudioRendererCallbacks &cb) { MEDIA_INFO_LOG("Registering audio render callbacks"); - mAudioRendererCallbacks = (AudioRendererCallbacks *) &cb; + mAudioRendererCallbacks = (AudioRendererCallbacks *)&cb; } void AudioServiceClient::RegisterAudioCapturerCallbacks(const AudioCapturerCallbacks &cb) { MEDIA_INFO_LOG("Registering audio record callbacks"); - mAudioCapturerCallbacks = (AudioCapturerCallbacks *) &cb; + mAudioCapturerCallbacks = (AudioCapturerCallbacks *)&cb; } int32_t AudioServiceClient::SetStreamVolume(float volume) @@ -1165,7 +1196,7 @@ void AudioServiceClient::GetSinkInputInfoVolumeCb(pa_context *c, const pa_sink_i AudioServiceClient *thiz = reinterpret_cast(userdata); if (eol < 0) { - MEDIA_ERR_LOG("Failed to get sink input information: %s", pa_strerror(pa_context_errno(c))); + MEDIA_ERR_LOG("Failed to get sink input information: %{public}s", pa_strerror(pa_context_errno(c))); return; } @@ -1199,7 +1230,7 @@ void AudioServiceClient::GetSinkInputInfoVolumeCb(pa_context *c, const pa_sink_i pa_cvolume_set(&cv, i->channel_map.channels, volume); pa_operation_unref(pa_context_set_sink_input_volume(c, i->index, &cv, NULL, NULL)); - MEDIA_INFO_LOG("Applied volume : %{public}f for stream : %{public}s, volumeInt%{public}d", + MEDIA_INFO_LOG("Applied volume : %{public}f for stream : %{public}s, pa volume: %{public}d", vol, i->name, volume); return; diff --git a/services/src/client/audio_system_manager.cpp b/services/src/client/audio_system_manager.cpp index bc76591f3725a5d2d11c07bb8d441d0e3d2266e0..305de016e27b27e988606d49d14b95a392d6ecb9 100644 --- a/services/src/client/audio_system_manager.cpp +++ b/services/src/client/audio_system_manager.cpp @@ -240,7 +240,7 @@ bool AudioSystemManager::IsMicrophoneMute() const return g_sProxy->IsMicrophoneMute(); } -std::vector> AudioSystemManager::GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) +std::vector> AudioSystemManager::GetDevices(DeviceFlag deviceFlag) const { return g_sProxy->GetDevices(deviceFlag); @@ -275,8 +275,8 @@ AudioDeviceDescriptor *AudioDeviceDescriptor::Unmarshalling(Parcel &in) if (audioDeviceDescriptor == nullptr) { return nullptr; } - audioDeviceDescriptor->deviceType_ = static_cast(in.ReadInt32()); - audioDeviceDescriptor->deviceRole_ = static_cast(in.ReadInt32()); + audioDeviceDescriptor->deviceType_ = static_cast(in.ReadInt32()); + audioDeviceDescriptor->deviceRole_ = static_cast(in.ReadInt32()); return audioDeviceDescriptor; } } // namespace AudioStandard diff --git a/services/src/server/audio_manager_stub.cpp b/services/src/server/audio_manager_stub.cpp index 8236b896f2eeb9d2725ee9232765645c0dbd8c1c..1de8af574749ae851d65cf0a620b220d7c02e546 100644 --- a/services/src/server/audio_manager_stub.cpp +++ b/services/src/server/audio_manager_stub.cpp @@ -54,8 +54,8 @@ int AudioManagerStub::OnRemoteRequest( case GET_DEVICES: { MEDIA_DEBUG_LOG("GET_DEVICES AudioManagerStub"); int deviceFlag = data.ReadInt32(); - AudioDeviceDescriptor::DeviceFlag deviceFlagConfig = - static_cast(deviceFlag); + DeviceFlag deviceFlagConfig = + static_cast(deviceFlag); std::vector> devices = GetDevices(deviceFlagConfig); int32_t size = devices.size(); MEDIA_DEBUG_LOG("GET_DEVICES size= %{public}d", size); diff --git a/services/src/server/audio_server.cpp b/services/src/server/audio_server.cpp index ff7d99527b74d5f36cbe407716b283435432a459..364b3d61ede2ee5635b2686878b832339f58d631 100644 --- a/services/src/server/audio_server.cpp +++ b/services/src/server/audio_server.cpp @@ -35,7 +35,7 @@ REGISTER_SYSTEM_ABILITY_BY_ID(AudioServer, AUDIO_DISTRIBUTED_SERVICE_ID, true) #ifdef PA constexpr int PA_ARG_COUNT = 1; -void* AudioServer::paDaemonThread(void* arg) +void *AudioServer::paDaemonThread(void *arg) { /* Load the mandatory pulseaudio modules at start */ char *argv[] = { @@ -139,7 +139,7 @@ bool AudioServer::IsMicrophoneMute() return isMute; } -std::vector> AudioServer::GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) +std::vector> AudioServer::GetDevices(DeviceFlag deviceFlag) { MEDIA_DEBUG_LOG("GetDevices server"); audioDeviceDescriptor_.clear(); @@ -148,20 +148,20 @@ std::vector> AudioServer::GetDevices(AudioDeviceDesc MEDIA_ERR_LOG("new AudioDeviceDescriptor fail"); return audioDeviceDescriptor_; } - if (AudioDeviceDescriptor::DeviceFlag::INPUT_DEVICES_FLAG == deviceFlag) { - audioDescriptor->deviceType_ = AudioDeviceDescriptor::DeviceType::MIC; - audioDescriptor->deviceRole_ = AudioDeviceDescriptor::DeviceRole::INPUT_DEVICE; - } else if (AudioDeviceDescriptor::DeviceFlag::OUTPUT_DEVICES_FLAG == deviceFlag) { - audioDescriptor->deviceType_ = AudioDeviceDescriptor::DeviceType::SPEAKER; - audioDescriptor->deviceRole_ = AudioDeviceDescriptor::DeviceRole::OUTPUT_DEVICE; - } else if (AudioDeviceDescriptor::DeviceFlag::ALL_DEVICES_FLAG == deviceFlag) { + if (DeviceFlag::INPUT_DEVICES_FLAG == deviceFlag) { + audioDescriptor->deviceType_ = DeviceType::DEVICE_TYPE_MIC; + audioDescriptor->deviceRole_ = DeviceRole::INPUT_DEVICE; + } else if (DeviceFlag::OUTPUT_DEVICES_FLAG == deviceFlag) { + audioDescriptor->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER; + audioDescriptor->deviceRole_ = DeviceRole::OUTPUT_DEVICE; + } else if (DeviceFlag::ALL_DEVICES_FLAG == deviceFlag) { sptr audioDescriptor_inputDevice = new(std::nothrow) AudioDeviceDescriptor(); sptr audioDescriptor_outputDevice = new(std::nothrow) AudioDeviceDescriptor(); - audioDescriptor_inputDevice->deviceType_ = AudioDeviceDescriptor::DeviceType::MIC; - audioDescriptor_inputDevice->deviceRole_ = AudioDeviceDescriptor::DeviceRole::INPUT_DEVICE; + audioDescriptor_inputDevice->deviceType_ = DeviceType::DEVICE_TYPE_MIC; + audioDescriptor_inputDevice->deviceRole_ = DeviceRole::INPUT_DEVICE; audioDeviceDescriptor_.push_back(audioDescriptor_inputDevice); - audioDescriptor_outputDevice->deviceType_ = AudioDeviceDescriptor::DeviceType::SPEAKER; - audioDescriptor_outputDevice->deviceRole_ = AudioDeviceDescriptor::DeviceRole::OUTPUT_DEVICE; + audioDescriptor_outputDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER; + audioDescriptor_outputDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE; audioDeviceDescriptor_.push_back(audioDescriptor_outputDevice); return audioDeviceDescriptor_; } diff --git a/services/test/audio_capturer_test.cpp b/services/test/audio_capturer_test.cpp index cc6c2d27c1db65d11eb6ef2a7af8049e94c3af56..37f56c36c82f8d66432f6dbe1ae820c0983b7c55 100644 --- a/services/test/audio_capturer_test.cpp +++ b/services/test/audio_capturer_test.cpp @@ -96,7 +96,7 @@ public: return false; } - uint8_t* buffer = (uint8_t *)malloc(bufferLen); + auto buffer = std::make_unique(bufferLen); if (buffer == nullptr) { MEDIA_ERR_LOG("AudioCapturerTest: Failed to allocate buffer"); return false; @@ -107,7 +107,7 @@ public: while (numBuffersToCapture) { size_t bytesRead = 0; while (bytesRead < bufferLen) { - int32_t len = audioCapturer->Read(*(buffer + bytesRead), bufferLen - bytesRead, isBlocking); + int32_t len = audioCapturer->Read(*(buffer.get() + bytesRead), bufferLen - bytesRead, isBlocking); if (len >= 0) { bytesRead += len; } else { @@ -122,7 +122,7 @@ public: continue; } - if (fwrite(buffer, size, bytesRead, pFile) != bytesRead) { + if (fwrite(buffer.get(), size, bytesRead, pFile) != bytesRead) { MEDIA_ERR_LOG("error occured in fwrite"); } numBuffersToCapture--; @@ -138,7 +138,6 @@ public: } } } - free(buffer); return true; } diff --git a/services/test/audio_policy_test.cpp b/services/test/audio_policy_test.cpp index 3805af2e8d28ba3b1c4d9147780c64c8c8385f7d..9b0a5388018ebd08464e8e41bf7348c240355f8c 100644 --- a/services/test/audio_policy_test.cpp +++ b/services/test/audio_policy_test.cpp @@ -66,8 +66,9 @@ static void PrintUsage(void) cout << "\tWritten by Sajeesh Sidharthan and Anurup M" << endl << endl; } -static void HandleVolume(const AudioSystemManager *audioSystemMgr, int streamType, char option) +static void HandleVolume(int streamType, char option) { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); if (option == 'v') { float volume = audioSystemMgr->GetVolume(static_cast(streamType)); cout << "Get Volume : " << volume << endl; @@ -80,8 +81,9 @@ static void HandleVolume(const AudioSystemManager *audioSystemMgr, int streamTyp } } -static void HandleMute(const AudioSystemManager *audioSystemMgr, int streamType, char option) +static void HandleMute(int streamType, char option) { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); if (option == 'm') { bool muteStatus = audioSystemMgr->IsStreamMute(static_cast(streamType)); cout << "Get Mute : " << muteStatus << endl; @@ -94,8 +96,9 @@ static void HandleMute(const AudioSystemManager *audioSystemMgr, int streamType, } } -static void HandleMicMute(const AudioSystemManager *audioSystemMgr, char option) +static void HandleMicMute(char option) { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); if (option == 'u') { bool muteStatus = audioSystemMgr->IsMicrophoneMute(); cout << "Is Mic Mute : " << muteStatus << endl; @@ -113,15 +116,17 @@ static void SetStreamType(int &streamType) cout << "Set Stream : " << streamType << endl; } -static void IsStreamActive(const AudioSystemManager *audioSystemMgr) +static void IsStreamActive() { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); int streamType = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); cout << "Stream Active: " << audioSystemMgr->IsStreamActive( static_cast(streamType)) << endl; } -static void SetDeviceActive(const AudioSystemManager *audioSystemMgr, int argc, char* argv[]) +static void SetDeviceActive(int argc, char* argv[]) { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); int active = -1; int device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); cout << "Set Device : " << device << endl; @@ -137,15 +142,17 @@ static void SetDeviceActive(const AudioSystemManager *audioSystemMgr, int argc, cout << "Set DeviceActive Result: " << result << endl; } -static void IsDeviceActive(const AudioSystemManager *audioSystemMgr) +static void IsDeviceActive() { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); int device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); bool devActiveStatus = audioSystemMgr->IsDeviceActive(ActiveDeviceType(device)); cout << "GetDevice Active : " << devActiveStatus << endl; } -static void HandleRingerMode(const AudioSystemManager *audioSystemMgr, char option) +static void HandleRingerMode(char option) { + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); if (option == 'r') { int ringMode = static_cast(audioSystemMgr->GetRingerMode()); cout << "Get Ringer Mode : " << ringMode << endl; @@ -183,36 +190,35 @@ int main(int argc, char* argv[]) } int streamType = static_cast(AudioSystemManager::AudioVolumeType::STREAM_MUSIC); - AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); while ((opt = getopt(argc, argv, ":V:U:S:D:M:R:d:s:vmru")) != -1) { switch (opt) { case 'V': case 'v': - HandleVolume(audioSystemMgr, streamType, opt); + HandleVolume(streamType, opt); break; case 'M': case 'm': - HandleMute(audioSystemMgr, streamType, opt); + HandleMute(streamType, opt); break; case 'U': case 'u': - HandleMicMute(audioSystemMgr, opt); + HandleMicMute(opt); break; case 'S': SetStreamType(streamType); break; case 's': - IsStreamActive(audioSystemMgr); + IsStreamActive(); break; case 'D': - SetDeviceActive(audioSystemMgr, argc, argv); + SetDeviceActive(argc, argv); break; case 'd': - IsDeviceActive(audioSystemMgr); + IsDeviceActive(); break; case 'R': case 'r': - HandleRingerMode(audioSystemMgr, opt); + HandleRingerMode(opt); break; case ':': NoValueError(); diff --git a/services/test/audio_renderer_test.cpp b/services/test/audio_renderer_test.cpp index 26aea417bcb6987013a55b7d9065eec61dc91266..812746ee69b7cbe304b6d2f4dd908299749008df 100644 --- a/services/test/audio_renderer_test.cpp +++ b/services/test/audio_renderer_test.cpp @@ -102,9 +102,9 @@ public: } bool TestPauseStop(const unique_ptr &audioRenderer, bool &pauseTested, bool &stopTested, - FILE *wavFile) const + FILE &wavFile) const { - uint64_t currFilePos = ftell(wavFile); + uint64_t currFilePos = ftell(&wavFile); if (!stopTested && (currFilePos > AudioTestConstants::STOP_BUFFER_POSITION) && audioRenderer->Stop()) { stopTested = true; sleep(AudioTestConstants::STOP_RENDER_TIME_SECONDS); @@ -167,7 +167,7 @@ public: } int32_t n = 2; - uint8_t *buffer = (uint8_t *) malloc(n * bufferLen); + auto buffer = std::make_unique(n * bufferLen); if (buffer == nullptr) { MEDIA_ERR_LOG("AudioRendererTest: Failed to allocate buffer"); return false; @@ -181,11 +181,11 @@ public: bool pauseTested = false; while (!feof(wavFile)) { - bytesToWrite = fread(buffer, 1, bufferLen, wavFile); + bytesToWrite = fread(buffer.get(), 1, bufferLen, wavFile); bytesWritten = 0; MEDIA_INFO_LOG("AudioRendererTest: Bytes to write: %{public}zu", bytesToWrite); - if (!TestPauseStop(audioRenderer, pauseTested, stopTested, wavFile)) { + if (!TestPauseStop(audioRenderer, pauseTested, stopTested, *wavFile)) { break; } @@ -195,7 +195,7 @@ public: } while ((bytesWritten < bytesToWrite) && ((bytesToWrite - bytesWritten) > minBytes)) { - bytesWritten += audioRenderer->Write(buffer + bytesWritten, + bytesWritten += audioRenderer->Write(buffer.get() + bytesWritten, bytesToWrite - bytesWritten); MEDIA_INFO_LOG("AudioRendererTest: Bytes written: %{public}zu", bytesWritten); if (bytesWritten < 0) { @@ -210,8 +210,6 @@ public: MEDIA_ERR_LOG("AudioRendererTest: Drain failed"); } - free(buffer); - return true; }