diff --git a/frameworks/innerkitsimpl/audiocapturer/include/audio_capturer_source.h b/frameworks/innerkitsimpl/audiocapturer/include/audio_capturer_source.h index 9af4396c64ea77f7744caa663969acebf312e189..d2e675cdea3ac1a3a07fdab4eddccd87bc107794 100644 --- a/frameworks/innerkitsimpl/audiocapturer/include/audio_capturer_source.h +++ b/frameworks/innerkitsimpl/audiocapturer/include/audio_capturer_source.h @@ -77,6 +77,9 @@ private: void *handle_; + int32_t CreateCapture(struct AudioPort &capturePort); + int32_t InitAudioManager(); + #ifdef CAPTURE_DUMP FILE *pfd; #endif diff --git a/frameworks/innerkitsimpl/audiocapturer/src/audio_capturer_source.cpp b/frameworks/innerkitsimpl/audiocapturer/src/audio_capturer_source.cpp index 910114e8101e3aff052446ba148afb22a81219ba..915f97e9e0a914dee32620010734409fed65b025 100644 --- a/frameworks/innerkitsimpl/audiocapturer/src/audio_capturer_source.cpp +++ b/frameworks/innerkitsimpl/audiocapturer/src/audio_capturer_source.cpp @@ -27,7 +27,8 @@ const char *g_audioOutTestFilePath = "/data/local/tmp/audio_capture.pcm"; #endif // CAPTURE_DUMP AudioCapturerSource::AudioCapturerSource() - : capturerInited_(false), started_(false), paused_(false), leftVolume_(MAX_VOLUME_LEVEL), rightVolume_(MAX_VOLUME_LEVEL), + : capturerInited_(false), started_(false), paused_(false), + leftVolume_(MAX_VOLUME_LEVEL), rightVolume_(MAX_VOLUME_LEVEL), audioManager_(nullptr), audioAdapter_(nullptr), audioCapture_(nullptr) { attr_ = {}; @@ -71,24 +72,22 @@ void AudioCapturerSource::DeInit() #endif // CAPTURE_DUMP } -int32_t InitAttrsCapture(struct AudioSampleAttributes *attrs) +int32_t InitAttrsCapture(struct AudioSampleAttributes &attrs) { /* Initialization of audio parameters for playback */ - attrs->format = AUDIO_FORMAT_PCM_16_BIT; - attrs->channelCount = AUDIO_CHANNELCOUNT; - attrs->sampleRate = AUDIO_SAMPLE_RATE_48K; - attrs->interleaved = 0; - attrs->type = AUDIO_IN_MEDIA; - attrs->period = DEEP_BUFFER_CAPTURE_PERIOD_SIZE; - /* 16 * attrs->channelCount / 8,Byte */ - attrs->frameSize = PCM_16_BIT * attrs->channelCount / PCM_8_BIT; - attrs->isBigEndian = false; - attrs->isSignedData = true; - /* DEEP_BUFFER_CAPTURE_PERIOD_SIZE / (16 * attrs->channelCount / 8) */ - attrs->startThreshold = DEEP_BUFFER_CAPTURE_PERIOD_SIZE / (attrs->frameSize); - attrs->stopThreshold = INT_32_MAX; + attrs.format = AUDIO_FORMAT_PCM_16_BIT; + attrs.channelCount = AUDIO_CHANNELCOUNT; + attrs.sampleRate = AUDIO_SAMPLE_RATE_48K; + attrs.interleaved = 0; + attrs.type = AUDIO_IN_MEDIA; + attrs.period = DEEP_BUFFER_CAPTURE_PERIOD_SIZE; + attrs.frameSize = PCM_16_BIT * attrs.channelCount / PCM_8_BIT; + attrs.isBigEndian = false; + attrs.isSignedData = true; + attrs.startThreshold = DEEP_BUFFER_CAPTURE_PERIOD_SIZE / (attrs.frameSize); + attrs.stopThreshold = INT_32_MAX; /* 16 * 1024 */ - attrs->silenceThreshold = AUDIO_BUFF_SIZE; + attrs.silenceThreshold = AUDIO_BUFF_SIZE; return SUCCESS; } @@ -117,32 +116,72 @@ int32_t SwitchAdapterCapture(struct AudioAdapterDescriptor *descs, const char *a return ERR_INVALID_INDEX; } -int32_t AudioCapturerSource::Init(AudioSourceAttr &attr) +int32_t AudioCapturerSource::InitAudioManager() { - attr_ = attr; - int32_t ret; - int32_t index; - int32_t size = 0; char resolvedPath[100] = "/system/lib/libhdi_audio.z.so"; - struct AudioPort audioPort; - struct AudioAdapterDescriptor *descs = nullptr; - struct AudioPort capturePort; struct AudioManager *(*getAudioManager)() = nullptr; - audioPort.dir = PORT_IN; - audioPort.portId = 0; - audioPort.portName = "AOP"; handle_ = dlopen(resolvedPath, 1); if (handle_ == nullptr) { MEDIA_ERR_LOG("Open Capturer so Fail"); return ERR_INVALID_HANDLE; } + getAudioManager = (struct AudioManager *(*)())(dlsym(handle_, "GetAudioManagerFuncs")); audioManager_ = getAudioManager(); if (audioManager_ == nullptr) { return ERR_INVALID_HANDLE; } + return 0; +} + +int32_t AudioCapturerSource::CreateCapture(struct AudioPort &capturePort) +{ + // Initialization port information, can fill through mode and other parameters + int32_t ret = audioAdapter_->InitAllPorts(audioAdapter_); + if (ret != 0) { + MEDIA_ERR_LOG("InitAllPorts failed"); + return ERR_DEVICE_INIT; + } + + struct AudioSampleAttributes param; + // User needs to set + InitAttrsCapture(param); + param.sampleRate = attr_.sampleRate; + param.format = attr_.format; + param.channelCount = attr_.channel; + + struct AudioDeviceDescriptor deviceDesc; + deviceDesc.portId = capturePort.portId; + deviceDesc.pins = PIN_IN_MIC; + deviceDesc.desc = nullptr; + + ret = audioAdapter_->CreateCapture(audioAdapter_, &deviceDesc, ¶m, &audioCapture_); + if (audioCapture_ == nullptr || ret < 0) { + MEDIA_ERR_LOG("Create capture failed"); + return ERR_NOT_STARTED; + } + + capturerInited_ = true; + + return 0; +} + +int32_t AudioCapturerSource::Init(AudioSourceAttr &attr) +{ + attr_ = attr; + int32_t ret; + int32_t index; + int32_t size = 0; + struct AudioAdapterDescriptor *descs = nullptr; + struct AudioPort capturePort; + + if (InitAudioManager() != 0) { + MEDIA_ERR_LOG("Init audio manager Fail"); + return ERR_INVALID_HANDLE; + } + ret = audioManager_->GetAllAdapters(audioManager_, &descs, &size); // adapters is 0~3 if (size > MAX_AUDIO_ADAPTER_NUM || size == 0 || descs == nullptr || ret < 0) { @@ -152,7 +191,7 @@ int32_t AudioCapturerSource::Init(AudioSourceAttr &attr) // Get qualified sound card and port char adapterNameCase[PATH_LEN] = "internal"; - index = SwitchAdapterCapture(descs, adapterNameCase, audioPort.dir, &capturePort, size); + index = SwitchAdapterCapture(descs, adapterNameCase, PORT_IN, &capturePort, size); if (index < 0) { MEDIA_ERR_LOG("Switch Adapter Fail"); return ERR_NOT_STARTED; @@ -167,33 +206,11 @@ int32_t AudioCapturerSource::Init(AudioSourceAttr &attr) MEDIA_ERR_LOG("Load audio device failed"); return ERR_NOT_STARTED; } - // Initialization port information, can fill through mode and other parameters - ret = audioAdapter_->InitAllPorts(audioAdapter_); - if (ret != 0) { - MEDIA_ERR_LOG("InitAllPorts failed"); - return ERR_DEVICE_INIT; - } - struct AudioSampleAttributes param; - // User needs to set - InitAttrsCapture(¶m); - param.sampleRate = attr_.sampleRate; - param.format = attr_.format; - param.channelCount = attr_.channel; - - struct AudioDeviceDescriptor deviceDesc; - deviceDesc.portId = capturePort.portId; - deviceDesc.pins = PIN_IN_MIC; - deviceDesc.desc = nullptr; - - ret = audioAdapter_->CreateCapture(audioAdapter_, &deviceDesc, ¶m, &audioCapture_); - if (audioCapture_ == nullptr || ret < 0) { + if (CreateCapture(capturePort) != 0) { MEDIA_ERR_LOG("Create capture failed"); return ERR_NOT_STARTED; } - - capturerInited_ = true; - #ifdef CAPTURE_DUMP pfd = fopen(g_audioOutTestFilePath, "wb+"); if (pfd == nullptr) { diff --git a/frameworks/innerkitsimpl/audiorecorder/include/audio_recorder_private.h b/frameworks/innerkitsimpl/audiorecorder/include/audio_recorder_private.h new file mode 100644 index 0000000000000000000000000000000000000000..03354f80e78265d344350662e350d66cd449345f --- /dev/null +++ b/frameworks/innerkitsimpl/audiorecorder/include/audio_recorder_private.h @@ -0,0 +1,41 @@ +/* + * 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_recorder.h" +#include "audio_stream.h" + +namespace OHOS { +namespace AudioStandard { +class AudioRecorderPrivate : public AudioRecorder { +public: + int32_t GetFrameCount(uint32_t &frameCount) const override; + int32_t SetParams(const AudioRecorderParams params) const override; + int32_t GetParams(AudioRecorderParams ¶ms) const override; + bool Start() const override; + int32_t Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) const override; + RecorderState GetStatus() const override; + bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const override; + bool Stop() const override; + bool Flush() const override; + bool Release() const override; + int32_t GetBufferSize(size_t &bufferSize) const override; + + std::unique_ptr audioRecorder; + + explicit AudioRecorderPrivate(AudioStreamType audioStreamType); + virtual ~AudioRecorderPrivate(); +}; +} // namespace AudioStandard +} // namespace OHOS diff --git a/frameworks/innerkitsimpl/audiorecorder/src/audio_recorder.cpp b/frameworks/innerkitsimpl/audiorecorder/src/audio_recorder.cpp index 8416566ed7ca7fdeeca5866d381240d7038df705..f7346036ce4ce5cd825e359c095117282e190d4d 100644 --- a/frameworks/innerkitsimpl/audiorecorder/src/audio_recorder.cpp +++ b/frameworks/innerkitsimpl/audiorecorder/src/audio_recorder.cpp @@ -17,31 +17,11 @@ #include "audio_errors.h" #include "audio_recorder.h" +#include "audio_recorder_private.h" #include "audio_stream.h" namespace OHOS { namespace AudioStandard { - -class AudioRecorderPrivate : public AudioRecorder { -public: - int32_t GetFrameCount(uint32_t &frameCount) override; - int32_t SetParams(const AudioRecorderParams params) override; - int32_t GetParams(AudioRecorderParams ¶ms) override; - bool Start() override; - int32_t Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) override; - RecorderState GetStatus() override; - bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) override; - bool Stop() override; - bool Flush() override; - bool Release() override; - int32_t GetBufferSize(size_t &bufferSize) override; - - std::unique_ptr audioRecorder; - - AudioRecorderPrivate(AudioStreamType audioStreamType); - virtual ~AudioRecorderPrivate(); -}; - AudioRecorder::~AudioRecorder() = default; AudioRecorderPrivate::~AudioRecorderPrivate() = default; @@ -55,12 +35,12 @@ AudioRecorderPrivate::AudioRecorderPrivate(AudioStreamType audioStreamType) audioRecorder = std::make_unique(audioStreamType, AUDIO_MODE_RECORD); } -int32_t AudioRecorderPrivate::GetFrameCount(uint32_t &frameCount) +int32_t AudioRecorderPrivate::GetFrameCount(uint32_t &frameCount) const { return audioRecorder->GetFrameCount(frameCount); } -int32_t AudioRecorderPrivate::SetParams(const AudioRecorderParams params) +int32_t AudioRecorderPrivate::SetParams(const AudioRecorderParams params) const { AudioStreamParams audioStreamParams; audioStreamParams.format = params.audioSampleFormat; @@ -71,7 +51,7 @@ int32_t AudioRecorderPrivate::SetParams(const AudioRecorderParams params) return audioRecorder->SetAudioStreamInfo(audioStreamParams); } -int32_t AudioRecorderPrivate::GetParams(AudioRecorderParams ¶ms) +int32_t AudioRecorderPrivate::GetParams(AudioRecorderParams ¶ms) const { AudioStreamParams audioStreamParams; int32_t result = audioRecorder->GetAudioStreamInfo(audioStreamParams); @@ -85,42 +65,42 @@ int32_t AudioRecorderPrivate::GetParams(AudioRecorderParams ¶ms) return result; } -bool AudioRecorderPrivate::Start() +bool AudioRecorderPrivate::Start() const { return audioRecorder->StartAudioStream(); } -int32_t AudioRecorderPrivate::Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) +int32_t AudioRecorderPrivate::Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) const { return audioRecorder->Read(buffer, userSize, isBlockingRead); } -RecorderState AudioRecorderPrivate::GetStatus() +RecorderState AudioRecorderPrivate::GetStatus() const { return (RecorderState)audioRecorder->GetState(); } -bool AudioRecorderPrivate::GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) +bool AudioRecorderPrivate::GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const { - return audioRecorder->GetAudioTime(timestamp,base); + return audioRecorder->GetAudioTime(timestamp, base); } -bool AudioRecorderPrivate::Stop() +bool AudioRecorderPrivate::Stop() const { return audioRecorder->StopAudioStream(); } -bool AudioRecorderPrivate::Flush() +bool AudioRecorderPrivate::Flush() const { return audioRecorder->FlushAudioStream(); } -bool AudioRecorderPrivate::Release() +bool AudioRecorderPrivate::Release() const { return audioRecorder->ReleaseAudioStream(); } -int32_t AudioRecorderPrivate::GetBufferSize(size_t &bufferSize) +int32_t AudioRecorderPrivate::GetBufferSize(size_t &bufferSize) const { return audioRecorder->GetBufferSize(bufferSize); } diff --git a/pulseaudio/src/modules/hdi/hdi_source.h b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_private.h similarity index 34% rename from pulseaudio/src/modules/hdi/hdi_source.h rename to frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_private.h index fd12658f3ee07026f962af897613c6bdda1ccc8a..78ea1b596cc37d32f34306dae0f8e9a480a29a09 100644 --- a/pulseaudio/src/modules/hdi/hdi_source.h +++ b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_private.h @@ -13,46 +13,34 @@ * limitations under the License. */ -#include -#include -#include -#include -#include -#include +#ifndef AUDIO_RECORDER_PRIVATE_H +#define AUDIO_RECORDER_PRIVATE_H -#include -#include +#include "audio_renderer.h" +#include "audio_stream.h" -#define DEFAULT_SOURCE_NAME "hdi_input" -#define DEFAULT_AUDIO_DEVICE_NAME "Internal Mic" +namespace OHOS { +namespace AudioStandard { +class AudioRendererPrivate : public AudioRenderer { +public: + int32_t GetFrameCount(uint32_t &frameCount) const override; + int32_t GetLatency(uint64_t &latency) const override; + int32_t SetParams(const AudioRendererParams params) const override; + int32_t GetParams(AudioRendererParams ¶ms) const override; + bool Start() const override; + int32_t Write(uint8_t *buffer, size_t bufferSize) override; + RendererState GetStatus() const override; + bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const override; + bool Drain() const override; + bool Stop() const override; + bool Release() const override; + int32_t GetBufferSize(size_t &bufferSize) const override; -#define DEFAULT_BUFFER_SIZE (1024 * 16) -#define MAX_VOLUME_VALUE 15.0 -#define DEFAULT_LEFT_VOLUME MAX_VOLUME_VALUE -#define DEFAULT_RIGHT_VOLUME MAX_VOLUME_VALUE -#define FIVE_MSEC 5000 -#define MAX_RETRIES 5 -#define MAX_LATENCY_USEC (PA_USEC_PER_SEC * 2) -#define MIN_LATENCY_USEC (500) -#define AUDIO_POINT_NUM 1024 -#define AUDIO_FRAME_NUM_IN_BUF 30 + std::unique_ptr audioRenderer; -struct userdata { - pa_core *core; - pa_module *module; - pa_source *source; - pa_thread *thread; - pa_thread_mq thread_mq; - pa_rtpoll *rtpoll; - size_t buffer_size; - pa_usec_t block_usec; - pa_usec_t timestamp; - AudioSourceAttr attrs; - // A flag to signal us to prevent silent record during bootup - bool IsReady; - bool IsCapturerInit; + explicit AudioRendererPrivate(AudioStreamType audioStreamType); + virtual ~AudioRendererPrivate(); }; - -pa_source* pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver); - -void pa_hdi_source_free(pa_source *s); +} // namespace AudioStandard +} // namespace OHOS +#endif // AUDIO_RECORDER_PRIVATE_H diff --git a/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink.h b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink.h index 154a2966f35dbbbe59c02285f38ff217cffed117..b756adfd5cdbd4a7f8710e41fb7e5572ac9efee0 100644 --- a/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink.h +++ b/frameworks/innerkitsimpl/audiorenderer/include/audio_renderer_sink.h @@ -58,6 +58,9 @@ private: struct AudioAdapter *audioAdapter_; struct AudioRender *audioRender_; void *handle_; + + int32_t CreateRender(struct AudioPort &renderPort); + int32_t InitAudioManager(); #ifdef DUMPFILE FILE *pfd; #endif // DUMPFILE diff --git a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer.cpp b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer.cpp index 333249edac7a0b3084239f38414d730d4dd00ab6..87c8fdc3395c8bb6c84057b79b2bc90238cf48e3 100644 --- a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer.cpp +++ b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer.cpp @@ -17,32 +17,11 @@ #include "audio_errors.h" #include "audio_renderer.h" +#include "audio_renderer_private.h" #include "audio_stream.h" namespace OHOS { namespace AudioStandard { - -class AudioRendererPrivate : public AudioRenderer { -public: - int32_t GetFrameCount(uint32_t &frameCount) override; - int32_t GetLatency(uint64_t &latency) override; - int32_t SetParams(const AudioRendererParams params) override; - int32_t GetParams(AudioRendererParams ¶ms) override; - bool Start() override; - int32_t Write(uint8_t *buffer, size_t bufferSize) override; - RendererState GetStatus() override; - bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) override; - bool Drain() override; - bool Stop() override; - bool Release() override; - int32_t GetBufferSize(size_t &bufferSize) override; - - std::unique_ptr audioRenderer; - - AudioRendererPrivate(AudioStreamType audioStreamType); - virtual ~AudioRendererPrivate(); -}; - AudioRenderer::~AudioRenderer() = default; AudioRendererPrivate::~AudioRendererPrivate() = default; @@ -56,17 +35,17 @@ AudioRendererPrivate::AudioRendererPrivate(AudioStreamType audioStreamType) audioRenderer = std::make_unique(audioStreamType, AUDIO_MODE_PLAYBACK); } -int32_t AudioRendererPrivate::GetFrameCount(uint32_t &frameCount) +int32_t AudioRendererPrivate::GetFrameCount(uint32_t &frameCount) const { return audioRenderer->GetFrameCount(frameCount); } -int32_t AudioRendererPrivate::GetLatency(uint64_t &latency) +int32_t AudioRendererPrivate::GetLatency(uint64_t &latency) const { return audioRenderer->GetLatency(latency); } -int32_t AudioRendererPrivate::SetParams(const AudioRendererParams params) +int32_t AudioRendererPrivate::SetParams(const AudioRendererParams params) const { AudioStreamParams audioStreamParams; audioStreamParams.format = params.sampleFormat; @@ -77,11 +56,11 @@ int32_t AudioRendererPrivate::SetParams(const AudioRendererParams params) return audioRenderer->SetAudioStreamInfo(audioStreamParams); } -int32_t AudioRendererPrivate::GetParams(AudioRendererParams ¶ms) +int32_t AudioRendererPrivate::GetParams(AudioRendererParams ¶ms) const { AudioStreamParams audioStreamParams; int32_t result = audioRenderer->GetAudioStreamInfo(audioStreamParams); - if(!result) { + if (!result) { params.sampleFormat = static_cast(audioStreamParams.format); params.sampleRate = static_cast(audioStreamParams.samplingRate); params.channelCount = static_cast(audioStreamParams.channels); @@ -91,7 +70,7 @@ int32_t AudioRendererPrivate::GetParams(AudioRendererParams ¶ms) return result; } -bool AudioRendererPrivate::Start() +bool AudioRendererPrivate::Start() const { return audioRenderer->StartAudioStream(); } @@ -101,32 +80,32 @@ int32_t AudioRendererPrivate::Write(uint8_t *buffer, size_t bufferSize) return audioRenderer->Write(buffer, bufferSize); } -RendererState AudioRendererPrivate::GetStatus() +RendererState AudioRendererPrivate::GetStatus() const { return static_cast(audioRenderer->GetState()); } -bool AudioRendererPrivate::GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) +bool AudioRendererPrivate::GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const { - return audioRenderer->GetAudioTime(timestamp,base); + return audioRenderer->GetAudioTime(timestamp, base); } -bool AudioRendererPrivate::Drain() +bool AudioRendererPrivate::Drain() const { return audioRenderer->DrainAudioStream(); } -bool AudioRendererPrivate::Stop() +bool AudioRendererPrivate::Stop() const { return audioRenderer->StopAudioStream(); } -bool AudioRendererPrivate::Release() +bool AudioRendererPrivate::Release() const { return audioRenderer->ReleaseAudioStream(); } -int32_t AudioRendererPrivate::GetBufferSize(size_t &bufferSize) +int32_t AudioRendererPrivate::GetBufferSize(size_t &bufferSize) const { return audioRenderer->GetBufferSize(bufferSize); } diff --git a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp index ee93ed2b1220fe17ec6ea15e8c083c5ca069f0da..c0271f061fb749d7ff73cc4d5453e45707ef468c 100644 --- a/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp +++ b/frameworks/innerkitsimpl/audiorenderer/src/audio_renderer_sink.cpp @@ -23,18 +23,16 @@ namespace OHOS { namespace AudioStandard { -#define AUDIO_CHANNELCOUNT 2 -#define AUDIO_SAMPLE_RATE_48K 48000 -#define DEEP_BUFFER_RENDER_PERIOD_SIZE 4096 -#define INT_32_MAX 0x7fffffff -#define PERIOD_SIZE 1024 -#define PCM_8_BIT 8 -#define PCM_16_BIT 16 - namespace { const int32_t HALF_FACTOR = 2; const int32_t MAX_AUDIO_ADAPTER_NUM = 3; const float DEFAULT_VOLUME_LEVEL = 1.0f; +const uint32_t AUDIO_CHANNELCOUNT = 2; +const uint32_t AUDIO_SAMPLE_RATE_48K = 48000; +const uint32_t DEEP_BUFFER_RENDER_PERIOD_SIZE = 4096; +const uint32_t INT_32_MAX = 0x7fffffff; +#define PCM_8_BIT 8 +#define PCM_16_BIT 16 } #ifdef DUMPFILE @@ -88,30 +86,27 @@ void AudioRendererSink::DeInit() #endif // DUMPFILE } -int32_t InitAttrs(struct AudioSampleAttributes *attrs) +int32_t InitAttrs(struct AudioSampleAttributes &attrs) { /* Initialization of audio parameters for playback */ - attrs->format = AUDIO_FORMAT_PCM_16_BIT; - attrs->channelCount = AUDIO_CHANNELCOUNT; - attrs->sampleRate = AUDIO_SAMPLE_RATE_48K; - attrs->interleaved = 0; - attrs->type = AUDIO_IN_MEDIA; - attrs->period = DEEP_BUFFER_RENDER_PERIOD_SIZE; - /* PERIOD_SIZE * 16 * attrs->channelCount / 8 */ - attrs->frameSize = PCM_16_BIT * attrs->channelCount / PCM_8_BIT; - attrs->isBigEndian = false; - attrs->isSignedData = true; - /* DEEP_BUFFER_RENDER_PERIOD_SIZE / (16 * attrs->channelCount / 8) */ - attrs->startThreshold = DEEP_BUFFER_RENDER_PERIOD_SIZE / (attrs->frameSize); - attrs->stopThreshold = INT_32_MAX; - attrs->silenceThreshold = 0; + attrs.format = AUDIO_FORMAT_PCM_16_BIT; + attrs.channelCount = AUDIO_CHANNELCOUNT; + attrs.sampleRate = AUDIO_SAMPLE_RATE_48K; + attrs.interleaved = 0; + attrs.type = AUDIO_IN_MEDIA; + attrs.period = DEEP_BUFFER_RENDER_PERIOD_SIZE; + attrs.frameSize = PCM_16_BIT * attrs.channelCount / PCM_8_BIT; + attrs.isBigEndian = false; + attrs.isSignedData = true; + attrs.startThreshold = DEEP_BUFFER_RENDER_PERIOD_SIZE / (attrs.frameSize); + attrs.stopThreshold = INT_32_MAX; + attrs.silenceThreshold = 0; return SUCCESS; } -static int32_t SwitchAdapter(struct AudioAdapterDescriptor *descs, - const char *adapterNameCase, enum AudioPortDirection portFlag, - struct AudioPort *renderPort, int32_t size) +static int32_t SwitchAdapter(struct AudioAdapterDescriptor *descs, const char *adapterNameCase, + enum AudioPortDirection portFlag, struct AudioPort *renderPort, int32_t size) { for (int32_t index = 0; index < size; index++) { struct AudioAdapterDescriptor *desc = &descs[index]; @@ -134,12 +129,8 @@ static int32_t SwitchAdapter(struct AudioAdapterDescriptor *descs, return ERR_INVALID_INDEX; } -int32_t AudioRendererSink::Init(AudioSinkAttr &attr) +int32_t AudioRendererSink::InitAudioManager() { - attr_ = attr; - struct AudioPort renderPort; - const char *adapterNameCase = "usb"; // Set sound card information - enum AudioPortDirection port = PORT_OUT; // Set port information char resolvedPath[100] = "/system/lib/libhdi_audio.z.so"; struct AudioManager *(*getAudioManager)() = nullptr; @@ -148,17 +139,61 @@ int32_t AudioRendererSink::Init(AudioSinkAttr &attr) MEDIA_ERR_LOG("Open so Fail"); return ERR_INVALID_HANDLE; } + getAudioManager = (struct AudioManager* (*)())(dlsym(handle_, "GetAudioManagerFuncs")); audioManager_ = getAudioManager(); if (audioManager_ == nullptr) { return ERR_INVALID_HANDLE; } - int32_t ret = 0; + return 0; +} + +int32_t AudioRendererSink::CreateRender(struct AudioPort &renderPort) +{ + // Initialization port information, can fill through mode and other parameters + int32_t ret = audioAdapter_->InitAllPorts(audioAdapter_); + if (ret != 0) { + MEDIA_ERR_LOG("InitAllPorts failed"); + return ERR_NOT_STARTED; + } + + struct AudioSampleAttributes param; + InitAttrs(param); + param.sampleRate = attr_.sampleRate; + param.channelCount = attr_.channel; + + struct AudioDeviceDescriptor deviceDesc; + deviceDesc.portId = renderPort.portId; + deviceDesc.pins = PIN_OUT_SPEAKER; + deviceDesc.desc = nullptr; + ret = audioAdapter_->CreateRender(audioAdapter_, &deviceDesc, ¶m, &audioRender_); + if (ret != 0 || audioRender_ == nullptr) { + MEDIA_ERR_LOG("AudioDeviceCreateRender failed"); + audioManager_->UnloadAdapter(audioManager_, audioAdapter_); + return ERR_NOT_STARTED; + } + + rendererInited_ = true; + return 0; +} + +int32_t AudioRendererSink::Init(AudioSinkAttr &attr) +{ + attr_ = attr; + struct AudioPort renderPort; + const char *adapterNameCase = "usb"; // Set sound card information + enum AudioPortDirection port = PORT_OUT; // Set port information + + if (InitAudioManager() != 0) { + MEDIA_ERR_LOG("Init audio manager Fail"); + return ERR_NOT_STARTED; + } + int32_t size = -1; struct AudioAdapterDescriptor *descs = nullptr; audioManager_->GetAllAdapters(audioManager_, &descs, &size); - if (size > MAX_AUDIO_ADAPTER_NUM || size == 0 || descs == nullptr || ret < 0) { + if (size > MAX_AUDIO_ADAPTER_NUM || size == 0 || descs == nullptr) { MEDIA_ERR_LOG("Get adapters Fail"); return ERR_NOT_STARTED; } @@ -180,30 +215,11 @@ int32_t AudioRendererSink::Init(AudioSinkAttr &attr) return ERR_NOT_STARTED; } - // Initialization port information, can fill through mode and other parameters - ret = audioAdapter_->InitAllPorts(audioAdapter_); - if (ret != 0) { - MEDIA_ERR_LOG("InitAllPorts failed"); + if (CreateRender(renderPort) != 0) { + MEDIA_ERR_LOG("Create render failed"); return ERR_NOT_STARTED; } - struct AudioSampleAttributes param; - InitAttrs(¶m); - param.sampleRate = attr_.sampleRate; - param.channelCount = attr_.channel; - - struct AudioDeviceDescriptor deviceDesc; - deviceDesc.portId = renderPort.portId; - deviceDesc.pins = PIN_OUT_SPEAKER; - deviceDesc.desc = nullptr; - ret = audioAdapter_->CreateRender(audioAdapter_, &deviceDesc, ¶m, &audioRender_); - if (ret != 0 || audioRender_ == nullptr) { - MEDIA_ERR_LOG("AudioDeviceCreateRender failed"); - audioManager_->UnloadAdapter(audioManager_, audioAdapter_); - return ERR_NOT_STARTED; - } - rendererInited_ = true; - #ifdef DUMPFILE pfd = fopen(g_audioOutTestFilePath, "wb+"); if (pfd == nullptr) { diff --git a/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp b/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp index 0594107853f29b4655c90bca7ff09493a5cbb742..d6563962b3a6661c80d64652858df69e74f4fb6b 100644 --- a/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp +++ b/frameworks/kitsimpl/audio_manager/src/audio_manager_napi.cpp @@ -799,7 +799,8 @@ napi_value AudioManagerNapi::SetRingerMode(napi_env env, napi_callback_info info env, nullptr, resource, [](napi_env env, void* data) { auto context = static_cast(data); - context->status = context->objectInfo->audioMngr_->SetRingerMode(static_cast(context->ringMode)); + context->status = + context->objectInfo->audioMngr_->SetRingerMode(static_cast(context->ringMode)); }, SetFunctionAsyncCallbackComplete, static_cast(asyncContext.get()), &asyncContext->work); if (status != napi_ok) { diff --git a/interfaces/innerkits/native/audiocommon/include/audio_info.h b/interfaces/innerkits/native/audiocommon/include/audio_info.h index e39e9c99e01681d8273d9e2d5770f6919cc3b9b1..21c16df9d7a9e7fd468cfd3beb4e57af2b784251 100644 --- a/interfaces/innerkits/native/audiocommon/include/audio_info.h +++ b/interfaces/innerkits/native/audiocommon/include/audio_info.h @@ -16,7 +16,6 @@ #define AUDIO_INFO_H #ifdef __MUSL__ -#include #include #endif // __MUSL__ @@ -209,30 +208,6 @@ struct AudioStreamParams { uint8_t channels; }; -/** - * @brief Represents Timestamp information, including the frame position information and high-resolution time source. - */ -class Timestamp { -public: - Timestamp() : framePosition(0) - { - time.tv_sec = 0; - time.tv_nsec = 0; - } - virtual ~Timestamp() = default; - uint32_t framePosition; - struct timespec time; - - /** - * @brief Enumerates the time base of this Timestamp. Different timing methods are supported. - * - */ - enum Timestampbase { - /** Monotonically increasing time, excluding the system sleep time */ - MONOTONIC = 0 - }; -}; - // Supported audio parameters for both renderer and recorder const std::vector AUDIO_SUPPORTED_FORMATS { SAMPLE_U8, diff --git a/interfaces/innerkits/native/audiocommon/include/timestamp.h b/interfaces/innerkits/native/audiocommon/include/timestamp.h new file mode 100644 index 0000000000000000000000000000000000000000..2295c3b85cc972cc61f97f9a2adf23a5e89526a2 --- /dev/null +++ b/interfaces/innerkits/native/audiocommon/include/timestamp.h @@ -0,0 +1,51 @@ +/* + * 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 TIMESTAMP_H +#define TIMESTAMP_H +#ifdef __MUSL__ +#include + +#include +#endif // __MUSL__ +#include + +namespace OHOS { +namespace AudioStandard { +/** + * @brief Represents Timestamp information, including the frame position information and high-resolution time source. + */ +class Timestamp { +public: + Timestamp() : framePosition(0) + { + time.tv_sec = 0; + time.tv_nsec = 0; + } + virtual ~Timestamp() = default; + uint32_t framePosition; + struct timespec time; + + /** + * @brief Enumerates the time base of this Timestamp. Different timing methods are supported. + * + */ + enum Timestampbase { + /** Monotonically increasing time, excluding the system sleep time */ + MONOTONIC = 0 + }; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // TIMESTAMP_H diff --git a/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h b/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h index 27c9de122555be51c36fba2453acb60b11999815..cde085460a19da073e9ea0912ba10d03c5be3b09 100644 --- a/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h +++ b/interfaces/innerkits/native/audiomanager/include/audio_system_manager.h @@ -144,22 +144,22 @@ enum AudioVolumeType { STREAM_ACCESSIBILITY = 10 }; static AudioSystemManager* GetInstance(); - int32_t SetVolume(AudioSystemManager::AudioVolumeType volumeType, float volume); - float GetVolume(AudioSystemManager::AudioVolumeType volumeType); - float GetMaxVolume(AudioSystemManager::AudioVolumeType volumeType); - float GetMinVolume(AudioSystemManager::AudioVolumeType volumeType); - int32_t SetMute(AudioSystemManager::AudioVolumeType volumeType, bool mute); - bool IsStreamMute(AudioSystemManager::AudioVolumeType volumeType); - int32_t SetMicrophoneMute(bool IsMute); - bool IsMicrophoneMute(void); - std::vector> GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag); - const std::string GetAudioParameter(const std::string key); - void SetAudioParameter(const std::string key, const std::string value); - int32_t SetDeviceActive(AudioDeviceDescriptor::DeviceType deviceType, bool flag); - bool IsDeviceActive(AudioDeviceDescriptor::DeviceType deviceType); - bool IsStreamActive(AudioSystemManager::AudioVolumeType volumeType); - bool SetRingerMode(AudioRingerMode ringMode); - AudioRingerMode GetRingerMode(); + int32_t SetVolume(AudioSystemManager::AudioVolumeType volumeType, float volume) const; + float GetVolume(AudioSystemManager::AudioVolumeType volumeType) const; + float GetMaxVolume(AudioSystemManager::AudioVolumeType volumeType) const; + float GetMinVolume(AudioSystemManager::AudioVolumeType volumeType) const; + int32_t SetMute(AudioSystemManager::AudioVolumeType volumeType, bool mute) const; + bool IsStreamMute(AudioSystemManager::AudioVolumeType volumeType) const; + int32_t SetMicrophoneMute(bool isMute) const; + bool IsMicrophoneMute(void) const; + std::vector> GetDevices(AudioDeviceDescriptor::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(AudioDeviceDescriptor::DeviceType deviceType, bool flag) const; + bool IsDeviceActive(AudioDeviceDescriptor::DeviceType deviceType) const; + bool IsStreamActive(AudioSystemManager::AudioVolumeType volumeType) const; + bool SetRingerMode(AudioRingerMode ringMode) const; + AudioRingerMode GetRingerMode() const; private: AudioSystemManager(); virtual ~AudioSystemManager(); diff --git a/interfaces/innerkits/native/audiopolicy/BUILD.gn b/interfaces/innerkits/native/audiopolicy/BUILD.gn index 4e4ba1a4c7565a18655dc532a307a50e9e030034..73aaa5789715966169c7f0ebad3618697dd74662 100644 --- a/interfaces/innerkits/native/audiopolicy/BUILD.gn +++ b/interfaces/innerkits/native/audiopolicy/BUILD.gn @@ -86,6 +86,7 @@ ohos_executable("audio_policy_test") { deps = [ "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiomanager:audio_client", + "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] diff --git a/interfaces/innerkits/native/audiorecorder/BUILD.gn b/interfaces/innerkits/native/audiorecorder/BUILD.gn index 5cefb05e3acf223decea7e1360fea0554e8bc82b..12029f91354fe7f5d07bdb59ac8984fbb2b3139f 100644 --- a/interfaces/innerkits/native/audiorecorder/BUILD.gn +++ b/interfaces/innerkits/native/audiorecorder/BUILD.gn @@ -24,6 +24,7 @@ group("audio_recorder_test_packages") { config("audio_recorder_config") { include_dirs = [ "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiorecorder/include", + "//foundation/multimedia/audio_standard/frameworks/innerkitsimpl/audiorecorder/include", "//foundation/multimedia/audio_standard/frameworks/innerkitsimpl/common/include", "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiocommon/include", "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiostream/include", diff --git a/interfaces/innerkits/native/audiorecorder/include/audio_recorder.h b/interfaces/innerkits/native/audiorecorder/include/audio_recorder.h index c36435812f38bf701fb0674db683a27dcd156e12..f557908842850e08a93beb7e647bac9a225ad6a0 100644 --- a/interfaces/innerkits/native/audiorecorder/include/audio_recorder.h +++ b/interfaces/innerkits/native/audiorecorder/include/audio_recorder.h @@ -19,6 +19,7 @@ #include #include "audio_info.h" +#include "timestamp.h" namespace OHOS { namespace AudioStandard { @@ -75,7 +76,7 @@ public: * @return Returns {@link SUCCESS} if frameCount is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetFrameCount(uint32_t &frameCount) = 0; + virtual int32_t GetFrameCount(uint32_t &frameCount) const = 0; /** * @brief Sets audio record parameters. @@ -85,25 +86,26 @@ public: * @return Returns {@link SUCCESS} if the setting is successful; returns an error code defined * in {@link audio_errors.h} otherwise. */ - virtual int32_t SetParams(const AudioRecorderParams params) = 0; + virtual int32_t SetParams(const AudioRecorderParams params) const = 0; /** * @brief Obtains audio recorder parameters. * * This function can be called after {@link SetParams} is successful. * - * @param params Indicates information about audio recorder parameters. For details, see {@link AudioRecorderParams}. + * @param params Indicates information about audio recorder parameters.For details,see + * {@link AudioRecorderParams}. * @return Returns {@link SUCCESS} if the parameter information is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetParams(AudioRecorderParams ¶ms) = 0; + virtual int32_t GetParams(AudioRecorderParams ¶ms) const = 0; /** * @brief Starts audio recording. * * @return Returns true if the recording is successfully started; returns false otherwise. */ - virtual bool Start() = 0; + virtual bool Start() const = 0; /** * @brief record audio data. @@ -119,14 +121,14 @@ public: * ERR_ILLEGAL_STATE: The AudioRecorder instance is not initialized. * ERR_INVALID_READ: The read size < 0. */ - virtual int32_t Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) = 0; + virtual int32_t Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) const = 0; /** * @brief Obtains the audio record state. * * @return Returns the audio record state defined in {@link RecorderState}. */ - virtual RecorderState GetStatus() = 0; + virtual RecorderState GetStatus() const = 0; /** * @brief Obtains the Timestamp. @@ -136,27 +138,27 @@ public: * {@link Timestamp.Timestampbase#MONOTONIC}. * @return Returns true if the timestamp is successfully obtained; returns false otherwise. */ - virtual bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) = 0; + virtual bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const = 0; /** * @brief Stops audio recording. * * @return Returns true if the recording is successfully stopped; returns false otherwise. */ - virtual bool Stop() = 0; + virtual bool Stop() const = 0; /** * @brief flush record stream. * * @return Returns true if the object is successfully flushed; returns false otherwise. */ - virtual bool Flush() = 0; + virtual bool Flush() const = 0; /** * @brief Releases a local AudioRecorder object. * * @return Returns true if the object is successfully released; returns false otherwise. */ - virtual bool Release() = 0; + virtual bool Release() const = 0; /** * @brief Obtains a reasonable minimum buffer size for recorder, however, the recorder can @@ -166,7 +168,7 @@ public: * @return Returns {@link SUCCESS} if bufferSize is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetBufferSize(size_t &bufferSize) = 0; + virtual int32_t GetBufferSize(size_t &bufferSize) const = 0; /** * @brief Obtains the recorder supported formats. diff --git a/interfaces/innerkits/native/audiorenderer/BUILD.gn b/interfaces/innerkits/native/audiorenderer/BUILD.gn index f09ef6b71e503a0807e94a1a99cff272ffe09a4c..26cb43c9ecde6c5c27adf959d63974c6b221d090 100644 --- a/interfaces/innerkits/native/audiorenderer/BUILD.gn +++ b/interfaces/innerkits/native/audiorenderer/BUILD.gn @@ -18,6 +18,7 @@ pulseaudio_dir = "//third_party/pulseaudio" config("audio_renderer_config") { include_dirs = [ "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiorecorder/include", + "//foundation/multimedia/audio_standard/frameworks/innerkitsimpl/audiorenderer/include", "//foundation/multimedia/audio_standard/frameworks/innerkitsimpl/common/include", "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiocommon/include", "//foundation/multimedia/audio_standard/interfaces/innerkits/native/audiostream/include", diff --git a/interfaces/innerkits/native/audiorenderer/include/audio_renderer.h b/interfaces/innerkits/native/audiorenderer/include/audio_renderer.h index 227c606bcfe4fd09eeb5f2e573fdb0bb214ad0e7..ce6d9e8de627417ec6570f2844f348b5a322d501 100644 --- a/interfaces/innerkits/native/audiorenderer/include/audio_renderer.h +++ b/interfaces/innerkits/native/audiorenderer/include/audio_renderer.h @@ -19,6 +19,7 @@ #include #include "audio_info.h" +#include "timestamp.h" namespace OHOS { namespace AudioStandard { @@ -75,7 +76,7 @@ public: * @return Returns {@link SUCCESS} if frameCount is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetFrameCount(uint32_t &frameCount) = 0; + virtual int32_t GetFrameCount(uint32_t &frameCount) const = 0; /** * @brief Sets audio renderer parameters. @@ -85,25 +86,26 @@ public: * @return Returns {@link SUCCESS} if the setting is successful; returns an error code defined * in {@link audio_errors.h} otherwise. */ - virtual int32_t SetParams(const AudioRendererParams params) = 0; + virtual int32_t SetParams(const AudioRendererParams params) const = 0; /** * @brief Obtains audio renderer parameters. * * This function can be called after {@link SetParams} is successful. * - * @param params Indicates information about audio renderer parameters. For details, see {@link AudioRendererParams}. + * @param params Indicates information about audio renderer parameters. For details, see + * {@link AudioRendererParams}. * @return Returns {@link SUCCESS} if the parameter information is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetParams(AudioRendererParams ¶ms) = 0; + virtual int32_t GetParams(AudioRendererParams ¶ms) const = 0; /** * @brief Starts audio rendering. * * @return Returns true if the rendering is successfully started; returns false otherwise. */ - virtual bool Start() = 0; + virtual bool Start() const = 0; /** * @brief Writes audio data. @@ -117,14 +119,14 @@ public: * ERR_INVALID_WRITE: The written audio data size is < 0. * ERR_WRITE_FAILED: The audio data write failed . */ - virtual int32_t Write(uint8_t *buffer, size_t bufferSize) = 0; + virtual int32_t Write(uint8_t *buffer, size_t bufferSize) = 0; /** * @brief Obtains the audio renderer state. * * @return Returns the audio renderer state defined in {@link RendererState}. */ - virtual RendererState GetStatus() = 0; + virtual RendererState GetStatus() const = 0; /** * @brief Obtains the timestamp. @@ -134,7 +136,7 @@ public: * {@link Timestamp.Timestampbase#MONOTONIC}. * @return Returns true if the timestamp is successfully obtained; returns false otherwise. */ - virtual bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) = 0; + virtual bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) const = 0; /** * @brief Obtains the latency in microseconds. @@ -143,28 +145,28 @@ public: * @return Returns {@link SUCCESS} if latency is successfully obtained, returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetLatency(uint64_t &latency) = 0; + virtual int32_t GetLatency(uint64_t &latency) const = 0; /** * @brief drain renderer buffer. * * @return Returns true if the buffer is successfully drained; returns false otherwise. */ - virtual bool Drain() = 0; + virtual bool Drain() const = 0; /** * @brief Stops audio rendering. * * @return Returns true if the rendering is successfully stopped; returns false otherwise. */ - virtual bool Stop() = 0; + virtual bool Stop() const = 0; /** * @brief Releases a local AudioRenderer object. * * @return Returns true if the object is successfully released; returns false otherwise. */ - virtual bool Release() = 0; + virtual bool Release() const = 0; /** * @brief Obtains a reasonable minimum buffer size for rendering, however, the renderer can @@ -174,7 +176,7 @@ public: * @return Returns {@link SUCCESS} if bufferSize is successfully obtained; returns an error code * defined in {@link audio_errors.h} otherwise. */ - virtual int32_t GetBufferSize(size_t &bufferSize) = 0; + virtual int32_t GetBufferSize(size_t &bufferSize) const = 0; /** * @brief Obtains the foramts supported by renderer. diff --git a/interfaces/innerkits/native/audiostream/include/audio_stream.h b/interfaces/innerkits/native/audiostream/include/audio_stream.h index ea8fbacdcddbeaa12e34b8fedee82855b4ddac68..d24838e832adab38adf42e23fb3446321b8b7af8 100644 --- a/interfaces/innerkits/native/audiostream/include/audio_stream.h +++ b/interfaces/innerkits/native/audiostream/include/audio_stream.h @@ -13,6 +13,7 @@ * limitations under the License. */ #include "audio_session.h" +#include "timestamp.h" #ifndef AUDIO_STREAM_H #define AUDIO_STREAM_H diff --git a/pulseaudio/src/BUILD.gn b/pulseaudio/src/BUILD.gn index 063115d247102260f5706a737e68b8090437a4dd..71c492c3554d4f57b55c5f3728f262fac0edbe99 100644 --- a/pulseaudio/src/BUILD.gn +++ b/pulseaudio/src/BUILD.gn @@ -147,3 +147,4 @@ ohos_prebuilt_etc("pa_client_config") { module_install_dir = "etc/pulse" part_name = "multimedia_audio_standard" } + diff --git a/pulseaudio/src/modules/hdi/hdi_source.c b/pulseaudio/src/modules/hdi/hdi_source.c index 06391bafc79f178b3ec56a39802df1efbe9827a6..9b14c5f875342610af5a76cde062fd44c9ee38a4 100644 --- a/pulseaudio/src/modules/hdi/hdi_source.c +++ b/pulseaudio/src/modules/hdi/hdi_source.c @@ -17,29 +17,61 @@ #include #endif +#include #include #include -#include #include #include #include #include + #include -#include -#include -#include #include #include #include #include +#include +#include +#include +#include #include #include -#include -#include "hdi_source.h" +#include + +#include + #include "media_log.h" +#define DEFAULT_SOURCE_NAME "hdi_input" +#define DEFAULT_AUDIO_DEVICE_NAME "Internal Mic" + +#define DEFAULT_BUFFER_SIZE (1024 * 16) +#define MAX_VOLUME_VALUE 15.0 +#define DEFAULT_LEFT_VOLUME MAX_VOLUME_VALUE +#define DEFAULT_RIGHT_VOLUME MAX_VOLUME_VALUE +#define MAX_LATENCY_USEC (PA_USEC_PER_SEC * 2) +#define MIN_LATENCY_USEC 500 +#define AUDIO_POINT_NUM 1024 +#define AUDIO_FRAME_NUM_IN_BUF 30 + +struct userdata { + pa_core *core; + pa_module *module; + pa_source *source; + pa_thread *thread; + pa_thread_mq thread_mq; + pa_rtpoll *rtpoll; + size_t buffer_size; + pa_usec_t block_usec; + pa_usec_t timestamp; + AudioSourceAttr attrs; + // A flag to signal us to prevent silent record during bootup + bool IsReady; + bool IsCapturerInit; +}; + static int pa_capturer_init(struct userdata *u); static void pa_capturer_exit(void); @@ -71,21 +103,21 @@ static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t off switch (code) { case PA_SOURCE_MESSAGE_GET_LATENCY: { - pa_usec_t now; - now = pa_rtclock_now(); - *((int64_t*) data) = (int64_t)now - (int64_t)u->timestamp; - return 0; + pa_usec_t now; + now = pa_rtclock_now(); + *((int64_t*) data) = (int64_t)now - (int64_t)u->timestamp; + return 0; } default: { - pa_log("source_process_msg default case"); - return pa_source_process_msg(o, code, data, offset, chunk); + pa_log("source_process_msg default case"); + return pa_source_process_msg(o, code, data, offset, chunk); } } } /* Called from the IO thread. */ static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) { - struct userdata *u; + struct userdata *u = NULL; pa_assert(s); pa_assert_se(u = s->userdata); if (s->thread_info.state == PA_SOURCE_SUSPENDED || s->thread_info.state == PA_SOURCE_INIT) { @@ -99,7 +131,6 @@ static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_ static pa_hook_result_t source_output_fixate_hook_cb(pa_core *c, pa_source_output_new_data *data, struct userdata *u) { int ret; - MEDIA_DEBUG_LOG("HDI Source: Detected source output"); pa_assert(data); pa_assert(u); @@ -160,12 +191,11 @@ static void thread_func(void *userdata) { u->timestamp = pa_rtclock_now(); MEDIA_DEBUG_LOG("HDI Source: u->timestamp : %{public}llu", u->timestamp); - for (;;) { + while(true) { int ret = 0; - int retries = 0; uint64_t requestBytes; uint64_t replyBytes = 0; - void *p; + void *p = NULL; if (PA_SOURCE_IS_OPENED(u->source->thread_info.state) && (u->source->thread_info.state != PA_SOURCE_SUSPENDED) && u->IsReady && u->IsCapturerInit) { @@ -195,20 +225,12 @@ static void thread_func(void *userdata) { } if (replyBytes == 0) { - MEDIA_INFO_LOG("HDI Source: reply bytes 0"); - if (retries < MAX_RETRIES) { - usleep(FIVE_MSEC); - ++retries; - MEDIA_DEBUG_LOG("HDI Source: Requested data Length: %{public}llu bytes, Read: %{public}llu bytes. Sleep: %{public}d usec microseconds. Retry Times %{public}d", requestBytes, replyBytes, FIVE_MSEC, retries); - continue; - } else { - MEDIA_ERR_LOG("HDI Source: Failed to read after %{public}d retries, Requested data Length: %{public}llu bytes, Read: %{public}llu bytes, %{public}d ret", retries, requestBytes, replyBytes, ret); - pa_memblock_unref(chunk.memblock); - break; - } + MEDIA_ERR_LOG("HDI Source: Failed to read, Requested data Length: %{public}llu bytes," + " Read: %{public}llu bytes, %{public}d ret", requestBytes, replyBytes, ret); + pa_memblock_unref(chunk.memblock); + break; } - retries = 0; chunk.index = 0; chunk.length = replyBytes; pa_source_post(u->source, &chunk); @@ -234,7 +256,8 @@ static void thread_func(void *userdata) { /* If this was no regular exit from the loop we have to continue * processing messages until we received PA_MESSAGE_SHUTDOWN */ MEDIA_INFO_LOG("HDI Source: pa_rtpoll_run ret:%{public}d failed", ret ); - pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL); + pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, + 0, NULL, NULL); pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN); return; } @@ -242,7 +265,6 @@ static void thread_func(void *userdata) { timer_elapsed = pa_rtpoll_timer_elapsed(u->rtpoll); if (ret == 0) { - MEDIA_INFO_LOG("HDI Source: pa_rtpoll_run ret:%{public}d return", ret ); return; } } @@ -320,7 +342,7 @@ pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver) { u->attrs.channel = ss.channels; u->attrs.sampleRate = ss.rate; MEDIA_INFO_LOG("AudioDeviceCreateCapture format: %{public}d, channel: %{public}d, sampleRate: %{public}d", - u->attrs.format, u->attrs.channel, u->attrs.sampleRate); + u->attrs.format, u->attrs.channel, u->attrs.sampleRate); ret = pa_capturer_init(u); if (ret != 0) { goto fail; @@ -333,7 +355,7 @@ pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver) { pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, DEFAULT_AUDIO_DEVICE_NAME); pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "HDI source %s", DEFAULT_AUDIO_DEVICE_NAME); pa_source_new_data_set_sample_spec(&data, &ss); - pa_source_new_data_set_channel_map(&data, &map);; + pa_source_new_data_set_channel_map(&data, &map); pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%lu", (unsigned long)u->buffer_size); if (pa_modargs_get_proplist(ma, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) { @@ -342,7 +364,7 @@ pa_source *pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver) { goto fail; } - u->source = pa_source_new(m->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY); + u->source = pa_source_new(m->core, &data, PA_SOURCE_HARDWARE | PA_SOURCE_LATENCY); pa_source_new_data_done(&data); if (!u->source) { diff --git a/pulseaudio/src/modules/hdi/module_hdi_source.c b/pulseaudio/src/modules/hdi/module_hdi_source.c index e739bf7ea6a94881e768648baee3159a9aebe289..4e8760c937f138f9ad2e11f8f5130fffe858de00 100644 --- a/pulseaudio/src/modules/hdi/module_hdi_source.c +++ b/pulseaudio/src/modules/hdi/module_hdi_source.c @@ -19,12 +19,14 @@ #include -#include +#include #include +#include #include -#include -#include "hdi_source.h" +pa_source* pa_hdi_source_new(pa_module *m, pa_modargs *ma, const char*driver); + +void pa_hdi_source_free(pa_source *s); PA_MODULE_AUTHOR("OpenHarmony"); PA_MODULE_DESCRIPTION("OpenHarmony HDI Source"); @@ -51,7 +53,7 @@ static const char * const VALID_MODARGS[] = { NULL }; -int pa__init(pa_module*m) +int pa__init(pa_module *m) { pa_modargs *ma = NULL; diff --git a/services/include/audio_policy/client/audio_policy_base.h b/services/include/audio_policy/client/audio_policy_base.h index a3db6c077694e8745fb89e541da618b7ed08afb0..1fd80b4ed080c330bdf030a7884b2c158c7b15cd 100644 --- a/services/include/audio_policy/client/audio_policy_base.h +++ b/services/include/audio_policy/client/audio_policy_base.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef I_ST_AUDIO_POLICY_BASE_H -#define I_ST_AUDIO_POLICY_BASE_H +#ifndef I_AUDIO_POLICY_BASE_H +#define I_AUDIO_POLICY_BASE_H #include "audio_policy_types.h" #include "ipc_types.h" @@ -47,14 +47,6 @@ public: public: DECLARE_INTERFACE_DESCRIPTOR(u"IAudioPolicy"); }; - -class AudioPolicyManagerStub : public IRemoteStub { -public: - virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, - MessageParcel &reply, MessageOption &option) override; - bool IsPermissionValid(); -}; } // AudioStandard } // namespace OHOS - -#endif // I_ST_AUDIO_POLICY_BASE_H +#endif // I_AUDIO_POLICY_BASE_H diff --git a/services/include/audio_policy/client/audio_policy_manager_stub.h b/services/include/audio_policy/client/audio_policy_manager_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..6bacdadbc03b698b674c78f6c3323a438ba4d5bf --- /dev/null +++ b/services/include/audio_policy/client/audio_policy_manager_stub.h @@ -0,0 +1,42 @@ +/* + * 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_POLICY_MANAGER_STUB_H +#define AUDIO_POLICY_MANAGER_STUB_H + +#include "audio_policy_base.h" + +namespace OHOS { +namespace AudioStandard { +class AudioPolicyManagerStub : public IRemoteStub { +public: + virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) override; + bool IsPermissionValid(); + +private: + void SetStreamVolumeInternal(MessageParcel &data, MessageParcel &reply); + void SetRingerModeInternal(MessageParcel &data, MessageParcel &reply); + void GetRingerModeInternal(MessageParcel &data); + void GetStreamVolumeInternal(MessageParcel &data, MessageParcel &reply); + void SetStreamMuteInternal(MessageParcel &data, MessageParcel &reply); + void GetStreamMuteInternal(MessageParcel &data, MessageParcel &reply); + void IsStreamActiveInternal(MessageParcel &data, MessageParcel &reply); + void SetDeviceActiveInternal(MessageParcel &data, MessageParcel &reply); + void IsDeviceActiveInternal(MessageParcel &data, MessageParcel &reply); +}; +} // AudioStandard +} // namespace OHOS +#endif // AUDIO_POLICY_MANAGER_STUB_H diff --git a/services/include/audio_policy/server/audio_policy_server.h b/services/include/audio_policy/server/audio_policy_server.h index a5cb6564fba798d19b16aed96e1e65847623deaa..290e35aa3d775f85d337b72486c52f8bf594fecd 100644 --- a/services/include/audio_policy/server/audio_policy_server.h +++ b/services/include/audio_policy/server/audio_policy_server.h @@ -19,7 +19,7 @@ #include #include -#include "audio_policy_base.h" +#include "audio_policy_manager_stub.h" #include "audio_policy_service.h" #include "iremote_stub.h" #include "system_ability.h" diff --git a/services/include/client/audio_service_client.h b/services/include/client/audio_service_client.h index 6acaf3c206f3b28d32da9a0c34d45da2423f29e6..d8b39f746380943c3b046b98f3c8e8e15a9639c5 100644 --- a/services/include/client/audio_service_client.h +++ b/services/include/client/audio_service_client.h @@ -42,7 +42,7 @@ typedef pa_client_info ClientInfo; struct StreamBuffer { uint8_t *buffer; // the virtual address of stream - uint32_t bufferLen; // stream length, by bytes + uint32_t bufferLen; // stream length in bytes }; struct AudioCache { @@ -305,6 +305,8 @@ private: int32_t InitializeAudioCache(); size_t WriteToAudioCache(const StreamBuffer &stream); int32_t DrainAudioCache(); + + int32_t UpdateReadBuffer(uint8_t *buffer, size_t &length, size_t &readSize); int32_t PaWriteStream(const uint8_t *buffer, size_t &length); // Error code used @@ -318,7 +320,6 @@ private: static const uint32_t AUDIO_CLIENT_WRITE_STREAM_ERR = -7; static const uint32_t AUDIO_CLIENT_PA_ERR = -8; - // Default values static const uint32_t MINIMUM_BUFFER_SIZE = 1024; static const uint32_t DEFAULT_SAMPLING_RATE = 44100; @@ -332,7 +333,6 @@ private: // Resets PA audio client and free up resources if any with this API void ResetPAAudioClient(); - // Callbacks to be implemented static void PAStreamStateCb(pa_stream *stream, void *userdata); static void PAStreamUnderFlowCb(pa_stream *stream, void *userdata); diff --git a/services/src/audio_policy/server/audio_policy_manager_stub.cpp b/services/src/audio_policy/server/audio_policy_manager_stub.cpp index 1b76750036ec2f6c4604224178e5e443a76d60fe..2594769d58e91454ddba657bda5413e6c8830a7f 100644 --- a/services/src/audio_policy/server/audio_policy_manager_stub.cpp +++ b/services/src/audio_policy/server/audio_policy_manager_stub.cpp @@ -14,95 +14,130 @@ */ #include "audio_errors.h" -#include "audio_policy_base.h" +#include "audio_policy_manager_stub.h" #include "audio_policy_server.h" #include "audio_policy_types.h" #include "media_log.h" namespace OHOS { namespace AudioStandard { +void AudioPolicyManagerStub::SetStreamVolumeInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioStreamType streamType = static_cast(data.ReadInt32()); + float volume = data.ReadFloat(); + int result = SetStreamVolume(streamType, volume); + if (result == SUCCESS) + reply.WriteInt32(MEDIA_OK); + else + reply.WriteInt32(MEDIA_ERR); +} + +void AudioPolicyManagerStub::SetRingerModeInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioRingerMode rMode = static_cast(data.ReadInt32()); + int32_t result = SetRingerMode(rMode); + reply.WriteInt32(result); +} + +void AudioPolicyManagerStub::GetRingerModeInternal(MessageParcel &reply) +{ + AudioRingerMode rMode = GetRingerMode(); + reply.WriteInt32(static_cast(rMode)); +} + +void AudioPolicyManagerStub::GetStreamVolumeInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioStreamType streamType = static_cast(data.ReadInt32()); + float volume = GetStreamVolume(streamType); + reply.WriteFloat(volume); +} + +void AudioPolicyManagerStub::SetStreamMuteInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioStreamType streamType = static_cast(data.ReadInt32()); + bool mute = data.ReadBool(); + int result = SetStreamMute(streamType, mute); + if (result == SUCCESS) + reply.WriteInt32(MEDIA_OK); + else + reply.WriteInt32(MEDIA_ERR); +} + +void AudioPolicyManagerStub::GetStreamMuteInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioStreamType streamType = static_cast(data.ReadInt32()); + bool mute = GetStreamMute(streamType); + reply.WriteBool(mute); +} + +void AudioPolicyManagerStub::IsStreamActiveInternal(MessageParcel &data, MessageParcel &reply) +{ + AudioStreamType streamType = static_cast(data.ReadInt32()); + bool isActive = IsStreamActive(streamType); + reply.WriteBool(isActive); +} + +void AudioPolicyManagerStub::SetDeviceActiveInternal(MessageParcel &data, MessageParcel &reply) +{ + DeviceType deviceType = static_cast(data.ReadInt32()); + bool active = data.ReadBool(); + int32_t result = SetDeviceActive(deviceType, active); + if (result == SUCCESS) + reply.WriteInt32(MEDIA_OK); + else + reply.WriteInt32(MEDIA_ERR); +} + +void AudioPolicyManagerStub::IsDeviceActiveInternal(MessageParcel &data, MessageParcel &reply) +{ + DeviceType deviceType = static_cast(data.ReadInt32()); + bool result = IsDeviceActive(deviceType); + reply.WriteBool(result); +} + int AudioPolicyManagerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { switch (code) { - case SET_STREAM_VOLUME: { - AudioStreamType streamType = static_cast(data.ReadInt32()); - float volume = data.ReadFloat(); - int result = SetStreamVolume(streamType, volume); - if (result == SUCCESS) - reply.WriteInt32(MEDIA_OK); - else - reply.WriteInt32(MEDIA_ERR); + case SET_STREAM_VOLUME: + SetStreamVolumeInternal(data, reply); break; - } - case SET_RINGER_MODE: { - AudioRingerMode rMode = static_cast(data.ReadInt32()); - int32_t result = SetRingerMode(rMode); - reply.WriteInt32(result); + case SET_RINGER_MODE: + SetRingerModeInternal(data, reply); break; - } - case GET_RINGER_MODE: { - AudioRingerMode rMode = GetRingerMode(); - reply.WriteInt32(static_cast(rMode)); + case GET_RINGER_MODE: + GetRingerModeInternal(reply); break; - } - case GET_STREAM_VOLUME: { - AudioStreamType streamType = static_cast(data.ReadInt32()); - float volume = GetStreamVolume(streamType); - reply.WriteFloat(volume); + case GET_STREAM_VOLUME: + GetStreamVolumeInternal(data, reply); break; - } - - case SET_STREAM_MUTE: { - AudioStreamType streamType = static_cast(data.ReadInt32()); - bool mute = data.ReadBool(); - int result = SetStreamMute(streamType, mute); - if (result == SUCCESS) - reply.WriteInt32(MEDIA_OK); - else - reply.WriteInt32(MEDIA_ERR); + + case SET_STREAM_MUTE: + SetStreamMuteInternal(data, reply); break; - } - case GET_STREAM_MUTE: { - AudioStreamType streamType = static_cast(data.ReadInt32()); - bool mute = GetStreamMute(streamType); - reply.WriteBool(mute); + case GET_STREAM_MUTE: + GetStreamMuteInternal(data, reply); break; - } - case IS_STREAM_ACTIVE: { - AudioStreamType streamType = static_cast(data.ReadInt32()); - bool isActive = IsStreamActive(streamType); - reply.WriteBool(isActive); + case IS_STREAM_ACTIVE: + IsStreamActiveInternal(data, reply); break; - } - - case SET_DEVICE_ACTIVE: { - DeviceType deviceType = static_cast(data.ReadInt32()); - bool active = data.ReadBool(); - int32_t result = SetDeviceActive(deviceType, active); - if (result == SUCCESS) - reply.WriteInt32(MEDIA_OK); - else - reply.WriteInt32(MEDIA_ERR); + + case SET_DEVICE_ACTIVE: + SetDeviceActiveInternal(data, reply); break; - } - case IS_DEVICE_ACTIVE: { - DeviceType deviceType = static_cast(data.ReadInt32()); - bool result = IsDeviceActive(deviceType); - reply.WriteBool(result); + case IS_DEVICE_ACTIVE: + IsDeviceActiveInternal(data, reply); break; - } - default: { + default: MEDIA_ERR_LOG("default case, need check AudioPolicyManagerStub"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } } return MEDIA_OK; } 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 86d49dbbbd0487d53ec55aead24a872f3a3fc285..124c0dbe356a71dd8aa179398a58ffe42385990b 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 @@ -18,7 +18,7 @@ #include "audio_info.h" #include "audio_policy_manager_factory.h" -#include "iaudio_policy.h" +#include "iaudio_policy_interface.h" #include "iport_observer.h" #include "parser_factory.h" 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 68f7c907f3ee6e103ca4fb01f7822599b2d95327..91524a270b0be21e3147b3efe7cbd0ff4f505a3e 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 @@ -16,6 +16,8 @@ #ifndef ST_AUDIO_CONFIG_H #define ST_AUDIO_CONFIG_H +#include + #include "audio_info.h" #ifdef __cplusplus @@ -91,8 +93,7 @@ public: virtual ~AudioPortInfo() {} }; -struct AudioPortPinInfo : public PortInfo -{ +struct AudioPortPinInfo : public PortInfo { public: char* pinType; AudioPortPinInfo() diff --git a/services/src/audio_policy/server/service/include/interface/iaudio_policy.h b/services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h similarity index 100% rename from services/src/audio_policy/server/service/include/interface/iaudio_policy.h rename to services/src/audio_policy/server/service/include/interface/iaudio_policy_interface.h 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 ca97ee3ac2244f60b72b1de8a47e9f0b8235e4d5..af7ef9ab68cde912018ae414d648cf94d5b9aeb9 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 @@ -17,7 +17,7 @@ #define ST_AUDIO_PORT_OBSERVER_H #include "audio_info.h" -#include "iaudio_policy.h" +#include "iaudio_policy_interface.h" namespace OHOS { namespace AudioStandard { diff --git a/services/src/audio_policy/server/service/include/manager/pulseaudio_policy_manager.h b/services/src/audio_policy/server/service/include/manager/pulseaudio_policy_manager.h index 1056ace7a7ef65f7e15b069e4a9d9b00ee32b75d..dc8eca5bcb42e07be0f1e2bc04070f136c88b71d 100644 --- a/services/src/audio_policy/server/service/include/manager/pulseaudio_policy_manager.h +++ b/services/src/audio_policy/server/service/include/manager/pulseaudio_policy_manager.h @@ -28,7 +28,7 @@ extern "C" { #include #include "distributed_kv_data_manager.h" -#include "iaudio_policy.h" +#include "iaudio_policy_interface.h" #include "types.h" namespace OHOS { 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 a05d13b2961de4c5907bc4569cf471eb6f5ed91a..5bb9e7d3e4690d1eda4050fc9077f2ca7c9ad23a 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 @@ -150,7 +150,7 @@ void XMLParser::ParseAudioPorts(xmlNode* node) for (; child; child = child->next) { if (!xmlStrcmp(child->name, reinterpret_cast("AudioPort"))) { - std::shared_ptr portInfo = std::make_unique(); + std::shared_ptr portInfo = std::make_shared(); portInfo->type = TYPE_AUDIO_PORT; if (xmlHasProp(child, reinterpret_cast(const_cast("role")))) { @@ -202,7 +202,7 @@ void XMLParser::ParseAudioPortPins(xmlNode* node) for (; child; child = child->next) { if (!xmlStrcmp(child->name, reinterpret_cast("AudioPortPin"))) { - std::shared_ptr portInfo = std::make_unique(); + std::shared_ptr portInfo = std::make_shared(); portInfo->type = TYPE_AUDIO_PORT_PIN; if (xmlHasProp(child, reinterpret_cast(const_cast("role")))) diff --git a/services/src/audio_policy/server/service/src/manager/pulseaudio_policy_manager.cpp b/services/src/audio_policy/server/service/src/manager/pulseaudio_policy_manager.cpp index c8d9e8622cf83590fc6dd1b91407249ed0689efc..8b43169d8edea2e95b9e49b0520187fb186823a3 100644 --- a/services/src/audio_policy/server/service/src/manager/pulseaudio_policy_manager.cpp +++ b/services/src/audio_policy/server/service/src/manager/pulseaudio_policy_manager.cpp @@ -14,6 +14,7 @@ */ #include + #include "audio_errors.h" #include "media_log.h" #include "pulseaudio_policy_manager.h" @@ -89,19 +90,16 @@ void PulseAudioPolicyManager::Deinit(void) int32_t PulseAudioPolicyManager::SetStreamVolume(AudioStreamType streamType, float volume) { + std::unique_ptr userData = std::make_unique(); + userData->thiz = this; + userData->volume = volume; + userData->streamType = streamType; + if (mContext == NULL) { MEDIA_ERR_LOG("[PolicyManager] mContext is nullptr"); return ERROR; } - UserData* userData = new UserData; - if (userData == nullptr) - return ERROR; - - userData->thiz = this; - userData->volume = volume; - userData->streamType = streamType; - // Incase if KvStore didnot connect during bootup if (mAudioPolicyKvStore == nullptr) { bool isFirstBoot = false; @@ -114,13 +112,13 @@ int32_t PulseAudioPolicyManager::SetStreamVolume(AudioStreamType streamType, flo pa_threaded_mainloop_lock(mMainLoop); pa_operation *operation = pa_context_get_sink_input_info_list(mContext, - PulseAudioPolicyManager::GetSinkInputInfoVolumeCb, reinterpret_cast(userData)); + PulseAudioPolicyManager::GetSinkInputInfoVolumeCb, reinterpret_cast(userData.get())); if (operation == NULL) { MEDIA_ERR_LOG("[PolicyManager] pa_context_get_sink_input_info_list returned nullptr"); - delete userData; pa_threaded_mainloop_unlock(mMainLoop); return ERROR; } + userData.release(); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mMainLoop); @@ -138,16 +136,16 @@ float PulseAudioPolicyManager::GetStreamVolume(AudioStreamType streamType) int32_t PulseAudioPolicyManager::SetStreamMute(AudioStreamType streamType, bool mute) { + std::unique_ptr userData = std::make_unique(); + userData->thiz = this; + userData->mute = mute; + userData->streamType = streamType; + if (mContext == NULL) { MEDIA_ERR_LOG("[PolicyManager] mContext is nullptr"); return ERROR; } - std::shared_ptr userData = std::make_shared(); - userData->thiz = this; - userData->mute = mute; - userData->streamType = streamType; - pa_threaded_mainloop_lock(mMainLoop); pa_operation* operation = pa_context_get_sink_input_info_list(mContext, @@ -170,16 +168,16 @@ int32_t PulseAudioPolicyManager::SetStreamMute(AudioStreamType streamType, bool bool PulseAudioPolicyManager::GetStreamMute(AudioStreamType streamType) { + std::unique_ptr userData = std::make_unique(); + userData->thiz = this; + userData->streamType = streamType; + userData->mute = false; + if (mContext == NULL) { MEDIA_ERR_LOG("[PolicyManager] mContext is nullptr"); return false; } - std::shared_ptr userData = std::make_shared(); - userData->thiz = this; - userData->streamType = streamType; - userData->mute = false; - pa_threaded_mainloop_lock(mMainLoop); pa_operation *operation = pa_context_get_sink_input_info_list(mContext, @@ -202,20 +200,20 @@ bool PulseAudioPolicyManager::GetStreamMute(AudioStreamType streamType) bool PulseAudioPolicyManager::IsStreamActive(AudioStreamType streamType) { + std::unique_ptr userData = std::make_unique(); + userData->thiz = this; + userData->streamType = streamType; + userData->isCorked = true; + if (mContext == NULL) { MEDIA_ERR_LOG("[PolicyManager] mContext is nullptr"); return false; } - std::shared_ptr userData = std::make_shared(); - userData->thiz = this; - userData->streamType = streamType; - userData->isCorked = true; - pa_threaded_mainloop_lock(mMainLoop); - pa_operation *operation = pa_context_get_sink_input_info_list(mContext, PulseAudioPolicyManager::GetSinkInputInfoCorkStatusCb, - reinterpret_cast(userData.get())); + pa_operation *operation = pa_context_get_sink_input_info_list(mContext, + PulseAudioPolicyManager::GetSinkInputInfoCorkStatusCb, reinterpret_cast(userData.get())); if (operation == NULL) { MEDIA_ERR_LOG("[PolicyManager] pa_context_get_sink_input_info_list returned nullptr"); pa_threaded_mainloop_unlock(mMainLoop); @@ -235,7 +233,9 @@ bool PulseAudioPolicyManager::IsStreamActive(AudioStreamType streamType) return (userData->isCorked) ? false : true; } -int32_t PulseAudioPolicyManager::SetDeviceActive(AudioIOHandle ioHandle, DeviceType deviceType, std::string name, bool active) + +int32_t PulseAudioPolicyManager::SetDeviceActive(AudioIOHandle ioHandle, DeviceType deviceType, + std::string name, bool active) { pa_threaded_mainloop_lock(mMainLoop); @@ -313,7 +313,7 @@ AudioIOHandle PulseAudioPolicyManager::OpenAudioPort(std::shared_ptr userData = std::make_shared(); + std::unique_ptr userData = std::make_unique(); userData->thiz = this; pa_operation* operation = pa_context_load_module(mContext, audioPortInfo->name, moduleArgs.c_str(), ModuleLoadCb, @@ -689,16 +689,17 @@ void PulseAudioPolicyManager::WriteRingerModeToKvStore(AudioRingerMode ringerMod void PulseAudioPolicyManager::HandleSinkInputEvent(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { - UserData* userData = new UserData; + std::unique_ptr userData = std::make_unique(); userData->thiz = this; if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW) { pa_operation* operation = pa_context_get_sink_input_info(c, idx, - PulseAudioPolicyManager::GetSinkInputInfoVolumeCb, reinterpret_cast(userData)); + PulseAudioPolicyManager::GetSinkInputInfoVolumeCb, reinterpret_cast(userData.get())); if (operation == NULL) { MEDIA_ERR_LOG("[PolicyManager] pa_context_get_sink_input_info_list returned nullptr"); return; } + userData.release(); pa_operation_unref(operation); } @@ -831,12 +832,14 @@ void PulseAudioPolicyManager::GetSinkInputInfoVolumeCb(pa_context *c, const pa_s pa_cvolume_set(&cv, i->channel_map.channels, volume); pa_operation_unref(pa_context_set_sink_input_volume(c, i->index, &cv, NULL, NULL)); - if (i->mute) { - pa_operation_unref(pa_context_set_sink_input_mute(c, i->index, 0, NULL, NULL)); + if (streamID == userData->streamType) { + if (i->mute) { + pa_operation_unref(pa_context_set_sink_input_mute(c, i->index, 0, NULL, NULL)); + } } MEDIA_INFO_LOG("[PolicyManager] Applied volume : %{public}f for stream : %{public}s, volumeInt%{public}d", - userData->volume, i->name, volume); + vol, i->name, volume); return; } diff --git a/services/src/client/audio_service_client.cpp b/services/src/client/audio_service_client.cpp index ef25241bc2e096b478ab59b65d2af11b5cb2c9f5..cc63a15612c42369325581998fc493e47a0b9f21 100644 --- a/services/src/client/audio_service_client.cpp +++ b/services/src/client/audio_service_client.cpp @@ -391,10 +391,10 @@ int32_t AudioServiceClient::ConnectStreamToPA() pa_threaded_mainloop_lock(mainLoop); pa_buffer_attr bufferAttr; - bufferAttr.fragsize = (uint32_t) -1; - bufferAttr.prebuf = (uint32_t) -1; - bufferAttr.maxlength = (uint32_t) -1; - bufferAttr.tlength = (uint32_t) -1; + bufferAttr.fragsize = static_cast(-1); + bufferAttr.prebuf = static_cast(-1); + bufferAttr.maxlength = static_cast(-1); + bufferAttr.tlength = static_cast(-1); bufferAttr.minreq = pa_usec_to_bytes(LATENCY_IN_MSEC * PA_USEC_PER_MSEC, &sampleSpec); if (eAudioClientType == AUDIO_SERVICE_CLIENT_PLAYBACK) result = pa_stream_connect_playback(paStream, NULL, &bufferAttr, @@ -842,6 +842,30 @@ size_t AudioServiceClient::WriteStream(const StreamBuffer &stream, int32_t &pErr return cachedLen; } +int32_t AudioServiceClient::UpdateReadBuffer(uint8_t *buffer, size_t &length, size_t &readSize) +{ + size_t l = (internalRdBufLen < length) ? internalRdBufLen : length; + memcpy_s(buffer, length, (const uint8_t*) internalReadBuffer + internalRdBufIndex, l); + + length -= l; + internalRdBufIndex += l; + internalRdBufLen -= l; + readSize += l; + + if (!internalRdBufLen) { + int retVal = pa_stream_drop(paStream); + internalReadBuffer = NULL; + internalRdBufLen = 0; + internalRdBufIndex = 0; + if (retVal < 0) { + MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %d", retVal); + return AUDIO_CLIENT_READ_STREAM_ERR; + } + } + + return 0; +} + int32_t AudioServiceClient::ReadStream(StreamBuffer &stream, bool isBlocking) { uint8_t* buffer = stream.buffer; @@ -852,8 +876,6 @@ int32_t AudioServiceClient::ReadStream(StreamBuffer &stream, bool isBlocking) pa_threaded_mainloop_lock(mainLoop); while (length > 0) { - size_t l; - while (!internalReadBuffer) { int retVal = pa_stream_peek(paStream, &internalReadBuffer, &internalRdBufLen); if (retVal < 0) { @@ -882,27 +904,11 @@ int32_t AudioServiceClient::ReadStream(StreamBuffer &stream, bool isBlocking) } } - l = (internalRdBufLen < length) ? internalRdBufLen : length; - memcpy_s(buffer, length, (const uint8_t*) internalReadBuffer + internalRdBufIndex, l); - - buffer = (uint8_t*) buffer + l; - length -= l; - - internalRdBufIndex += l; - internalRdBufLen -= l; - readSize += l; - - if (!internalRdBufLen) { - int retVal = pa_stream_drop(paStream); - internalReadBuffer = NULL; - internalRdBufLen = 0; - internalRdBufIndex = 0; - if (retVal < 0) { - MEDIA_ERR_LOG("pa_stream_drop failed, retVal: %d", retVal); - pa_threaded_mainloop_unlock(mainLoop); - return AUDIO_CLIENT_READ_STREAM_ERR; - } + if (UpdateReadBuffer(buffer, length, readSize) != 0) { + pa_threaded_mainloop_unlock(mainLoop); + return AUDIO_CLIENT_READ_STREAM_ERR; } + buffer = stream.buffer + readSize; } pa_threaded_mainloop_unlock(mainLoop); return readSize; @@ -1007,9 +1013,9 @@ int32_t AudioServiceClient::GetCurrentTimeStamp(uint64_t &timeStamp) if (!info) { retVal = AUDIO_CLIENT_ERR; } else { - if(eAudioClientType == AUDIO_SERVICE_CLIENT_PLAYBACK) { + if (eAudioClientType == AUDIO_SERVICE_CLIENT_PLAYBACK) { timeStamp = pa_bytes_to_usec(info->write_index, &sampleSpec); - } else if(eAudioClientType == AUDIO_SERVICE_CLIENT_RECORD) { + } else if (eAudioClientType == AUDIO_SERVICE_CLIENT_RECORD) { timeStamp = pa_bytes_to_usec(info->read_index, &sampleSpec); } } diff --git a/services/src/client/audio_stream.cpp b/services/src/client/audio_stream.cpp index aa767d8a7d72075669ca9e8e63bcde83cff946f3..22f6c473b3f662396f2197f811bad7b7fd04dc1e 100644 --- a/services/src/client/audio_stream.cpp +++ b/services/src/client/audio_stream.cpp @@ -149,7 +149,7 @@ bool IsSamplingRateValid(uint32_t samplingRate) int32_t AudioStream::GetAudioStreamInfo(AudioStreamParams &audioStreamInfo) { MEDIA_INFO_LOG("AudioStream: GetAudioStreamInfo"); - if(GetAudioStreamParams(audioStreamInfo) != 0) { + if (GetAudioStreamParams(audioStreamInfo) != 0) { return ERR_OPERATION_FAILED; } diff --git a/services/src/client/audio_system_manager.cpp b/services/src/client/audio_system_manager.cpp index e73928363d27d9e8c87a91f6e1086be23f5eec28..ffe8bfd4d7032ef07b716d839a9bd087cc1f327f 100644 --- a/services/src/client/audio_system_manager.cpp +++ b/services/src/client/audio_system_manager.cpp @@ -16,8 +16,8 @@ #include "audio_errors.h" #include "audio_manager_proxy.h" #include "audio_policy_manager.h" -#include "audio_system_manager.h" #include "audio_stream.h" +#include "audio_system_manager.h" #include "iservice_registry.h" #include "media_log.h" #include "system_ability_definition.h" @@ -64,19 +64,19 @@ void AudioSystemManager::init() } } -bool AudioSystemManager::SetRingerMode(AudioRingerMode ringMode) +bool AudioSystemManager::SetRingerMode(AudioRingerMode ringMode) const { /* Call Audio Policy SetRingerMode */ return AudioPolicyManager::GetInstance().SetRingerMode(ringMode); } -AudioRingerMode AudioSystemManager::GetRingerMode() +AudioRingerMode AudioSystemManager::GetRingerMode() const { /* Call Audio Policy GetRingerMode */ return (AudioPolicyManager::GetInstance().GetRingerMode()); } -int32_t AudioSystemManager::SetDeviceActive(AudioDeviceDescriptor::DeviceType deviceType, bool flag) +int32_t AudioSystemManager::SetDeviceActive(AudioDeviceDescriptor::DeviceType deviceType, bool flag) const { switch (deviceType) { case SPEAKER: @@ -94,7 +94,7 @@ int32_t AudioSystemManager::SetDeviceActive(AudioDeviceDescriptor::DeviceType de return (AudioPolicyManager::GetInstance().SetDeviceActive(devType, flag)); } -bool AudioSystemManager::IsDeviceActive(AudioDeviceDescriptor::DeviceType deviceType) +bool AudioSystemManager::IsDeviceActive(AudioDeviceDescriptor::DeviceType deviceType) const { switch (deviceType) { case SPEAKER: @@ -112,7 +112,7 @@ bool AudioSystemManager::IsDeviceActive(AudioDeviceDescriptor::DeviceType device return (AudioPolicyManager::GetInstance().IsDeviceActive(devType)); } -bool AudioSystemManager::IsStreamActive(AudioSystemManager::AudioVolumeType volumeType) +bool AudioSystemManager::IsStreamActive(AudioSystemManager::AudioVolumeType volumeType) const { switch (volumeType) { case STREAM_MUSIC: @@ -127,17 +127,17 @@ bool AudioSystemManager::IsStreamActive(AudioSystemManager::AudioVolumeType volu return AudioPolicyManager::GetInstance().IsStreamActive(StreamVolType); } -const std::string AudioSystemManager::GetAudioParameter(const std::string key) +const std::string AudioSystemManager::GetAudioParameter(const std::string key) const { return g_sProxy->GetAudioParameter(key); } -void AudioSystemManager::SetAudioParameter(const std::string key, const std::string value) +void AudioSystemManager::SetAudioParameter(const std::string key, const std::string value) const { g_sProxy->SetAudioParameter(key, value); } -int32_t AudioSystemManager::SetVolume(AudioSystemManager::AudioVolumeType volumeType, float volume) +int32_t AudioSystemManager::SetVolume(AudioSystemManager::AudioVolumeType volumeType, float volume) const { /* Validate and return INVALID_PARAMS error */ if ((volume < 0) || (volume > 1)) { @@ -159,7 +159,7 @@ int32_t AudioSystemManager::SetVolume(AudioSystemManager::AudioVolumeType volume return AudioPolicyManager::GetInstance().SetStreamVolume(StreamVolType, volume); } -float AudioSystemManager::GetVolume(AudioSystemManager::AudioVolumeType volumeType) +float AudioSystemManager::GetVolume(AudioSystemManager::AudioVolumeType volumeType) const { switch (volumeType) { case STREAM_MUSIC: @@ -175,17 +175,17 @@ float AudioSystemManager::GetVolume(AudioSystemManager::AudioVolumeType volumeTy return AudioPolicyManager::GetInstance().GetStreamVolume(StreamVolType); } -float AudioSystemManager::GetMaxVolume(AudioSystemManager::AudioVolumeType volumeType) +float AudioSystemManager::GetMaxVolume(AudioSystemManager::AudioVolumeType volumeType) const { return g_sProxy->GetMaxVolume(volumeType); } -float AudioSystemManager::GetMinVolume(AudioSystemManager::AudioVolumeType volumeType) +float AudioSystemManager::GetMinVolume(AudioSystemManager::AudioVolumeType volumeType) const { return g_sProxy->GetMinVolume(volumeType); } -int32_t AudioSystemManager::SetMute(AudioSystemManager::AudioVolumeType volumeType, bool mute) +int32_t AudioSystemManager::SetMute(AudioSystemManager::AudioVolumeType volumeType, bool mute) const { switch (volumeType) { case STREAM_MUSIC: @@ -201,7 +201,7 @@ int32_t AudioSystemManager::SetMute(AudioSystemManager::AudioVolumeType volumeTy return AudioPolicyManager::GetInstance().SetStreamMute(StreamVolType, mute); } -bool AudioSystemManager::IsStreamMute(AudioSystemManager::AudioVolumeType volumeType) +bool AudioSystemManager::IsStreamMute(AudioSystemManager::AudioVolumeType volumeType) const { MEDIA_DEBUG_LOG("AudioSystemManager::GetMute Client"); @@ -219,17 +219,18 @@ bool AudioSystemManager::IsStreamMute(AudioSystemManager::AudioVolumeType volume return AudioPolicyManager::GetInstance().GetStreamMute(StreamVolType); } -int32_t AudioSystemManager::SetMicrophoneMute(bool isMute) +int32_t AudioSystemManager::SetMicrophoneMute(bool isMute) const { return g_sProxy->SetMicrophoneMute(isMute); } -bool AudioSystemManager::IsMicrophoneMute() +bool AudioSystemManager::IsMicrophoneMute() const { return g_sProxy->IsMicrophoneMute(); } std::vector> AudioSystemManager::GetDevices(AudioDeviceDescriptor::DeviceFlag deviceFlag) + const { return g_sProxy->GetDevices(deviceFlag); } diff --git a/services/src/server/audio_server.cpp b/services/src/server/audio_server.cpp index faf80e8324979352dc9b9aa722c23e931fa5de9d..7c92f2bc459797e33e81231b82b8dc0374a3af1e 100644 --- a/services/src/server/audio_server.cpp +++ b/services/src/server/audio_server.cpp @@ -130,7 +130,7 @@ bool AudioServer::IsMicrophoneMute() if (audioCapturerSourceInstance->capturerInited_ == false) { MEDIA_ERR_LOG("Capturer is not initialized. Start the recording first !"); } else if (audioCapturerSourceInstance->GetMute(isMute)) { - MEDIA_ERR_LOG("GetMute status in capturer returned Error !"); + MEDIA_ERR_LOG("GetMute status in capturer returned Error !"); } return isMute; @@ -140,7 +140,7 @@ std::vector> AudioServer::GetDevices(AudioDeviceDesc { MEDIA_DEBUG_LOG("GetDevices server"); audioDeviceDescriptor_.clear(); - AudioDeviceDescriptor *audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(); + sptr audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(); if (audioDescriptor == nullptr) { MEDIA_ERR_LOG("new AudioDeviceDescriptor fail"); return audioDeviceDescriptor_; @@ -152,8 +152,8 @@ std::vector> AudioServer::GetDevices(AudioDeviceDesc audioDescriptor->deviceType_ = AudioDeviceDescriptor::DeviceType::SPEAKER; audioDescriptor->deviceRole_ = AudioDeviceDescriptor::DeviceRole::OUTPUT_DEVICE; } else if (AudioDeviceDescriptor::DeviceFlag::ALL_DEVICES_FLAG == deviceFlag) { - AudioDeviceDescriptor *audioDescriptor_inputDevice = new(std::nothrow) AudioDeviceDescriptor(); - AudioDeviceDescriptor *audioDescriptor_outputDevice = new(std::nothrow) AudioDeviceDescriptor(); + 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; audioDeviceDescriptor_.push_back(audioDescriptor_inputDevice); diff --git a/services/test/audio_policy_test.cpp b/services/test/audio_policy_test.cpp index 58a7524dd38462c40986c6651b91e10cdd90f111..9c0a6c0de4d93e74fe1595309e059b2253382924 100644 --- a/services/test/audio_policy_test.cpp +++ b/services/test/audio_policy_test.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "audio_errors.h" @@ -32,7 +33,6 @@ namespace AudioPolicyTest { const int SECOND_ARG = 2; const int OPT_ARG_BASE = 10; const int OPT_SHORT_LEN = 3; - const float VOLUME = 0.5f; } static void PrintUsage(void) @@ -65,108 +65,155 @@ static void PrintUsage(void) cout << "\tWritten by Sajeesh Sidharthan and Anurup M" << endl << endl; } -int main(int argc, char* argv[]) +static void SetStreamVolume(const AudioSystemManager *audioSystemMgr, int streamType) +{ + float volume = strtof(optarg, nullptr); + cout << "Set Volume : " << volume << endl; + int32_t result = audioSystemMgr->SetVolume(static_cast(streamType), volume); + cout << "Set Volume Result: " << result << endl; +} + +static void GetStreamVolume(const AudioSystemManager *audioSystemMgr, int streamType) +{ + float volume = audioSystemMgr->GetVolume(static_cast(streamType)); + cout << "Get Volume : " << volume << endl; +} + +static void SetStreamMute(const AudioSystemManager *audioSystemMgr, int streamType) +{ + int mute = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); + cout << "Set Mute : " << mute << endl; + int32_t result = audioSystemMgr->SetMute(static_cast(streamType), + (mute) ? true : false); + cout << "Set Mute Result: " << result << endl; +} + +static void IsStreamMute(const AudioSystemManager *audioSystemMgr, int streamType) +{ + bool muteStatus = audioSystemMgr->IsStreamMute(static_cast(streamType)); + cout << "Get Mute : " << muteStatus << endl; +} + +static void SetStreamType(int &streamType) +{ + streamType = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); + cout << "Set Stream : " << streamType << endl; +} + +static void IsStreamActive(const AudioSystemManager *audioSystemMgr) +{ + 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[]) { - int32_t result; - float volume = AudioPolicyTest::VOLUME; - int device = -1; int active = -1; - int mute = -1; - bool muteStatus = false; - bool devActiveStatus = false; - int opt = 0; - int ringMode = 0; - int streamType = static_cast(AudioSystemManager::AudioVolumeType::STREAM_MUSIC); + int device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); + cout << "Set Device : " << device << endl; + + if (optind < argc && *argv[optind] != '-') { + active = strtol(argv[optind], nullptr, AudioPolicyTest::OPT_ARG_BASE); + optind++; + } + cout << "Active : " << active << endl << endl; + int32_t result = audioSystemMgr->SetDeviceActive(AudioDeviceDescriptor::DeviceType(device), + (active) ? true : false); + cout << "Set DeviceActive Result: " << result << endl; +} + +static void IsDeviceActive(const AudioSystemManager *audioSystemMgr) +{ + int device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); + bool devActiveStatus = audioSystemMgr->IsDeviceActive(AudioDeviceDescriptor::DeviceType(device)); + cout << "GetDevice Active : " << devActiveStatus << endl; +} + +static void SetRingerMode(const AudioSystemManager *audioSystemMgr) +{ + int ringMode = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); + cout << "Set Ringer Mode : " << ringMode << endl; + audioSystemMgr->SetRingerMode(static_cast(ringMode)); +} + +static void GetRingerMode(const AudioSystemManager *audioSystemMgr) +{ + int ringMode = static_cast(audioSystemMgr->GetRingerMode()); + cout << "Get Ringer Mode : " << ringMode << endl; +} + +static void NoValueError() +{ + char option[AudioPolicyTest::OPT_SHORT_LEN]; + cout << "option "; + snprintf_s(option, sizeof(option), sizeof(option) - 1, "-%c", optopt); + cout << option << " needs a value" << endl << endl; + PrintUsage(); +} + +static void UnknownOptionError() +{ + char option[AudioPolicyTest::OPT_SHORT_LEN]; + snprintf_s(option, sizeof(option), sizeof(option) - 1, "-%c", optopt); + cout << "unknown option: " << option << endl << endl; + PrintUsage(); +} + +int main(int argc, char* argv[]) +{ + int opt = 0; if (((argc >= AudioPolicyTest::SECOND_ARG) && !strcmp(argv[AudioPolicyTest::FIRST_ARG], "--help")) || (argc == AudioPolicyTest::FIRST_ARG)) { PrintUsage(); return ERR_INVALID_PARAM; } + int streamType = static_cast(AudioSystemManager::AudioVolumeType::STREAM_MUSIC); AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); - while ((opt = getopt(argc, argv, ":V:S:D:M:R:d:s:vmr")) != -1) { switch (opt) { case 'V': - volume = strtof(optarg, nullptr); - cout << "Set Volume : " << volume << endl; - result = audioSystemMgr->SetVolume(static_cast(streamType), - volume); - cout << "Set Volume Result: " << result << endl; + SetStreamVolume(audioSystemMgr, streamType); break; case 'v': - volume = audioSystemMgr->GetVolume(static_cast(streamType)); - cout << "Get Volume : " << volume << endl; + GetStreamVolume(audioSystemMgr, streamType); break; case 'M': - mute = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - cout << "Set Mute : " << mute << endl; - result = audioSystemMgr->SetMute(static_cast(streamType), - (mute) ? true : false); - cout << "Set Mute Result: " << result << endl; + SetStreamMute(audioSystemMgr, streamType); break; case 'm': - muteStatus = audioSystemMgr->IsStreamMute( - static_cast(streamType)); - cout << "Get Mute : " << muteStatus << endl; + IsStreamMute(audioSystemMgr, streamType); break; case 'S': - streamType = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - cout << "Set Stream : " << streamType << endl; + SetStreamType(streamType); break; case 's': - streamType = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - cout << "Stream Active: " << audioSystemMgr->IsStreamActive( - static_cast(streamType)) << endl; + IsStreamActive(audioSystemMgr); break; case 'D': - device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - cout << "Set Device : " << device << endl; - - if (optind < argc && *argv[optind] != '-') { - active = strtol(argv[optind], nullptr, AudioPolicyTest::OPT_ARG_BASE); - optind++; - } - cout << "Active : " << active << endl << endl; - - result = audioSystemMgr->SetDeviceActive(AudioDeviceDescriptor::DeviceType(device), - (active) ? true : false); - cout << "Set DeviceActive Result: " << result << endl; + SetDeviceActive(audioSystemMgr, argc, argv); break; case 'd': - device = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - devActiveStatus = audioSystemMgr->IsDeviceActive(AudioDeviceDescriptor::DeviceType(device)); - cout << "GetDevice Active : " << devActiveStatus << endl; + IsDeviceActive(audioSystemMgr); break; case 'R': - ringMode = strtol(optarg, nullptr, AudioPolicyTest::OPT_ARG_BASE); - cout << "Set Ringer Mode : " << ringMode << endl; - audioSystemMgr->SetRingerMode(static_cast(ringMode)); + SetRingerMode(audioSystemMgr); break; case 'r': - ringMode = static_cast(audioSystemMgr->GetRingerMode()); - cout << "Get Ringer Mode : " << ringMode << endl; + GetRingerMode(audioSystemMgr); break; case ':': - char option[AudioPolicyTest::OPT_SHORT_LEN]; - cout << "option "; - snprintf(option, AudioPolicyTest::OPT_SHORT_LEN, "-%c", optopt); - cout << option << " needs a value" << endl << endl; - PrintUsage(); + NoValueError(); break; - case '?': { - char option[AudioPolicyTest::OPT_SHORT_LEN]; - snprintf(option, AudioPolicyTest::OPT_SHORT_LEN, "-%c", optopt); - cout << "unknown option: " << option << endl << endl; - PrintUsage(); + case '?': + UnknownOptionError(); break; - } default: break; } } - cout<<"Exit from test app"<< endl; return 0; } diff --git a/services/test/audio_recorder_test.cpp b/services/test/audio_recorder_test.cpp index d9f10ea0a08b402503409132ae9d45a63ed57d57..e7640fe6059ab06ba747a02ef9cac1bea48a08f6 100644 --- a/services/test/audio_recorder_test.cpp +++ b/services/test/audio_recorder_test.cpp @@ -30,13 +30,10 @@ namespace AudioTestConstants { constexpr int32_t SUCCESS = 0; } -class StreamRecorderTest { +class AudioRecorderTest { public: - bool TestRecord(int argc, char *argv[]) const + void CheckSupportedParams() const { - MEDIA_INFO_LOG("TestCapture start "); - - unique_ptr audioRecorder = AudioRecorder::Create(AudioStreamType::STREAM_MUSIC); vector supportedFormatList = AudioRecorder::GetSupportedFormats(); MEDIA_INFO_LOG("Supported formats:"); for (auto i = supportedFormatList.begin(); i != supportedFormatList.end(); ++i) { @@ -61,11 +58,10 @@ public: for (auto i = supportedSamplingRates.begin(); i != supportedSamplingRates.end(); ++i) { MEDIA_INFO_LOG("sampling rate %{public}d", *i); } - AudioRecorderParams recorderParams; - recorderParams.audioSampleFormat = SAMPLE_S16LE; - recorderParams.samplingRate = static_cast(atoi(argv[AudioTestConstants::SECOND_ARG_IDX])); - recorderParams.audioChannel = AudioChannel::STEREO; - recorderParams.audioEncoding = ENCODING_PCM; + } + + bool InitRecord(const unique_ptr &audioRecorder, const AudioRecorderParams &recorderParams) const + { if (audioRecorder->SetParams(recorderParams) != AudioTestConstants::SUCCESS) { MEDIA_ERR_LOG("Set audio stream parameters failed"); audioRecorder->Release(); @@ -89,6 +85,11 @@ public: MEDIA_INFO_LOG("Get Audio channels: %{public}d", getRecorderParams.audioChannel); } + return true; + } + + bool StartRecord(const unique_ptr &audioRecorder, bool isBlocking, FILE *pFile) const + { size_t bufferLen; if (audioRecorder->GetBufferSize(bufferLen) < 0) { MEDIA_ERR_LOG(" GetMinimumBufferSize failed"); @@ -103,12 +104,8 @@ public: } MEDIA_INFO_LOG("Frame count: %{public}d", frameCount); - bool isBlocking = (atoi(argv[AudioTestConstants::THIRD_ARG_IDX]) == 1); - MEDIA_INFO_LOG("Is blocking read: %{public}s", isBlocking ? "true" : "false"); - uint8_t* buffer = nullptr; buffer = (uint8_t *) malloc(bufferLen); - FILE *pFile = fopen(argv[AudioTestConstants::SECOND_ARG_IDX - 1], "wb"); size_t size = 1; size_t numBuffersToRecord = 1024; @@ -136,6 +133,36 @@ public: } } } + free(buffer); + + return true; + } + + bool TestRecord(int argc, char *argv[]) const + { + MEDIA_INFO_LOG("TestCapture start "); + + unique_ptr audioRecorder = AudioRecorder::Create(AudioStreamType::STREAM_MUSIC); + + CheckSupportedParams(); + + AudioRecorderParams recorderParams; + recorderParams.audioSampleFormat = SAMPLE_S16LE; + recorderParams.samplingRate = static_cast(atoi(argv[AudioTestConstants::SECOND_ARG_IDX])); + recorderParams.audioChannel = AudioChannel::STEREO; + recorderParams.audioEncoding = ENCODING_PCM; + if (!InitRecord(audioRecorder, recorderParams)) { + MEDIA_ERR_LOG("Initialize record failed"); + return false; + } + + bool isBlocking = (atoi(argv[AudioTestConstants::THIRD_ARG_IDX]) == 1); + MEDIA_INFO_LOG("Is blocking read: %{public}s", isBlocking ? "true" : "false"); + FILE *pFile = fopen(argv[AudioTestConstants::SECOND_ARG_IDX - 1], "wb"); + if (!StartRecord(audioRecorder, isBlocking, pFile)) { + MEDIA_ERR_LOG("Start record failed"); + return false; + } Timestamp timestamp; if (audioRecorder->GetAudioTime(timestamp, Timestamp::Timestampbase::MONOTONIC)) { @@ -144,18 +171,17 @@ public: } fflush(pFile); - if(!audioRecorder->Flush()) { + if (!audioRecorder->Flush()) { MEDIA_ERR_LOG("AudioRecorderTest: flush failed"); } - if(!audioRecorder->Stop()) { + if (!audioRecorder->Stop()) { MEDIA_ERR_LOG("AudioRecorderTest: Stop failed"); } - if(!audioRecorder->Release()) { + if (!audioRecorder->Release()) { MEDIA_ERR_LOG("AudioRecorderTest: Release failed"); } - free(buffer); fclose(pFile); MEDIA_INFO_LOG("TestCapture end"); @@ -177,7 +203,7 @@ int main(int argc, char *argv[]) MEDIA_INFO_LOG("argv[2]=%{public}s", argv[AudioTestConstants::SECOND_ARG_IDX]); MEDIA_INFO_LOG("argv[3]=%{public}s", argv[AudioTestConstants::THIRD_ARG_IDX]); - StreamRecorderTest testObj; + AudioRecorderTest testObj; bool ret = testObj.TestRecord(argc, argv); return ret; diff --git a/services/test/audio_renderer_test.cpp b/services/test/audio_renderer_test.cpp index 5df0c5b902c534f9cf299772a6359d8418f34556..7e8418e7703a57899b17912c2d5f19d96cdd8967 100644 --- a/services/test/audio_renderer_test.cpp +++ b/services/test/audio_renderer_test.cpp @@ -23,31 +23,15 @@ using namespace OHOS; using namespace OHOS::AudioStandard; namespace AudioTestConstants { - constexpr int32_t SECOND_ARG_IDX = 2; + constexpr int32_t ARGS_INDEX_TWO = 2; + constexpr int32_t ARGS_COUNT_TWO = 2; constexpr int32_t SUCCESS = 0; } class AudioRendererTest { public: - bool TestPlayback(int argc, char *argv[]) const + void CheckSupportedParams() const { - MEDIA_INFO_LOG("AudioRendererTest: TestPlayback start "); - - wav_hdr wavHeader; - size_t headerSize = sizeof(wav_hdr); - FILE* wavFile = fopen(argv[1], "rb"); - if (wavFile == nullptr) { - MEDIA_INFO_LOG("AudioRendererTest: Unable to open wave file"); - return false; - } - size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile); - MEDIA_INFO_LOG("AudioRendererTest: Header Read in bytes %{public}d", bytesRead); - - AudioStreamType streamType = AudioStreamType::STREAM_MUSIC; - if (argc > 2) - streamType = static_cast(strtol(argv[AudioTestConstants::SECOND_ARG_IDX], NULL, 10)); - unique_ptr audioRenderer = AudioRenderer::Create(streamType); - vector supportedFormatList = AudioRenderer::GetSupportedFormats(); MEDIA_INFO_LOG("AudioRendererTest: Supported formats:"); for (auto i = supportedFormatList.begin(); i != supportedFormatList.end(); ++i) { @@ -72,15 +56,13 @@ public: for (auto i = supportedSamplingRates.begin(); i != supportedSamplingRates.end(); ++i) { MEDIA_INFO_LOG("AudioRendererTest: sampling rate %{public}d", *i); } + } - AudioRendererParams rendererParams; - rendererParams.sampleFormat = static_cast(wavHeader.bitsPerSample); - rendererParams.sampleRate = static_cast(wavHeader.SamplesPerSec); - rendererParams.channelCount = static_cast(wavHeader.NumOfChan); - rendererParams.encodingType = static_cast(ENCODING_PCM); + bool InitRender(const unique_ptr &audioRenderer, const AudioRendererParams &rendererParams) const + { if (audioRenderer->SetParams(rendererParams) != AudioTestConstants::SUCCESS) { MEDIA_ERR_LOG("AudioRendererTest: Set audio renderer parameters failed"); - if(!audioRenderer->Release()) { + if (!audioRenderer->Release()) { MEDIA_ERR_LOG("AudioRendererTest: Release failed"); } return false; @@ -90,7 +72,7 @@ public: MEDIA_INFO_LOG("AudioRendererTest: Starting renderer"); if (!audioRenderer->Start()) { MEDIA_ERR_LOG("AudioRendererTest: Start failed"); - if(!audioRenderer->Release()) { + if (!audioRenderer->Release()) { MEDIA_ERR_LOG("AudioRendererTest: Release failed"); } return false; @@ -103,10 +85,15 @@ public: MEDIA_INFO_LOG("AudioRendererTest: Get Audio format: %{public}d", paRendererParams.sampleFormat); MEDIA_INFO_LOG("AudioRendererTest: Get Audio sampling rate: %{public}d", paRendererParams.sampleRate); MEDIA_INFO_LOG("AudioRendererTest: Get Audio channels: %{public}d", paRendererParams.channelCount); - } - else { + } else { MEDIA_ERR_LOG("AudioRendererTest: Get Audio parameters failed"); } + + return true; + } + + bool StartRender(const unique_ptr &audioRenderer, FILE* wavFile) const + { size_t bufferLen; if (audioRenderer->GetBufferSize(bufferLen)) { MEDIA_ERR_LOG("AudioRendererTest: GetMinimumBufferSize failed"); @@ -150,24 +137,65 @@ public: } } - if(!audioRenderer->Drain()) { + if (!audioRenderer->Drain()) { MEDIA_ERR_LOG("AudioRendererTest: Drain failed"); } + Timestamp timeStamp; if (audioRenderer->GetAudioTime(timeStamp, Timestamp::Timestampbase::MONOTONIC)) { MEDIA_INFO_LOG("AudioRendererTest: Timestamp seconds: %{public}ld", timeStamp.time.tv_sec); MEDIA_INFO_LOG("AudioRendererTest: Timestamp nanoseconds: %{public}ld", timeStamp.time.tv_nsec); } + free(buffer); + + return true; + } + + bool TestPlayback(int argc, char *argv[]) const + { + MEDIA_INFO_LOG("AudioRendererTest: TestPlayback start "); + + int numBase = 10; + wav_hdr wavHeader; + size_t headerSize = sizeof(wav_hdr); + FILE* wavFile = fopen(argv[1], "rb"); + if (wavFile == nullptr) { + MEDIA_INFO_LOG("AudioRendererTest: Unable to open wave file"); + return false; + } + size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile); + MEDIA_INFO_LOG("AudioRendererTest: Header Read in bytes %{public}d", bytesRead); + + AudioStreamType streamType = AudioStreamType::STREAM_MUSIC; + if (argc > AudioTestConstants::ARGS_COUNT_TWO) + streamType = static_cast(strtol(argv[AudioTestConstants::ARGS_INDEX_TWO], NULL, numBase)); + unique_ptr audioRenderer = AudioRenderer::Create(streamType); + + CheckSupportedParams(); + + AudioRendererParams rendererParams; + rendererParams.sampleFormat = static_cast(wavHeader.bitsPerSample); + rendererParams.sampleRate = static_cast(wavHeader.SamplesPerSec); + rendererParams.channelCount = static_cast(wavHeader.NumOfChan); + rendererParams.encodingType = static_cast(ENCODING_PCM); + if (!InitRender(audioRenderer, rendererParams)) { + MEDIA_ERR_LOG("AudioRendererTest: Init render failed"); + return false; + } - if(!audioRenderer->Stop()) { + if (StartRender(audioRenderer, wavFile)) { + MEDIA_ERR_LOG("AudioRendererTest: Start render failed"); + return false; + } + + if (!audioRenderer->Stop()) { MEDIA_ERR_LOG("AudioRendererTest: Stop failed"); } - if(!audioRenderer->Release()) { + if (!audioRenderer->Release()) { MEDIA_ERR_LOG("AudioRendererTest: Release failed"); } - free(buffer); fclose(wavFile); MEDIA_INFO_LOG("AudioRendererTest: TestPlayback end"); @@ -179,7 +207,7 @@ int main(int argc, char *argv[]) { MEDIA_INFO_LOG("AudioRendererTest: Render test in"); - if ((argv == nullptr) || (argc < AudioTestConstants::SECOND_ARG_IDX)) { + if ((argv == nullptr) || (argc < AudioTestConstants::ARGS_INDEX_TWO)) { MEDIA_ERR_LOG("AudioRendererTest: argv is null"); return 0; } diff --git a/services/test/pcm2wav.h b/services/test/pcm2wav.h index 29f8accb3ff1730226f56f4ca91dd9b81101f765..55aec245db6aa4b07bea136546d83b42772275f9 100644 --- a/services/test/pcm2wav.h +++ b/services/test/pcm2wav.h @@ -15,10 +15,10 @@ #ifndef PCM_2_WAV_H #define PCM_2_WAV_H -typedef struct WAV_HEADER { +struct WAV_HEADER { /* RIFF Chunk Descriptor */ uint8_t RIFF[4] = {'R', 'I', 'F', 'F'}; // RIFF Header Magic header - uint32_t ChunkSize; // RIFF Chunk Size + uint32_t ChunkSize = 0; // RIFF Chunk Size uint8_t WAVE[4] = {'W', 'A', 'V', 'E'}; // WAVE Header /* "fmt" sub-chunk */ uint8_t fmt[4] = {'f', 'm', 't', ' '}; // FMT header @@ -31,6 +31,8 @@ typedef struct WAV_HEADER { uint16_t bitsPerSample = 16; // Number of bits per sample /* "data" sub-chunk */ uint8_t Subchunk2ID[4] = {'d', 'a', 't', 'a'}; // "data" string - uint32_t Subchunk2Size; // Sampled data length -} wav_hdr; + uint32_t Subchunk2Size = 0; // Sampled data length +}; + +using wav_hdr = struct WAV_HEADER; #endif // PCM_2_WAV_H \ No newline at end of file diff --git a/services/test/playback_test.cpp b/services/test/playback_test.cpp index 2fb09a8272d7ff0746ef6d17beefb15c7a43876d..5fcd97de557fe7b128f7dabe9c3dd2d77c185a07 100644 --- a/services/test/playback_test.cpp +++ b/services/test/playback_test.cpp @@ -25,6 +25,8 @@ using namespace OHOS::AudioStandard; namespace { constexpr uint8_t DEFAULT_FORMAT = SAMPLE_S16LE; constexpr uint8_t DEFAULT_CHANNELS = 2; +constexpr int32_t ARGS_INDEX_TWO = 2; +constexpr int32_t ARGS_INDEX_THREE = 3; } // namespace class PlaybackTest : public AudioRendererCallbacks { @@ -44,30 +46,8 @@ public: virtual void OnEventCb(AudioServiceEventTypes error) const{} }; -int main(int argc, char* argv[]) +static int32_t InitPlayback(std::unique_ptr &client, AudioStreamParams &audioParams) { - wav_hdr wavHeader; - size_t headerSize = sizeof(wav_hdr); - FILE* wavFile = fopen(argv[1], "rb"); - if (wavFile == nullptr) { - fprintf(stderr, "Unable to open wave file"); - return -1; - } - - float volume = 0.5; - if (argc >= 3) - volume = strtof(argv[2], nullptr); - - size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile); - MEDIA_INFO_LOG("Header Read in bytes %{public}d", bytesRead); - AudioStreamParams audioParams; - audioParams.format = DEFAULT_FORMAT; - audioParams.samplingRate = wavHeader.SamplesPerSec; - audioParams.channels = DEFAULT_CHANNELS; - StreamBuffer stream; - PlaybackTest customCb; - - std::unique_ptr client = std::make_unique(); if (client == nullptr) { MEDIA_ERR_LOG("Create AudioServiceClient instance failed"); return -1; @@ -77,6 +57,7 @@ int main(int argc, char* argv[]) if (client->Initialize(AUDIO_SERVICE_CLIENT_PLAYBACK) < 0) return -1; + PlaybackTest customCb; client->RegisterAudioRendererCallbacks(customCb); MEDIA_INFO_LOG("Creating Stream"); @@ -87,10 +68,21 @@ int main(int argc, char* argv[]) if (client->StartStream() < 0) return -1; - AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); - audioSystemMgr->SetVolume(AudioSystemManager::AudioVolumeType::STREAM_MUSIC, volume); + return 0; +} +int32_t StartPlayback(std::unique_ptr &client, FILE *wavFile) +{ + uint8_t* buffer = nullptr; + int32_t n = 2; + size_t bytesToWrite = 0; + size_t bytesWritten = 0; + size_t minBytes = 4; + int32_t writeError; + uint64_t timeStamp; size_t bufferLen; + StreamBuffer stream; + if (client->GetMinimumBufferSize(bufferLen) < 0) { MEDIA_ERR_LOG(" GetMinimumBufferSize failed"); return -1; @@ -98,15 +90,7 @@ int main(int argc, char* argv[]) MEDIA_DEBUG_LOG("minimum buffer length: %{public}zu", bufferLen); - uint8_t* buffer = nullptr; - int32_t n = 2; buffer = (uint8_t *) malloc(n * bufferLen); - size_t bytesToWrite = 0; - size_t bytesWritten = 0; - size_t minBytes = 4; - int32_t writeError; - uint64_t timeStamp; - while (!feof(wavFile)) { bytesToWrite = fread(buffer, 1, bufferLen, wavFile); bytesWritten = 0; @@ -120,10 +104,50 @@ int main(int argc, char* argv[]) } } + free(buffer); + + return 0; +} + +int main(int argc, char* argv[]) +{ + wav_hdr wavHeader; + size_t headerSize = sizeof(wav_hdr); + FILE* wavFile = fopen(argv[1], "rb"); + if (wavFile == nullptr) { + fprintf(stderr, "Unable to open wave file"); + return -1; + } + + float volume = 0.5; + if (argc >= ARGS_INDEX_THREE) { + volume = strtof(argv[ARGS_INDEX_TWO], nullptr); + } + + size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile); + MEDIA_INFO_LOG("Header Read in bytes %{public}d", bytesRead); + AudioStreamParams audioParams; + audioParams.format = DEFAULT_FORMAT; + audioParams.samplingRate = wavHeader.SamplesPerSec; + audioParams.channels = DEFAULT_CHANNELS; + + std::unique_ptr client = std::make_unique(); + if (InitPlayback(client, audioParams) < 0) { + MEDIA_INFO_LOG("Initialize playback failed"); + return -1; + } + + AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); + audioSystemMgr->SetVolume(AudioSystemManager::AudioVolumeType::STREAM_MUSIC, volume); + + if (StartPlayback(client, wavFile) < 0) { + MEDIA_INFO_LOG("Start playback failed"); + return -1; + } + client->FlushStream(); client->StopStream(); client->ReleaseStream(); - free(buffer); fclose(wavFile); MEDIA_INFO_LOG("Exit from test app"); return 0;