2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #include "webrtc/modules/audio_processing/audio_processing_impl.h"
15 #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
16 #include "webrtc/modules/audio_processing/audio_buffer.h"
17 #include "webrtc/modules/audio_processing/echo_cancellation_impl_wrapper.h"
18 #include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
19 #include "webrtc/modules/audio_processing/gain_control_impl.h"
20 #include "webrtc/modules/audio_processing/high_pass_filter_impl.h"
21 #include "webrtc/modules/audio_processing/level_estimator_impl.h"
22 #include "webrtc/modules/audio_processing/noise_suppression_impl.h"
23 #include "webrtc/modules/audio_processing/processing_component.h"
24 #include "webrtc/modules/audio_processing/voice_detection_impl.h"
25 #include "webrtc/modules/interface/module_common_types.h"
26 #include "webrtc/system_wrappers/interface/compile_assert.h"
27 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
28 #include "webrtc/system_wrappers/interface/file_wrapper.h"
29 #include "webrtc/system_wrappers/interface/logging.h"
31 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
32 // Files generated at build-time by the protobuf compiler.
33 #ifdef WEBRTC_ANDROID_PLATFORM_BUILD
34 #include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
36 #include "webrtc/audio_processing/debug.pb.h"
38 #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
40 static const int kChunkSizeMs = 10;
42 #define RETURN_ON_ERR(expr) \
45 if (err != kNoError) { \
52 // Throughout webrtc, it's assumed that success is represented by zero.
53 COMPILE_ASSERT(AudioProcessing::kNoError == 0, no_error_must_be_zero);
55 AudioProcessing* AudioProcessing::Create(int id) {
59 AudioProcessing* AudioProcessing::Create() {
61 return Create(config);
64 AudioProcessing* AudioProcessing::Create(const Config& config) {
65 AudioProcessingImpl* apm = new AudioProcessingImpl(config);
66 if (apm->Initialize() != kNoError) {
74 AudioProcessingImpl::AudioProcessingImpl(const Config& config)
75 : echo_cancellation_(NULL),
76 echo_control_mobile_(NULL),
78 high_pass_filter_(NULL),
79 level_estimator_(NULL),
80 noise_suppression_(NULL),
81 voice_detection_(NULL),
82 crit_(CriticalSectionWrapper::CreateCriticalSection()),
85 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
86 debug_file_(FileWrapper::Create()),
87 event_msg_(new audioproc::Event()),
89 sample_rate_hz_(kSampleRate16kHz),
90 split_sample_rate_hz_(kSampleRate16kHz),
91 samples_per_channel_(kChunkSizeMs * sample_rate_hz_ / 1000),
94 was_stream_delay_set_(false),
95 num_reverse_channels_(1),
96 num_input_channels_(1),
97 num_output_channels_(1),
98 output_will_be_muted_(false),
100 echo_cancellation_ = EchoCancellationImplWrapper::Create(this);
101 component_list_.push_back(echo_cancellation_);
103 echo_control_mobile_ = new EchoControlMobileImpl(this);
104 component_list_.push_back(echo_control_mobile_);
106 gain_control_ = new GainControlImpl(this);
107 component_list_.push_back(gain_control_);
109 high_pass_filter_ = new HighPassFilterImpl(this);
110 component_list_.push_back(high_pass_filter_);
112 level_estimator_ = new LevelEstimatorImpl(this);
113 component_list_.push_back(level_estimator_);
115 noise_suppression_ = new NoiseSuppressionImpl(this);
116 component_list_.push_back(noise_suppression_);
118 voice_detection_ = new VoiceDetectionImpl(this);
119 component_list_.push_back(voice_detection_);
121 SetExtraOptions(config);
124 AudioProcessingImpl::~AudioProcessingImpl() {
126 CriticalSectionScoped crit_scoped(crit_);
127 while (!component_list_.empty()) {
128 ProcessingComponent* component = component_list_.front();
129 component->Destroy();
131 component_list_.pop_front();
134 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
135 if (debug_file_->Open()) {
136 debug_file_->CloseFile();
141 delete render_audio_;
142 render_audio_ = NULL;
145 if (capture_audio_) {
146 delete capture_audio_;
147 capture_audio_ = NULL;
155 CriticalSectionWrapper* AudioProcessingImpl::crit() const {
159 int AudioProcessingImpl::split_sample_rate_hz() const {
160 return split_sample_rate_hz_;
163 int AudioProcessingImpl::Initialize() {
164 CriticalSectionScoped crit_scoped(crit_);
165 return InitializeLocked();
168 int AudioProcessingImpl::InitializeLocked() {
169 if (render_audio_ != NULL) {
170 delete render_audio_;
171 render_audio_ = NULL;
174 if (capture_audio_ != NULL) {
175 delete capture_audio_;
176 capture_audio_ = NULL;
179 render_audio_ = new AudioBuffer(num_reverse_channels_,
180 samples_per_channel_);
181 capture_audio_ = new AudioBuffer(num_input_channels_,
182 samples_per_channel_);
184 // Initialize all components.
185 std::list<ProcessingComponent*>::iterator it;
186 for (it = component_list_.begin(); it != component_list_.end(); ++it) {
187 int err = (*it)->Initialize();
188 if (err != kNoError) {
193 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
194 if (debug_file_->Open()) {
195 int err = WriteInitMessage();
196 if (err != kNoError) {
205 void AudioProcessingImpl::SetExtraOptions(const Config& config) {
206 CriticalSectionScoped crit_scoped(crit_);
207 std::list<ProcessingComponent*>::iterator it;
208 for (it = component_list_.begin(); it != component_list_.end(); ++it)
209 (*it)->SetExtraOptions(config);
212 int AudioProcessingImpl::EnableExperimentalNs(bool enable) {
216 int AudioProcessingImpl::set_sample_rate_hz(int rate) {
217 CriticalSectionScoped crit_scoped(crit_);
218 if (rate == sample_rate_hz_) {
221 if (rate != kSampleRate8kHz &&
222 rate != kSampleRate16kHz &&
223 rate != kSampleRate32kHz) {
224 return kBadParameterError;
226 if (echo_control_mobile_->is_enabled() && rate > kSampleRate16kHz) {
227 LOG(LS_ERROR) << "AECM only supports 16 kHz or lower sample rates";
228 return kUnsupportedComponentError;
231 sample_rate_hz_ = rate;
232 samples_per_channel_ = rate / 100;
234 if (sample_rate_hz_ == kSampleRate32kHz) {
235 split_sample_rate_hz_ = kSampleRate16kHz;
237 split_sample_rate_hz_ = sample_rate_hz_;
240 return InitializeLocked();
243 int AudioProcessingImpl::sample_rate_hz() const {
244 CriticalSectionScoped crit_scoped(crit_);
245 return sample_rate_hz_;
248 int AudioProcessingImpl::set_num_reverse_channels(int channels) {
249 CriticalSectionScoped crit_scoped(crit_);
250 if (channels == num_reverse_channels_) {
253 // Only stereo supported currently.
254 if (channels > 2 || channels < 1) {
255 return kBadParameterError;
258 num_reverse_channels_ = channels;
260 return InitializeLocked();
263 int AudioProcessingImpl::num_reverse_channels() const {
264 return num_reverse_channels_;
267 int AudioProcessingImpl::set_num_channels(
269 int output_channels) {
270 CriticalSectionScoped crit_scoped(crit_);
271 if (input_channels == num_input_channels_ &&
272 output_channels == num_output_channels_) {
275 if (output_channels > input_channels) {
276 return kBadParameterError;
278 // Only stereo supported currently.
279 if (input_channels > 2 || input_channels < 1 ||
280 output_channels > 2 || output_channels < 1) {
281 return kBadParameterError;
284 num_input_channels_ = input_channels;
285 num_output_channels_ = output_channels;
287 return InitializeLocked();
290 int AudioProcessingImpl::num_input_channels() const {
291 return num_input_channels_;
294 int AudioProcessingImpl::num_output_channels() const {
295 return num_output_channels_;
298 void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
299 output_will_be_muted_ = muted;
302 bool AudioProcessingImpl::output_will_be_muted() const {
303 return output_will_be_muted_;
306 int AudioProcessingImpl::MaybeInitializeLocked(int sample_rate_hz,
307 int num_input_channels, int num_output_channels, int num_reverse_channels) {
308 if (sample_rate_hz == sample_rate_hz_ &&
309 num_input_channels == num_input_channels_ &&
310 num_output_channels == num_output_channels_ &&
311 num_reverse_channels == num_reverse_channels_) {
315 if (sample_rate_hz != kSampleRate8kHz &&
316 sample_rate_hz != kSampleRate16kHz &&
317 sample_rate_hz != kSampleRate32kHz) {
318 return kBadSampleRateError;
320 if (num_output_channels > num_input_channels) {
321 return kBadNumberChannelsError;
323 // Only mono and stereo supported currently.
324 if (num_input_channels > 2 || num_input_channels < 1 ||
325 num_output_channels > 2 || num_output_channels < 1 ||
326 num_reverse_channels > 2 || num_reverse_channels < 1) {
327 return kBadNumberChannelsError;
329 if (echo_control_mobile_->is_enabled() && sample_rate_hz > kSampleRate16kHz) {
330 LOG(LS_ERROR) << "AECM only supports 16 or 8 kHz sample rates";
331 return kUnsupportedComponentError;
334 sample_rate_hz_ = sample_rate_hz;
335 samples_per_channel_ = kChunkSizeMs * sample_rate_hz / 1000;
336 num_input_channels_ = num_input_channels;
337 num_output_channels_ = num_output_channels;
338 num_reverse_channels_ = num_reverse_channels;
340 if (sample_rate_hz_ == kSampleRate32kHz) {
341 split_sample_rate_hz_ = kSampleRate16kHz;
343 split_sample_rate_hz_ = sample_rate_hz_;
346 return InitializeLocked();
349 int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
350 CriticalSectionScoped crit_scoped(crit_);
354 return kNullPointerError;
356 // TODO(ajm): We now always set the output channels equal to the input
357 // channels here. Remove the ability to downmix entirely.
358 RETURN_ON_ERR(MaybeInitializeLocked(frame->sample_rate_hz_,
359 frame->num_channels_, frame->num_channels_, num_reverse_channels_));
360 if (frame->samples_per_channel_ != samples_per_channel_) {
361 return kBadDataLengthError;
364 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
365 if (debug_file_->Open()) {
366 event_msg_->set_type(audioproc::Event::STREAM);
367 audioproc::Stream* msg = event_msg_->mutable_stream();
368 const size_t data_size = sizeof(int16_t) *
369 frame->samples_per_channel_ *
370 frame->num_channels_;
371 msg->set_input_data(frame->data_, data_size);
372 msg->set_delay(stream_delay_ms_);
373 msg->set_drift(echo_cancellation_->stream_drift_samples());
374 msg->set_level(gain_control_->stream_analog_level());
375 msg->set_keypress(key_pressed_);
379 capture_audio_->DeinterleaveFrom(frame);
381 // TODO(ajm): experiment with mixing and AEC placement.
382 if (num_output_channels_ < num_input_channels_) {
383 capture_audio_->Mix(num_output_channels_);
384 frame->num_channels_ = num_output_channels_;
387 bool data_processed = is_data_processed();
388 if (analysis_needed(data_processed)) {
389 for (int i = 0; i < num_output_channels_; i++) {
390 // Split into a low and high band.
391 WebRtcSpl_AnalysisQMF(capture_audio_->data(i),
392 capture_audio_->samples_per_channel(),
393 capture_audio_->low_pass_split_data(i),
394 capture_audio_->high_pass_split_data(i),
395 capture_audio_->analysis_filter_state1(i),
396 capture_audio_->analysis_filter_state2(i));
400 err = high_pass_filter_->ProcessCaptureAudio(capture_audio_);
401 if (err != kNoError) {
405 err = gain_control_->AnalyzeCaptureAudio(capture_audio_);
406 if (err != kNoError) {
410 err = echo_cancellation_->ProcessCaptureAudio(capture_audio_);
411 if (err != kNoError) {
415 if (echo_control_mobile_->is_enabled() &&
416 noise_suppression_->is_enabled()) {
417 capture_audio_->CopyLowPassToReference();
420 err = noise_suppression_->ProcessCaptureAudio(capture_audio_);
421 if (err != kNoError) {
425 err = echo_control_mobile_->ProcessCaptureAudio(capture_audio_);
426 if (err != kNoError) {
430 err = voice_detection_->ProcessCaptureAudio(capture_audio_);
431 if (err != kNoError) {
435 err = gain_control_->ProcessCaptureAudio(capture_audio_);
436 if (err != kNoError) {
440 if (synthesis_needed(data_processed)) {
441 for (int i = 0; i < num_output_channels_; i++) {
442 // Recombine low and high bands.
443 WebRtcSpl_SynthesisQMF(capture_audio_->low_pass_split_data(i),
444 capture_audio_->high_pass_split_data(i),
445 capture_audio_->samples_per_split_channel(),
446 capture_audio_->data(i),
447 capture_audio_->synthesis_filter_state1(i),
448 capture_audio_->synthesis_filter_state2(i));
452 // The level estimator operates on the recombined data.
453 err = level_estimator_->ProcessStream(capture_audio_);
454 if (err != kNoError) {
458 capture_audio_->InterleaveTo(frame, interleave_needed(data_processed));
460 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
461 if (debug_file_->Open()) {
462 audioproc::Stream* msg = event_msg_->mutable_stream();
463 const size_t data_size = sizeof(int16_t) *
464 frame->samples_per_channel_ *
465 frame->num_channels_;
466 msg->set_output_data(frame->data_, data_size);
467 err = WriteMessageToDebugFile();
468 if (err != kNoError) {
474 was_stream_delay_set_ = false;
478 // TODO(ajm): Have AnalyzeReverseStream accept sample rates not matching the
479 // primary stream and convert ourselves rather than having the user manage it.
480 // We can be smarter and use the splitting filter when appropriate. Similarly,
481 // perform downmixing here.
482 int AudioProcessingImpl::AnalyzeReverseStream(AudioFrame* frame) {
483 CriticalSectionScoped crit_scoped(crit_);
486 return kNullPointerError;
488 if (frame->sample_rate_hz_ != sample_rate_hz_) {
489 return kBadSampleRateError;
491 RETURN_ON_ERR(MaybeInitializeLocked(sample_rate_hz_, num_input_channels_,
492 num_output_channels_, frame->num_channels_));
494 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
495 if (debug_file_->Open()) {
496 event_msg_->set_type(audioproc::Event::REVERSE_STREAM);
497 audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream();
498 const size_t data_size = sizeof(int16_t) *
499 frame->samples_per_channel_ *
500 frame->num_channels_;
501 msg->set_data(frame->data_, data_size);
502 err = WriteMessageToDebugFile();
503 if (err != kNoError) {
509 render_audio_->DeinterleaveFrom(frame);
511 if (sample_rate_hz_ == kSampleRate32kHz) {
512 for (int i = 0; i < num_reverse_channels_; i++) {
513 // Split into low and high band.
514 WebRtcSpl_AnalysisQMF(render_audio_->data(i),
515 render_audio_->samples_per_channel(),
516 render_audio_->low_pass_split_data(i),
517 render_audio_->high_pass_split_data(i),
518 render_audio_->analysis_filter_state1(i),
519 render_audio_->analysis_filter_state2(i));
523 // TODO(ajm): warnings possible from components?
524 err = echo_cancellation_->ProcessRenderAudio(render_audio_);
525 if (err != kNoError) {
529 err = echo_control_mobile_->ProcessRenderAudio(render_audio_);
530 if (err != kNoError) {
534 err = gain_control_->ProcessRenderAudio(render_audio_);
535 if (err != kNoError) {
539 return err; // TODO(ajm): this is for returning warnings; necessary?
542 int AudioProcessingImpl::set_stream_delay_ms(int delay) {
543 Error retval = kNoError;
544 was_stream_delay_set_ = true;
545 delay += delay_offset_ms_;
549 retval = kBadStreamParameterWarning;
552 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
555 retval = kBadStreamParameterWarning;
558 stream_delay_ms_ = delay;
562 int AudioProcessingImpl::stream_delay_ms() const {
563 return stream_delay_ms_;
566 bool AudioProcessingImpl::was_stream_delay_set() const {
567 return was_stream_delay_set_;
570 void AudioProcessingImpl::set_delay_offset_ms(int offset) {
571 CriticalSectionScoped crit_scoped(crit_);
572 delay_offset_ms_ = offset;
575 int AudioProcessingImpl::delay_offset_ms() const {
576 return delay_offset_ms_;
579 void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
580 key_pressed_ = key_pressed;
583 bool AudioProcessingImpl::stream_key_pressed() const {
587 int AudioProcessingImpl::StartDebugRecording(
588 const char filename[AudioProcessing::kMaxFilenameSize]) {
589 CriticalSectionScoped crit_scoped(crit_);
590 assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize);
592 if (filename == NULL) {
593 return kNullPointerError;
596 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
597 // Stop any ongoing recording.
598 if (debug_file_->Open()) {
599 if (debug_file_->CloseFile() == -1) {
604 if (debug_file_->OpenFile(filename, false) == -1) {
605 debug_file_->CloseFile();
609 int err = WriteInitMessage();
610 if (err != kNoError) {
615 return kUnsupportedFunctionError;
616 #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
619 int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
620 CriticalSectionScoped crit_scoped(crit_);
622 if (handle == NULL) {
623 return kNullPointerError;
626 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
627 // Stop any ongoing recording.
628 if (debug_file_->Open()) {
629 if (debug_file_->CloseFile() == -1) {
634 if (debug_file_->OpenFromFileHandle(handle, true, false) == -1) {
638 int err = WriteInitMessage();
639 if (err != kNoError) {
644 return kUnsupportedFunctionError;
645 #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
648 int AudioProcessingImpl::StopDebugRecording() {
649 CriticalSectionScoped crit_scoped(crit_);
651 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
652 // We just return if recording hasn't started.
653 if (debug_file_->Open()) {
654 if (debug_file_->CloseFile() == -1) {
660 return kUnsupportedFunctionError;
661 #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
664 EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
665 return echo_cancellation_;
668 EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
669 return echo_control_mobile_;
672 GainControl* AudioProcessingImpl::gain_control() const {
673 return gain_control_;
676 HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
677 return high_pass_filter_;
680 LevelEstimator* AudioProcessingImpl::level_estimator() const {
681 return level_estimator_;
684 NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
685 return noise_suppression_;
688 VoiceDetection* AudioProcessingImpl::voice_detection() const {
689 return voice_detection_;
692 bool AudioProcessingImpl::is_data_processed() const {
693 int enabled_count = 0;
694 std::list<ProcessingComponent*>::const_iterator it;
695 for (it = component_list_.begin(); it != component_list_.end(); it++) {
696 if ((*it)->is_component_enabled()) {
701 // Data is unchanged if no components are enabled, or if only level_estimator_
702 // or voice_detection_ is enabled.
703 if (enabled_count == 0) {
705 } else if (enabled_count == 1) {
706 if (level_estimator_->is_enabled() || voice_detection_->is_enabled()) {
709 } else if (enabled_count == 2) {
710 if (level_estimator_->is_enabled() && voice_detection_->is_enabled()) {
717 bool AudioProcessingImpl::interleave_needed(bool is_data_processed) const {
718 // Check if we've upmixed or downmixed the audio.
719 return (num_output_channels_ != num_input_channels_ || is_data_processed);
722 bool AudioProcessingImpl::synthesis_needed(bool is_data_processed) const {
723 return (is_data_processed && sample_rate_hz_ == kSampleRate32kHz);
726 bool AudioProcessingImpl::analysis_needed(bool is_data_processed) const {
727 if (!is_data_processed && !voice_detection_->is_enabled()) {
728 // Only level_estimator_ is enabled.
730 } else if (sample_rate_hz_ == kSampleRate32kHz) {
731 // Something besides level_estimator_ is enabled, and we have super-wb.
737 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
738 int AudioProcessingImpl::WriteMessageToDebugFile() {
739 int32_t size = event_msg_->ByteSize();
741 return kUnspecifiedError;
743 #if defined(WEBRTC_ARCH_BIG_ENDIAN)
744 // TODO(ajm): Use little-endian "on the wire". For the moment, we can be
745 // pretty safe in assuming little-endian.
748 if (!event_msg_->SerializeToString(&event_str_)) {
749 return kUnspecifiedError;
752 // Write message preceded by its size.
753 if (!debug_file_->Write(&size, sizeof(int32_t))) {
756 if (!debug_file_->Write(event_str_.data(), event_str_.length())) {
765 int AudioProcessingImpl::WriteInitMessage() {
766 event_msg_->set_type(audioproc::Event::INIT);
767 audioproc::Init* msg = event_msg_->mutable_init();
768 msg->set_sample_rate(sample_rate_hz_);
769 msg->set_device_sample_rate(echo_cancellation_->device_sample_rate_hz());
770 msg->set_num_input_channels(num_input_channels_);
771 msg->set_num_output_channels(num_output_channels_);
772 msg->set_num_reverse_channels(num_reverse_channels_);
774 int err = WriteMessageToDebugFile();
775 if (err != kNoError) {
781 #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
782 } // namespace webrtc