1 /*
2  *  Copyright (c) 2011 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 WEBRTC_MODULES_AUDIO_PROCESSING_MAIN_INTERFACE_AUDIO_PROCESSING_H_
12 #define WEBRTC_MODULES_AUDIO_PROCESSING_MAIN_INTERFACE_AUDIO_PROCESSING_H_
13 
14 #include <stddef.h> // size_t
15 
16 #include "typedefs.h"
17 #include "module.h"
18 
19 namespace webrtc {
20 
21 class AudioFrame;
22 class EchoCancellation;
23 class EchoControlMobile;
24 class GainControl;
25 class HighPassFilter;
26 class LevelEstimator;
27 class NoiseSuppression;
28 class VoiceDetection;
29 
30 // The Audio Processing Module (APM) provides a collection of voice processing
31 // components designed for real-time communications software.
32 //
33 // APM operates on two audio streams on a frame-by-frame basis. Frames of the
34 // primary stream, on which all processing is applied, are passed to
35 // |ProcessStream()|. Frames of the reverse direction stream, which are used for
36 // analysis by some components, are passed to |AnalyzeReverseStream()|. On the
37 // client-side, this will typically be the near-end (capture) and far-end
38 // (render) streams, respectively. APM should be placed in the signal chain as
39 // close to the audio hardware abstraction layer (HAL) as possible.
40 //
41 // On the server-side, the reverse stream will normally not be used, with
42 // processing occurring on each incoming stream.
43 //
44 // Component interfaces follow a similar pattern and are accessed through
45 // corresponding getters in APM. All components are disabled at create-time,
46 // with default settings that are recommended for most situations. New settings
47 // can be applied without enabling a component. Enabling a component triggers
48 // memory allocation and initialization to allow it to start processing the
49 // streams.
50 //
51 // Thread safety is provided with the following assumptions to reduce locking
52 // overhead:
53 //   1. The stream getters and setters are called from the same thread as
54 //      ProcessStream(). More precisely, stream functions are never called
55 //      concurrently with ProcessStream().
56 //   2. Parameter getters are never called concurrently with the corresponding
57 //      setter.
58 //
59 // APM accepts only 16-bit linear PCM audio data in frames of 10 ms. Multiple
60 // channels should be interleaved.
61 //
62 // Usage example, omitting error checking:
63 // AudioProcessing* apm = AudioProcessing::Create(0);
64 // apm->set_sample_rate_hz(32000); // Super-wideband processing.
65 //
66 // // Mono capture and stereo render.
67 // apm->set_num_channels(1, 1);
68 // apm->set_num_reverse_channels(2);
69 //
70 // apm->high_pass_filter()->Enable(true);
71 //
72 // apm->echo_cancellation()->enable_drift_compensation(false);
73 // apm->echo_cancellation()->Enable(true);
74 //
75 // apm->noise_reduction()->set_level(kHighSuppression);
76 // apm->noise_reduction()->Enable(true);
77 //
78 // apm->gain_control()->set_analog_level_limits(0, 255);
79 // apm->gain_control()->set_mode(kAdaptiveAnalog);
80 // apm->gain_control()->Enable(true);
81 //
82 // apm->voice_detection()->Enable(true);
83 //
84 // // Start a voice call...
85 //
86 // // ... Render frame arrives bound for the audio HAL ...
87 // apm->AnalyzeReverseStream(render_frame);
88 //
89 // // ... Capture frame arrives from the audio HAL ...
90 // // Call required set_stream_ functions.
91 // apm->set_stream_delay_ms(delay_ms);
92 // apm->gain_control()->set_stream_analog_level(analog_level);
93 //
94 // apm->ProcessStream(capture_frame);
95 //
96 // // Call required stream_ functions.
97 // analog_level = apm->gain_control()->stream_analog_level();
98 // has_voice = apm->stream_has_voice();
99 //
100 // // Repeate render and capture processing for the duration of the call...
101 // // Start a new call...
102 // apm->Initialize();
103 //
104 // // Close the application...
105 // AudioProcessing::Destroy(apm);
106 // apm = NULL;
107 //
108 class AudioProcessing : public Module {
109  public:
110   // Creates a APM instance, with identifier |id|. Use one instance for every
111   // primary audio stream requiring processing. On the client-side, this would
112   // typically be one instance for the near-end stream, and additional instances
113   // for each far-end stream which requires processing. On the server-side,
114   // this would typically be one instance for every incoming stream.
115   static AudioProcessing* Create(int id);
~AudioProcessing()116   virtual ~AudioProcessing() {};
117 
118   // TODO(andrew): remove this method. We now allow users to delete instances
119   // directly, useful for scoped_ptr.
120   // Destroys a |apm| instance.
121   static void Destroy(AudioProcessing* apm);
122 
123   // Initializes internal states, while retaining all user settings. This
124   // should be called before beginning to process a new audio stream. However,
125   // it is not necessary to call before processing the first stream after
126   // creation.
127   virtual int Initialize() = 0;
128 
129   // Sets the sample |rate| in Hz for both the primary and reverse audio
130   // streams. 8000, 16000 or 32000 Hz are permitted.
131   virtual int set_sample_rate_hz(int rate) = 0;
132   virtual int sample_rate_hz() const = 0;
133 
134   // Sets the number of channels for the primary audio stream. Input frames must
135   // contain a number of channels given by |input_channels|, while output frames
136   // will be returned with number of channels given by |output_channels|.
137   virtual int set_num_channels(int input_channels, int output_channels) = 0;
138   virtual int num_input_channels() const = 0;
139   virtual int num_output_channels() const = 0;
140 
141   // Sets the number of channels for the reverse audio stream. Input frames must
142   // contain a number of channels given by |channels|.
143   virtual int set_num_reverse_channels(int channels) = 0;
144   virtual int num_reverse_channels() const = 0;
145 
146   // Processes a 10 ms |frame| of the primary audio stream. On the client-side,
147   // this is the near-end (or captured) audio.
148   //
149   // If needed for enabled functionality, any function with the set_stream_ tag
150   // must be called prior to processing the current frame. Any getter function
151   // with the stream_ tag which is needed should be called after processing.
152   //
153   // The |_frequencyInHz|, |_audioChannel|, and |_payloadDataLengthInSamples|
154   // members of |frame| must be valid, and correspond to settings supplied
155   // to APM.
156   virtual int ProcessStream(AudioFrame* frame) = 0;
157 
158   // Analyzes a 10 ms |frame| of the reverse direction audio stream. The frame
159   // will not be modified. On the client-side, this is the far-end (or to be
160   // rendered) audio.
161   //
162   // It is only necessary to provide this if echo processing is enabled, as the
163   // reverse stream forms the echo reference signal. It is recommended, but not
164   // necessary, to provide if gain control is enabled. On the server-side this
165   // typically will not be used. If you're not sure what to pass in here,
166   // chances are you don't need to use it.
167   //
168   // The |_frequencyInHz|, |_audioChannel|, and |_payloadDataLengthInSamples|
169   // members of |frame| must be valid.
170   //
171   // TODO(ajm): add const to input; requires an implementation fix.
172   virtual int AnalyzeReverseStream(AudioFrame* frame) = 0;
173 
174   // This must be called if and only if echo processing is enabled.
175   //
176   // Sets the |delay| in ms between AnalyzeReverseStream() receiving a far-end
177   // frame and ProcessStream() receiving a near-end frame containing the
178   // corresponding echo. On the client-side this can be expressed as
179   //   delay = (t_render - t_analyze) + (t_process - t_capture)
180   // where,
181   //   - t_analyze is the time a frame is passed to AnalyzeReverseStream() and
182   //     t_render is the time the first sample of the same frame is rendered by
183   //     the audio hardware.
184   //   - t_capture is the time the first sample of a frame is captured by the
185   //     audio hardware and t_pull is the time the same frame is passed to
186   //     ProcessStream().
187   virtual int set_stream_delay_ms(int delay) = 0;
188   virtual int stream_delay_ms() const = 0;
189 
190   // Starts recording debugging information to a file specified by |filename|,
191   // a NULL-terminated string. If there is an ongoing recording, the old file
192   // will be closed, and recording will continue in the newly specified file.
193   // An already existing file will be overwritten without warning.
194   static const size_t kMaxFilenameSize = 1024;
195   virtual int StartDebugRecording(const char filename[kMaxFilenameSize]) = 0;
196 
197   // Stops recording debugging information, and closes the file. Recording
198   // cannot be resumed in the same file (without overwriting it).
199   virtual int StopDebugRecording() = 0;
200 
201   // These provide access to the component interfaces and should never return
202   // NULL. The pointers will be valid for the lifetime of the APM instance.
203   // The memory for these objects is entirely managed internally.
204   virtual EchoCancellation* echo_cancellation() const = 0;
205   virtual EchoControlMobile* echo_control_mobile() const = 0;
206   virtual GainControl* gain_control() const = 0;
207   virtual HighPassFilter* high_pass_filter() const = 0;
208   virtual LevelEstimator* level_estimator() const = 0;
209   virtual NoiseSuppression* noise_suppression() const = 0;
210   virtual VoiceDetection* voice_detection() const = 0;
211 
212   struct Statistic {
213     int instant;  // Instantaneous value.
214     int average;  // Long-term average.
215     int maximum;  // Long-term maximum.
216     int minimum;  // Long-term minimum.
217   };
218 
219   // Fatal errors.
220   enum Errors {
221     kNoError = 0,
222     kUnspecifiedError = -1,
223     kCreationFailedError = -2,
224     kUnsupportedComponentError = -3,
225     kUnsupportedFunctionError = -4,
226     kNullPointerError = -5,
227     kBadParameterError = -6,
228     kBadSampleRateError = -7,
229     kBadDataLengthError = -8,
230     kBadNumberChannelsError = -9,
231     kFileError = -10,
232     kStreamParameterNotSetError = -11,
233     kNotEnabledError = -12
234   };
235 
236   // Warnings are non-fatal.
237   enum Warnings {
238     // This results when a set_stream_ parameter is out of range. Processing
239     // will continue, but the parameter may have been truncated.
240     kBadStreamParameterWarning = -13,
241   };
242 
243   // Inherited from Module.
TimeUntilNextProcess()244   virtual WebRtc_Word32 TimeUntilNextProcess() { return -1; };
Process()245   virtual WebRtc_Word32 Process() { return -1; };
246 };
247 
248 // The acoustic echo cancellation (AEC) component provides better performance
249 // than AECM but also requires more processing power and is dependent on delay
250 // stability and reporting accuracy. As such it is well-suited and recommended
251 // for PC and IP phone applications.
252 //
253 // Not recommended to be enabled on the server-side.
254 class EchoCancellation {
255  public:
256   // EchoCancellation and EchoControlMobile may not be enabled simultaneously.
257   // Enabling one will disable the other.
258   virtual int Enable(bool enable) = 0;
259   virtual bool is_enabled() const = 0;
260 
261   // Differences in clock speed on the primary and reverse streams can impact
262   // the AEC performance. On the client-side, this could be seen when different
263   // render and capture devices are used, particularly with webcams.
264   //
265   // This enables a compensation mechanism, and requires that
266   // |set_device_sample_rate_hz()| and |set_stream_drift_samples()| be called.
267   virtual int enable_drift_compensation(bool enable) = 0;
268   virtual bool is_drift_compensation_enabled() const = 0;
269 
270   // Provides the sampling rate of the audio devices. It is assumed the render
271   // and capture devices use the same nominal sample rate. Required if and only
272   // if drift compensation is enabled.
273   virtual int set_device_sample_rate_hz(int rate) = 0;
274   virtual int device_sample_rate_hz() const = 0;
275 
276   // Sets the difference between the number of samples rendered and captured by
277   // the audio devices since the last call to |ProcessStream()|. Must be called
278   // if and only if drift compensation is enabled, prior to |ProcessStream()|.
279   virtual int set_stream_drift_samples(int drift) = 0;
280   virtual int stream_drift_samples() const = 0;
281 
282   enum SuppressionLevel {
283     kLowSuppression,
284     kModerateSuppression,
285     kHighSuppression
286   };
287 
288   // Sets the aggressiveness of the suppressor. A higher level trades off
289   // double-talk performance for increased echo suppression.
290   virtual int set_suppression_level(SuppressionLevel level) = 0;
291   virtual SuppressionLevel suppression_level() const = 0;
292 
293   // Returns false if the current frame almost certainly contains no echo
294   // and true if it _might_ contain echo.
295   virtual bool stream_has_echo() const = 0;
296 
297   // Enables the computation of various echo metrics. These are obtained
298   // through |GetMetrics()|.
299   virtual int enable_metrics(bool enable) = 0;
300   virtual bool are_metrics_enabled() const = 0;
301 
302   // Each statistic is reported in dB.
303   // P_far:  Far-end (render) signal power.
304   // P_echo: Near-end (capture) echo signal power.
305   // P_out:  Signal power at the output of the AEC.
306   // P_a:    Internal signal power at the point before the AEC's non-linear
307   //         processor.
308   struct Metrics {
309     // RERL = ERL + ERLE
310     AudioProcessing::Statistic residual_echo_return_loss;
311 
312     // ERL = 10log_10(P_far / P_echo)
313     AudioProcessing::Statistic echo_return_loss;
314 
315     // ERLE = 10log_10(P_echo / P_out)
316     AudioProcessing::Statistic echo_return_loss_enhancement;
317 
318     // (Pre non-linear processing suppression) A_NLP = 10log_10(P_echo / P_a)
319     AudioProcessing::Statistic a_nlp;
320   };
321 
322   // TODO(ajm): discuss the metrics update period.
323   virtual int GetMetrics(Metrics* metrics) = 0;
324 
325   // Enables computation and logging of delay values. Statistics are obtained
326   // through |GetDelayMetrics()|.
327   virtual int enable_delay_logging(bool enable) = 0;
328   virtual bool is_delay_logging_enabled() const = 0;
329 
330   // The delay metrics consists of the delay |median| and the delay standard
331   // deviation |std|. The values are averaged over the time period since the
332   // last call to |GetDelayMetrics()|.
333   virtual int GetDelayMetrics(int* median, int* std) = 0;
334 
335  protected:
~EchoCancellation()336   virtual ~EchoCancellation() {};
337 };
338 
339 // The acoustic echo control for mobile (AECM) component is a low complexity
340 // robust option intended for use on mobile devices.
341 //
342 // Not recommended to be enabled on the server-side.
343 class EchoControlMobile {
344  public:
345   // EchoCancellation and EchoControlMobile may not be enabled simultaneously.
346   // Enabling one will disable the other.
347   virtual int Enable(bool enable) = 0;
348   virtual bool is_enabled() const = 0;
349 
350   // Recommended settings for particular audio routes. In general, the louder
351   // the echo is expected to be, the higher this value should be set. The
352   // preferred setting may vary from device to device.
353   enum RoutingMode {
354     kQuietEarpieceOrHeadset,
355     kEarpiece,
356     kLoudEarpiece,
357     kSpeakerphone,
358     kLoudSpeakerphone
359   };
360 
361   // Sets echo control appropriate for the audio routing |mode| on the device.
362   // It can and should be updated during a call if the audio routing changes.
363   virtual int set_routing_mode(RoutingMode mode) = 0;
364   virtual RoutingMode routing_mode() const = 0;
365 
366   // Comfort noise replaces suppressed background noise to maintain a
367   // consistent signal level.
368   virtual int enable_comfort_noise(bool enable) = 0;
369   virtual bool is_comfort_noise_enabled() const = 0;
370 
371   // A typical use case is to initialize the component with an echo path from a
372   // previous call. The echo path is retrieved using |GetEchoPath()|, typically
373   // at the end of a call. The data can then be stored for later use as an
374   // initializer before the next call, using |SetEchoPath()|.
375   //
376   // Controlling the echo path this way requires the data |size_bytes| to match
377   // the internal echo path size. This size can be acquired using
378   // |echo_path_size_bytes()|. |SetEchoPath()| causes an entire reset, worth
379   // noting if it is to be called during an ongoing call.
380   //
381   // It is possible that version incompatibilities may result in a stored echo
382   // path of the incorrect size. In this case, the stored path should be
383   // discarded.
384   virtual int SetEchoPath(const void* echo_path, size_t size_bytes) = 0;
385   virtual int GetEchoPath(void* echo_path, size_t size_bytes) const = 0;
386 
387   // The returned path size is guaranteed not to change for the lifetime of
388   // the application.
389   static size_t echo_path_size_bytes();
390 
391  protected:
~EchoControlMobile()392   virtual ~EchoControlMobile() {};
393 };
394 
395 // The automatic gain control (AGC) component brings the signal to an
396 // appropriate range. This is done by applying a digital gain directly and, in
397 // the analog mode, prescribing an analog gain to be applied at the audio HAL.
398 //
399 // Recommended to be enabled on the client-side.
400 class GainControl {
401  public:
402   virtual int Enable(bool enable) = 0;
403   virtual bool is_enabled() const = 0;
404 
405   // When an analog mode is set, this must be called prior to |ProcessStream()|
406   // to pass the current analog level from the audio HAL. Must be within the
407   // range provided to |set_analog_level_limits()|.
408   virtual int set_stream_analog_level(int level) = 0;
409 
410   // When an analog mode is set, this should be called after |ProcessStream()|
411   // to obtain the recommended new analog level for the audio HAL. It is the
412   // users responsibility to apply this level.
413   virtual int stream_analog_level() = 0;
414 
415   enum Mode {
416     // Adaptive mode intended for use if an analog volume control is available
417     // on the capture device. It will require the user to provide coupling
418     // between the OS mixer controls and AGC through the |stream_analog_level()|
419     // functions.
420     //
421     // It consists of an analog gain prescription for the audio device and a
422     // digital compression stage.
423     kAdaptiveAnalog,
424 
425     // Adaptive mode intended for situations in which an analog volume control
426     // is unavailable. It operates in a similar fashion to the adaptive analog
427     // mode, but with scaling instead applied in the digital domain. As with
428     // the analog mode, it additionally uses a digital compression stage.
429     kAdaptiveDigital,
430 
431     // Fixed mode which enables only the digital compression stage also used by
432     // the two adaptive modes.
433     //
434     // It is distinguished from the adaptive modes by considering only a
435     // short time-window of the input signal. It applies a fixed gain through
436     // most of the input level range, and compresses (gradually reduces gain
437     // with increasing level) the input signal at higher levels. This mode is
438     // preferred on embedded devices where the capture signal level is
439     // predictable, so that a known gain can be applied.
440     kFixedDigital
441   };
442 
443   virtual int set_mode(Mode mode) = 0;
444   virtual Mode mode() const = 0;
445 
446   // Sets the target peak |level| (or envelope) of the AGC in dBFs (decibels
447   // from digital full-scale). The convention is to use positive values. For
448   // instance, passing in a value of 3 corresponds to -3 dBFs, or a target
449   // level 3 dB below full-scale. Limited to [0, 31].
450   //
451   // TODO(ajm): use a negative value here instead, if/when VoE will similarly
452   //            update its interface.
453   virtual int set_target_level_dbfs(int level) = 0;
454   virtual int target_level_dbfs() const = 0;
455 
456   // Sets the maximum |gain| the digital compression stage may apply, in dB. A
457   // higher number corresponds to greater compression, while a value of 0 will
458   // leave the signal uncompressed. Limited to [0, 90].
459   virtual int set_compression_gain_db(int gain) = 0;
460   virtual int compression_gain_db() const = 0;
461 
462   // When enabled, the compression stage will hard limit the signal to the
463   // target level. Otherwise, the signal will be compressed but not limited
464   // above the target level.
465   virtual int enable_limiter(bool enable) = 0;
466   virtual bool is_limiter_enabled() const = 0;
467 
468   // Sets the |minimum| and |maximum| analog levels of the audio capture device.
469   // Must be set if and only if an analog mode is used. Limited to [0, 65535].
470   virtual int set_analog_level_limits(int minimum,
471                                       int maximum) = 0;
472   virtual int analog_level_minimum() const = 0;
473   virtual int analog_level_maximum() const = 0;
474 
475   // Returns true if the AGC has detected a saturation event (period where the
476   // signal reaches digital full-scale) in the current frame and the analog
477   // level cannot be reduced.
478   //
479   // This could be used as an indicator to reduce or disable analog mic gain at
480   // the audio HAL.
481   virtual bool stream_is_saturated() const = 0;
482 
483  protected:
~GainControl()484   virtual ~GainControl() {};
485 };
486 
487 // A filtering component which removes DC offset and low-frequency noise.
488 // Recommended to be enabled on the client-side.
489 class HighPassFilter {
490  public:
491   virtual int Enable(bool enable) = 0;
492   virtual bool is_enabled() const = 0;
493 
494  protected:
~HighPassFilter()495   virtual ~HighPassFilter() {};
496 };
497 
498 // An estimation component used to retrieve level metrics.
499 class LevelEstimator {
500  public:
501   virtual int Enable(bool enable) = 0;
502   virtual bool is_enabled() const = 0;
503 
504   // Returns the root mean square (RMS) level in dBFs (decibels from digital
505   // full-scale), or alternately dBov. It is computed over all primary stream
506   // frames since the last call to RMS(). The returned value is positive but
507   // should be interpreted as negative. It is constrained to [0, 127].
508   //
509   // The computation follows:
510   // http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-05
511   // with the intent that it can provide the RTP audio level indication.
512   //
513   // Frames passed to ProcessStream() with an |_energy| of zero are considered
514   // to have been muted. The RMS of the frame will be interpreted as -127.
515   virtual int RMS() = 0;
516 
517  protected:
~LevelEstimator()518   virtual ~LevelEstimator() {};
519 };
520 
521 // The noise suppression (NS) component attempts to remove noise while
522 // retaining speech. Recommended to be enabled on the client-side.
523 //
524 // Recommended to be enabled on the client-side.
525 class NoiseSuppression {
526  public:
527   virtual int Enable(bool enable) = 0;
528   virtual bool is_enabled() const = 0;
529 
530   // Determines the aggressiveness of the suppression. Increasing the level
531   // will reduce the noise level at the expense of a higher speech distortion.
532   enum Level {
533     kLow,
534     kModerate,
535     kHigh,
536     kVeryHigh
537   };
538 
539   virtual int set_level(Level level) = 0;
540   virtual Level level() const = 0;
541 
542  protected:
~NoiseSuppression()543   virtual ~NoiseSuppression() {};
544 };
545 
546 // The voice activity detection (VAD) component analyzes the stream to
547 // determine if voice is present. A facility is also provided to pass in an
548 // external VAD decision.
549 //
550 // In addition to |stream_has_voice()| the VAD decision is provided through the
551 // |AudioFrame| passed to |ProcessStream()|. The |_vadActivity| member will be
552 // modified to reflect the current decision.
553 class VoiceDetection {
554  public:
555   virtual int Enable(bool enable) = 0;
556   virtual bool is_enabled() const = 0;
557 
558   // Returns true if voice is detected in the current frame. Should be called
559   // after |ProcessStream()|.
560   virtual bool stream_has_voice() const = 0;
561 
562   // Some of the APM functionality requires a VAD decision. In the case that
563   // a decision is externally available for the current frame, it can be passed
564   // in here, before |ProcessStream()| is called.
565   //
566   // VoiceDetection does _not_ need to be enabled to use this. If it happens to
567   // be enabled, detection will be skipped for any frame in which an external
568   // VAD decision is provided.
569   virtual int set_stream_has_voice(bool has_voice) = 0;
570 
571   // Specifies the likelihood that a frame will be declared to contain voice.
572   // A higher value makes it more likely that speech will not be clipped, at
573   // the expense of more noise being detected as voice.
574   enum Likelihood {
575     kVeryLowLikelihood,
576     kLowLikelihood,
577     kModerateLikelihood,
578     kHighLikelihood
579   };
580 
581   virtual int set_likelihood(Likelihood likelihood) = 0;
582   virtual Likelihood likelihood() const = 0;
583 
584   // Sets the |size| of the frames in ms on which the VAD will operate. Larger
585   // frames will improve detection accuracy, but reduce the frequency of
586   // updates.
587   //
588   // This does not impact the size of frames passed to |ProcessStream()|.
589   virtual int set_frame_size_ms(int size) = 0;
590   virtual int frame_size_ms() const = 0;
591 
592  protected:
~VoiceDetection()593   virtual ~VoiceDetection() {};
594 };
595 }  // namespace webrtc
596 
597 #endif  // WEBRTC_MODULES_AUDIO_PROCESSING_MAIN_INTERFACE_AUDIO_PROCESSING_H_
598