audio_processing.h 36 KB

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