Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / renderer / media / webrtc_local_audio_renderer.cc
blob727ed361d123719c421dd7d8f958dedb335940ac
1 // Copyright (c) 2012 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 #include "content/renderer/media/webrtc_local_audio_renderer.h"
7 #include "base/logging.h"
8 #include "base/message_loop/message_loop_proxy.h"
9 #include "base/metrics/histogram.h"
10 #include "base/synchronization/lock.h"
11 #include "base/trace_event/trace_event.h"
12 #include "content/renderer/media/audio_device_factory.h"
13 #include "content/renderer/media/media_stream_dispatcher.h"
14 #include "content/renderer/media/webrtc_audio_capturer.h"
15 #include "content/renderer/media/webrtc_audio_renderer.h"
16 #include "content/renderer/render_frame_impl.h"
17 #include "media/audio/audio_output_device.h"
18 #include "media/base/audio_bus.h"
19 #include "media/base/audio_shifter.h"
21 namespace content {
23 namespace {
25 enum LocalRendererSinkStates {
26 kSinkStarted = 0,
27 kSinkNeverStarted,
28 kSinkStatesMax // Must always be last!
31 } // namespace
33 // media::AudioRendererSink::RenderCallback implementation
34 int WebRtcLocalAudioRenderer::Render(
35 media::AudioBus* audio_bus, int audio_delay_milliseconds) {
36 TRACE_EVENT0("audio", "WebRtcLocalAudioRenderer::Render");
37 base::AutoLock auto_lock(thread_lock_);
39 if (!playing_ || !volume_ || !audio_shifter_) {
40 audio_bus->Zero();
41 return 0;
44 audio_shifter_->Pull(
45 audio_bus,
46 base::TimeTicks::Now() -
47 base::TimeDelta::FromMilliseconds(audio_delay_milliseconds));
49 return audio_bus->frames();
52 void WebRtcLocalAudioRenderer::OnRenderError() {
53 NOTIMPLEMENTED();
56 // content::MediaStreamAudioSink implementation
57 void WebRtcLocalAudioRenderer::OnData(const media::AudioBus& audio_bus,
58 base::TimeTicks estimated_capture_time) {
59 DCHECK(capture_thread_checker_.CalledOnValidThread());
60 DCHECK(!estimated_capture_time.is_null());
62 TRACE_EVENT0("audio", "WebRtcLocalAudioRenderer::CaptureData");
64 base::AutoLock auto_lock(thread_lock_);
65 if (!playing_ || !volume_ || !audio_shifter_)
66 return;
68 scoped_ptr<media::AudioBus> audio_data(
69 media::AudioBus::Create(audio_bus.channels(), audio_bus.frames()));
70 audio_bus.CopyTo(audio_data.get());
71 audio_shifter_->Push(audio_data.Pass(), estimated_capture_time);
72 const base::TimeTicks now = base::TimeTicks::Now();
73 total_render_time_ += now - last_render_time_;
74 last_render_time_ = now;
77 void WebRtcLocalAudioRenderer::OnSetFormat(
78 const media::AudioParameters& params) {
79 DVLOG(1) << "WebRtcLocalAudioRenderer::OnSetFormat()";
80 // If the source is restarted, we might have changed to another capture
81 // thread.
82 capture_thread_checker_.DetachFromThread();
83 DCHECK(capture_thread_checker_.CalledOnValidThread());
85 // Post a task on the main render thread to reconfigure the |sink_| with the
86 // new format.
87 message_loop_->PostTask(
88 FROM_HERE,
89 base::Bind(&WebRtcLocalAudioRenderer::ReconfigureSink, this,
90 params));
93 // WebRtcLocalAudioRenderer::WebRtcLocalAudioRenderer implementation.
94 WebRtcLocalAudioRenderer::WebRtcLocalAudioRenderer(
95 const blink::WebMediaStreamTrack& audio_track,
96 int source_render_frame_id,
97 int session_id,
98 int frames_per_buffer)
99 : audio_track_(audio_track),
100 source_render_frame_id_(source_render_frame_id),
101 session_id_(session_id),
102 message_loop_(base::MessageLoopProxy::current()),
103 playing_(false),
104 frames_per_buffer_(frames_per_buffer),
105 volume_(0.0),
106 sink_started_(false) {
107 DVLOG(1) << "WebRtcLocalAudioRenderer::WebRtcLocalAudioRenderer()";
110 WebRtcLocalAudioRenderer::~WebRtcLocalAudioRenderer() {
111 DCHECK(message_loop_->BelongsToCurrentThread());
112 DCHECK(!sink_.get());
113 DVLOG(1) << "WebRtcLocalAudioRenderer::~WebRtcLocalAudioRenderer()";
116 void WebRtcLocalAudioRenderer::Start() {
117 DVLOG(1) << "WebRtcLocalAudioRenderer::Start()";
118 DCHECK(message_loop_->BelongsToCurrentThread());
120 // We get audio data from |audio_track_|...
121 MediaStreamAudioSink::AddToAudioTrack(this, audio_track_);
122 // ...and |sink_| will get audio data from us.
123 DCHECK(!sink_.get());
124 sink_ = AudioDeviceFactory::NewOutputDevice(source_render_frame_id_);
126 base::AutoLock auto_lock(thread_lock_);
127 last_render_time_ = base::TimeTicks::Now();
128 playing_ = false;
131 void WebRtcLocalAudioRenderer::Stop() {
132 DVLOG(1) << "WebRtcLocalAudioRenderer::Stop()";
133 DCHECK(message_loop_->BelongsToCurrentThread());
136 base::AutoLock auto_lock(thread_lock_);
137 playing_ = false;
138 audio_shifter_.reset();
141 // Stop the output audio stream, i.e, stop asking for data to render.
142 // It is safer to call Stop() on the |sink_| to clean up the resources even
143 // when the |sink_| is never started.
144 if (sink_.get()) {
145 sink_->Stop();
146 sink_ = NULL;
149 if (!sink_started_) {
150 UMA_HISTOGRAM_ENUMERATION("Media.LocalRendererSinkStates",
151 kSinkNeverStarted, kSinkStatesMax);
153 sink_started_ = false;
155 // Ensure that the capturer stops feeding us with captured audio.
156 MediaStreamAudioSink::RemoveFromAudioTrack(this, audio_track_);
159 void WebRtcLocalAudioRenderer::Play() {
160 DVLOG(1) << "WebRtcLocalAudioRenderer::Play()";
161 DCHECK(message_loop_->BelongsToCurrentThread());
163 if (!sink_.get())
164 return;
167 base::AutoLock auto_lock(thread_lock_);
168 // Resumes rendering by ensuring that WebRtcLocalAudioRenderer::Render()
169 // now reads data from the local FIFO.
170 playing_ = true;
171 last_render_time_ = base::TimeTicks::Now();
174 // Note: If volume_ is currently muted, the |sink_| will not be started yet.
175 MaybeStartSink();
178 void WebRtcLocalAudioRenderer::Pause() {
179 DVLOG(1) << "WebRtcLocalAudioRenderer::Pause()";
180 DCHECK(message_loop_->BelongsToCurrentThread());
182 if (!sink_.get())
183 return;
185 base::AutoLock auto_lock(thread_lock_);
186 // Temporarily suspends rendering audio.
187 // WebRtcLocalAudioRenderer::Render() will return early during this state
188 // and only zeros will be provided to the active sink.
189 playing_ = false;
192 void WebRtcLocalAudioRenderer::SetVolume(float volume) {
193 DVLOG(1) << "WebRtcLocalAudioRenderer::SetVolume(" << volume << ")";
194 DCHECK(message_loop_->BelongsToCurrentThread());
197 base::AutoLock auto_lock(thread_lock_);
198 // Cache the volume.
199 volume_ = volume;
202 // Lazily start the |sink_| when the local renderer is unmuted during
203 // playing.
204 MaybeStartSink();
206 if (sink_.get())
207 sink_->SetVolume(volume);
210 base::TimeDelta WebRtcLocalAudioRenderer::GetCurrentRenderTime() const {
211 DCHECK(message_loop_->BelongsToCurrentThread());
212 base::AutoLock auto_lock(thread_lock_);
213 if (!sink_.get())
214 return base::TimeDelta();
215 return total_render_time();
218 bool WebRtcLocalAudioRenderer::IsLocalRenderer() const {
219 return true;
222 void WebRtcLocalAudioRenderer::MaybeStartSink() {
223 DCHECK(message_loop_->BelongsToCurrentThread());
224 DVLOG(1) << "WebRtcLocalAudioRenderer::MaybeStartSink()";
226 if (!sink_.get() || !source_params_.IsValid())
227 return;
230 // Clear up the old data in the FIFO.
231 base::AutoLock auto_lock(thread_lock_);
232 audio_shifter_->Flush();
235 if (!sink_params_.IsValid() || !playing_ || !volume_ || sink_started_)
236 return;
238 DVLOG(1) << "WebRtcLocalAudioRenderer::MaybeStartSink() -- Starting sink_.";
239 sink_->InitializeWithSessionId(sink_params_, this, session_id_);
240 sink_->Start();
241 sink_started_ = true;
242 UMA_HISTOGRAM_ENUMERATION("Media.LocalRendererSinkStates",
243 kSinkStarted, kSinkStatesMax);
246 void WebRtcLocalAudioRenderer::ReconfigureSink(
247 const media::AudioParameters& params) {
248 DCHECK(message_loop_->BelongsToCurrentThread());
250 DVLOG(1) << "WebRtcLocalAudioRenderer::ReconfigureSink()";
252 int implicit_ducking_effect = 0;
253 RenderFrameImpl* const frame =
254 RenderFrameImpl::FromRoutingID(source_render_frame_id_);
255 MediaStreamDispatcher* const dispatcher = frame ?
256 frame->GetMediaStreamDispatcher() : NULL;
257 if (dispatcher && dispatcher->IsAudioDuckingActive()) {
258 DVLOG(1) << "Forcing DUCKING to be ON for output";
259 implicit_ducking_effect = media::AudioParameters::DUCKING;
260 } else {
261 DVLOG(1) << "DUCKING not forced ON for output";
264 if (source_params_.Equals(params))
265 return;
267 // Reset the |source_params_|, |sink_params_| and |loopback_fifo_| to match
268 // the new format.
270 source_params_ = params;
272 sink_params_ = media::AudioParameters(source_params_.format(),
273 source_params_.channel_layout(), source_params_.sample_rate(),
274 source_params_.bits_per_sample(),
275 WebRtcAudioRenderer::GetOptimalBufferSize(source_params_.sample_rate(),
276 frames_per_buffer_),
277 // If DUCKING is enabled on the source, it needs to be enabled on the
278 // sink as well.
279 source_params_.effects() | implicit_ducking_effect);
282 // Note: The max buffer is fairly large, but will rarely be used.
283 // Cast needs the buffer to hold at least one second of audio.
284 // The clock accuracy is set to 20ms because clock accuracy is
285 // ~15ms on windows.
286 media::AudioShifter* const new_shifter = new media::AudioShifter(
287 base::TimeDelta::FromSeconds(2),
288 base::TimeDelta::FromMilliseconds(20),
289 base::TimeDelta::FromSeconds(20),
290 source_params_.sample_rate(),
291 params.channels());
293 base::AutoLock auto_lock(thread_lock_);
294 audio_shifter_.reset(new_shifter);
297 if (!sink_.get())
298 return; // WebRtcLocalAudioRenderer has not yet been started.
300 // Stop |sink_| and re-create a new one to be initialized with different audio
301 // parameters. Then, invoke MaybeStartSink() to restart everything again.
302 if (sink_started_) {
303 sink_->Stop();
304 sink_started_ = false;
307 sink_ = AudioDeviceFactory::NewOutputDevice(source_render_frame_id_);
308 MaybeStartSink();
311 } // namespace content