Debian Codegraph @

Xpjproject/third_party/webrtc_aec3/src/modules/audio_processing/include/audio_processing.h

raw symbols SCIP
1 /*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
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
11 #ifndef MODULES_AUDIO_PROCESSING_INCLUDE_AUDIO_PROCESSING_H_
12 #define MODULES_AUDIO_PROCESSING_INCLUDE_AUDIO_PROCESSING_H_
13
14 // MSVC++ requires this to be set before any other includes to get M_PI.
15 #ifndef _USE_MATH_DEFINES
16 #define _USE_MATH_DEFINES
17 #endif
18
19 #include <math.h>
20 #include <stddef.h> // size_t
21 #include <stdio.h> // FILE
22 #include <string.h>
23
24 #include <vector>
25
26 #include "absl/types/optional.h"
27 #include "api/array_view.h"
28 #include "api/audio/echo_canceller3_config.h"
29 #include "api/audio/echo_control.h"
30 #include "api/scoped_refptr.h"
31 #include "modules/audio_processing/include/audio_processing_statistics.h"
32 #include "modules/audio_processing/include/config.h"
33 #include "rtc_base/arraysize.h"
34 #include "rtc_base/constructor_magic.h"
35 #include "rtc_base/ref_count.h"
36 #include "rtc_base/system/file_wrapper.h"
37 #include "rtc_base/system/rtc_export.h"
38
39 namespace rtc {
40 class TaskQueue;
41 } // namespace rtc
42
43 namespace webrtc {
44
45 class AecDump;
46 class AudioBuffer;
47
48 class StreamConfig;
49 class ProcessingConfig;
50
51 class EchoDetector;
52 class CustomAudioAnalyzer;
53 class CustomProcessing;
54
55 // Use to enable experimental gain control (AGC). At startup the experimental
56 // AGC moves the microphone volume up to |startup_min_volume| if the current
57 // microphone volume is set too low. The value is clamped to its operating range
58 // [12, 255]. Here, 255 maps to 100%.
59 //
60 // Must be provided through AudioProcessingBuilder().Create(config).
61 #if defined(WEBRTC_CHROMIUM_BUILD)
62 static const int kAgcStartupMinVolume = 85;
63 #else
64 static const int kAgcStartupMinVolume = 0;
65 #endif // defined(WEBRTC_CHROMIUM_BUILD)
66 static constexpr int kClippedLevelMin = 70;
67
68 // To be deprecated: Please instead use the flag in the
69 // AudioProcessing::Config::AnalogGainController.
70 // TODO(webrtc:5298): Remove.
71 struct ExperimentalAgc {
72 ExperimentalAgc() = default;
73 explicit ExperimentalAgc(bool enabled) : enabled(enabled) {}
74 ExperimentalAgc(bool enabled, int startup_min_volume)
75 : enabled(enabled), startup_min_volume(startup_min_volume) {}
76 static const ConfigOptionID identifier = ConfigOptionID::kExperimentalAgc;
77 bool enabled = true;
78 int startup_min_volume = kAgcStartupMinVolume;
79 // Lowest microphone level that will be applied in response to clipping.
80 int clipped_level_min = kClippedLevelMin;
81 bool digital_adaptive_disabled = false;
82 };
83
84 // To be deprecated: Please instead use the flag in the
85 // AudioProcessing::Config::TransientSuppression.
86 //
87 // Use to enable experimental noise suppression. It can be set in the
88 // constructor.
89 // TODO(webrtc:5298): Remove.
90 struct ExperimentalNs {
91 ExperimentalNs() : enabled(false) {}
92 explicit ExperimentalNs(bool enabled) : enabled(enabled) {}
93 static const ConfigOptionID identifier = ConfigOptionID::kExperimentalNs;
94 bool enabled;
95 };
96
97 // The Audio Processing Module (APM) provides a collection of voice processing
98 // components designed for real-time communications software.
99 //
100 // APM operates on two audio streams on a frame-by-frame basis. Frames of the
101 // primary stream, on which all processing is applied, are passed to
102 // |ProcessStream()|. Frames of the reverse direction stream are passed to
103 // |ProcessReverseStream()|. On the client-side, this will typically be the
104 // near-end (capture) and far-end (render) streams, respectively. APM should be
105 // placed in the signal chain as close to the audio hardware abstraction layer
106 // (HAL) as possible.
107 //
108 // On the server-side, the reverse stream will normally not be used, with
109 // processing occurring on each incoming stream.
110 //
111 // Component interfaces follow a similar pattern and are accessed through
112 // corresponding getters in APM. All components are disabled at create-time,
113 // with default settings that are recommended for most situations. New settings
114 // can be applied without enabling a component. Enabling a component triggers
115 // memory allocation and initialization to allow it to start processing the
116 // streams.
117 //
118 // Thread safety is provided with the following assumptions to reduce locking
119 // overhead:
120 // 1. The stream getters and setters are called from the same thread as
121 // ProcessStream(). More precisely, stream functions are never called
122 // concurrently with ProcessStream().
123 // 2. Parameter getters are never called concurrently with the corresponding
124 // setter.
125 //
126 // APM accepts only linear PCM audio data in chunks of 10 ms. The int16
127 // interfaces use interleaved data, while the float interfaces use deinterleaved
128 // data.
129 //
130 // Usage example, omitting error checking:
131 // AudioProcessing* apm = AudioProcessingBuilder().Create();
132 //
133 // AudioProcessing::Config config;
134 // config.echo_canceller.enabled = true;
135 // config.echo_canceller.mobile_mode = false;
136 //
137 // config.gain_controller1.enabled = true;
138 // config.gain_controller1.mode =
139 // AudioProcessing::Config::GainController1::kAdaptiveAnalog;
140 // config.gain_controller1.analog_level_minimum = 0;
141 // config.gain_controller1.analog_level_maximum = 255;
142 //
143 // config.gain_controller2.enabled = true;
144 //
145 // config.high_pass_filter.enabled = true;
146 //
147 // config.voice_detection.enabled = true;
148 //
149 // apm->ApplyConfig(config)
150 //
151 // apm->noise_reduction()->set_level(kHighSuppression);
152 // apm->noise_reduction()->Enable(true);
153 //
154 // // Start a voice call...
155 //
156 // // ... Render frame arrives bound for the audio HAL ...
157 // apm->ProcessReverseStream(render_frame);
158 //
159 // // ... Capture frame arrives from the audio HAL ...
160 // // Call required set_stream_ functions.
161 // apm->set_stream_delay_ms(delay_ms);
162 // apm->set_stream_analog_level(analog_level);
163 //
164 // apm->ProcessStream(capture_frame);
165 //
166 // // Call required stream_ functions.
167 // analog_level = apm->recommended_stream_analog_level();
168 // has_voice = apm->stream_has_voice();
169 //
170 // // Repeat render and capture processing for the duration of the call...
171 // // Start a new call...
172 // apm->Initialize();
173 //
174 // // Close the application...
175 // delete apm;
176 //
177 class RTC_EXPORT AudioProcessing : public rtc::RefCountInterface {
178 public:
179 // The struct below constitutes the new parameter scheme for the audio
180 // processing. It is being introduced gradually and until it is fully
181 // introduced, it is prone to change.
182 // TODO(peah): Remove this comment once the new config scheme is fully rolled
183 // out.
184 //
185 // The parameters and behavior of the audio processing module are controlled
186 // by changing the default values in the AudioProcessing::Config struct.
187 // The config is applied by passing the struct to the ApplyConfig method.
188 //
189 // This config is intended to be used during setup, and to enable/disable
190 // top-level processing effects. Use during processing may cause undesired
191 // submodule resets, affecting the audio quality. Use the RuntimeSetting
192 // construct for runtime configuration.
193 struct RTC_EXPORT Config {
194
195 // Sets the properties of the audio processing pipeline.
196 struct RTC_EXPORT Pipeline {
197 // Maximum allowed processing rate used internally. May only be set to
198 // 32000 or 48000 and any differing values will be treated as 48000.
199 int maximum_internal_processing_rate = 48000;
200 // Allow multi-channel processing of render audio.
201 bool multi_channel_render = false;
202 // Allow multi-channel processing of capture audio when AEC3 is active
203 // or a custom AEC is injected..
204 bool multi_channel_capture = false;
205 } pipeline;
206
207 // Enabled the pre-amplifier. It amplifies the capture signal
208 // before any other processing is done.
209 // TODO(webrtc:5298): Deprecate and use the pre-gain functionality in
210 // capture_level_adjustment instead.
211 struct PreAmplifier {
212 bool enabled = false;
213 float fixed_gain_factor = 1.0f;
214 } pre_amplifier;
215
216 // Functionality for general level adjustment in the capture pipeline. This
217 // should not be used together with the legacy PreAmplifier functionality.
218 struct CaptureLevelAdjustment {
219 bool operator==(const CaptureLevelAdjustment& rhs) const;
220 bool operator!=(const CaptureLevelAdjustment& rhs) const {
221 return !(*this == rhs);
222 }
223 bool enabled = false;
224 // The `pre_gain_factor` scales the signal before any processing is done.
225 float pre_gain_factor = 1.0f;
226 // The `post_gain_factor` scales the signal after all processing is done.
227 float post_gain_factor = 1.0f;
228 struct AnalogMicGainEmulation {
229 bool operator==(const AnalogMicGainEmulation& rhs) const;
230 bool operator!=(const AnalogMicGainEmulation& rhs) const {
231 return !(*this == rhs);
232 }
233 bool enabled = false;
234 // Initial analog gain level to use for the emulated analog gain. Must
235 // be in the range [0...255].
236 int initial_level = 255;
237 } analog_mic_gain_emulation;
238 } capture_level_adjustment;
239
240 struct HighPassFilter {
241 bool enabled = false;
242 bool apply_in_full_band = true;
243 } high_pass_filter;
244
245 struct EchoCanceller {
246 bool enabled = false;
247 bool mobile_mode = false;
248 bool export_linear_aec_output = false;
249 // Enforce the highpass filter to be on (has no effect for the mobile
250 // mode).
251 bool enforce_high_pass_filtering = true;
252 } echo_canceller;
253
254 // Enables background noise suppression.
255 struct NoiseSuppression {
256 bool enabled = false;
257 enum Level { kLow, kModerate, kHigh, kVeryHigh };
258 Level level = kModerate;
259 bool analyze_linear_aec_output_when_available = false;
260 } noise_suppression;
261
262 // Enables transient suppression.
263 struct TransientSuppression {
264 bool enabled = false;
265 } transient_suppression;
266
267 // Enables reporting of |voice_detected| in webrtc::AudioProcessingStats.
268 struct VoiceDetection {
269 bool enabled = false;
270 } voice_detection;
271
272 // Enables automatic gain control (AGC) functionality.
273 // The automatic gain control (AGC) component brings the signal to an
274 // appropriate range. This is done by applying a digital gain directly and,
275 // in the analog mode, prescribing an analog gain to be applied at the audio
276 // HAL.
277 // Recommended to be enabled on the client-side.
278 struct GainController1 {
279 bool operator==(const GainController1& rhs) const;
280 bool operator!=(const GainController1& rhs) const {
281 return !(*this == rhs);
282 }
283
284 bool enabled = false;
285 enum Mode {
286 // Adaptive mode intended for use if an analog volume control is
287 // available on the capture device. It will require the user to provide
288 // coupling between the OS mixer controls and AGC through the
289 // stream_analog_level() functions.
290 // It consists of an analog gain prescription for the audio device and a
291 // digital compression stage.
292 kAdaptiveAnalog,
293 // Adaptive mode intended for situations in which an analog volume
294 // control is unavailable. It operates in a similar fashion to the
295 // adaptive analog mode, but with scaling instead applied in the digital
296 // domain. As with the analog mode, it additionally uses a digital
297 // compression stage.
298 kAdaptiveDigital,
299 // Fixed mode which enables only the digital compression stage also used
300 // by the two adaptive modes.
301 // It is distinguished from the adaptive modes by considering only a
302 // short time-window of the input signal. It applies a fixed gain
303 // through most of the input level range, and compresses (gradually
304 // reduces gain with increasing level) the input signal at higher
305 // levels. This mode is preferred on embedded devices where the capture
306 // signal level is predictable, so that a known gain can be applied.
307 kFixedDigital
308 };
309 Mode mode = kAdaptiveAnalog;
310 // Sets the target peak level (or envelope) of the AGC in dBFs (decibels
311 // from digital full-scale). The convention is to use positive values. For
312 // instance, passing in a value of 3 corresponds to -3 dBFs, or a target
313 // level 3 dB below full-scale. Limited to [0, 31].
314 int target_level_dbfs = 3;
315 // Sets the maximum gain the digital compression stage may apply, in dB. A
316 // higher number corresponds to greater compression, while a value of 0
317 // will leave the signal uncompressed. Limited to [0, 90].
318 // For updates after APM setup, use a RuntimeSetting instead.
319 int compression_gain_db = 9;
320 // When enabled, the compression stage will hard limit the signal to the
321 // target level. Otherwise, the signal will be compressed but not limited
322 // above the target level.
323 bool enable_limiter = true;
324 // Sets the minimum and maximum analog levels of the audio capture device.
325 // Must be set if an analog mode is used. Limited to [0, 65535].
326 int analog_level_minimum = 0;
327 int analog_level_maximum = 255;
328
329 // Enables the analog gain controller functionality.
330 struct AnalogGainController {
331 bool enabled = true;
332 int startup_min_volume = kAgcStartupMinVolume;
333 // Lowest analog microphone level that will be applied in response to
334 // clipping.
335 int clipped_level_min = kClippedLevelMin;
336 bool enable_digital_adaptive = true;
337 } analog_gain_controller;
338 } gain_controller1;
339
340 // Enables the next generation AGC functionality. This feature replaces the
341 // standard methods of gain control in the previous AGC. Enabling this
342 // submodule enables an adaptive digital AGC followed by a limiter. By
343 // setting |fixed_gain_db|, the limiter can be turned into a compressor that
344 // first applies a fixed gain. The adaptive digital AGC can be turned off by
345 // setting |adaptive_digital_mode=false|.
346 struct GainController2 {
347 bool operator==(const GainController2& rhs) const;
348 bool operator!=(const GainController2& rhs) const {
349 return !(*this == rhs);
350 }
351
352 // TODO(crbug.com/webrtc/7494): Remove `LevelEstimator`.
353 enum LevelEstimator { kRms, kPeak };
354 enum NoiseEstimator { kStationaryNoise, kNoiseFloor };
355 bool enabled = false;
356 struct FixedDigital {
357 float gain_db = 0.0f;
358 } fixed_digital;
359 struct AdaptiveDigital {
360 bool enabled = false;
361 NoiseEstimator noise_estimator = kNoiseFloor;
362 int vad_reset_period_ms = 1500;
363 int adjacent_speech_frames_threshold = 12;
364 float max_gain_change_db_per_second = 3.0f;
365 float max_output_noise_level_dbfs = -50.0f;
366 bool sse2_allowed = true;
367 bool avx2_allowed = true;
368 bool neon_allowed = true;
369 // TODO(crbug.com/webrtc/7494): Remove deprecated settings below.
370 float vad_probability_attack = 1.0f;
371 LevelEstimator level_estimator = kRms;
372 int level_estimator_adjacent_speech_frames_threshold = 12;
373 bool use_saturation_protector = true;
374 float initial_saturation_margin_db = 25.0f;
375 float extra_saturation_margin_db = 5.0f;
376 int gain_applier_adjacent_speech_frames_threshold = 12;
377 } adaptive_digital;
378 } gain_controller2;
379
380 struct ResidualEchoDetector {
381 bool enabled = true;
382 } residual_echo_detector;
383
384 // Enables reporting of |output_rms_dbfs| in webrtc::AudioProcessingStats.
385 struct LevelEstimation {
386 bool enabled = false;
387 } level_estimation;
388
389 std::string ToString() const;
390 };
391
392 // TODO(mgraczyk): Remove once all methods that use ChannelLayout are gone.
393 enum ChannelLayout {
394 kMono,
395 // Left, right.
396 kStereo,
397 // Mono, keyboard, and mic.
398 kMonoAndKeyboard,
399 // Left, right, keyboard, and mic.
400 kStereoAndKeyboard
401 };
402
403 // Specifies the properties of a setting to be passed to AudioProcessing at
404 // runtime.
405 class RuntimeSetting {
406 public:
407 enum class Type {
408 kNotSpecified,
409 kCapturePreGain,
410 kCaptureCompressionGain,
411 kCaptureFixedPostGain,
412 kPlayoutVolumeChange,
413 kCustomRenderProcessingRuntimeSetting,
414 kPlayoutAudioDeviceChange,
415 kCapturePostGain,
416 kCaptureOutputUsed
417 };
418
419 // Play-out audio device properties.
420 struct PlayoutAudioDeviceInfo {
421 int id; // Identifies the audio device.
422 int max_volume; // Maximum play-out volume.
423 };
424
425 RuntimeSetting() : type_(Type::kNotSpecified), value_(0.0f) {}
426 ~RuntimeSetting() = default;
427
428 static RuntimeSetting CreateCapturePreGain(float gain) {
429 return {Type::kCapturePreGain, gain};
430 }
431
432 static RuntimeSetting CreateCapturePostGain(float gain) {
433 return {Type::kCapturePostGain, gain};
434 }
435
436 // Corresponds to Config::GainController1::compression_gain_db, but for
437 // runtime configuration.
438 static RuntimeSetting CreateCompressionGainDb(int gain_db) {
439 RTC_DCHECK_GE(gain_db, 0);
440 RTC_DCHECK_LE(gain_db, 90);
441 return {Type::kCaptureCompressionGain, static_cast<float>(gain_db)};
442 }
443
444 // Corresponds to Config::GainController2::fixed_digital::gain_db, but for
445 // runtime configuration.
446 static RuntimeSetting CreateCaptureFixedPostGain(float gain_db) {
447 RTC_DCHECK_GE(gain_db, 0.0f);
448 RTC_DCHECK_LE(gain_db, 90.0f);
449 return {Type::kCaptureFixedPostGain, gain_db};
450 }
451
452 // Creates a runtime setting to notify play-out (aka render) audio device
453 // changes.
454 static RuntimeSetting CreatePlayoutAudioDeviceChange(
455 PlayoutAudioDeviceInfo audio_device) {
456 return {Type::kPlayoutAudioDeviceChange, audio_device};
457 }
458
459 // Creates a runtime setting to notify play-out (aka render) volume changes.
460 // |volume| is the unnormalized volume, the maximum of which
461 static RuntimeSetting CreatePlayoutVolumeChange(int volume) {
462 return {Type::kPlayoutVolumeChange, volume};
463 }
464
465 static RuntimeSetting CreateCustomRenderSetting(float payload) {
466 return {Type::kCustomRenderProcessingRuntimeSetting, payload};
467 }
468
469 static RuntimeSetting CreateCaptureOutputUsedSetting(
470 bool capture_output_used) {
471 return {Type::kCaptureOutputUsed, capture_output_used};
472 }
473
474 Type type() const { return type_; }
475 // Getters do not return a value but instead modify the argument to protect
476 // from implicit casting.
477 void GetFloat(float* value) const {
478 RTC_DCHECK(value);
479 *value = value_.float_value;
480 }
481 void GetInt(int* value) const {
482 RTC_DCHECK(value);
483 *value = value_.int_value;
484 }
485 void GetBool(bool* value) const {
486 RTC_DCHECK(value);
487 *value = value_.bool_value;
488 }
489 void GetPlayoutAudioDeviceInfo(PlayoutAudioDeviceInfo* value) const {
490 RTC_DCHECK(value);
491 *value = value_.playout_audio_device_info;
492 }
493
494 private:
495 RuntimeSetting(Type id, float value) : type_(id), value_(value) {}
496 RuntimeSetting(Type id, int value) : type_(id), value_(value) {}
497 RuntimeSetting(Type id, PlayoutAudioDeviceInfo value)
498 : type_(id), value_(value) {}
499 Type type_;
500 union U {
501 U() {}
502 U(int value) : int_value(value) {}
503 U(float value) : float_value(value) {}
504 U(PlayoutAudioDeviceInfo value) : playout_audio_device_info(value) {}
505 float float_value;
506 int int_value;
507 bool bool_value;
508 PlayoutAudioDeviceInfo playout_audio_device_info;
509 } value_;
510 };
511
512 ~AudioProcessing() override {}
513
514 // Initializes internal states, while retaining all user settings. This
515 // should be called before beginning to process a new audio stream. However,
516 // it is not necessary to call before processing the first stream after
517 // creation.
518 //
519 // It is also not necessary to call if the audio parameters (sample
520 // rate and number of channels) have changed. Passing updated parameters
521 // directly to |ProcessStream()| and |ProcessReverseStream()| is permissible.
522 // If the parameters are known at init-time though, they may be provided.
523 // TODO(webrtc:5298): Change to return void.
524 virtual int Initialize() = 0;
525
526 // The int16 interfaces require:
527 // - only |NativeRate|s be used
528 // - that the input, output and reverse rates must match
529 // - that |processing_config.output_stream()| matches
530 // |processing_config.input_stream()|.
531 //
532 // The float interfaces accept arbitrary rates and support differing input and
533 // output layouts, but the output must have either one channel or the same
534 // number of channels as the input.
535 virtual int Initialize(const ProcessingConfig& processing_config) = 0;
536
537 // Initialize with unpacked parameters. See Initialize() above for details.
538 //
539 // TODO(mgraczyk): Remove once clients are updated to use the new interface.
540 virtual int Initialize(int capture_input_sample_rate_hz,
541 int capture_output_sample_rate_hz,
542 int render_sample_rate_hz,
543 ChannelLayout capture_input_layout,
544 ChannelLayout capture_output_layout,
545 ChannelLayout render_input_layout) = 0;
546
547 // TODO(peah): This method is a temporary solution used to take control
548 // over the parameters in the audio processing module and is likely to change.
549 virtual void ApplyConfig(const Config& config) = 0;
550
551 // TODO(ajm): Only intended for internal use. Make private and friend the
552 // necessary classes?
553 virtual int proc_sample_rate_hz() const = 0;
554 virtual int proc_split_sample_rate_hz() const = 0;
555 virtual size_t num_input_channels() const = 0;
556 virtual size_t num_proc_channels() const = 0;
557 virtual size_t num_output_channels() const = 0;
558 virtual size_t num_reverse_channels() const = 0;
559
560 // Set to true when the output of AudioProcessing will be muted or in some
561 // other way not used. Ideally, the captured audio would still be processed,
562 // but some components may change behavior based on this information.
563 // Default false. This method takes a lock. To achieve this in a lock-less
564 // manner the PostRuntimeSetting can instead be used.
565 virtual void set_output_will_be_muted(bool muted) = 0;
566
567 // Enqueues a runtime setting.
568 virtual void SetRuntimeSetting(RuntimeSetting setting) = 0;
569
570 // Enqueues a runtime setting. Returns a bool indicating whether the
571 // enqueueing was successfull.
572 virtual bool PostRuntimeSetting(RuntimeSetting setting) = 0;
573
574 // Accepts and produces a 10 ms frame interleaved 16 bit integer audio as
575 // specified in |input_config| and |output_config|. |src| and |dest| may use
576 // the same memory, if desired.
577 virtual int ProcessStream(const int16_t* const src,
578 const StreamConfig& input_config,
579 const StreamConfig& output_config,
580 int16_t* const dest) = 0;
581
582 // Accepts deinterleaved float audio with the range [-1, 1]. Each element of
583 // |src| points to a channel buffer, arranged according to |input_stream|. At
584 // output, the channels will be arranged according to |output_stream| in
585 // |dest|.
586 //
587 // The output must have one channel or as many channels as the input. |src|
588 // and |dest| may use the same memory, if desired.
589 virtual int ProcessStream(const float* const* src,
590 const StreamConfig& input_config,
591 const StreamConfig& output_config,
592 float* const* dest) = 0;
593
594 // Accepts and produces a 10 ms frame of interleaved 16 bit integer audio for
595 // the reverse direction audio stream as specified in |input_config| and
596 // |output_config|. |src| and |dest| may use the same memory, if desired.
597 virtual int ProcessReverseStream(const int16_t* const src,
598 const StreamConfig& input_config,
599 const StreamConfig& output_config,
600 int16_t* const dest) = 0;
601
602 // Accepts deinterleaved float audio with the range [-1, 1]. Each element of
603 // |data| points to a channel buffer, arranged according to |reverse_config|.
604 virtual int ProcessReverseStream(const float* const* src,
605 const StreamConfig& input_config,
606 const StreamConfig& output_config,
607 float* const* dest) = 0;
608
609 // Accepts deinterleaved float audio with the range [-1, 1]. Each element
610 // of |data| points to a channel buffer, arranged according to
611 // |reverse_config|.
612 virtual int AnalyzeReverseStream(const float* const* data,
613 const StreamConfig& reverse_config) = 0;
614
615 // Returns the most recently produced 10 ms of the linear AEC output at a rate
616 // of 16 kHz. If there is more than one capture channel, a mono representation
617 // of the input is returned. Returns true/false to indicate whether an output
618 // returned.
619 virtual bool GetLinearAecOutput(
620 rtc::ArrayView<std::array<float, 160>> linear_output) const = 0;
621
622 // This must be called prior to ProcessStream() if and only if adaptive analog
623 // gain control is enabled, to pass the current analog level from the audio
624 // HAL. Must be within the range provided in Config::GainController1.
625 virtual void set_stream_analog_level(int level) = 0;
626
627 // When an analog mode is set, this should be called after ProcessStream()
628 // to obtain the recommended new analog level for the audio HAL. It is the
629 // user's responsibility to apply this level.
630 virtual int recommended_stream_analog_level() const = 0;
631
632 // This must be called if and only if echo processing is enabled.
633 //
634 // Sets the |delay| in ms between ProcessReverseStream() receiving a far-end
635 // frame and ProcessStream() receiving a near-end frame containing the
636 // corresponding echo. On the client-side this can be expressed as
637 // delay = (t_render - t_analyze) + (t_process - t_capture)
638 // where,
639 // - t_analyze is the time a frame is passed to ProcessReverseStream() and
640 // t_render is the time the first sample of the same frame is rendered by
641 // the audio hardware.
642 // - t_capture is the time the first sample of a frame is captured by the
643 // audio hardware and t_process is the time the same frame is passed to
644 // ProcessStream().
645 virtual int set_stream_delay_ms(int delay) = 0;
646 virtual int stream_delay_ms() const = 0;
647
648 // Call to signal that a key press occurred (true) or did not occur (false)
649 // with this chunk of audio.
650 virtual void set_stream_key_pressed(bool key_pressed) = 0;
651
652 // Creates and attaches an webrtc::AecDump for recording debugging
653 // information.
654 // The |worker_queue| may not be null and must outlive the created
655 // AecDump instance. |max_log_size_bytes == -1| means the log size
656 // will be unlimited. |handle| may not be null. The AecDump takes
657 // responsibility for |handle| and closes it in the destructor. A
658 // return value of true indicates that the file has been
659 // sucessfully opened, while a value of false indicates that
660 // opening the file failed.
661 virtual bool CreateAndAttachAecDump(const std::string& file_name,
662 int64_t max_log_size_bytes,
663 rtc::TaskQueue* worker_queue) = 0;
664 virtual bool CreateAndAttachAecDump(FILE* handle,
665 int64_t max_log_size_bytes,
666 rtc::TaskQueue* worker_queue) = 0;
667
668 // TODO(webrtc:5298) Deprecated variant.
669 // Attaches provided webrtc::AecDump for recording debugging
670 // information. Log file and maximum file size logic is supposed to
671 // be handled by implementing instance of AecDump. Calling this
672 // method when another AecDump is attached resets the active AecDump
673 // with a new one. This causes the d-tor of the earlier AecDump to
674 // be called. The d-tor call may block until all pending logging
675 // tasks are completed.
676 virtual void AttachAecDump(std::unique_ptr<AecDump> aec_dump) = 0;
677
678 // If no AecDump is attached, this has no effect. If an AecDump is
679 // attached, it's destructor is called. The d-tor may block until
680 // all pending logging tasks are completed.
681 virtual void DetachAecDump() = 0;
682
683 // Get audio processing statistics.
684 virtual AudioProcessingStats GetStatistics() = 0;
685 // TODO(webrtc:5298) Deprecated variant. The |has_remote_tracks| argument
686 // should be set if there are active remote tracks (this would usually be true
687 // during a call). If there are no remote tracks some of the stats will not be
688 // set by AudioProcessing, because they only make sense if there is at least
689 // one remote track.
690 virtual AudioProcessingStats GetStatistics(bool has_remote_tracks) = 0;
691
692 // Returns the last applied configuration.
693 virtual AudioProcessing::Config GetConfig() const = 0;
694
695 enum Error {
696 // Fatal errors.
697 kNoError = 0,
698 kUnspecifiedError = -1,
699 kCreationFailedError = -2,
700 kUnsupportedComponentError = -3,
701 kUnsupportedFunctionError = -4,
702 kNullPointerError = -5,
703 kBadParameterError = -6,
704 kBadSampleRateError = -7,
705 kBadDataLengthError = -8,
706 kBadNumberChannelsError = -9,
707 kFileError = -10,
708 kStreamParameterNotSetError = -11,
709 kNotEnabledError = -12,
710
711 // Warnings are non-fatal.
712 // This results when a set_stream_ parameter is out of range. Processing
713 // will continue, but the parameter may have been truncated.
714 kBadStreamParameterWarning = -13
715 };
716
717 // Native rates supported by the integer interfaces.
718 enum NativeRate {
719 kSampleRate8kHz = 8000,
720 kSampleRate16kHz = 16000,
721 kSampleRate32kHz = 32000,
722 kSampleRate48kHz = 48000
723 };
724
725 // TODO(kwiberg): We currently need to support a compiler (Visual C++) that
726 // complains if we don't explicitly state the size of the array here. Remove
727 // the size when that's no longer the case.
728 static constexpr int kNativeSampleRatesHz[4] = {
729 kSampleRate8kHz, kSampleRate16kHz, kSampleRate32kHz, kSampleRate48kHz};
730 static constexpr size_t kNumNativeSampleRates =
731 arraysize(kNativeSampleRatesHz);
732 static constexpr int kMaxNativeSampleRateHz =
733 kNativeSampleRatesHz[kNumNativeSampleRates - 1];
734
735 static constexpr int kChunkSizeMs = 10;
736 };
737
738 class RTC_EXPORT AudioProcessingBuilder {
739 public:
740 AudioProcessingBuilder();
741 ~AudioProcessingBuilder();
742 // The AudioProcessingBuilder takes ownership of the echo_control_factory.
743 AudioProcessingBuilder& SetEchoControlFactory(
744 std::unique_ptr<EchoControlFactory> echo_control_factory) {
745 echo_control_factory_ = std::move(echo_control_factory);
746 return *this;
747 }
748 // The AudioProcessingBuilder takes ownership of the capture_post_processing.
749 AudioProcessingBuilder& SetCapturePostProcessing(
750 std::unique_ptr<CustomProcessing> capture_post_processing) {
751 capture_post_processing_ = std::move(capture_post_processing);
752 return *this;
753 }
754 // The AudioProcessingBuilder takes ownership of the render_pre_processing.
755 AudioProcessingBuilder& SetRenderPreProcessing(
756 std::unique_ptr<CustomProcessing> render_pre_processing) {
757 render_pre_processing_ = std::move(render_pre_processing);
758 return *this;
759 }
760 // The AudioProcessingBuilder takes ownership of the echo_detector.
761 AudioProcessingBuilder& SetEchoDetector(
762 rtc::scoped_refptr<EchoDetector> echo_detector) {
763 echo_detector_ = std::move(echo_detector);
764 return *this;
765 }
766 // The AudioProcessingBuilder takes ownership of the capture_analyzer.
767 AudioProcessingBuilder& SetCaptureAnalyzer(
768 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
769 capture_analyzer_ = std::move(capture_analyzer);
770 return *this;
771 }
772 // This creates an APM instance using the previously set components. Calling
773 // the Create function resets the AudioProcessingBuilder to its initial state.
774 AudioProcessing* Create();
775 AudioProcessing* Create(const webrtc::Config& config);
776
777 private:
778 std::unique_ptr<EchoControlFactory> echo_control_factory_;
779 std::unique_ptr<CustomProcessing> capture_post_processing_;
780 std::unique_ptr<CustomProcessing> render_pre_processing_;
781 rtc::scoped_refptr<EchoDetector> echo_detector_;
782 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer_;
783 RTC_DISALLOW_COPY_AND_ASSIGN(AudioProcessingBuilder);
784 };
785
786 class StreamConfig {
787 public:
788 // sample_rate_hz: The sampling rate of the stream.
789 //
790 // num_channels: The number of audio channels in the stream, excluding the
791 // keyboard channel if it is present. When passing a
792 // StreamConfig with an array of arrays T*[N],
793 //
794 // N == {num_channels + 1 if has_keyboard
795 // {num_channels if !has_keyboard
796 //
797 // has_keyboard: True if the stream has a keyboard channel. When has_keyboard
798 // is true, the last channel in any corresponding list of
799 // channels is the keyboard channel.
800 StreamConfig(int sample_rate_hz = 0,
801 size_t num_channels = 0,
802 bool has_keyboard = false)
803 : sample_rate_hz_(sample_rate_hz),
804 num_channels_(num_channels),
805 has_keyboard_(has_keyboard),
806 num_frames_(calculate_frames(sample_rate_hz)) {}
807
808 void set_sample_rate_hz(int value) {
809 sample_rate_hz_ = value;
810 num_frames_ = calculate_frames(value);
811 }
812 void set_num_channels(size_t value) { num_channels_ = value; }
813 void set_has_keyboard(bool value) { has_keyboard_ = value; }
814
815 int sample_rate_hz() const { return sample_rate_hz_; }
816
817 // The number of channels in the stream, not including the keyboard channel if
818 // present.
819 size_t num_channels() const { return num_channels_; }
820
821 bool has_keyboard() const { return has_keyboard_; }
822 size_t num_frames() const { return num_frames_; }
823 size_t num_samples() const { return num_channels_ * num_frames_; }
824
825 bool operator==(const StreamConfig& other) const {
826 return sample_rate_hz_ == other.sample_rate_hz_ &&
827 num_channels_ == other.num_channels_ &&
828 has_keyboard_ == other.has_keyboard_;
829 }
830
831 bool operator!=(const StreamConfig& other) const { return !(*this == other); }
832
833 private:
834 static size_t calculate_frames(int sample_rate_hz) {
835 return static_cast<size_t>(AudioProcessing::kChunkSizeMs * sample_rate_hz /
836 1000);
837 }
838
839 int sample_rate_hz_;
840 size_t num_channels_;
841 bool has_keyboard_;
842 size_t num_frames_;
843 };
844
845 class ProcessingConfig {
846 public:
847 enum StreamName {
848 kInputStream,
849 kOutputStream,
850 kReverseInputStream,
851 kReverseOutputStream,
852 kNumStreamNames,
853 };
854
855 const StreamConfig& input_stream() const {
856 return streams[StreamName::kInputStream];
857 }
858 const StreamConfig& output_stream() const {
859 return streams[StreamName::kOutputStream];
860 }
861 const StreamConfig& reverse_input_stream() const {
862 return streams[StreamName::kReverseInputStream];
863 }
864 const StreamConfig& reverse_output_stream() const {
865 return streams[StreamName::kReverseOutputStream];
866 }
867
868 StreamConfig& input_stream() { return streams[StreamName::kInputStream]; }
869 StreamConfig& output_stream() { return streams[StreamName::kOutputStream]; }
870 StreamConfig& reverse_input_stream() {
871 return streams[StreamName::kReverseInputStream];
872 }
873 StreamConfig& reverse_output_stream() {
874 return streams[StreamName::kReverseOutputStream];
875 }
876
877 bool operator==(const ProcessingConfig& other) const {
878 for (int i = 0; i < StreamName::kNumStreamNames; ++i) {
879 if (this->streams[i] != other.streams[i]) {
880 return false;
881 }
882 }
883 return true;
884 }
885
886 bool operator!=(const ProcessingConfig& other) const {
887 return !(*this == other);
888 }
889
890 StreamConfig streams[StreamName::kNumStreamNames];
891 };
892
893 // Experimental interface for a custom analysis submodule.
894 class CustomAudioAnalyzer {
895 public:
896 // (Re-) Initializes the submodule.
897 virtual void Initialize(int sample_rate_hz, int num_channels) = 0;
898 // Analyzes the given capture or render signal.
899 virtual void Analyze(const AudioBuffer* audio) = 0;
900 // Returns a string representation of the module state.
901 virtual std::string ToString() const = 0;
902
903 virtual ~CustomAudioAnalyzer() {}
904 };
905
906 // Interface for a custom processing submodule.
907 class CustomProcessing {
908 public:
909 // (Re-)Initializes the submodule.
910 virtual void Initialize(int sample_rate_hz, int num_channels) = 0;
911 // Processes the given capture or render signal.
912 virtual void Process(AudioBuffer* audio) = 0;
913 // Returns a string representation of the module state.
914 virtual std::string ToString() const = 0;
915 // Handles RuntimeSettings. TODO(webrtc:9262): make pure virtual
916 // after updating dependencies.
917 virtual void SetRuntimeSetting(AudioProcessing::RuntimeSetting setting);
918
919 virtual ~CustomProcessing() {}
920 };
921
922 // Interface for an echo detector submodule.
923 class EchoDetector : public rtc::RefCountInterface {
924 public:
925 // (Re-)Initializes the submodule.
926 virtual void Initialize(int capture_sample_rate_hz,
927 int num_capture_channels,
928 int render_sample_rate_hz,
929 int num_render_channels) = 0;
930
931 // Analysis (not changing) of the render signal.
932 virtual void AnalyzeRenderAudio(rtc::ArrayView<const float> render_audio) = 0;
933
934 // Analysis (not changing) of the capture signal.
935 virtual void AnalyzeCaptureAudio(
936 rtc::ArrayView<const float> capture_audio) = 0;
937
938 // Pack an AudioBuffer into a vector<float>.
939 static void PackRenderAudioBuffer(AudioBuffer* audio,
940 std::vector<float>* packed_buffer);
941
942 struct Metrics {
943 absl::optional<double> echo_likelihood;
944 absl::optional<double> echo_likelihood_recent_max;
945 };
946
947 // Collect current metrics from the echo detector.
948 virtual Metrics GetMetrics() const = 0;
949 };
950
951 } // namespace webrtc
952
953 #endif // MODULES_AUDIO_PROCESSING_INCLUDE_AUDIO_PROCESSING_H_