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