blob: c6f92005a50f0fc4b5ded8226dd956fa726efced [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
bjornv@webrtc.org0c6f9312012-01-30 09:39:08 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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.
9 */
10
bjornv@webrtc.org21a2fc92013-02-15 17:01:03 +000011#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
bjornv@webrtc.org21a2fc92013-02-15 17:01:03 +000013#include <assert.h>
niklase@google.com470e71d2011-07-07 08:21:25 +000014#include <string.h>
15
andrew@webrtc.org1760a172013-09-25 23:17:38 +000016extern "C" {
17#include "webrtc/modules/audio_processing/aec/aec_core.h"
18}
Henrik Kjellander9b72af92015-11-11 20:16:11 +010019#include "webrtc/modules/audio_processing/aec/echo_cancellation.h"
bjornv@webrtc.org21a2fc92013-02-15 17:01:03 +000020#include "webrtc/modules/audio_processing/audio_buffer.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010021#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000022
niklase@google.com470e71d2011-07-07 08:21:25 +000023namespace webrtc {
24
25typedef void Handle;
26
27namespace {
pbos@webrtc.orgb7192b82013-04-10 07:50:54 +000028int16_t MapSetting(EchoCancellation::SuppressionLevel level) {
niklase@google.com470e71d2011-07-07 08:21:25 +000029 switch (level) {
30 case EchoCancellation::kLowSuppression:
31 return kAecNlpConservative;
32 case EchoCancellation::kModerateSuppression:
33 return kAecNlpModerate;
34 case EchoCancellation::kHighSuppression:
35 return kAecNlpAggressive;
niklase@google.com470e71d2011-07-07 08:21:25 +000036 }
andrew@webrtc.org648af742012-02-08 01:57:29 +000037 assert(false);
mflodman@webrtc.org657b2a42012-02-06 11:06:01 +000038 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +000039}
40
andrew@webrtc.org648af742012-02-08 01:57:29 +000041AudioProcessing::Error MapError(int err) {
niklase@google.com470e71d2011-07-07 08:21:25 +000042 switch (err) {
43 case AEC_UNSUPPORTED_FUNCTION_ERROR:
44 return AudioProcessing::kUnsupportedFunctionError;
niklase@google.com470e71d2011-07-07 08:21:25 +000045 case AEC_BAD_PARAMETER_ERROR:
46 return AudioProcessing::kBadParameterError;
niklase@google.com470e71d2011-07-07 08:21:25 +000047 case AEC_BAD_PARAMETER_WARNING:
48 return AudioProcessing::kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +000049 default:
50 // AEC_UNSPECIFIED_ERROR
51 // AEC_UNINITIALIZED_ERROR
52 // AEC_NULL_POINTER_ERROR
53 return AudioProcessing::kUnspecifiedError;
54 }
55}
56} // namespace
57
peahfa6228e2015-11-16 16:27:42 -080058const size_t EchoCancellationImpl::kAllowedValuesOfSamplesPerFrame1;
59const size_t EchoCancellationImpl::kAllowedValuesOfSamplesPerFrame2;
60
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000061EchoCancellationImpl::EchoCancellationImpl(const AudioProcessing* apm,
62 CriticalSectionWrapper* crit)
Henrik Lundin441f6342015-06-09 16:03:13 +020063 : ProcessingComponent(),
64 apm_(apm),
65 crit_(crit),
66 drift_compensation_enabled_(false),
67 metrics_enabled_(false),
68 suppression_level_(kModerateSuppression),
69 stream_drift_samples_(0),
70 was_stream_drift_set_(false),
71 stream_has_echo_(false),
72 delay_logging_enabled_(false),
73 extended_filter_enabled_(false),
peahfa6228e2015-11-16 16:27:42 -080074 delay_agnostic_enabled_(false),
75 render_queue_element_max_size_(0) {
76 AllocateRenderQueue();
Henrik Lundin441f6342015-06-09 16:03:13 +020077}
niklase@google.com470e71d2011-07-07 08:21:25 +000078
79EchoCancellationImpl::~EchoCancellationImpl() {}
80
81int EchoCancellationImpl::ProcessRenderAudio(const AudioBuffer* audio) {
82 if (!is_component_enabled()) {
83 return apm_->kNoError;
84 }
85
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000086 assert(audio->num_frames_per_band() <= 160);
niklase@google.com470e71d2011-07-07 08:21:25 +000087 assert(audio->num_channels() == apm_->num_reverse_channels());
88
89 int err = apm_->kNoError;
90
91 // The ordering convention must be followed to pass to the correct AEC.
92 size_t handle_index = 0;
peahfa6228e2015-11-16 16:27:42 -080093 render_queue_buffer_.clear();
niklase@google.com470e71d2011-07-07 08:21:25 +000094 for (int i = 0; i < apm_->num_output_channels(); i++) {
95 for (int j = 0; j < audio->num_channels(); j++) {
96 Handle* my_handle = static_cast<Handle*>(handle(handle_index));
peahfa6228e2015-11-16 16:27:42 -080097 // Retrieve any error code produced by the buffering of the farend
98 // signal
99 err = WebRtcAec_GetBufferFarendError(
100 my_handle, audio->split_bands_const_f(j)[kBand0To8kHz],
Peter Kastingdce40cf2015-08-24 14:52:23 -0700101 audio->num_frames_per_band());
niklase@google.com470e71d2011-07-07 08:21:25 +0000102
103 if (err != apm_->kNoError) {
peahc12be392015-11-09 23:53:50 -0800104 return MapError(err); // TODO(ajm): warning possible?
niklase@google.com470e71d2011-07-07 08:21:25 +0000105 }
106
peahfa6228e2015-11-16 16:27:42 -0800107 // Buffer the samples in the render queue.
108 render_queue_buffer_.insert(render_queue_buffer_.end(),
109 audio->split_bands_const_f(j)[kBand0To8kHz],
110 (audio->split_bands_const_f(j)[kBand0To8kHz] +
111 audio->num_frames_per_band()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000112 }
113 }
114
peahfa6228e2015-11-16 16:27:42 -0800115 // Insert the samples into the queue.
116 if (!render_signal_queue_->Insert(&render_queue_buffer_)) {
117 ReadQueuedRenderData();
118
119 // Retry the insert (should always work).
120 RTC_DCHECK_EQ(render_signal_queue_->Insert(&render_queue_buffer_), true);
121 }
122
niklase@google.com470e71d2011-07-07 08:21:25 +0000123 return apm_->kNoError;
124}
125
peahfa6228e2015-11-16 16:27:42 -0800126// Read chunks of data that were received and queued on the render side from
127// a queue. All the data chunks are buffered into the farend signal of the AEC.
128void EchoCancellationImpl::ReadQueuedRenderData() {
129 if (!is_component_enabled()) {
130 return;
131 }
132
133 while (render_signal_queue_->Remove(&capture_queue_buffer_)) {
134 size_t handle_index = 0;
135 int buffer_index = 0;
136 const int num_frames_per_band =
137 capture_queue_buffer_.size() /
138 (apm_->num_output_channels() * apm_->num_reverse_channels());
139 for (int i = 0; i < apm_->num_output_channels(); i++) {
140 for (int j = 0; j < apm_->num_reverse_channels(); j++) {
141 Handle* my_handle = static_cast<Handle*>(handle(handle_index));
142 WebRtcAec_BufferFarend(my_handle, &capture_queue_buffer_[buffer_index],
143 num_frames_per_band);
144
145 buffer_index += num_frames_per_band;
146 handle_index++;
147 }
148 }
149 }
150}
151
niklase@google.com470e71d2011-07-07 08:21:25 +0000152int EchoCancellationImpl::ProcessCaptureAudio(AudioBuffer* audio) {
153 if (!is_component_enabled()) {
154 return apm_->kNoError;
155 }
156
157 if (!apm_->was_stream_delay_set()) {
158 return apm_->kStreamParameterNotSetError;
159 }
160
161 if (drift_compensation_enabled_ && !was_stream_drift_set_) {
162 return apm_->kStreamParameterNotSetError;
163 }
164
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000165 assert(audio->num_frames_per_band() <= 160);
niklase@google.com470e71d2011-07-07 08:21:25 +0000166 assert(audio->num_channels() == apm_->num_output_channels());
167
168 int err = apm_->kNoError;
169
170 // The ordering convention must be followed to pass to the correct AEC.
171 size_t handle_index = 0;
172 stream_has_echo_ = false;
173 for (int i = 0; i < audio->num_channels(); i++) {
174 for (int j = 0; j < apm_->num_reverse_channels(); j++) {
175 Handle* my_handle = handle(handle_index);
176 err = WebRtcAec_Process(
177 my_handle,
aluebs@webrtc.orgc78d81a2015-01-21 19:10:55 +0000178 audio->split_bands_const_f(i),
179 audio->num_bands(),
180 audio->split_bands_f(i),
Peter Kastingdce40cf2015-08-24 14:52:23 -0700181 audio->num_frames_per_band(),
niklase@google.com470e71d2011-07-07 08:21:25 +0000182 apm_->stream_delay_ms(),
183 stream_drift_samples_);
184
185 if (err != apm_->kNoError) {
peahc12be392015-11-09 23:53:50 -0800186 err = MapError(err);
niklase@google.com470e71d2011-07-07 08:21:25 +0000187 // TODO(ajm): Figure out how to return warnings properly.
188 if (err != apm_->kBadStreamParameterWarning) {
189 return err;
190 }
191 }
192
bjornv@webrtc.org21a2fc92013-02-15 17:01:03 +0000193 int status = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000194 err = WebRtcAec_get_echo_status(my_handle, &status);
195 if (err != apm_->kNoError) {
peahc12be392015-11-09 23:53:50 -0800196 return MapError(err);
niklase@google.com470e71d2011-07-07 08:21:25 +0000197 }
198
199 if (status == 1) {
200 stream_has_echo_ = true;
201 }
202
203 handle_index++;
204 }
205 }
206
207 was_stream_drift_set_ = false;
208 return apm_->kNoError;
209}
210
211int EchoCancellationImpl::Enable(bool enable) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000212 CriticalSectionScoped crit_scoped(crit_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000213 // Ensure AEC and AECM are not both enabled.
214 if (enable && apm_->echo_control_mobile()->is_enabled()) {
215 return apm_->kBadParameterError;
216 }
217
218 return EnableComponent(enable);
219}
220
221bool EchoCancellationImpl::is_enabled() const {
222 return is_component_enabled();
223}
224
225int EchoCancellationImpl::set_suppression_level(SuppressionLevel level) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000226 CriticalSectionScoped crit_scoped(crit_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000227 if (MapSetting(level) == -1) {
228 return apm_->kBadParameterError;
229 }
230
231 suppression_level_ = level;
232 return Configure();
233}
234
235EchoCancellation::SuppressionLevel EchoCancellationImpl::suppression_level()
236 const {
237 return suppression_level_;
238}
239
240int EchoCancellationImpl::enable_drift_compensation(bool enable) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000241 CriticalSectionScoped crit_scoped(crit_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000242 drift_compensation_enabled_ = enable;
243 return Configure();
244}
245
246bool EchoCancellationImpl::is_drift_compensation_enabled() const {
247 return drift_compensation_enabled_;
248}
249
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000250void EchoCancellationImpl::set_stream_drift_samples(int drift) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000251 was_stream_drift_set_ = true;
252 stream_drift_samples_ = drift;
niklase@google.com470e71d2011-07-07 08:21:25 +0000253}
254
255int EchoCancellationImpl::stream_drift_samples() const {
256 return stream_drift_samples_;
257}
258
259int EchoCancellationImpl::enable_metrics(bool enable) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000260 CriticalSectionScoped crit_scoped(crit_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000261 metrics_enabled_ = enable;
262 return Configure();
263}
264
265bool EchoCancellationImpl::are_metrics_enabled() const {
266 return metrics_enabled_;
267}
268
269// TODO(ajm): we currently just use the metrics from the first AEC. Think more
270// aboue the best way to extend this to multi-channel.
271int EchoCancellationImpl::GetMetrics(Metrics* metrics) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000272 CriticalSectionScoped crit_scoped(crit_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000273 if (metrics == NULL) {
274 return apm_->kNullPointerError;
275 }
276
277 if (!is_component_enabled() || !metrics_enabled_) {
278 return apm_->kNotEnabledError;
279 }
280
281 AecMetrics my_metrics;
282 memset(&my_metrics, 0, sizeof(my_metrics));
283 memset(metrics, 0, sizeof(Metrics));
284
285 Handle* my_handle = static_cast<Handle*>(handle(0));
286 int err = WebRtcAec_GetMetrics(my_handle, &my_metrics);
287 if (err != apm_->kNoError) {
peahc12be392015-11-09 23:53:50 -0800288 return MapError(err);
niklase@google.com470e71d2011-07-07 08:21:25 +0000289 }
290
291 metrics->residual_echo_return_loss.instant = my_metrics.rerl.instant;
292 metrics->residual_echo_return_loss.average = my_metrics.rerl.average;
293 metrics->residual_echo_return_loss.maximum = my_metrics.rerl.max;
294 metrics->residual_echo_return_loss.minimum = my_metrics.rerl.min;
295
296 metrics->echo_return_loss.instant = my_metrics.erl.instant;
297 metrics->echo_return_loss.average = my_metrics.erl.average;
298 metrics->echo_return_loss.maximum = my_metrics.erl.max;
299 metrics->echo_return_loss.minimum = my_metrics.erl.min;
300
301 metrics->echo_return_loss_enhancement.instant = my_metrics.erle.instant;
302 metrics->echo_return_loss_enhancement.average = my_metrics.erle.average;
303 metrics->echo_return_loss_enhancement.maximum = my_metrics.erle.max;
304 metrics->echo_return_loss_enhancement.minimum = my_metrics.erle.min;
305
306 metrics->a_nlp.instant = my_metrics.aNlp.instant;
307 metrics->a_nlp.average = my_metrics.aNlp.average;
308 metrics->a_nlp.maximum = my_metrics.aNlp.max;
309 metrics->a_nlp.minimum = my_metrics.aNlp.min;
310
311 return apm_->kNoError;
312}
313
314bool EchoCancellationImpl::stream_has_echo() const {
315 return stream_has_echo_;
316}
317
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000318int EchoCancellationImpl::enable_delay_logging(bool enable) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000319 CriticalSectionScoped crit_scoped(crit_);
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000320 delay_logging_enabled_ = enable;
321 return Configure();
322}
323
324bool EchoCancellationImpl::is_delay_logging_enabled() const {
325 return delay_logging_enabled_;
326}
327
Minyue13b96ba2015-10-03 00:39:14 +0200328bool EchoCancellationImpl::is_delay_agnostic_enabled() const {
329 return delay_agnostic_enabled_;
330}
331
332bool EchoCancellationImpl::is_extended_filter_enabled() const {
333 return extended_filter_enabled_;
334}
335
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000336// TODO(bjornv): How should we handle the multi-channel case?
337int EchoCancellationImpl::GetDelayMetrics(int* median, int* std) {
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000338 float fraction_poor_delays = 0;
339 return GetDelayMetrics(median, std, &fraction_poor_delays);
340}
341
342int EchoCancellationImpl::GetDelayMetrics(int* median, int* std,
343 float* fraction_poor_delays) {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000344 CriticalSectionScoped crit_scoped(crit_);
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000345 if (median == NULL) {
346 return apm_->kNullPointerError;
347 }
348 if (std == NULL) {
349 return apm_->kNullPointerError;
350 }
351
352 if (!is_component_enabled() || !delay_logging_enabled_) {
353 return apm_->kNotEnabledError;
354 }
355
356 Handle* my_handle = static_cast<Handle*>(handle(0));
peahc12be392015-11-09 23:53:50 -0800357 const int err =
358 WebRtcAec_GetDelayMetrics(my_handle, median, std, fraction_poor_delays);
359 if (err != apm_->kNoError) {
360 return MapError(err);
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000361 }
362
363 return apm_->kNoError;
364}
365
bjornv@webrtc.org91d11b32013-03-05 16:53:09 +0000366struct AecCore* EchoCancellationImpl::aec_core() const {
andrew@webrtc.org56e4a052014-02-27 22:23:17 +0000367 CriticalSectionScoped crit_scoped(crit_);
bjornv@webrtc.org91d11b32013-03-05 16:53:09 +0000368 if (!is_component_enabled()) {
369 return NULL;
370 }
371 Handle* my_handle = static_cast<Handle*>(handle(0));
372 return WebRtcAec_aec_core(my_handle);
373}
374
niklase@google.com470e71d2011-07-07 08:21:25 +0000375int EchoCancellationImpl::Initialize() {
376 int err = ProcessingComponent::Initialize();
377 if (err != apm_->kNoError || !is_component_enabled()) {
378 return err;
379 }
380
peahfa6228e2015-11-16 16:27:42 -0800381 AllocateRenderQueue();
382
niklase@google.com470e71d2011-07-07 08:21:25 +0000383 return apm_->kNoError;
384}
385
peahfa6228e2015-11-16 16:27:42 -0800386void EchoCancellationImpl::AllocateRenderQueue() {
387 const size_t max_frame_size = std::max<size_t>(
388 kAllowedValuesOfSamplesPerFrame1, kAllowedValuesOfSamplesPerFrame2);
389
390 const size_t new_render_queue_element_max_size = std::max<size_t>(
391 static_cast<size_t>(1), max_frame_size * num_handles_required());
392
393 // Reallocate the queue if the queue item size is too small to fit the
394 // data to put in the queue.
395 if (new_render_queue_element_max_size > render_queue_element_max_size_) {
396 render_queue_element_max_size_ = new_render_queue_element_max_size;
397
398 std::vector<float> template_queue_element(render_queue_element_max_size_);
399
400 render_signal_queue_.reset(
401 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
402 kMaxNumFramesToBuffer, template_queue_element,
403 RenderQueueItemVerifier<float>(render_queue_element_max_size_)));
404 } else {
405 render_signal_queue_->Clear();
406 }
407
408 render_queue_buffer_.resize(new_render_queue_element_max_size);
409 capture_queue_buffer_.resize(new_render_queue_element_max_size);
410}
411
andrew@webrtc.org1760a172013-09-25 23:17:38 +0000412void EchoCancellationImpl::SetExtraOptions(const Config& config) {
Henrik Lundinb02af182015-06-16 09:53:23 +0200413 extended_filter_enabled_ = config.Get<ExtendedFilter>().enabled;
henrik.lundin366e9522015-07-03 00:50:05 -0700414 delay_agnostic_enabled_ = config.Get<DelayAgnostic>().enabled;
andrew@webrtc.org1760a172013-09-25 23:17:38 +0000415 Configure();
416}
417
niklase@google.com470e71d2011-07-07 08:21:25 +0000418void* EchoCancellationImpl::CreateHandle() const {
Bjorn Volcker9345e862015-06-10 21:43:36 +0200419 return WebRtcAec_Create();
niklase@google.com470e71d2011-07-07 08:21:25 +0000420}
421
bjornv@webrtc.org5964fe02014-04-22 06:52:28 +0000422void EchoCancellationImpl::DestroyHandle(void* handle) const {
niklase@google.com470e71d2011-07-07 08:21:25 +0000423 assert(handle != NULL);
bjornv@webrtc.org5964fe02014-04-22 06:52:28 +0000424 WebRtcAec_Free(static_cast<Handle*>(handle));
niklase@google.com470e71d2011-07-07 08:21:25 +0000425}
426
427int EchoCancellationImpl::InitializeHandle(void* handle) const {
428 assert(handle != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000429 // TODO(ajm): Drift compensation is disabled in practice. If restored, it
430 // should be managed internally and not depend on the hardware sample rate.
431 // For now, just hardcode a 48 kHz value.
niklase@google.com470e71d2011-07-07 08:21:25 +0000432 return WebRtcAec_Init(static_cast<Handle*>(handle),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000433 apm_->proc_sample_rate_hz(),
434 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +0000435}
436
437int EchoCancellationImpl::ConfigureHandle(void* handle) const {
438 assert(handle != NULL);
439 AecConfig config;
440 config.metricsMode = metrics_enabled_;
441 config.nlpMode = MapSetting(suppression_level_);
442 config.skewMode = drift_compensation_enabled_;
bjornv@google.com1ba3dbe2011-10-03 08:18:10 +0000443 config.delay_logging = delay_logging_enabled_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
Henrik Lundin441f6342015-06-09 16:03:13 +0200445 WebRtcAec_enable_extended_filter(
446 WebRtcAec_aec_core(static_cast<Handle*>(handle)),
447 extended_filter_enabled_ ? 1 : 0);
henrik.lundin0f133b92015-07-02 00:17:55 -0700448 WebRtcAec_enable_delay_agnostic(
449 WebRtcAec_aec_core(static_cast<Handle*>(handle)),
450 delay_agnostic_enabled_ ? 1 : 0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000451 return WebRtcAec_set_config(static_cast<Handle*>(handle), config);
452}
453
454int EchoCancellationImpl::num_handles_required() const {
455 return apm_->num_output_channels() *
456 apm_->num_reverse_channels();
457}
458
459int EchoCancellationImpl::GetHandleError(void* handle) const {
460 assert(handle != NULL);
peahc12be392015-11-09 23:53:50 -0800461 return AudioProcessing::kUnspecifiedError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000462}
463} // namespace webrtc