Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(157)

Side by Side Diff: content/browser/renderer_host/media/audio_renderer_host.cc

Issue 2443573003: Factor out AudioOutputDelegate from AudioRendererHost. (Closed)
Patch Set: Simplify. Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/renderer_host/media/audio_renderer_host.h" 5 #include "content/browser/renderer_host/media/audio_renderer_host.h"
6 6
7 #include <stdint.h> 7 #include <stdint.h>
8 #include <utility> 8 #include <utility>
9 9
10 #include "base/bind.h" 10 #include "base/bind.h"
11 #include "base/bind_helpers.h" 11 #include "base/bind_helpers.h"
12 #include "base/lazy_instance.h" 12 #include "base/lazy_instance.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/metrics/histogram_macros.h" 13 #include "base/metrics/histogram_macros.h"
16 #include "base/process/process.h" 14 #include "base/process/process.h"
17 #include "content/browser/bad_message.h" 15 #include "content/browser/bad_message.h"
18 #include "content/browser/browser_main_loop.h" 16 #include "content/browser/browser_main_loop.h"
19 #include "content/browser/media/audio_stream_monitor.h" 17 #include "content/browser/media/audio_stream_monitor.h"
20 #include "content/browser/media/capture/audio_mirroring_manager.h" 18 #include "content/browser/media/capture/audio_mirroring_manager.h"
21 #include "content/browser/media/media_internals.h" 19 #include "content/browser/media/media_internals.h"
22 #include "content/browser/renderer_host/media/audio_input_device_manager.h" 20 #include "content/browser/renderer_host/media/audio_input_device_manager.h"
23 #include "content/browser/renderer_host/media/audio_sync_reader.h" 21 #include "content/browser/renderer_host/media/audio_sync_reader.h"
24 #include "content/browser/renderer_host/media/media_stream_manager.h" 22 #include "content/browser/renderer_host/media/media_stream_manager.h"
(...skipping 87 matching lines...) Expand 10 before | Expand all | Expand 10 after
112 const base::Callback<void(bool)>& callback) { 110 const base::Callback<void(bool)>& callback) {
113 DCHECK_CURRENTLY_ON(BrowserThread::UI); 111 DCHECK_CURRENTLY_ON(BrowserThread::UI);
114 const bool frame_exists = 112 const bool frame_exists =
115 !!RenderFrameHost::FromID(render_process_id, render_frame_id); 113 !!RenderFrameHost::FromID(render_process_id, render_frame_id);
116 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, 114 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
117 base::Bind(callback, frame_exists)); 115 base::Bind(callback, frame_exists));
118 } 116 }
119 117
120 } // namespace 118 } // namespace
121 119
122 class AudioRendererHost::AudioEntry
123 : public media::AudioOutputController::EventHandler {
124 public:
125 ~AudioEntry() override;
126
127 // Returns nullptr on failure.
128 static std::unique_ptr<AudioRendererHost::AudioEntry> Create(
129 AudioRendererHost* host,
130 int stream_id,
131 int render_frame_id,
132 const media::AudioParameters& params,
133 const std::string& output_device_id);
134
135 int stream_id() const {
136 return stream_id_;
137 }
138
139 int render_frame_id() const { return render_frame_id_; }
140
141 media::AudioOutputController* controller() const { return controller_.get(); }
142
143 AudioSyncReader* reader() const { return reader_.get(); }
144
145 // Used by ARH to track the number of active streams for UMA stats.
146 bool playing() const { return playing_; }
147 void set_playing(bool playing) { playing_ = playing; }
148
149 private:
150 AudioEntry(AudioRendererHost* host,
151 int stream_id,
152 int render_frame_id,
153 const media::AudioParameters& params,
154 const std::string& output_device_id,
155 std::unique_ptr<AudioSyncReader> reader);
156
157 // media::AudioOutputController::EventHandler implementation.
158 void OnCreated() override;
159 void OnPlaying() override;
160 void OnPaused() override;
161 void OnError() override;
162
163 AudioRendererHost* const host_;
164 const int stream_id_;
165
166 // The routing ID of the source RenderFrame.
167 const int render_frame_id_;
168
169 // The synchronous reader to be used by |controller_|.
170 const std::unique_ptr<AudioSyncReader> reader_;
171
172 // The AudioOutputController that manages the audio stream.
173 const scoped_refptr<media::AudioOutputController> controller_;
174
175 bool playing_;
176
177 DISALLOW_COPY_AND_ASSIGN(AudioEntry);
178 };
179
180 AudioRendererHost::AudioEntry::AudioEntry(
181 AudioRendererHost* host,
182 int stream_id,
183 int render_frame_id,
184 const media::AudioParameters& params,
185 const std::string& output_device_id,
186 std::unique_ptr<AudioSyncReader> reader)
187 : host_(host),
188 stream_id_(stream_id),
189 render_frame_id_(render_frame_id),
190 reader_(std::move(reader)),
191 controller_(media::AudioOutputController::Create(host->audio_manager_,
192 this,
193 params,
194 output_device_id,
195 reader_.get())),
196 playing_(false) {
197 DCHECK(controller_);
198 }
199
200 AudioRendererHost::AudioEntry::~AudioEntry() {}
201
202 // static
203 std::unique_ptr<AudioRendererHost::AudioEntry>
204 AudioRendererHost::AudioEntry::Create(AudioRendererHost* host,
205 int stream_id,
206 int render_frame_id,
207 const media::AudioParameters& params,
208 const std::string& output_device_id) {
209 std::unique_ptr<AudioSyncReader> reader(AudioSyncReader::Create(params));
210 if (!reader) {
211 return nullptr;
212 }
213 return base::WrapUnique(new AudioEntry(host, stream_id, render_frame_id,
214 params, output_device_id,
215 std::move(reader)));
216 }
217
218 /////////////////////////////////////////////////////////////////////////////// 120 ///////////////////////////////////////////////////////////////////////////////
219 // AudioRendererHost implementations. 121 // AudioRendererHost implementations.
220 122
221 AudioRendererHost::AudioRendererHost(int render_process_id, 123 AudioRendererHost::AudioRendererHost(int render_process_id,
222 media::AudioManager* audio_manager, 124 media::AudioManager* audio_manager,
223 AudioMirroringManager* mirroring_manager, 125 AudioMirroringManager* mirroring_manager,
224 MediaInternals* media_internals, 126 MediaInternals* media_internals,
225 MediaStreamManager* media_stream_manager, 127 MediaStreamManager* media_stream_manager,
226 const std::string& salt) 128 const std::string& salt)
227 : BrowserMessageFilter(AudioMsgStart), 129 : BrowserMessageFilter(AudioMsgStart),
228 render_process_id_(render_process_id), 130 render_process_id_(render_process_id),
229 audio_manager_(audio_manager), 131 audio_manager_(audio_manager),
230 mirroring_manager_(mirroring_manager), 132 mirroring_manager_(mirroring_manager),
231 audio_log_(media_internals->CreateAudioLog( 133 audio_log_(media_internals->CreateAudioLog(
232 media::AudioLogFactory::AUDIO_OUTPUT_CONTROLLER)), 134 media::AudioLogFactory::AUDIO_OUTPUT_CONTROLLER)),
233 media_stream_manager_(media_stream_manager), 135 media_stream_manager_(media_stream_manager),
234 num_playing_streams_(0), 136 num_playing_streams_(0),
235 salt_(salt), 137 salt_(salt),
236 validate_render_frame_id_function_(&ValidateRenderFrameId), 138 validate_render_frame_id_function_(&ValidateRenderFrameId),
237 max_simultaneous_streams_(0) { 139 max_simultaneous_streams_(0) {
238 DCHECK(audio_manager_); 140 DCHECK(audio_manager_);
239 DCHECK(media_stream_manager_); 141 DCHECK(media_stream_manager_);
240 } 142 }
241 143
242 AudioRendererHost::~AudioRendererHost() { 144 AudioRendererHost::~AudioRendererHost() {
243 DCHECK_CURRENTLY_ON(BrowserThread::IO); 145 DCHECK_CURRENTLY_ON(BrowserThread::IO);
244 CHECK(audio_entries_.empty()); 146 CHECK(delegates_.empty());
245 147
246 // If we had any streams, report UMA stats for the maximum number of 148 // If we had any streams, report UMA stats for the maximum number of
247 // simultaneous streams for this render process and for the whole browser 149 // simultaneous streams for this render process and for the whole browser
248 // process since last reported. 150 // process since last reported.
249 if (max_simultaneous_streams_ > 0) { 151 if (max_simultaneous_streams_ > 0) {
250 UMA_HISTOGRAM_CUSTOM_COUNTS("Media.AudioRendererIpcStreams", 152 UMA_HISTOGRAM_CUSTOM_COUNTS("Media.AudioRendererIpcStreams",
251 max_simultaneous_streams_, 1, 50, 51); 153 max_simultaneous_streams_, 1, 50, 51);
252 UMA_HISTOGRAM_CUSTOM_COUNTS( 154 UMA_HISTOGRAM_CUSTOM_COUNTS(
253 "Media.AudioRendererIpcStreamsTotal", 155 "Media.AudioRendererIpcStreamsTotal",
254 g_audio_streams_tracker.Get().max_stream_count(), 156 g_audio_streams_tracker.Get().max_stream_count(),
255 1, 100, 101); 157 1, 100, 101);
256 g_audio_streams_tracker.Get().ResetMaxStreamCount(); 158 g_audio_streams_tracker.Get().ResetMaxStreamCount();
257 } 159 }
258 } 160 }
259 161
260 void AudioRendererHost::GetOutputControllers( 162 void AudioRendererHost::GetOutputControllers(
261 const RenderProcessHost::GetAudioOutputControllersCallback& 163 const RenderProcessHost::GetAudioOutputControllersCallback&
262 callback) const { 164 callback) const {
263 BrowserThread::PostTaskAndReplyWithResult( 165 BrowserThread::PostTaskAndReplyWithResult(
264 BrowserThread::IO, FROM_HERE, 166 BrowserThread::IO, FROM_HERE,
265 base::Bind(&AudioRendererHost::DoGetOutputControllers, this), callback); 167 base::Bind(&AudioRendererHost::DoGetOutputControllers, this), callback);
266 } 168 }
267 169
268 void AudioRendererHost::OnChannelClosing() { 170 void AudioRendererHost::OnChannelClosing() {
269 DCHECK_CURRENTLY_ON(BrowserThread::IO); 171 DCHECK_CURRENTLY_ON(BrowserThread::IO);
270 // Since the IPC sender is gone, close all requested audio streams. 172 // Since the IPC sender is gone, close all requested audio streams.
271 while (!audio_entries_.empty()) { 173 while (!delegates_.empty()) {
272 // Note: OnCloseStream() removes the entries from audio_entries_. 174 // Note: OnCloseStream() removes the delegates from delegates_.
273 OnCloseStream(audio_entries_.begin()->first); 175 OnCloseStream(delegates_[0]->stream_id());
274 } 176 }
275 177
276 // Remove any authorizations for streams that were not yet created 178 // Remove any authorizations for streams that were not yet created
277 authorizations_.clear(); 179 authorizations_.clear();
278 } 180 }
279 181
280 void AudioRendererHost::OnDestruct() const { 182 void AudioRendererHost::OnDestruct() const {
281 BrowserThread::DeleteOnIOThread::Destruct(this); 183 BrowserThread::DeleteOnIOThread::Destruct(this);
282 } 184 }
283 185
284 void AudioRendererHost::AudioEntry::OnCreated() { 186 void AudioRendererHost::OnStreamCreated(
285 BrowserThread::PostTask( 187 int stream_id,
286 BrowserThread::IO, 188 base::SharedMemory* shared_memory,
287 FROM_HERE, 189 base::CancelableSyncSocket* foreign_socket) {
288 base::Bind(&AudioRendererHost::DoCompleteCreation, host_, stream_id_));
289 }
290
291 void AudioRendererHost::AudioEntry::OnPlaying() {
292 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
293 base::Bind(&AudioRendererHost::StreamStateChanged,
294 host_, stream_id_, true));
295 }
296
297 void AudioRendererHost::AudioEntry::OnPaused() {
298 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
299 base::Bind(&AudioRendererHost::StreamStateChanged,
300 host_, stream_id_, false));
301 }
302
303 void AudioRendererHost::AudioEntry::OnError() {
304 BrowserThread::PostTask(
305 BrowserThread::IO,
306 FROM_HERE,
307 base::Bind(&AudioRendererHost::ReportErrorAndClose, host_, stream_id_));
308 }
309
310 void AudioRendererHost::DoCompleteCreation(int stream_id) {
311 DCHECK_CURRENTLY_ON(BrowserThread::IO); 190 DCHECK_CURRENTLY_ON(BrowserThread::IO);
312 191
313 if (!PeerHandle()) { 192 if (!PeerHandle()) {
314 DLOG(WARNING) << "Renderer process handle is invalid."; 193 DLOG(WARNING) << "Renderer process handle is invalid.";
315 ReportErrorAndClose(stream_id); 194 OnStreamError(stream_id);
316 return; 195 return;
317 } 196 }
318 197
319 AudioEntry* const entry = LookupById(stream_id);
320 if (!entry) {
321 ReportErrorAndClose(stream_id);
322 return;
323 }
324
325 // Now construction is done and we are ready to send the shared memory and the
326 // sync socket to the renderer.
327 base::SharedMemory* shared_memory = entry->reader()->shared_memory();
328 base::CancelableSyncSocket* foreign_socket =
329 entry->reader()->foreign_socket();
330
331 base::SharedMemoryHandle foreign_memory_handle; 198 base::SharedMemoryHandle foreign_memory_handle;
332 base::SyncSocket::TransitDescriptor socket_descriptor; 199 base::SyncSocket::TransitDescriptor socket_descriptor;
333 size_t shared_memory_size = shared_memory->requested_size(); 200 size_t shared_memory_size = shared_memory->requested_size();
334 201
335 if (!(shared_memory->ShareToProcess(PeerHandle(), &foreign_memory_handle) && 202 if (!(shared_memory->ShareToProcess(PeerHandle(), &foreign_memory_handle) &&
336 foreign_socket->PrepareTransitDescriptor(PeerHandle(), 203 foreign_socket->PrepareTransitDescriptor(PeerHandle(),
337 &socket_descriptor))) { 204 &socket_descriptor))) {
338 // Something went wrong in preparing the IPC handles. 205 // Something went wrong in preparing the IPC handles.
339 ReportErrorAndClose(entry->stream_id()); 206 OnStreamError(stream_id);
340 return; 207 return;
341 } 208 }
342 209
343 Send(new AudioMsg_NotifyStreamCreated( 210 Send(new AudioMsg_NotifyStreamCreated(
344 stream_id, foreign_memory_handle, socket_descriptor, 211 stream_id, foreign_memory_handle, socket_descriptor,
345 base::checked_cast<uint32_t>(shared_memory_size))); 212 base::checked_cast<uint32_t>(shared_memory_size)));
346 } 213 }
347 214
215 void AudioRendererHost::OnStreamStateChanged(bool is_playing) {
216 DCHECK_CURRENTLY_ON(BrowserThread::IO);
217 if (is_playing) {
218 base::AtomicRefCountInc(&num_playing_streams_);
219
220 // Inform the RenderProcessHost when audio starts playing for the first
221 // time.
222 if (base::AtomicRefCountIsOne(&num_playing_streams_)) {
223 BrowserThread::PostTask(
224 BrowserThread::UI, FROM_HERE,
225 base::Bind(&NotifyRenderProcessHostThatAudioStateChanged,
226 render_process_id_));
227 }
228 } else {
229 // Inform the RenderProcessHost when there is no more audio playing.
230 if (!base::AtomicRefCountDec(&num_playing_streams_)) {
231 BrowserThread::PostTask(
232 BrowserThread::UI, FROM_HERE,
233 base::Bind(&NotifyRenderProcessHostThatAudioStateChanged,
234 render_process_id_));
235 }
236 }
237 }
238
239 void AudioRendererHost::OnStreamError(int stream_id) {
240 DCHECK_CURRENTLY_ON(BrowserThread::IO);
241
242 // Make sure this isn't a stray callback executing after the stream has been
243 // closed, so error notifications aren't sent after clients believe the stream
244 // is closed.
245 if (!LookupById(stream_id))
246 return;
247
248 SendErrorMessage(stream_id);
249
250 OnCloseStream(stream_id);
251 }
252
348 void AudioRendererHost::DidValidateRenderFrame(int stream_id, bool is_valid) { 253 void AudioRendererHost::DidValidateRenderFrame(int stream_id, bool is_valid) {
349 DCHECK_CURRENTLY_ON(BrowserThread::IO); 254 DCHECK_CURRENTLY_ON(BrowserThread::IO);
350 255
351 if (!is_valid) { 256 if (!is_valid) {
352 DLOG(WARNING) << "Render frame for stream (id=" << stream_id 257 DLOG(WARNING) << "Render frame for stream (id=" << stream_id
353 << ") no longer exists."; 258 << ") no longer exists.";
354 ReportErrorAndClose(stream_id); 259 OnStreamError(stream_id);
355 } 260 }
356 } 261 }
357 262
358 void AudioRendererHost::StreamStateChanged(int stream_id, bool is_playing) {
359 DCHECK_CURRENTLY_ON(BrowserThread::IO);
360
361 AudioEntry* const entry = LookupById(stream_id);
362 if (!entry)
363 return;
364
365 if (is_playing) {
366 AudioStreamMonitor::StartMonitoringStream(
367 render_process_id_,
368 entry->render_frame_id(),
369 entry->stream_id(),
370 base::Bind(&media::AudioOutputController::ReadCurrentPowerAndClip,
371 entry->controller()));
372 } else {
373 AudioStreamMonitor::StopMonitoringStream(
374 render_process_id_, entry->render_frame_id(), entry->stream_id());
375 }
376 UpdateNumPlayingStreams(entry, is_playing);
377 }
378
379 RenderProcessHost::AudioOutputControllerList 263 RenderProcessHost::AudioOutputControllerList
380 AudioRendererHost::DoGetOutputControllers() const { 264 AudioRendererHost::DoGetOutputControllers() const {
381 DCHECK_CURRENTLY_ON(BrowserThread::IO); 265 DCHECK_CURRENTLY_ON(BrowserThread::IO);
382 266
383 RenderProcessHost::AudioOutputControllerList controllers; 267 RenderProcessHost::AudioOutputControllerList controllers;
384 for (AudioEntryMap::const_iterator it = audio_entries_.begin(); 268 for (const auto& delegate : delegates_)
385 it != audio_entries_.end(); 269 controllers.push_back(delegate->controller());
386 ++it) {
387 controllers.push_back(it->second->controller());
388 }
389 270
390 return controllers; 271 return controllers;
391 } 272 }
392 273
393 /////////////////////////////////////////////////////////////////////////////// 274 ///////////////////////////////////////////////////////////////////////////////
394 // IPC Messages handler 275 // IPC Messages handler
395 bool AudioRendererHost::OnMessageReceived(const IPC::Message& message) { 276 bool AudioRendererHost::OnMessageReceived(const IPC::Message& message) {
396 bool handled = true; 277 bool handled = true;
397 IPC_BEGIN_MESSAGE_MAP(AudioRendererHost, message) 278 IPC_BEGIN_MESSAGE_MAP(AudioRendererHost, message)
398 IPC_MESSAGE_HANDLER(AudioHostMsg_RequestDeviceAuthorization, 279 IPC_MESSAGE_HANDLER(AudioHostMsg_RequestDeviceAuthorization,
(...skipping 28 matching lines...) Expand all
427 return; 308 return;
428 309
429 if (!IsValidDeviceId(device_id)) { 310 if (!IsValidDeviceId(device_id)) {
430 UMALogDeviceAuthorizationTime(auth_start_time); 311 UMALogDeviceAuthorizationTime(auth_start_time);
431 Send(new AudioMsg_NotifyDeviceAuthorized( 312 Send(new AudioMsg_NotifyDeviceAuthorized(
432 stream_id, media::OUTPUT_DEVICE_STATUS_ERROR_NOT_FOUND, 313 stream_id, media::OUTPUT_DEVICE_STATUS_ERROR_NOT_FOUND,
433 media::AudioParameters::UnavailableDeviceParams(), std::string())); 314 media::AudioParameters::UnavailableDeviceParams(), std::string()));
434 return; 315 return;
435 } 316 }
436 317
437 // If |session_id should be used for output device selection and such output 318 // If |session_id| should be used for output device selection and such output
438 // device is found, reuse the input device permissions. 319 // device is found, reuse the input device permissions.
439 if (media::AudioDeviceDescription::UseSessionIdToSelectDevice(session_id, 320 if (media::AudioDeviceDescription::UseSessionIdToSelectDevice(session_id,
440 device_id)) { 321 device_id)) {
441 const StreamDeviceInfo* info = 322 const StreamDeviceInfo* info =
442 media_stream_manager_->audio_input_device_manager() 323 media_stream_manager_->audio_input_device_manager()
443 ->GetOpenedDeviceInfoById(session_id); 324 ->GetOpenedDeviceInfoById(session_id);
444 if (info) { 325 if (info) {
445 media::AudioParameters output_params( 326 media::AudioParameters output_params(
446 media::AudioParameters::AUDIO_PCM_LOW_LATENCY, 327 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
447 static_cast<media::ChannelLayout>( 328 static_cast<media::ChannelLayout>(
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
486 // to create it now. 367 // to create it now.
487 content::bad_message::ReceivedBadMessage( 368 content::bad_message::ReceivedBadMessage(
488 this, bad_message::ARH_CREATED_STREAM_WITHOUT_AUTHORIZATION); 369 this, bad_message::ARH_CREATED_STREAM_WITHOUT_AUTHORIZATION);
489 return; 370 return;
490 } 371 }
491 device_unique_id.swap(auth_data->second.second); 372 device_unique_id.swap(auth_data->second.second);
492 authorizations_.erase(auth_data); 373 authorizations_.erase(auth_data);
493 } 374 }
494 375
495 // Fail early if either of two sanity-checks fail: 376 // Fail early if either of two sanity-checks fail:
496 // 1. There should not yet exist an AudioEntry for the given |stream_id| 377 // 1. There should not yet exist an AudioOutputDelegate for the given
497 // since the renderer may not create two streams with the same ID. 378 // |stream_id| since the renderer may not create two streams with the
379 // same ID.
498 // 2. An out-of-range render frame ID was provided. Renderers must *always* 380 // 2. An out-of-range render frame ID was provided. Renderers must *always*
499 // specify a valid render frame ID for each audio output they create, as 381 // specify a valid render frame ID for each audio output they create, as
500 // several browser-level features depend on this (e.g., OOM manager, UI 382 // several browser-level features depend on this (e.g., OOM manager, UI
501 // audio indicator, muting, audio capture). 383 // audio indicator, muting, audio capture).
502 // Note: media::AudioParameters is validated in the deserializer, so there is 384 // Note: media::AudioParameters is validated in the deserializer, so there is
503 // no need to check that here. 385 // no need to check that here.
504 if (LookupById(stream_id)) { 386 if (LookupById(stream_id)) {
505 SendErrorMessage(stream_id); 387 SendErrorMessage(stream_id);
506 return; 388 return;
507 } 389 }
508 if (render_frame_id <= 0) { 390 if (render_frame_id <= 0) {
509 SendErrorMessage(stream_id); 391 SendErrorMessage(stream_id);
510 return; 392 return;
511 } 393 }
512 394
513 // Post a task to the UI thread to check that the |render_frame_id| references 395 // Post a task to the UI thread to check that the |render_frame_id| references
514 // a valid render frame. This validation is important for all the reasons 396 // a valid render frame. This validation is important for all the reasons
515 // stated in the comments above. This does not block stream creation, but will 397 // stated in the comments above. This does not block stream creation, but will
516 // force-close the stream later if validation fails. 398 // force-close the stream later if validation fails.
517 BrowserThread::PostTask( 399 BrowserThread::PostTask(
518 BrowserThread::UI, FROM_HERE, 400 BrowserThread::UI, FROM_HERE,
519 base::Bind(validate_render_frame_id_function_, render_process_id_, 401 base::Bind(validate_render_frame_id_function_, render_process_id_,
520 render_frame_id, 402 render_frame_id,
521 base::Bind(&AudioRendererHost::DidValidateRenderFrame, this, 403 base::Bind(&AudioRendererHost::DidValidateRenderFrame, this,
522 stream_id))); 404 stream_id)));
523 405
524 std::unique_ptr<AudioEntry> entry = AudioEntry::Create(
525 this, stream_id, render_frame_id, params, device_unique_id);
526 if (!entry) {
527 SendErrorMessage(stream_id);
528 return;
529 }
530
531 MediaObserver* const media_observer = 406 MediaObserver* const media_observer =
532 GetContentClient()->browser()->GetMediaObserver(); 407 GetContentClient()->browser()->GetMediaObserver();
533 if (media_observer) 408 std::unique_ptr<AudioOutputDelegate> delegate(new AudioOutputDelegate(
534 media_observer->OnCreatingAudioStream(render_process_id_, render_frame_id); 409 this, audio_log_.get(), mirroring_manager_, media_observer, stream_id,
410 render_frame_id, render_process_id_, params, device_unique_id));
535 411
536 if (mirroring_manager_) { 412 delegates_.push_back(std::move(delegate));
537 mirroring_manager_->AddDiverter( 413
538 render_process_id_, entry->render_frame_id(), entry->controller());
539 }
540 audio_entries_.insert(std::make_pair(stream_id, entry.release()));
541 g_audio_streams_tracker.Get().IncreaseStreamCount(); 414 g_audio_streams_tracker.Get().IncreaseStreamCount();
542 415
543 audio_log_->OnCreated(stream_id, params, device_unique_id); 416 if (delegates_.size() > max_simultaneous_streams_)
544 MediaInternals::GetInstance()->SetWebContentsTitleForAudioLogEntry( 417 max_simultaneous_streams_ = delegates_.size();
545 stream_id, render_process_id_, render_frame_id, audio_log_.get());
546
547 if (audio_entries_.size() > max_simultaneous_streams_)
548 max_simultaneous_streams_ = audio_entries_.size();
549 } 418 }
550 419
551 void AudioRendererHost::OnPlayStream(int stream_id) { 420 void AudioRendererHost::OnPlayStream(int stream_id) {
552 DCHECK_CURRENTLY_ON(BrowserThread::IO); 421 DCHECK_CURRENTLY_ON(BrowserThread::IO);
553 422
554 AudioEntry* entry = LookupById(stream_id); 423 AudioOutputDelegate* delegate = LookupById(stream_id);
555 if (!entry) { 424 if (!delegate) {
556 SendErrorMessage(stream_id); 425 SendErrorMessage(stream_id);
557 return; 426 return;
558 } 427 }
559 428
560 entry->controller()->Play(); 429 delegate->OnPlayStream();
561 audio_log_->OnStarted(stream_id);
562 } 430 }
563 431
564 void AudioRendererHost::OnPauseStream(int stream_id) { 432 void AudioRendererHost::OnPauseStream(int stream_id) {
565 DCHECK_CURRENTLY_ON(BrowserThread::IO); 433 DCHECK_CURRENTLY_ON(BrowserThread::IO);
566 434
567 AudioEntry* entry = LookupById(stream_id); 435 AudioOutputDelegate* delegate = LookupById(stream_id);
568 if (!entry) { 436 if (!delegate) {
569 SendErrorMessage(stream_id); 437 SendErrorMessage(stream_id);
570 return; 438 return;
571 } 439 }
572 440
573 entry->controller()->Pause(); 441 delegate->OnPauseStream();
574 audio_log_->OnStopped(stream_id);
575 } 442 }
576 443
577 void AudioRendererHost::OnSetVolume(int stream_id, double volume) { 444 void AudioRendererHost::OnSetVolume(int stream_id, double volume) {
578 DCHECK_CURRENTLY_ON(BrowserThread::IO); 445 DCHECK_CURRENTLY_ON(BrowserThread::IO);
579 446
580 AudioEntry* entry = LookupById(stream_id); 447 AudioOutputDelegate* delegate = LookupById(stream_id);
581 if (!entry) { 448 if (!delegate) {
582 SendErrorMessage(stream_id); 449 SendErrorMessage(stream_id);
583 return; 450 return;
584 } 451 }
585 452
586 // Make sure the volume is valid. 453 // Make sure the volume is valid.
587 if (volume < 0 || volume > 1.0) 454 if (volume < 0 || volume > 1.0)
588 return; 455 return;
589 entry->controller()->SetVolume(volume); 456 delegate->OnSetVolume(volume);
590 audio_log_->OnSetVolume(stream_id, volume);
591 } 457 }
592 458
593 void AudioRendererHost::SendErrorMessage(int stream_id) { 459 void AudioRendererHost::SendErrorMessage(int stream_id) {
594 Send(new AudioMsg_NotifyStreamError(stream_id)); 460 Send(new AudioMsg_NotifyStreamError(stream_id));
595 } 461 }
596 462
597 void AudioRendererHost::OnCloseStream(int stream_id) { 463 void AudioRendererHost::OnCloseStream(int stream_id) {
598 DCHECK_CURRENTLY_ON(BrowserThread::IO); 464 DCHECK_CURRENTLY_ON(BrowserThread::IO);
599 authorizations_.erase(stream_id); 465 authorizations_.erase(stream_id);
600 466
601 // Prevent oustanding callbacks from attempting to close/delete the same 467 // Prevent oustanding callbacks from attempting to close/delete the same
602 // AudioEntry twice. 468 // AudioOutputDelegate twice.
603 AudioEntryMap::iterator i = audio_entries_.find(stream_id); 469 AudioOutputDelegateList::iterator i;
604 if (i == audio_entries_.end()) 470 for (i = delegates_.begin();
471 i != delegates_.end() && (*i)->stream_id() != stream_id; ++i) {
472 }
473 if (i == delegates_.end())
605 return; 474 return;
606 std::unique_ptr<AudioEntry> entry(i->second); 475
607 audio_entries_.erase(i); 476 std::unique_ptr<AudioOutputDelegate> delegate = std::move(*i);
477 *i = std::move(delegates_.back());
478 delegates_.pop_back();
479
480 delegate->OnCloseStream();
481
608 g_audio_streams_tracker.Get().DecreaseStreamCount(); 482 g_audio_streams_tracker.Get().DecreaseStreamCount();
609
610 media::AudioOutputController* const controller = entry->controller();
611 controller->Close(
612 base::Bind(&AudioRendererHost::DeleteEntry, this, base::Passed(&entry)));
613 audio_log_->OnClosed(stream_id);
614 } 483 }
615 484
616 void AudioRendererHost::DeleteEntry(std::unique_ptr<AudioEntry> entry) { 485 AudioOutputDelegate* AudioRendererHost::LookupById(int stream_id) {
617 DCHECK_CURRENTLY_ON(BrowserThread::IO); 486 DCHECK_CURRENTLY_ON(BrowserThread::IO);
618 487
619 // De-register the controller from the AudioMirroringManager now that the 488 AudioOutputDelegateList::iterator i;
620 // controller has closed the AudioOutputStream and shut itself down. This 489 for (i = delegates_.begin();
621 // ensures that calling RemoveDiverter() here won't trigger the controller to 490 i != delegates_.end() && (*i)->stream_id() != stream_id; ++i) {
o1ka 2016/10/25 12:32:34 (alternatively you can use std::find_if)
Max Morin 2016/10/26 09:20:17 Done.
622 // re-start the default AudioOutputStream and cause a brief audio blip to come
623 // out the user's speakers. http://crbug.com/474432
624 if (mirroring_manager_)
625 mirroring_manager_->RemoveDiverter(entry->controller());
626
627 AudioStreamMonitor::StopMonitoringStream(
628 render_process_id_, entry->render_frame_id(), entry->stream_id());
629 UpdateNumPlayingStreams(entry.get(), false);
630 }
631
632 void AudioRendererHost::ReportErrorAndClose(int stream_id) {
633 DCHECK_CURRENTLY_ON(BrowserThread::IO);
634
635 // Make sure this isn't a stray callback executing after the stream has been
636 // closed, so error notifications aren't sent after clients believe the stream
637 // is closed.
638 if (!LookupById(stream_id))
639 return;
640
641 SendErrorMessage(stream_id);
642
643 audio_log_->OnError(stream_id);
644 OnCloseStream(stream_id);
645 }
646
647 AudioRendererHost::AudioEntry* AudioRendererHost::LookupById(int stream_id) {
648 DCHECK_CURRENTLY_ON(BrowserThread::IO);
649
650 AudioEntryMap::const_iterator i = audio_entries_.find(stream_id);
651 return i != audio_entries_.end() ? i->second : NULL;
652 }
653
654 void AudioRendererHost::UpdateNumPlayingStreams(AudioEntry* entry,
655 bool is_playing) {
656 DCHECK_CURRENTLY_ON(BrowserThread::IO);
657 if (entry->playing() == is_playing)
658 return;
659
660 if (is_playing) {
661 entry->set_playing(true);
662 base::AtomicRefCountInc(&num_playing_streams_);
663
664 // Inform the RenderProcessHost when audio starts playing for the first
665 // time.
666 if (base::AtomicRefCountIsOne(&num_playing_streams_)) {
667 BrowserThread::PostTask(
668 BrowserThread::UI, FROM_HERE,
669 base::Bind(&NotifyRenderProcessHostThatAudioStateChanged,
670 render_process_id_));
671 }
672 } else {
673 entry->set_playing(false);
674 // Inform the RenderProcessHost when there is no more audio playing.
675 if (!base::AtomicRefCountDec(&num_playing_streams_)) {
676 BrowserThread::PostTask(
677 BrowserThread::UI, FROM_HERE,
678 base::Bind(&NotifyRenderProcessHostThatAudioStateChanged,
679 render_process_id_));
680 }
681 } 491 }
492 return i != delegates_.end() ? i->get() : nullptr;
682 } 493 }
683 494
684 bool AudioRendererHost::HasActiveAudio() { 495 bool AudioRendererHost::HasActiveAudio() {
685 return !base::AtomicRefCountIsZero(&num_playing_streams_); 496 return !base::AtomicRefCountIsZero(&num_playing_streams_);
686 } 497 }
687 498
688 void AudioRendererHost::CheckOutputDeviceAccess( 499 void AudioRendererHost::CheckOutputDeviceAccess(
689 int render_frame_id, 500 int render_frame_id,
690 const std::string& device_id, 501 const std::string& device_id,
691 const url::Origin& security_origin, 502 const url::Origin& security_origin,
(...skipping 149 matching lines...) Expand 10 before | Expand all | Expand 10 after
841 std::string() /* matched_device_id */)); 652 std::string() /* matched_device_id */));
842 } 653 }
843 654
844 bool AudioRendererHost::IsAuthorizationStarted(int stream_id) { 655 bool AudioRendererHost::IsAuthorizationStarted(int stream_id) {
845 DCHECK_CURRENTLY_ON(BrowserThread::IO); 656 DCHECK_CURRENTLY_ON(BrowserThread::IO);
846 const auto& i = authorizations_.find(stream_id); 657 const auto& i = authorizations_.find(stream_id);
847 return i != authorizations_.end(); 658 return i != authorizations_.end();
848 } 659 }
849 660
850 } // namespace content 661 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698