1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_RENDERER_MEDIA_WEBRTC_AUDIO_DEVICE_IMPL_H_
6 #define CONTENT_RENDERER_MEDIA_WEBRTC_AUDIO_DEVICE_IMPL_H_
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/files/file.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/threading/thread_checker.h"
18 #include "content/common/content_export.h"
19 #include "content/renderer/media/webrtc_audio_capturer.h"
20 #include "content/renderer/media/webrtc_audio_device_not_impl.h"
21 #include "ipc/ipc_platform_file.h"
22 #include "media/base/audio_capturer_source.h"
23 #include "media/base/audio_renderer_sink.h"
25 // A WebRtcAudioDeviceImpl instance implements the abstract interface
26 // webrtc::AudioDeviceModule which makes it possible for a user (e.g. webrtc::
27 // VoiceEngine) to register this class as an external AudioDeviceModule (ADM).
28 // Then WebRtcAudioDeviceImpl::SetSessionId() needs to be called to set the
29 // session id that tells which device to use. The user can then call
30 // WebRtcAudioDeviceImpl::StartPlayout() and
31 // WebRtcAudioDeviceImpl::StartRecording() from the render process to initiate
32 // and start audio rendering and capturing in the browser process. IPC is
33 // utilized to set up the media streams.
37 // using namespace webrtc;
40 // scoped_refptr<WebRtcAudioDeviceImpl> external_adm;
41 // external_adm = new WebRtcAudioDeviceImpl();
42 // external_adm->SetSessionId(session_id);
43 // VoiceEngine* voe = VoiceEngine::Create();
44 // VoEBase* base = VoEBase::GetInterface(voe);
45 // base->Init(external_adm);
46 // int ch = base->CreateChannel();
48 // base->StartReceive(ch)
49 // base->StartPlayout(ch);
50 // base->StartSending(ch);
52 // <== full-duplex audio session with AGC enabled ==>
54 // base->DeleteChannel(ch);
57 // VoiceEngine::Delete(voe);
60 // webrtc::VoiceEngine::Init() calls these ADM methods (in this order):
62 // RegisterAudioCallback(this)
63 // webrtc::VoiceEngine is an webrtc::AudioTransport implementation and
64 // implements the RecordedDataIsAvailable() and NeedMorePlayData() callbacks.
67 // Creates and initializes the AudioOutputDevice and AudioInputDevice
71 // Enables the adaptive analog mode of the AGC which ensures that a
72 // suitable microphone volume level will be set. This scheme will affect
73 // the actual microphone control slider.
77 // It aims to maintain a constant speech loudness level from the microphone.
78 // This is done by both controlling the analog microphone gain and applying
79 // digital gain. The microphone gain on the sound card is slowly
80 // increased/decreased during speech only. By observing the microphone control
81 // slider you can see it move when you speak. If you scream, the slider moves
82 // downwards and then upwards again when you return to normal. It is not
83 // uncommon that the slider hits the maximum. This means that the maximum
84 // analog gain is not large enough to give the desired loudness. Nevertheless,
85 // we can in general still attain the desired loudness. If the microphone
86 // control slider is moved manually, the gain adaptation restarts and returns
87 // to roughly the same position as before the change if the circumstances are
88 // still the same. When the input microphone signal causes saturation, the
89 // level is decreased dramatically and has to re-adapt towards the old level.
90 // The adaptation is a slowly varying process and at the beginning of capture
91 // this is noticed by a slow increase in volume. Smaller changes in microphone
92 // input level is leveled out by the built-in digital control. For larger
93 // differences we need to rely on the slow adaptation.
94 // See http://en.wikipedia.org/wiki/Automatic_gain_control for more details.
96 // AGC implementation details:
98 // The adaptive analog mode of the AGC is always enabled for desktop platforms
101 // Before recording starts, the ADM enables AGC on the AudioInputDevice.
103 // A capture session with AGC is started up as follows (simplified):
107 // ADM::StartRecording()
108 // AudioInputDevice::InitializeOnIOThread()
109 // AudioInputHostMsg_CreateStream(..., agc=true) [IPC]
111 // [IPC to the browser]
113 // AudioInputRendererHost::OnCreateStream()
114 // AudioInputController::CreateLowLatency()
115 // AudioInputController::DoSetAutomaticGainControl(true)
116 // AudioInputStream::SetAutomaticGainControl(true)
118 // AGC is now enabled in the media layer and streaming starts (details omitted).
119 // The figure below illustrates the AGC scheme which is active in combination
120 // with the default media flow explained earlier.
124 // AudioInputStream::(Capture thread loop)
125 // AgcAudioStream<AudioInputStream>::GetAgcVolume() => get latest mic volume
126 // AudioInputData::OnData(..., volume)
127 // AudioInputController::OnData(..., volume)
128 // AudioInputSyncWriter::Write(..., volume)
130 // [volume | size | data] is sent to the renderer [shared memory]
134 // AudioInputDevice::AudioThreadCallback::Process()
135 // WebRtcAudioDeviceImpl::Capture(..., volume)
136 // AudioTransport::RecordedDataIsAvailable(...,volume, new_volume)
138 // The AGC now uses the current volume input and computes a suitable new
139 // level given by the |new_level| output. This value is only non-zero if the
140 // AGC has take a decision that the microphone level should change.
142 // if (new_volume != 0)
143 // AudioInputDevice::SetVolume(new_volume)
144 // AudioInputHostMsg_SetVolume(new_volume) [IPC]
146 // [IPC to the browser]
148 // AudioInputRendererHost::OnSetVolume()
149 // AudioInputController::SetVolume()
150 // AudioInputStream::SetVolume(scaled_volume)
152 // Here we set the new microphone level in the media layer and at the same time
153 // read the new setting (we might not get exactly what is set).
155 // AudioInputData::OnData(..., updated_volume)
156 // AudioInputController::OnData(..., updated_volume)
159 // This process repeats until we stop capturing data. Note that, a common
160 // steady state is that the volume control reaches its max and the new_volume
161 // value from the AGC is zero. A loud voice input is required to break this
162 // state and start lowering the level again.
164 // Implementation notes:
166 // - This class must be created and destroyed on the main render thread and
167 // most methods are called on the same thread. However, some methods are
168 // also called on a Libjingle worker thread. RenderData is called on the
169 // AudioOutputDevice thread and CaptureData on the AudioInputDevice thread.
170 // To summarize: this class lives on four different threads.
171 // - The webrtc::AudioDeviceModule is reference counted.
172 // - AGC is only supported in combination with the WASAPI-based audio layer
173 // on Windows, i.e., it is not supported on Windows XP.
174 // - All volume levels required for the AGC scheme are transfered in a
175 // normalized range [0.0, 1.0]. Scaling takes place in both endpoints
176 // (WebRTC client a media layer). This approach ensures that we can avoid
177 // transferring maximum levels between the renderer and the browser.
182 class WebRtcAudioCapturer
;
183 class WebRtcAudioRenderer
;
185 // TODO(xians): Move the following two interfaces to webrtc so that
186 // libjingle can own references to the renderer and capturer.
187 class WebRtcAudioRendererSource
{
189 // Callback to get the rendered data.
190 virtual void RenderData(media::AudioBus
* audio_bus
,
192 int audio_delay_milliseconds
,
193 base::TimeDelta
* current_time
) = 0;
195 // Callback to notify the client that the renderer is going away.
196 virtual void RemoveAudioRenderer(WebRtcAudioRenderer
* renderer
) = 0;
199 virtual ~WebRtcAudioRendererSource() {}
202 // TODO(xians): Merge this interface with WebRtcAudioRendererSource.
203 // The reason why we could not do it today is that WebRtcAudioRendererSource
204 // gets the data by pulling, while the data is pushed into
205 // WebRtcPlayoutDataSource::Sink.
206 class WebRtcPlayoutDataSource
{
210 // Callback to get the playout data.
211 // Called on the render audio thread.
212 virtual void OnPlayoutData(media::AudioBus
* audio_bus
,
214 int audio_delay_milliseconds
) = 0;
216 // Callback to notify the sink that the source has changed.
217 // Called on the main render thread.
218 virtual void OnPlayoutDataSourceChanged() = 0;
224 // Adds/Removes the sink of WebRtcAudioRendererSource to the ADM.
225 // These methods are used by the MediaStreamAudioProcesssor to get the
226 // rendered data for AEC.
227 virtual void AddPlayoutSink(Sink
* sink
) = 0;
228 virtual void RemovePlayoutSink(Sink
* sink
) = 0;
231 virtual ~WebRtcPlayoutDataSource() {}
234 // Note that this class inherits from webrtc::AudioDeviceModule but due to
235 // the high number of non-implemented methods, we move the cruft over to the
236 // WebRtcAudioDeviceNotImpl.
237 class CONTENT_EXPORT WebRtcAudioDeviceImpl
238 : NON_EXPORTED_BASE(public WebRtcAudioDeviceNotImpl
),
239 NON_EXPORTED_BASE(public WebRtcAudioRendererSource
),
240 NON_EXPORTED_BASE(public WebRtcPlayoutDataSource
) {
242 // The maximum volume value WebRtc uses.
243 static const int kMaxVolumeLevel
= 255;
245 // Instances of this object are created on the main render thread.
246 WebRtcAudioDeviceImpl();
248 // webrtc::RefCountedModule implementation.
249 // The creator must call AddRef() after construction and use Release()
250 // to release the reference and delete this object.
251 // Called on the main render thread.
252 int32_t AddRef() override
;
253 int32_t Release() override
;
256 // webrtc::AudioDeviceModule implementation.
257 // All implemented methods are called on the main render thread unless
258 // anything else is stated.
260 int32_t RegisterAudioCallback(
261 webrtc::AudioTransport
* audio_callback
) override
;
263 int32_t Init() override
;
264 int32_t Terminate() override
;
265 bool Initialized() const override
;
267 int32_t PlayoutIsAvailable(bool* available
) override
;
268 bool PlayoutIsInitialized() const override
;
269 int32_t RecordingIsAvailable(bool* available
) override
;
270 bool RecordingIsInitialized() const override
;
272 // All Start/Stop methods are called on a libJingle worker thread.
273 int32_t StartPlayout() override
;
274 int32_t StopPlayout() override
;
275 bool Playing() const override
;
276 int32_t StartRecording() override
;
277 int32_t StopRecording() override
;
278 bool Recording() const override
;
280 // Called on the AudioInputDevice worker thread.
281 int32_t SetMicrophoneVolume(uint32_t volume
) override
;
283 // TODO(henrika): sort out calling thread once we start using this API.
284 int32_t MicrophoneVolume(uint32_t* volume
) const override
;
286 int32_t MaxMicrophoneVolume(uint32_t* max_volume
) const override
;
287 int32_t MinMicrophoneVolume(uint32_t* min_volume
) const override
;
288 int32_t StereoPlayoutIsAvailable(bool* available
) const override
;
289 int32_t StereoRecordingIsAvailable(bool* available
) const override
;
290 int32_t PlayoutDelay(uint16_t* delay_ms
) const override
;
291 int32_t RecordingDelay(uint16_t* delay_ms
) const override
;
292 int32_t RecordingSampleRate(uint32_t* sample_rate
) const override
;
293 int32_t PlayoutSampleRate(uint32_t* sample_rate
) const override
;
296 // Sets the |renderer_|, returns false if |renderer_| already exists.
297 // Called on the main renderer thread.
298 bool SetAudioRenderer(WebRtcAudioRenderer
* renderer
);
300 // Adds/Removes the capturer to the ADM.
301 // TODO(xians): Remove these two methods once the ADM does not need to pass
302 // hardware information up to WebRtc.
303 void AddAudioCapturer(const scoped_refptr
<WebRtcAudioCapturer
>& capturer
);
304 void RemoveAudioCapturer(const scoped_refptr
<WebRtcAudioCapturer
>& capturer
);
306 // Gets the default capturer, which is the last capturer in |capturers_|.
307 // The method can be called by both Libjingle thread and main render thread.
308 scoped_refptr
<WebRtcAudioCapturer
> GetDefaultCapturer() const;
310 // Gets paired device information of the capture device for the audio
311 // renderer. This is used to pass on a session id, sample rate and buffer
312 // size to a webrtc audio renderer (either local or remote), so that audio
313 // will be rendered to a matching output device.
314 // Returns true if the capture device has a paired output device, otherwise
315 // false. Note that if there are more than one open capture device the
316 // function will not be able to pick an appropriate device and return false.
317 bool GetAuthorizedDeviceInfoForAudioRenderer(
318 int* session_id
, int* output_sample_rate
, int* output_buffer_size
);
320 const scoped_refptr
<WebRtcAudioRenderer
>& renderer() const {
325 typedef std::list
<scoped_refptr
<WebRtcAudioCapturer
> > CapturerList
;
326 typedef std::list
<WebRtcPlayoutDataSource::Sink
*> PlayoutDataSinkList
;
329 // Make destructor private to ensure that we can only be deleted by Release().
330 ~WebRtcAudioDeviceImpl() override
;
332 // WebRtcAudioRendererSource implementation.
334 // Called on the AudioOutputDevice worker thread.
335 void RenderData(media::AudioBus
* audio_bus
,
337 int audio_delay_milliseconds
,
338 base::TimeDelta
* current_time
) override
;
340 // Called on the main render thread.
341 void RemoveAudioRenderer(WebRtcAudioRenderer
* renderer
) override
;
343 // WebRtcPlayoutDataSource implementation.
344 void AddPlayoutSink(WebRtcPlayoutDataSource::Sink
* sink
) override
;
345 void RemovePlayoutSink(WebRtcPlayoutDataSource::Sink
* sink
) override
;
347 // Used to check methods that run on the main render thread.
348 base::ThreadChecker main_thread_checker_
;
349 // Used to check methods that are called on libjingle's signaling thread.
350 base::ThreadChecker signaling_thread_checker_
;
351 base::ThreadChecker worker_thread_checker_
;
355 // List of captures which provides access to the native audio input layer
356 // in the browser process.
357 CapturerList capturers_
;
359 // Provides access to the audio renderer in the browser process.
360 scoped_refptr
<WebRtcAudioRenderer
> renderer_
;
362 // A list of raw pointer of WebRtcPlayoutDataSource::Sink objects which want
363 // to get the playout data, the sink need to call RemovePlayoutSink()
364 // before it goes away.
365 PlayoutDataSinkList playout_sinks_
;
367 // Weak reference to the audio callback.
368 // The webrtc client defines |audio_transport_callback_| by calling
369 // RegisterAudioCallback().
370 webrtc::AudioTransport
* audio_transport_callback_
;
372 // Cached value of the current audio delay on the input/capture side.
375 // Cached value of the current audio delay on the output/renderer side.
376 int output_delay_ms_
;
378 // Protects |recording_|, |output_delay_ms_|, |input_delay_ms_|, |renderer_|
379 // |recording_| and |microphone_volume_|.
380 mutable base::Lock lock_
;
382 // Used to protect the racing of calling OnData() since there can be more
383 // than one input stream calling OnData().
384 mutable base::Lock capture_callback_lock_
;
390 // Stores latest microphone volume received in a CaptureData() callback.
391 // Range is [0, 255].
392 uint32_t microphone_volume_
;
394 // Buffer used for temporary storage during render callback.
395 // It is only accessed by the audio render thread.
396 std::vector
<int16
> render_buffer_
;
398 DISALLOW_COPY_AND_ASSIGN(WebRtcAudioDeviceImpl
);
401 } // namespace content
403 #endif // CONTENT_RENDERER_MEDIA_WEBRTC_AUDIO_DEVICE_IMPL_H_