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/browser/renderer_host/media/media_stream_manager.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/power_monitor/power_monitor.h"
15 #include "base/rand_util.h"
16 #include "base/run_loop.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/threading/thread.h"
19 #include "content/browser/browser_main_loop.h"
20 #include "content/browser/media/capture/web_contents_capture_util.h"
21 #include "content/browser/renderer_host/media/audio_input_device_manager.h"
22 #include "content/browser/renderer_host/media/device_request_message_filter.h"
23 #include "content/browser/renderer_host/media/media_capture_devices_impl.h"
24 #include "content/browser/renderer_host/media/media_stream_requester.h"
25 #include "content/browser/renderer_host/media/media_stream_ui_proxy.h"
26 #include "content/browser/renderer_host/media/video_capture_manager.h"
27 #include "content/browser/renderer_host/render_process_host_impl.h"
28 #include "content/public/browser/browser_thread.h"
29 #include "content/public/browser/content_browser_client.h"
30 #include "content/public/browser/media_device_id.h"
31 #include "content/public/browser/media_observer.h"
32 #include "content/public/browser/media_request_state.h"
33 #include "content/public/browser/render_process_host.h"
34 #include "content/public/common/content_client.h"
35 #include "content/public/common/content_switches.h"
36 #include "content/public/common/media_stream_request.h"
37 #include "media/audio/audio_manager_base.h"
38 #include "media/audio/audio_parameters.h"
39 #include "media/base/channel_layout.h"
40 #include "media/base/media_switches.h"
41 #include "media/video/capture/video_capture_device_factory.h"
45 #include "base/win/scoped_com_initializer.h"
48 #if defined(OS_CHROMEOS)
49 #include "chromeos/audio/cras_audio_handler.h"
54 // Forward declaration of DeviceMonitorMac and its only useable method.
55 class DeviceMonitorMac {
58 const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner);
62 // Creates a random label used to identify requests.
63 std::string RandomLabel() {
64 // An earlier PeerConnection spec,
65 // http://dev.w3.org/2011/webrtc/editor/webrtc.html, specified the
66 // MediaStream::label alphabet as containing 36 characters from
67 // range: U+0021, U+0023 to U+0027, U+002A to U+002B, U+002D to U+002E,
68 // U+0030 to U+0039, U+0041 to U+005A, U+005E to U+007E.
69 // Here we use a safe subset.
70 static const char kAlphabet[] = "0123456789"
71 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
73 std::string label(36, ' ');
74 for (size_t i = 0; i < label.size(); ++i) {
75 int random_char = base::RandGenerator(sizeof(kAlphabet) - 1);
76 label[i] = kAlphabet[random_char];
81 void ParseStreamType(const StreamOptions& options,
82 MediaStreamType* audio_type,
83 MediaStreamType* video_type) {
84 *audio_type = MEDIA_NO_SERVICE;
85 *video_type = MEDIA_NO_SERVICE;
86 if (options.audio_requested) {
87 std::string audio_stream_source;
88 bool mandatory = false;
89 if (options.GetFirstAudioConstraintByName(kMediaStreamSource,
93 // This is tab or screen capture.
94 if (audio_stream_source == kMediaStreamSourceTab) {
95 *audio_type = content::MEDIA_TAB_AUDIO_CAPTURE;
96 } else if (audio_stream_source == kMediaStreamSourceSystem) {
97 *audio_type = content::MEDIA_LOOPBACK_AUDIO_CAPTURE;
100 // This is normal audio device capture.
101 *audio_type = MEDIA_DEVICE_AUDIO_CAPTURE;
104 if (options.video_requested) {
105 std::string video_stream_source;
106 bool mandatory = false;
107 if (options.GetFirstVideoConstraintByName(kMediaStreamSource,
108 &video_stream_source,
111 // This is tab or screen capture.
112 if (video_stream_source == kMediaStreamSourceTab) {
113 *video_type = content::MEDIA_TAB_VIDEO_CAPTURE;
114 } else if (video_stream_source == kMediaStreamSourceScreen) {
115 *video_type = content::MEDIA_DESKTOP_VIDEO_CAPTURE;
116 } else if (video_stream_source == kMediaStreamSourceDesktop) {
117 *video_type = content::MEDIA_DESKTOP_VIDEO_CAPTURE;
120 // This is normal video device capture.
121 *video_type = MEDIA_DEVICE_VIDEO_CAPTURE;
126 // Turns off available audio effects (removes the flag) if the options
127 // explicitly turn them off.
128 void FilterAudioEffects(const StreamOptions& options, int* effects) {
130 // TODO(ajm): Should we also handle ECHO_CANCELLER here?
132 if (options.GetFirstAudioConstraintByName(
133 kMediaStreamAudioDucking, &value, NULL) && value == "false") {
134 *effects &= ~media::AudioParameters::DUCKING;
138 // Private helper method for SendMessageToNativeLog() that obtains the global
139 // MediaStreamManager instance on the UI thread before sending |message| to the
140 // webrtcLoggingPrivate API.
141 void DoAddLogMessage(const std::string& message) {
142 // Must be on the UI thread to access BrowserMainLoop.
143 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
144 // May be null in tests.
145 // TODO(vrk): Handle this more elegantly by having native log messages become
146 // no-ops until MediaStreamManager is aware that a renderer process has
147 // started logging. crbug.com/333894
148 if (content::BrowserMainLoop::GetInstance()) {
149 BrowserThread::PostTask(
152 base::Bind(&MediaStreamManager::AddLogMessageOnIOThread,
153 base::Unretained(content::BrowserMainLoop::GetInstance()
154 ->media_stream_manager()),
159 // Private helper method to generate a string for the log message that lists the
160 // human readable names of |devices|.
161 std::string GetLogMessageString(MediaStreamType stream_type,
162 const StreamDeviceInfoArray& devices) {
163 std::string output_string =
164 base::StringPrintf("Getting devices for stream type %d:\n", stream_type);
165 if (devices.empty()) {
166 output_string += "No devices found.";
168 for (StreamDeviceInfoArray::const_iterator it = devices.begin();
169 it != devices.end(); ++it) {
170 output_string += " " + it->device.name + "\n";
173 return output_string;
176 // Needed for MediaStreamManager::GenerateStream below.
177 std::string ReturnEmptySalt() {
178 return std::string();
181 // Clears the MediaStreamDevice.name from all devices in |devices|.
182 static void ClearDeviceLabels(content::StreamDeviceInfoArray* devices) {
183 for (content::StreamDeviceInfoArray::iterator device_itr = devices->begin();
184 device_itr != devices->end();
186 device_itr->device.name.clear();
193 // MediaStreamManager::DeviceRequest represents a request to either enumerate
194 // available devices or open one or more devices.
195 // TODO(perkj): MediaStreamManager still needs refactoring. I propose we create
196 // several subclasses of DeviceRequest and move some of the responsibility of
197 // the MediaStreamManager to the subclasses to get rid of the way too many if
198 // statements in MediaStreamManager.
199 class MediaStreamManager::DeviceRequest {
201 DeviceRequest(MediaStreamRequester* requester,
202 int requesting_process_id,
203 int requesting_frame_id,
205 const GURL& security_origin,
207 MediaStreamRequestType request_type,
208 const StreamOptions& options,
209 const ResourceContext::SaltCallback& salt_callback)
210 : requester(requester),
211 requesting_process_id(requesting_process_id),
212 requesting_frame_id(requesting_frame_id),
213 page_request_id(page_request_id),
214 security_origin(security_origin),
215 user_gesture(user_gesture),
216 request_type(request_type),
218 salt_callback(salt_callback),
219 state_(NUM_MEDIA_TYPES, MEDIA_REQUEST_STATE_NOT_REQUESTED),
220 audio_type_(MEDIA_NO_SERVICE),
221 video_type_(MEDIA_NO_SERVICE) {
226 void SetAudioType(MediaStreamType audio_type) {
227 DCHECK(IsAudioInputMediaType(audio_type) ||
228 audio_type == MEDIA_DEVICE_AUDIO_OUTPUT ||
229 audio_type == MEDIA_NO_SERVICE);
230 audio_type_ = audio_type;
233 MediaStreamType audio_type() const { return audio_type_; }
235 void SetVideoType(MediaStreamType video_type) {
236 DCHECK(IsVideoMediaType(video_type) || video_type == MEDIA_NO_SERVICE);
237 video_type_ = video_type;
240 MediaStreamType video_type() const { return video_type_; }
242 // Creates a MediaStreamRequest object that is used by this request when UI
243 // is asked for permission and device selection.
244 void CreateUIRequest(const std::string& requested_audio_device_id,
245 const std::string& requested_video_device_id) {
246 DCHECK(!ui_request_);
247 ui_request_.reset(new MediaStreamRequest(requesting_process_id,
253 requested_audio_device_id,
254 requested_video_device_id,
259 // Creates a tab capture specific MediaStreamRequest object that is used by
260 // this request when UI is asked for permission and device selection.
261 void CreateTabCaptureUIRequest(int target_render_process_id,
262 int target_render_frame_id,
263 const std::string& tab_capture_id) {
264 DCHECK(!ui_request_);
265 ui_request_.reset(new MediaStreamRequest(target_render_process_id,
266 target_render_frame_id,
275 ui_request_->tab_capture_device_id = tab_capture_id;
278 const MediaStreamRequest* UIRequest() const { return ui_request_.get(); }
280 // Update the request state and notify observers.
281 void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
282 if (stream_type == NUM_MEDIA_TYPES) {
283 for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
284 const MediaStreamType stream_type = static_cast<MediaStreamType>(i);
285 state_[stream_type] = new_state;
288 state_[stream_type] = new_state;
291 MediaObserver* media_observer =
292 GetContentClient()->browser()->GetMediaObserver();
296 // If |ui_request_| doesn't exist, it means that the request has not yet
297 // been setup fully and there are no valid observers.
301 media_observer->OnMediaRequestStateChanged(
302 ui_request_->render_process_id, ui_request_->render_frame_id,
303 ui_request_->page_request_id, ui_request_->security_origin,
304 stream_type, new_state);
307 MediaRequestState state(MediaStreamType stream_type) const {
308 return state_[stream_type];
311 MediaStreamRequester* const requester; // Can be NULL.
314 // The render process id that requested this stream to be generated and that
315 // will receive a handle to the MediaStream. This may be different from
316 // MediaStreamRequest::render_process_id which in the tab capture case
317 // specifies the target renderer from which audio and video is captured.
318 const int requesting_process_id;
320 // The render frame id that requested this stream to be generated and that
321 // will receive a handle to the MediaStream. This may be different from
322 // MediaStreamRequest::render_frame_id which in the tab capture case
323 // specifies the target renderer from which audio and video is captured.
324 const int requesting_frame_id;
326 // An ID the render frame provided to identify this request.
327 const int page_request_id;
329 const GURL security_origin;
331 const bool user_gesture;
333 const MediaStreamRequestType request_type;
335 const StreamOptions options;
337 ResourceContext::SaltCallback salt_callback;
339 StreamDeviceInfoArray devices;
341 // Callback to the requester which audio/video devices have been selected.
342 // It can be null if the requester has no interest to know the result.
343 // Currently it is only used by |DEVICE_ACCESS| type.
344 MediaStreamManager::MediaRequestResponseCallback callback;
346 scoped_ptr<MediaStreamUIProxy> ui_proxy;
349 std::vector<MediaRequestState> state_;
350 scoped_ptr<MediaStreamRequest> ui_request_;
351 MediaStreamType audio_type_;
352 MediaStreamType video_type_;
355 MediaStreamManager::EnumerationCache::EnumerationCache()
359 MediaStreamManager::EnumerationCache::~EnumerationCache() {
362 MediaStreamManager::MediaStreamManager()
363 : audio_manager_(NULL),
364 monitoring_started_(false),
365 #if defined(OS_CHROMEOS)
366 has_checked_keyboard_mic_(false),
369 use_fake_ui_(false) {}
371 MediaStreamManager::MediaStreamManager(media::AudioManager* audio_manager)
372 : audio_manager_(audio_manager),
373 monitoring_started_(false),
374 #if defined(OS_CHROMEOS)
375 has_checked_keyboard_mic_(false),
378 use_fake_ui_(false) {
379 DCHECK(audio_manager_);
380 memset(active_enumeration_ref_count_, 0,
381 sizeof(active_enumeration_ref_count_));
383 // Some unit tests create the MSM in the IO thread and assumes the
384 // initialization is done synchronously.
385 if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
386 InitializeDeviceManagersOnIOThread();
388 BrowserThread::PostTask(
389 BrowserThread::IO, FROM_HERE,
390 base::Bind(&MediaStreamManager::InitializeDeviceManagersOnIOThread,
391 base::Unretained(this)));
394 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
395 // BrowserMainLoop always creates the PowerMonitor instance before creating
396 // MediaStreamManager, but power_monitor may be NULL in unit tests.
398 power_monitor->AddObserver(this);
401 MediaStreamManager::~MediaStreamManager() {
402 DVLOG(1) << "~MediaStreamManager";
403 DCHECK(requests_.empty());
404 DCHECK(!device_task_runner_.get());
406 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
407 // The PowerMonitor instance owned by BrowserMainLoops always outlives the
408 // MediaStreamManager, but it may be NULL in unit tests.
410 power_monitor->RemoveObserver(this);
413 VideoCaptureManager* MediaStreamManager::video_capture_manager() {
414 DCHECK_CURRENTLY_ON(BrowserThread::IO);
415 DCHECK(video_capture_manager_.get());
416 return video_capture_manager_.get();
419 AudioInputDeviceManager* MediaStreamManager::audio_input_device_manager() {
420 DCHECK_CURRENTLY_ON(BrowserThread::IO);
421 DCHECK(audio_input_device_manager_.get());
422 return audio_input_device_manager_.get();
425 std::string MediaStreamManager::MakeMediaAccessRequest(
426 int render_process_id,
429 const StreamOptions& options,
430 const GURL& security_origin,
431 const MediaRequestResponseCallback& callback) {
432 DCHECK_CURRENTLY_ON(BrowserThread::IO);
434 // TODO(perkj): The argument list with NULL parameters to DeviceRequest
435 // suggests that this is the wrong design. Can this be refactored?
436 DeviceRequest* request = new DeviceRequest(NULL,
441 false, // user gesture
444 base::Bind(&ReturnEmptySalt));
446 const std::string& label = AddRequest(request);
448 request->callback = callback;
449 // Post a task and handle the request asynchronously. The reason is that the
450 // requester won't have a label for the request until this function returns
451 // and thus can not handle a response. Using base::Unretained is safe since
452 // MediaStreamManager is deleted on the UI thread, after the IO thread has
454 BrowserThread::PostTask(
455 BrowserThread::IO, FROM_HERE,
456 base::Bind(&MediaStreamManager::SetupRequest,
457 base::Unretained(this), label));
461 void MediaStreamManager::GenerateStream(MediaStreamRequester* requester,
462 int render_process_id,
464 const ResourceContext::SaltCallback& sc,
466 const StreamOptions& options,
467 const GURL& security_origin,
469 DCHECK_CURRENTLY_ON(BrowserThread::IO);
470 DVLOG(1) << "GenerateStream()";
471 if (CommandLine::ForCurrentProcess()->HasSwitch(
472 switches::kUseFakeUIForMediaStream)) {
473 UseFakeUI(scoped_ptr<FakeMediaStreamUIProxy>());
476 DeviceRequest* request = new DeviceRequest(requester,
482 MEDIA_GENERATE_STREAM,
486 const std::string& label = AddRequest(request);
488 // Post a task and handle the request asynchronously. The reason is that the
489 // requester won't have a label for the request until this function returns
490 // and thus can not handle a response. Using base::Unretained is safe since
491 // MediaStreamManager is deleted on the UI thread, after the IO thread has
493 BrowserThread::PostTask(
494 BrowserThread::IO, FROM_HERE,
495 base::Bind(&MediaStreamManager::SetupRequest,
496 base::Unretained(this), label));
499 void MediaStreamManager::CancelRequest(int render_process_id,
501 int page_request_id) {
502 for (DeviceRequests::const_iterator request_it = requests_.begin();
503 request_it != requests_.end(); ++request_it) {
504 const DeviceRequest* request = request_it->second;
505 if (request->requesting_process_id == render_process_id &&
506 request->requesting_frame_id == render_frame_id &&
507 request->page_request_id == page_request_id) {
508 CancelRequest(request_it->first);
515 void MediaStreamManager::CancelRequest(const std::string& label) {
516 DCHECK_CURRENTLY_ON(BrowserThread::IO);
517 DVLOG(1) << "CancelRequest({label = " << label << "})";
518 DeviceRequest* request = FindRequest(label);
520 // The request does not exist.
521 LOG(ERROR) << "The request with label = " << label << " does not exist.";
525 if (request->request_type == MEDIA_ENUMERATE_DEVICES) {
526 // It isn't an ideal use of "CancelRequest" to make it a requirement
527 // for enumeration requests to be deleted via "CancelRequest" _after_
528 // the request has been successfully fulfilled.
529 // See note in FinalizeEnumerateDevices for a recommendation on how
530 // we should refactor this.
531 DeleteRequest(label);
535 // This is a request for opening one or more devices.
536 for (StreamDeviceInfoArray::iterator device_it = request->devices.begin();
537 device_it != request->devices.end(); ++device_it) {
538 MediaRequestState state = request->state(device_it->device.type);
539 // If we have not yet requested the device to be opened - just ignore it.
540 if (state != MEDIA_REQUEST_STATE_OPENING &&
541 state != MEDIA_REQUEST_STATE_DONE) {
544 // Stop the opening/opened devices of the requests.
545 CloseDevice(device_it->device.type, device_it->session_id);
548 // Cancel the request if still pending at UI side.
549 request->SetState(NUM_MEDIA_TYPES, MEDIA_REQUEST_STATE_CLOSING);
550 DeleteRequest(label);
553 void MediaStreamManager::CancelAllRequests(int render_process_id) {
554 DeviceRequests::iterator request_it = requests_.begin();
555 while (request_it != requests_.end()) {
556 if (request_it->second->requesting_process_id != render_process_id) {
561 std::string label = request_it->first;
563 CancelRequest(label);
567 void MediaStreamManager::StopStreamDevice(int render_process_id,
569 const std::string& device_id) {
570 DCHECK_CURRENTLY_ON(BrowserThread::IO);
571 DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} "
572 << ", {device_id = " << device_id << "})";
573 // Find the first request for this |render_process_id| and |render_frame_id|
574 // of type MEDIA_GENERATE_STREAM that has requested to use |device_id| and
576 for (DeviceRequests::iterator request_it = requests_.begin();
577 request_it != requests_.end(); ++request_it) {
578 DeviceRequest* request = request_it->second;
579 if (request->requesting_process_id != render_process_id ||
580 request->requesting_frame_id != render_frame_id ||
581 request->request_type != MEDIA_GENERATE_STREAM) {
585 StreamDeviceInfoArray& devices = request->devices;
586 for (StreamDeviceInfoArray::iterator device_it = devices.begin();
587 device_it != devices.end(); ++device_it) {
588 if (device_it->device.id == device_id) {
589 StopDevice(device_it->device.type, device_it->session_id);
596 void MediaStreamManager::StopDevice(MediaStreamType type, int session_id) {
597 DVLOG(1) << "StopDevice"
598 << "{type = " << type << "}"
599 << "{session_id = " << session_id << "}";
600 DeviceRequests::iterator request_it = requests_.begin();
601 while (request_it != requests_.end()) {
602 DeviceRequest* request = request_it->second;
603 StreamDeviceInfoArray* devices = &request->devices;
604 if (devices->empty()) {
605 // There is no device in use yet by this request.
609 StreamDeviceInfoArray::iterator device_it = devices->begin();
610 while (device_it != devices->end()) {
611 if (device_it->device.type != type ||
612 device_it->session_id != session_id) {
617 if (request->state(type) == MEDIA_REQUEST_STATE_DONE)
618 CloseDevice(type, session_id);
619 device_it = devices->erase(device_it);
622 // If this request doesn't have any active devices after a device
623 // has been stopped above, remove the request. Note that the request is
624 // only deleted if a device as been removed from |devices|.
625 if (devices->empty()) {
626 std::string label = request_it->first;
628 DeleteRequest(label);
635 void MediaStreamManager::CloseDevice(MediaStreamType type, int session_id) {
636 DVLOG(1) << "CloseDevice("
637 << "{type = " << type << "} "
638 << "{session_id = " << session_id << "})";
639 GetDeviceManager(type)->Close(session_id);
641 for (DeviceRequests::iterator request_it = requests_.begin();
642 request_it != requests_.end() ; ++request_it) {
643 StreamDeviceInfoArray* devices = &request_it->second->devices;
644 for (StreamDeviceInfoArray::iterator device_it = devices->begin();
645 device_it != devices->end(); ++device_it) {
646 if (device_it->session_id == session_id &&
647 device_it->device.type == type) {
648 // Notify observers that this device is being closed.
649 // Note that only one device per type can be opened.
650 request_it->second->SetState(type, MEDIA_REQUEST_STATE_CLOSING);
656 std::string MediaStreamManager::EnumerateDevices(
657 MediaStreamRequester* requester,
658 int render_process_id,
660 const ResourceContext::SaltCallback& sc,
662 MediaStreamType type,
663 const GURL& security_origin) {
664 DCHECK_CURRENTLY_ON(BrowserThread::IO);
666 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
667 type == MEDIA_DEVICE_VIDEO_CAPTURE ||
668 type == MEDIA_DEVICE_AUDIO_OUTPUT);
670 DeviceRequest* request = new DeviceRequest(requester,
675 false, // user gesture
676 MEDIA_ENUMERATE_DEVICES,
679 if (IsAudioInputMediaType(type) || type == MEDIA_DEVICE_AUDIO_OUTPUT)
680 request->SetAudioType(type);
681 else if (IsVideoMediaType(type))
682 request->SetVideoType(type);
684 const std::string& label = AddRequest(request);
685 // Post a task and handle the request asynchronously. The reason is that the
686 // requester won't have a label for the request until this function returns
687 // and thus can not handle a response. Using base::Unretained is safe since
688 // MediaStreamManager is deleted on the UI thread, after the IO thread has
690 BrowserThread::PostTask(
691 BrowserThread::IO, FROM_HERE,
692 base::Bind(&MediaStreamManager::DoEnumerateDevices,
693 base::Unretained(this), label));
697 void MediaStreamManager::DoEnumerateDevices(const std::string& label) {
698 DCHECK_CURRENTLY_ON(BrowserThread::IO);
699 DeviceRequest* request = FindRequest(label);
701 return; // This can happen if the request has been canceled.
703 if (request->audio_type() == MEDIA_DEVICE_AUDIO_OUTPUT) {
704 DCHECK_EQ(MEDIA_NO_SERVICE, request->video_type());
705 DCHECK_GE(active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_OUTPUT], 0);
706 request->SetState(MEDIA_DEVICE_AUDIO_OUTPUT, MEDIA_REQUEST_STATE_REQUESTED);
707 if (active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_OUTPUT] == 0) {
708 ++active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_OUTPUT];
709 device_task_runner_->PostTask(
711 base::Bind(&MediaStreamManager::EnumerateAudioOutputDevices,
712 base::Unretained(this),
718 MediaStreamType type;
719 EnumerationCache* cache;
720 if (request->audio_type() == MEDIA_DEVICE_AUDIO_CAPTURE) {
721 DCHECK_EQ(MEDIA_NO_SERVICE, request->video_type());
722 type = MEDIA_DEVICE_AUDIO_CAPTURE;
723 cache = &audio_enumeration_cache_;
725 DCHECK_EQ(MEDIA_DEVICE_VIDEO_CAPTURE, request->video_type());
726 DCHECK_EQ(MEDIA_NO_SERVICE, request->audio_type());
727 type = MEDIA_DEVICE_VIDEO_CAPTURE;
728 cache = &video_enumeration_cache_;
731 if (!EnumerationRequired(cache, type)) {
732 // Cached device list of this type exists. Just send it out.
733 request->SetState(type, MEDIA_REQUEST_STATE_REQUESTED);
734 request->devices = cache->devices;
735 FinalizeEnumerateDevices(label, request);
737 StartEnumeration(request);
739 DVLOG(1) << "Enumerate Devices ({label = " << label << "})";
742 void MediaStreamManager::EnumerateAudioOutputDevices(const std::string& label) {
743 DCHECK(device_task_runner_->BelongsToCurrentThread());
745 scoped_ptr<media::AudioDeviceNames> device_names(
746 new media::AudioDeviceNames());
747 audio_manager_->GetAudioOutputDeviceNames(device_names.get());
748 StreamDeviceInfoArray devices;
749 for (media::AudioDeviceNames::iterator it = device_names->begin();
750 it != device_names->end(); ++it) {
751 StreamDeviceInfo device(MEDIA_DEVICE_AUDIO_OUTPUT,
754 devices.push_back(device);
757 BrowserThread::PostTask(
758 BrowserThread::IO, FROM_HERE,
759 base::Bind(&MediaStreamManager::AudioOutputDevicesEnumerated,
760 base::Unretained(this),
764 void MediaStreamManager::AudioOutputDevicesEnumerated(
765 const StreamDeviceInfoArray& devices) {
766 DCHECK_CURRENTLY_ON(BrowserThread::IO);
767 DVLOG(1) << "AudioOutputDevicesEnumerated()";
769 std::string log_message = "New device enumeration result:\n" +
770 GetLogMessageString(MEDIA_DEVICE_AUDIO_OUTPUT,
772 SendMessageToNativeLog(log_message);
774 // Publish the result for all requests waiting for device list(s).
775 for (DeviceRequests::iterator it = requests_.begin(); it != requests_.end();
777 if (it->second->state(MEDIA_DEVICE_AUDIO_OUTPUT) ==
778 MEDIA_REQUEST_STATE_REQUESTED &&
779 it->second->audio_type() == MEDIA_DEVICE_AUDIO_OUTPUT) {
780 DCHECK_EQ(MEDIA_ENUMERATE_DEVICES, it->second->request_type);
781 it->second->SetState(MEDIA_DEVICE_AUDIO_OUTPUT,
782 MEDIA_REQUEST_STATE_PENDING_APPROVAL);
783 it->second->devices = devices;
784 FinalizeEnumerateDevices(it->first, it->second);
788 --active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_OUTPUT];
789 DCHECK_GE(active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_OUTPUT], 0);
792 void MediaStreamManager::OpenDevice(MediaStreamRequester* requester,
793 int render_process_id,
795 const ResourceContext::SaltCallback& sc,
797 const std::string& device_id,
798 MediaStreamType type,
799 const GURL& security_origin) {
800 DCHECK_CURRENTLY_ON(BrowserThread::IO);
801 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
802 type == MEDIA_DEVICE_VIDEO_CAPTURE);
803 DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
804 StreamOptions options;
805 if (IsAudioInputMediaType(type)) {
806 options.audio_requested = true;
807 options.mandatory_audio.push_back(
808 StreamOptions::Constraint(kMediaStreamSourceInfoId, device_id));
809 } else if (IsVideoMediaType(type)) {
810 options.video_requested = true;
811 options.mandatory_video.push_back(
812 StreamOptions::Constraint(kMediaStreamSourceInfoId, device_id));
816 DeviceRequest* request = new DeviceRequest(requester,
821 false, // user gesture
826 const std::string& label = AddRequest(request);
827 // Post a task and handle the request asynchronously. The reason is that the
828 // requester won't have a label for the request until this function returns
829 // and thus can not handle a response. Using base::Unretained is safe since
830 // MediaStreamManager is deleted on the UI thread, after the IO thread has
832 BrowserThread::PostTask(
833 BrowserThread::IO, FROM_HERE,
834 base::Bind(&MediaStreamManager::SetupRequest,
835 base::Unretained(this), label));
838 bool MediaStreamManager::TranslateSourceIdToDeviceId(
839 MediaStreamType stream_type,
840 const ResourceContext::SaltCallback& sc,
841 const GURL& security_origin,
842 const std::string& source_id,
843 std::string* device_id) const {
844 DCHECK(stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ||
845 stream_type == MEDIA_DEVICE_VIDEO_CAPTURE);
846 // The source_id can be empty if the constraint is set but empty.
847 if (source_id.empty())
850 const EnumerationCache* cache =
851 stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ?
852 &audio_enumeration_cache_ : &video_enumeration_cache_;
854 // If device monitoring hasn't started, the |device_guid| is not valid.
858 for (StreamDeviceInfoArray::const_iterator it = cache->devices.begin();
859 it != cache->devices.end();
861 if (content::DoesMediaDeviceIDMatchHMAC(sc, security_origin, source_id,
863 *device_id = it->device.id;
870 void MediaStreamManager::EnsureDeviceMonitorStarted() {
871 DCHECK_CURRENTLY_ON(BrowserThread::IO);
875 void MediaStreamManager::StopRemovedDevices(
876 const StreamDeviceInfoArray& old_devices,
877 const StreamDeviceInfoArray& new_devices) {
878 DVLOG(1) << "StopRemovedDevices("
879 << "{#old_devices = " << old_devices.size() << "} "
880 << "{#new_devices = " << new_devices.size() << "})";
881 for (StreamDeviceInfoArray::const_iterator old_dev_it = old_devices.begin();
882 old_dev_it != old_devices.end(); ++old_dev_it) {
883 bool device_found = false;
884 StreamDeviceInfoArray::const_iterator new_dev_it = new_devices.begin();
885 for (; new_dev_it != new_devices.end(); ++new_dev_it) {
886 if (old_dev_it->device.id == new_dev_it->device.id) {
893 // A device has been removed. We need to check if it is used by a
894 // MediaStream and in that case cleanup and notify the render process.
895 StopRemovedDevice(old_dev_it->device);
900 void MediaStreamManager::StopRemovedDevice(const MediaStreamDevice& device) {
901 std::vector<int> session_ids;
902 for (DeviceRequests::const_iterator it = requests_.begin();
903 it != requests_.end() ; ++it) {
904 const DeviceRequest* request = it->second;
905 for (StreamDeviceInfoArray::const_iterator device_it =
906 request->devices.begin();
907 device_it != request->devices.end(); ++device_it) {
908 std::string source_id = content::GetHMACForMediaDeviceID(
909 request->salt_callback,
910 request->security_origin,
912 if (device_it->device.id == source_id &&
913 device_it->device.type == device.type) {
914 session_ids.push_back(device_it->session_id);
915 if (it->second->requester) {
916 it->second->requester->DeviceStopped(
917 it->second->requesting_frame_id,
924 for (std::vector<int>::const_iterator it = session_ids.begin();
925 it != session_ids.end(); ++it) {
926 StopDevice(device.type, *it);
929 std::ostringstream oss;
930 oss << "Media input device removed: type = " <<
931 (device.type == MEDIA_DEVICE_AUDIO_CAPTURE ? "audio" : "video") <<
932 ", id = " << device.id << ", name = " << device.name;
933 AddLogMessageOnIOThread(oss.str());
936 void MediaStreamManager::StartMonitoring() {
937 DCHECK_CURRENTLY_ON(BrowserThread::IO);
938 if (monitoring_started_)
941 if (!base::SystemMonitor::Get())
944 monitoring_started_ = true;
945 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
947 // Enumerate both the audio and video devices to cache the device lists
948 // and send them to media observer.
949 ++active_enumeration_ref_count_[MEDIA_DEVICE_AUDIO_CAPTURE];
950 audio_input_device_manager_->EnumerateDevices(MEDIA_DEVICE_AUDIO_CAPTURE);
951 ++active_enumeration_ref_count_[MEDIA_DEVICE_VIDEO_CAPTURE];
952 video_capture_manager_->EnumerateDevices(MEDIA_DEVICE_VIDEO_CAPTURE);
954 #if defined(OS_MACOSX)
955 BrowserThread::PostTask(
956 BrowserThread::UI, FROM_HERE,
957 base::Bind(&MediaStreamManager::StartMonitoringOnUIThread,
958 base::Unretained(this)));
962 #if defined(OS_MACOSX)
963 void MediaStreamManager::StartMonitoringOnUIThread() {
964 DCHECK_CURRENTLY_ON(BrowserThread::UI);
965 BrowserMainLoop* browser_main_loop = content::BrowserMainLoop::GetInstance();
966 if (browser_main_loop) {
967 browser_main_loop->device_monitor_mac()
968 ->StartMonitoring(audio_manager_->GetWorkerTaskRunner());
973 void MediaStreamManager::StopMonitoring() {
974 DCHECK_EQ(base::MessageLoop::current(), io_loop_);
975 if (monitoring_started_) {
976 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
977 monitoring_started_ = false;
978 ClearEnumerationCache(&audio_enumeration_cache_);
979 ClearEnumerationCache(&video_enumeration_cache_);
983 bool MediaStreamManager::GetRequestedDeviceCaptureId(
984 const DeviceRequest* request,
985 MediaStreamType type,
986 std::string* device_id) const {
987 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
988 type == MEDIA_DEVICE_VIDEO_CAPTURE);
989 const StreamOptions::Constraints* mandatory =
990 (type == MEDIA_DEVICE_AUDIO_CAPTURE) ?
991 &request->options.mandatory_audio : &request->options.mandatory_video;
992 const StreamOptions::Constraints* optional =
993 (type == MEDIA_DEVICE_AUDIO_CAPTURE) ?
994 &request->options.optional_audio : &request->options.optional_video;
996 std::vector<std::string> source_ids;
997 StreamOptions::GetConstraintsByName(*mandatory,
998 kMediaStreamSourceInfoId, &source_ids);
999 if (source_ids.size() > 1) {
1000 LOG(ERROR) << "Only one mandatory " << kMediaStreamSourceInfoId
1001 << " is supported.";
1004 // If a specific device has been requested we need to find the real device
1006 if (source_ids.size() == 1 &&
1007 !TranslateSourceIdToDeviceId(type,
1008 request->salt_callback,
1009 request->security_origin,
1010 source_ids[0], device_id)) {
1011 LOG(WARNING) << "Invalid mandatory " << kMediaStreamSourceInfoId
1012 << " = " << source_ids[0] << ".";
1015 // Check for optional audio sourceIDs.
1016 if (device_id->empty()) {
1017 StreamOptions::GetConstraintsByName(*optional,
1018 kMediaStreamSourceInfoId,
1020 // Find the first sourceID that translates to device. Note that only one
1021 // device per type can call to GenerateStream is ever opened.
1022 for (std::vector<std::string>::const_iterator it = source_ids.begin();
1023 it != source_ids.end(); ++it) {
1024 if (TranslateSourceIdToDeviceId(type,
1025 request->salt_callback,
1026 request->security_origin,
1036 void MediaStreamManager::TranslateDeviceIdToSourceId(
1037 DeviceRequest* request,
1038 MediaStreamDevice* device) {
1039 if (request->audio_type() == MEDIA_DEVICE_AUDIO_CAPTURE ||
1040 request->audio_type() == MEDIA_DEVICE_AUDIO_OUTPUT ||
1041 request->video_type() == MEDIA_DEVICE_VIDEO_CAPTURE) {
1042 device->id = content::GetHMACForMediaDeviceID(
1043 request->salt_callback,
1044 request->security_origin,
1049 void MediaStreamManager::ClearEnumerationCache(EnumerationCache* cache) {
1050 DCHECK_EQ(base::MessageLoop::current(), io_loop_);
1051 cache->valid = false;
1054 bool MediaStreamManager::EnumerationRequired(EnumerationCache* cache,
1055 MediaStreamType stream_type) {
1056 DCHECK_EQ(base::MessageLoop::current(), io_loop_);
1057 if (stream_type == MEDIA_NO_SERVICE)
1060 DCHECK(stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1061 stream_type == MEDIA_DEVICE_VIDEO_CAPTURE);
1063 #if defined(OS_ANDROID)
1064 // There's no SystemMonitor on Android that notifies us when devices are
1065 // added or removed, so we need to populate the cache on every request.
1066 // Fortunately, there is an already up-to-date cache in the browser side
1067 // audio manager that we can rely on, so the performance impact of
1068 // invalidating the cache like this, is minimal.
1069 if (stream_type == MEDIA_DEVICE_AUDIO_CAPTURE) {
1070 // Make sure the cache is marked as invalid so that FinalizeEnumerateDevices
1071 // will be called at the end of the enumeration.
1072 ClearEnumerationCache(cache);
1075 // If the cache isn't valid, we need to start a full enumeration.
1076 return !cache->valid;
1079 void MediaStreamManager::StartEnumeration(DeviceRequest* request) {
1080 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1082 // Start monitoring the devices when doing the first enumeration.
1085 // Start enumeration for devices of all requested device types.
1086 const MediaStreamType streams[] = { request->audio_type(),
1087 request->video_type() };
1088 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(streams); ++i) {
1089 if (streams[i] == MEDIA_NO_SERVICE)
1091 request->SetState(streams[i], MEDIA_REQUEST_STATE_REQUESTED);
1092 DCHECK_GE(active_enumeration_ref_count_[streams[i]], 0);
1093 if (active_enumeration_ref_count_[streams[i]] == 0) {
1094 ++active_enumeration_ref_count_[streams[i]];
1095 GetDeviceManager(streams[i])->EnumerateDevices(streams[i]);
1100 std::string MediaStreamManager::AddRequest(DeviceRequest* request) {
1101 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1103 // Create a label for this request and verify it is unique.
1104 std::string unique_label;
1106 unique_label = RandomLabel();
1107 } while (FindRequest(unique_label) != NULL);
1109 requests_.push_back(std::make_pair(unique_label, request));
1111 return unique_label;
1114 MediaStreamManager::DeviceRequest*
1115 MediaStreamManager::FindRequest(const std::string& label) const {
1116 for (DeviceRequests::const_iterator request_it = requests_.begin();
1117 request_it != requests_.end(); ++request_it) {
1118 if (request_it->first == label)
1119 return request_it->second;
1124 void MediaStreamManager::DeleteRequest(const std::string& label) {
1125 DVLOG(1) << "DeleteRequest({label= " << label << "})";
1126 for (DeviceRequests::iterator request_it = requests_.begin();
1127 request_it != requests_.end(); ++request_it) {
1128 if (request_it->first == label) {
1129 scoped_ptr<DeviceRequest> request(request_it->second);
1130 requests_.erase(request_it);
1137 void MediaStreamManager::PostRequestToUI(const std::string& label,
1138 DeviceRequest* request) {
1139 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1140 DCHECK(request->UIRequest());
1141 DVLOG(1) << "PostRequestToUI({label= " << label << "})";
1143 const MediaStreamType audio_type = request->audio_type();
1144 const MediaStreamType video_type = request->video_type();
1146 // Post the request to UI and set the state.
1147 if (IsAudioInputMediaType(audio_type))
1148 request->SetState(audio_type, MEDIA_REQUEST_STATE_PENDING_APPROVAL);
1149 if (IsVideoMediaType(video_type))
1150 request->SetState(video_type, MEDIA_REQUEST_STATE_PENDING_APPROVAL);
1154 fake_ui_.reset(new FakeMediaStreamUIProxy());
1156 MediaStreamDevices devices;
1157 if (audio_enumeration_cache_.valid) {
1158 for (StreamDeviceInfoArray::const_iterator it =
1159 audio_enumeration_cache_.devices.begin();
1160 it != audio_enumeration_cache_.devices.end(); ++it) {
1161 devices.push_back(it->device);
1164 if (video_enumeration_cache_.valid) {
1165 for (StreamDeviceInfoArray::const_iterator it =
1166 video_enumeration_cache_.devices.begin();
1167 it != video_enumeration_cache_.devices.end(); ++it) {
1168 devices.push_back(it->device);
1172 fake_ui_->SetAvailableDevices(devices);
1174 request->ui_proxy = fake_ui_.Pass();
1176 request->ui_proxy = MediaStreamUIProxy::Create();
1179 request->ui_proxy->RequestAccess(
1180 *request->UIRequest(),
1181 base::Bind(&MediaStreamManager::HandleAccessRequestResponse,
1182 base::Unretained(this), label));
1185 void MediaStreamManager::SetupRequest(const std::string& label) {
1186 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1187 DeviceRequest* request = FindRequest(label);
1189 DVLOG(1) << "SetupRequest label " << label << " doesn't exist!!";
1190 return; // This can happen if the request has been canceled.
1193 if (!request->security_origin.is_valid()) {
1194 LOG(ERROR) << "Invalid security origin. "
1195 << request->security_origin;
1196 FinalizeRequestFailed(label,
1198 MEDIA_DEVICE_INVALID_SECURITY_ORIGIN);
1202 MediaStreamType audio_type = MEDIA_NO_SERVICE;
1203 MediaStreamType video_type = MEDIA_NO_SERVICE;
1204 ParseStreamType(request->options, &audio_type, &video_type);
1205 request->SetAudioType(audio_type);
1206 request->SetVideoType(video_type);
1208 bool is_web_contents_capture =
1209 audio_type == MEDIA_TAB_AUDIO_CAPTURE ||
1210 video_type == MEDIA_TAB_VIDEO_CAPTURE;
1211 if (is_web_contents_capture && !SetupTabCaptureRequest(request)) {
1212 FinalizeRequestFailed(label,
1214 MEDIA_DEVICE_TAB_CAPTURE_FAILURE);
1218 bool is_screen_capture =
1219 video_type == MEDIA_DESKTOP_VIDEO_CAPTURE;
1220 if (is_screen_capture && !SetupScreenCaptureRequest(request)) {
1221 FinalizeRequestFailed(label,
1223 MEDIA_DEVICE_SCREEN_CAPTURE_FAILURE);
1227 #if defined(OS_CHROMEOS)
1228 EnsureKeyboardMicChecked();
1231 if (!is_web_contents_capture && !is_screen_capture) {
1232 if (EnumerationRequired(&audio_enumeration_cache_, audio_type) ||
1233 EnumerationRequired(&video_enumeration_cache_, video_type)) {
1234 // Enumerate the devices if there is no valid device lists to be used.
1235 StartEnumeration(request);
1238 // Cache is valid, so log the cached devices for MediaStream requests.
1239 if (request->request_type == MEDIA_GENERATE_STREAM) {
1240 std::string log_message("Using cached devices for request.\n");
1241 if (audio_type != MEDIA_NO_SERVICE) {
1243 GetLogMessageString(audio_type, audio_enumeration_cache_.devices);
1245 if (video_type != MEDIA_NO_SERVICE) {
1247 GetLogMessageString(video_type, video_enumeration_cache_.devices);
1249 SendMessageToNativeLog(log_message);
1253 if (!SetupDeviceCaptureRequest(request)) {
1254 FinalizeRequestFailed(label, request, MEDIA_DEVICE_NO_HARDWARE);
1258 PostRequestToUI(label, request);
1261 bool MediaStreamManager::SetupDeviceCaptureRequest(DeviceRequest* request) {
1262 DCHECK((request->audio_type() == MEDIA_DEVICE_AUDIO_CAPTURE ||
1263 request->audio_type() == MEDIA_NO_SERVICE) &&
1264 (request->video_type() == MEDIA_DEVICE_VIDEO_CAPTURE ||
1265 request->video_type() == MEDIA_NO_SERVICE));
1266 std::string audio_device_id;
1267 if (request->options.audio_requested &&
1268 !GetRequestedDeviceCaptureId(request, request->audio_type(),
1269 &audio_device_id)) {
1273 std::string video_device_id;
1274 if (request->options.video_requested &&
1275 !GetRequestedDeviceCaptureId(request, request->video_type(),
1276 &video_device_id)) {
1279 request->CreateUIRequest(audio_device_id, video_device_id);
1280 DVLOG(3) << "Audio requested " << request->options.audio_requested
1281 << " device id = " << audio_device_id
1282 << "Video requested " << request->options.video_requested
1283 << " device id = " << video_device_id;
1287 bool MediaStreamManager::SetupTabCaptureRequest(DeviceRequest* request) {
1288 DCHECK(request->audio_type() == MEDIA_TAB_AUDIO_CAPTURE ||
1289 request->video_type() == MEDIA_TAB_VIDEO_CAPTURE);
1291 std::string capture_device_id;
1292 bool mandatory_audio = false;
1293 bool mandatory_video = false;
1294 if (!request->options.GetFirstAudioConstraintByName(kMediaStreamSourceId,
1296 &mandatory_audio) &&
1297 !request->options.GetFirstVideoConstraintByName(kMediaStreamSourceId,
1299 &mandatory_video)) {
1302 DCHECK(mandatory_audio || mandatory_video);
1304 // Customize options for a WebContents based capture.
1305 int target_render_process_id = 0;
1306 int target_render_frame_id = 0;
1308 bool has_valid_device_id = WebContentsCaptureUtil::ExtractTabCaptureTarget(
1309 capture_device_id, &target_render_process_id, &target_render_frame_id);
1310 if (!has_valid_device_id ||
1311 (request->audio_type() != MEDIA_TAB_AUDIO_CAPTURE &&
1312 request->audio_type() != MEDIA_NO_SERVICE) ||
1313 (request->video_type() != MEDIA_TAB_VIDEO_CAPTURE &&
1314 request->video_type() != MEDIA_NO_SERVICE)) {
1318 request->CreateTabCaptureUIRequest(target_render_process_id,
1319 target_render_frame_id,
1322 DVLOG(3) << "SetupTabCaptureRequest "
1323 << ", {capture_device_id = " << capture_device_id << "}"
1324 << ", {target_render_process_id = " << target_render_process_id
1326 << ", {target_render_frame_id = " << target_render_frame_id << "}";
1330 bool MediaStreamManager::SetupScreenCaptureRequest(DeviceRequest* request) {
1331 DCHECK(request->audio_type() == MEDIA_LOOPBACK_AUDIO_CAPTURE ||
1332 request->video_type() == MEDIA_DESKTOP_VIDEO_CAPTURE);
1334 // For screen capture we only support two valid combinations:
1335 // (1) screen video capture only, or
1336 // (2) screen video capture with loopback audio capture.
1337 if (request->video_type() != MEDIA_DESKTOP_VIDEO_CAPTURE ||
1338 (request->audio_type() != MEDIA_NO_SERVICE &&
1339 request->audio_type() != MEDIA_LOOPBACK_AUDIO_CAPTURE)) {
1340 LOG(ERROR) << "Invalid screen capture request.";
1344 std::string video_device_id;
1345 if (request->video_type() == MEDIA_DESKTOP_VIDEO_CAPTURE) {
1346 std::string video_stream_source;
1347 bool mandatory = false;
1348 if (!request->options.GetFirstVideoConstraintByName(
1350 &video_stream_source,
1352 LOG(ERROR) << kMediaStreamSource << " not found.";
1357 if (video_stream_source == kMediaStreamSourceDesktop) {
1358 if (!request->options.GetFirstVideoConstraintByName(
1359 kMediaStreamSourceId,
1362 LOG(ERROR) << kMediaStreamSourceId << " not found.";
1369 request->CreateUIRequest("", video_device_id);
1373 StreamDeviceInfoArray MediaStreamManager::GetDevicesOpenedByRequest(
1374 const std::string& label) const {
1375 DeviceRequest* request = FindRequest(label);
1377 return StreamDeviceInfoArray();
1378 return request->devices;
1381 bool MediaStreamManager::FindExistingRequestedDeviceInfo(
1382 const DeviceRequest& new_request,
1383 const MediaStreamDevice& new_device_info,
1384 StreamDeviceInfo* existing_device_info,
1385 MediaRequestState* existing_request_state) const {
1386 DCHECK(existing_device_info);
1387 DCHECK(existing_request_state);
1389 std::string source_id = content::GetHMACForMediaDeviceID(
1390 new_request.salt_callback,
1391 new_request.security_origin,
1392 new_device_info.id);
1394 for (DeviceRequests::const_iterator it = requests_.begin();
1395 it != requests_.end() ; ++it) {
1396 const DeviceRequest* request = it->second;
1397 if (request->requesting_process_id == new_request.requesting_process_id &&
1398 request->requesting_frame_id == new_request.requesting_frame_id &&
1399 request->request_type == new_request.request_type) {
1400 for (StreamDeviceInfoArray::const_iterator device_it =
1401 request->devices.begin();
1402 device_it != request->devices.end(); ++device_it) {
1403 if (device_it->device.id == source_id &&
1404 device_it->device.type == new_device_info.type) {
1405 *existing_device_info = *device_it;
1406 // Make sure that the audio |effects| reflect what the request
1407 // is set to and not what the capabilities are.
1408 FilterAudioEffects(request->options,
1409 &existing_device_info->device.input.effects);
1410 *existing_request_state = request->state(device_it->device.type);
1419 void MediaStreamManager::FinalizeGenerateStream(const std::string& label,
1420 DeviceRequest* request) {
1421 DVLOG(1) << "FinalizeGenerateStream label " << label;
1422 const StreamDeviceInfoArray& requested_devices = request->devices;
1424 // Partition the array of devices into audio vs video.
1425 StreamDeviceInfoArray audio_devices, video_devices;
1426 for (StreamDeviceInfoArray::const_iterator device_it =
1427 requested_devices.begin();
1428 device_it != requested_devices.end(); ++device_it) {
1429 if (IsAudioInputMediaType(device_it->device.type)) {
1430 audio_devices.push_back(*device_it);
1431 } else if (IsVideoMediaType(device_it->device.type)) {
1432 video_devices.push_back(*device_it);
1438 request->requester->StreamGenerated(
1439 request->requesting_frame_id,
1440 request->page_request_id,
1441 label, audio_devices, video_devices);
1444 void MediaStreamManager::FinalizeRequestFailed(
1445 const std::string& label,
1446 DeviceRequest* request,
1447 content::MediaStreamRequestResult result) {
1448 if (request->requester)
1449 request->requester->StreamGenerationFailed(
1450 request->requesting_frame_id,
1451 request->page_request_id,
1454 if (request->request_type == MEDIA_DEVICE_ACCESS &&
1455 !request->callback.is_null()) {
1456 request->callback.Run(MediaStreamDevices(), request->ui_proxy.Pass());
1459 DeleteRequest(label);
1462 void MediaStreamManager::FinalizeOpenDevice(const std::string& label,
1463 DeviceRequest* request) {
1464 const StreamDeviceInfoArray& requested_devices = request->devices;
1465 request->requester->DeviceOpened(request->requesting_frame_id,
1466 request->page_request_id,
1467 label, requested_devices.front());
1470 void MediaStreamManager::FinalizeEnumerateDevices(const std::string& label,
1471 DeviceRequest* request) {
1472 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1473 DCHECK_EQ(request->request_type, MEDIA_ENUMERATE_DEVICES);
1474 DCHECK(((request->audio_type() == MEDIA_DEVICE_AUDIO_CAPTURE ||
1475 request->audio_type() == MEDIA_DEVICE_AUDIO_OUTPUT) &&
1476 request->video_type() == MEDIA_NO_SERVICE) ||
1477 (request->audio_type() == MEDIA_NO_SERVICE &&
1478 request->video_type() == MEDIA_DEVICE_VIDEO_CAPTURE));
1480 if (request->security_origin.is_valid()) {
1481 for (StreamDeviceInfoArray::iterator it = request->devices.begin();
1482 it != request->devices.end(); ++it) {
1483 TranslateDeviceIdToSourceId(request, &it->device);
1486 request->devices.clear();
1491 fake_ui_.reset(new FakeMediaStreamUIProxy());
1492 request->ui_proxy = fake_ui_.Pass();
1494 request->ui_proxy = MediaStreamUIProxy::Create();
1497 // Output label permissions are based on input permission.
1498 MediaStreamType type =
1499 request->audio_type() == MEDIA_DEVICE_AUDIO_CAPTURE ||
1500 request->audio_type() == MEDIA_DEVICE_AUDIO_OUTPUT
1501 ? MEDIA_DEVICE_AUDIO_CAPTURE
1502 : MEDIA_DEVICE_VIDEO_CAPTURE;
1504 request->ui_proxy->CheckAccess(
1505 request->security_origin,
1507 request->requesting_process_id,
1508 request->requesting_frame_id,
1509 base::Bind(&MediaStreamManager::HandleCheckMediaAccessResponse,
1510 base::Unretained(this),
1514 void MediaStreamManager::HandleCheckMediaAccessResponse(
1515 const std::string& label,
1517 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1519 DeviceRequest* request = FindRequest(label);
1521 // This can happen if the request was cancelled.
1522 DVLOG(1) << "The request with label " << label << " does not exist.";
1527 ClearDeviceLabels(&request->devices);
1529 request->requester->DevicesEnumerated(
1530 request->requesting_frame_id,
1531 request->page_request_id,
1536 // Ideally enumeration requests should be deleted once they have been served
1537 // (as any request). However, this implementation mixes requests and
1538 // notifications together so enumeration requests are kept open by some
1539 // implementations (only Pepper?) and enumerations are done again when
1540 // device notifications are fired.
1541 // Implementations that just want to request the device list and be done
1542 // (e.g. DeviceRequestMessageFilter), they must (confusingly) call
1543 // CancelRequest() after the request has been fulfilled. This is not
1544 // obvious, not consistent in this class (see e.g. FinalizeMediaAccessRequest)
1545 // and can lead to subtle bugs (requests not deleted at all deleted too
1548 // Basically, it is not clear that using requests as an additional layer on
1549 // top of device notifications is necessary or good.
1551 // To add to this, MediaStreamManager currently relies on the external
1552 // implementations of MediaStreamRequester to delete enumeration requests via
1553 // CancelRequest and e.g. DeviceRequestMessageFilter does this. However the
1554 // Pepper implementation does not seem to to this at all (and from what I can
1555 // see, it is the only implementation that uses an enumeration request as a
1556 // notification mechanism).
1558 // We should decouple notifications from enumeration requests and once that
1559 // has been done, remove the requirement to call CancelRequest() to delete
1560 // enumeration requests and uncomment the following line:
1562 // DeleteRequest(label);
1565 void MediaStreamManager::FinalizeMediaAccessRequest(
1566 const std::string& label,
1567 DeviceRequest* request,
1568 const MediaStreamDevices& devices) {
1569 if (!request->callback.is_null())
1570 request->callback.Run(devices, request->ui_proxy.Pass());
1572 // Delete the request since it is done.
1573 DeleteRequest(label);
1576 void MediaStreamManager::InitializeDeviceManagersOnIOThread() {
1577 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1578 if (device_task_runner_.get())
1581 device_task_runner_ = audio_manager_->GetWorkerTaskRunner();
1583 audio_input_device_manager_ = new AudioInputDeviceManager(audio_manager_);
1584 audio_input_device_manager_->Register(this, device_task_runner_);
1586 // We want to be notified of IO message loop destruction to delete the thread
1587 // and the device managers.
1588 io_loop_ = base::MessageLoop::current();
1589 io_loop_->AddDestructionObserver(this);
1591 if (CommandLine::ForCurrentProcess()->HasSwitch(
1592 switches::kUseFakeDeviceForMediaStream)) {
1593 audio_input_device_manager()->UseFakeDevice();
1596 video_capture_manager_ =
1597 new VideoCaptureManager(media::VideoCaptureDeviceFactory::CreateFactory(
1598 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)));
1599 video_capture_manager_->Register(this, device_task_runner_);
1602 void MediaStreamManager::Opened(MediaStreamType stream_type,
1603 int capture_session_id) {
1604 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1605 DVLOG(1) << "Opened({stream_type = " << stream_type << "} "
1606 << "{capture_session_id = " << capture_session_id << "})";
1607 // Find the request(s) containing this device and mark it as used.
1608 // It can be used in several requests since the same device can be
1609 // requested from the same web page.
1610 for (DeviceRequests::iterator request_it = requests_.begin();
1611 request_it != requests_.end(); ++request_it) {
1612 const std::string& label = request_it->first;
1613 DeviceRequest* request = request_it->second;
1614 StreamDeviceInfoArray* devices = &(request->devices);
1615 for (StreamDeviceInfoArray::iterator device_it = devices->begin();
1616 device_it != devices->end(); ++device_it) {
1617 if (device_it->device.type == stream_type &&
1618 device_it->session_id == capture_session_id) {
1619 CHECK(request->state(device_it->device.type) ==
1620 MEDIA_REQUEST_STATE_OPENING);
1621 // We've found a matching request.
1622 request->SetState(device_it->device.type, MEDIA_REQUEST_STATE_DONE);
1624 if (IsAudioInputMediaType(device_it->device.type)) {
1625 // Store the native audio parameters in the device struct.
1626 // TODO(xians): Handle the tab capture sample rate/channel layout
1627 // in AudioInputDeviceManager::Open().
1628 if (device_it->device.type != content::MEDIA_TAB_AUDIO_CAPTURE) {
1629 const StreamDeviceInfo* info =
1630 audio_input_device_manager_->GetOpenedDeviceInfoById(
1631 device_it->session_id);
1632 device_it->device.input = info->device.input;
1634 // Since the audio input device manager will set the input
1635 // parameters to the default settings (including supported effects),
1636 // we need to adjust those settings here according to what the
1637 // request asks for.
1638 FilterAudioEffects(request->options,
1639 &device_it->device.input.effects);
1641 device_it->device.matched_output = info->device.matched_output;
1644 if (RequestDone(*request))
1645 HandleRequestDone(label, request);
1652 void MediaStreamManager::HandleRequestDone(const std::string& label,
1653 DeviceRequest* request) {
1654 DCHECK(RequestDone(*request));
1655 DVLOG(1) << "HandleRequestDone("
1656 << ", {label = " << label << "})";
1658 switch (request->request_type) {
1659 case MEDIA_OPEN_DEVICE:
1660 FinalizeOpenDevice(label, request);
1662 case MEDIA_GENERATE_STREAM: {
1663 FinalizeGenerateStream(label, request);
1671 if (request->ui_proxy.get()) {
1672 request->ui_proxy->OnStarted(
1673 base::Bind(&MediaStreamManager::StopMediaStreamFromBrowser,
1674 base::Unretained(this),
1676 base::Bind(&MediaStreamManager::OnMediaStreamUIWindowId,
1677 base::Unretained(this),
1678 request->video_type(),
1683 void MediaStreamManager::Closed(MediaStreamType stream_type,
1684 int capture_session_id) {
1685 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1688 void MediaStreamManager::DevicesEnumerated(
1689 MediaStreamType stream_type, const StreamDeviceInfoArray& devices) {
1690 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1691 DVLOG(1) << "DevicesEnumerated("
1692 << "{stream_type = " << stream_type << "})" << std::endl;
1694 std::string log_message = "New device enumeration result:\n" +
1695 GetLogMessageString(stream_type, devices);
1696 SendMessageToNativeLog(log_message);
1698 // Only cache the device list when the device list has been changed.
1699 bool need_update_clients = false;
1700 EnumerationCache* cache =
1701 stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ?
1702 &audio_enumeration_cache_ : &video_enumeration_cache_;
1703 if (!cache->valid ||
1704 devices.size() != cache->devices.size() ||
1705 !std::equal(devices.begin(), devices.end(), cache->devices.begin(),
1706 StreamDeviceInfo::IsEqual)) {
1707 StopRemovedDevices(cache->devices, devices);
1708 cache->devices = devices;
1709 need_update_clients = true;
1711 // The device might not be able to be enumerated when it is not warmed up,
1712 // for example, when the machine just wakes up from sleep. We set the cache
1713 // to be invalid so that the next media request will trigger the
1714 // enumeration again. See issue/317673.
1715 cache->valid = !devices.empty();
1718 if (need_update_clients && monitoring_started_)
1719 NotifyDevicesChanged(stream_type, devices);
1721 // Publish the result for all requests waiting for device list(s).
1722 // Find the requests waiting for this device list, store their labels and
1723 // release the iterator before calling device settings. We might get a call
1724 // back from device_settings that will need to iterate through devices.
1725 std::list<std::string> label_list;
1726 for (DeviceRequests::iterator it = requests_.begin(); it != requests_.end();
1728 if (it->second->state(stream_type) == MEDIA_REQUEST_STATE_REQUESTED &&
1729 (it->second->audio_type() == stream_type ||
1730 it->second->video_type() == stream_type)) {
1731 if (it->second->request_type != MEDIA_ENUMERATE_DEVICES)
1732 it->second->SetState(stream_type, MEDIA_REQUEST_STATE_PENDING_APPROVAL);
1733 label_list.push_back(it->first);
1737 for (std::list<std::string>::iterator it = label_list.begin();
1738 it != label_list.end(); ++it) {
1739 DeviceRequest* request = FindRequest(*it);
1740 switch (request->request_type) {
1741 case MEDIA_ENUMERATE_DEVICES:
1742 if (need_update_clients && request->requester) {
1743 request->devices = devices;
1744 FinalizeEnumerateDevices(*it, request);
1748 if (request->state(request->audio_type()) ==
1749 MEDIA_REQUEST_STATE_REQUESTED ||
1750 request->state(request->video_type()) ==
1751 MEDIA_REQUEST_STATE_REQUESTED) {
1752 // We are doing enumeration for other type of media, wait until it is
1753 // all done before posting the request to UI because UI needs
1754 // the device lists to handle the request.
1757 if (!SetupDeviceCaptureRequest(request)) {
1758 FinalizeRequestFailed(*it,
1760 MEDIA_DEVICE_NO_HARDWARE);
1762 PostRequestToUI(*it, request);
1768 --active_enumeration_ref_count_[stream_type];
1769 DCHECK_GE(active_enumeration_ref_count_[stream_type], 0);
1772 void MediaStreamManager::Aborted(MediaStreamType stream_type,
1773 int capture_session_id) {
1774 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1775 DVLOG(1) << "Aborted({stream_type = " << stream_type << "} "
1776 << "{capture_session_id = " << capture_session_id << "})";
1777 StopDevice(stream_type, capture_session_id);
1781 void MediaStreamManager::SendMessageToNativeLog(const std::string& message) {
1782 BrowserThread::PostTask(
1783 BrowserThread::UI, FROM_HERE,
1784 base::Bind(DoAddLogMessage, message));
1787 void MediaStreamManager::OnSuspend() {
1788 SendMessageToNativeLog("Power state suspended.");
1791 void MediaStreamManager::OnResume() {
1792 SendMessageToNativeLog("Power state resumed.");
1795 void MediaStreamManager::AddLogMessageOnIOThread(const std::string& message) {
1796 // Get render process ids on the IO thread.
1797 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1799 // Grab all unique process ids that request a MediaStream or have a
1800 // MediaStream running.
1801 std::set<int> requesting_process_ids;
1802 for (DeviceRequests::const_iterator it = requests_.begin();
1803 it != requests_.end(); ++it) {
1804 DeviceRequest* request = it->second;
1805 if (request->request_type == MEDIA_GENERATE_STREAM)
1806 requesting_process_ids.insert(request->requesting_process_id);
1809 // MediaStreamManager is a singleton in BrowserMainLoop, which owns the UI
1810 // thread. MediaStreamManager has the same lifetime as the UI thread, so it is
1811 // safe to use base::Unretained.
1812 BrowserThread::PostTask(
1815 base::Bind(&MediaStreamManager::AddLogMessageOnUIThread,
1816 base::Unretained(this),
1817 requesting_process_ids,
1821 void MediaStreamManager::AddLogMessageOnUIThread(
1822 const std::set<int>& requesting_process_ids,
1823 const std::string& message) {
1824 #if defined(ENABLE_WEBRTC)
1825 // Must be on the UI thread to access RenderProcessHost from process ID.
1826 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1828 for (std::set<int>::const_iterator it = requesting_process_ids.begin();
1829 it != requesting_process_ids.end(); ++it) {
1830 // Log the message to all renderers that are requesting a MediaStream or
1831 // have a MediaStream running.
1832 content::RenderProcessHostImpl* render_process_host_impl =
1833 static_cast<content::RenderProcessHostImpl*>(
1834 content::RenderProcessHost::FromID(*it));
1835 if (render_process_host_impl)
1836 render_process_host_impl->WebRtcLogMessage(message);
1841 void MediaStreamManager::HandleAccessRequestResponse(
1842 const std::string& label,
1843 const MediaStreamDevices& devices,
1844 content::MediaStreamRequestResult result) {
1845 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1846 DVLOG(1) << "HandleAccessRequestResponse("
1847 << ", {label = " << label << "})";
1849 DeviceRequest* request = FindRequest(label);
1851 // The request has been canceled before the UI returned.
1855 if (request->request_type == MEDIA_DEVICE_ACCESS) {
1856 FinalizeMediaAccessRequest(label, request, devices);
1860 // Handle the case when the request was denied.
1861 if (result != MEDIA_DEVICE_OK) {
1862 FinalizeRequestFailed(label, request, result);
1865 DCHECK(!devices.empty());
1867 // Process all newly-accepted devices for this request.
1868 bool found_audio = false;
1869 bool found_video = false;
1870 for (MediaStreamDevices::const_iterator device_it = devices.begin();
1871 device_it != devices.end(); ++device_it) {
1872 StreamDeviceInfo device_info;
1873 device_info.device = *device_it;
1875 if (device_info.device.type == content::MEDIA_TAB_VIDEO_CAPTURE ||
1876 device_info.device.type == content::MEDIA_TAB_AUDIO_CAPTURE) {
1877 device_info.device.id = request->UIRequest()->tab_capture_device_id;
1879 // Initialize the sample_rate and channel_layout here since for audio
1880 // mirroring, we don't go through EnumerateDevices where these are usually
1882 if (device_info.device.type == content::MEDIA_TAB_AUDIO_CAPTURE) {
1883 const media::AudioParameters parameters =
1884 audio_manager_->GetDefaultOutputStreamParameters();
1885 int sample_rate = parameters.sample_rate();
1886 // If we weren't able to get the native sampling rate or the sample_rate
1887 // is outside the valid range for input devices set reasonable defaults.
1888 if (sample_rate <= 0 || sample_rate > 96000)
1889 sample_rate = 44100;
1891 device_info.device.input.sample_rate = sample_rate;
1892 device_info.device.input.channel_layout = media::CHANNEL_LAYOUT_STEREO;
1896 if (device_info.device.type == request->audio_type()) {
1898 } else if (device_info.device.type == request->video_type()) {
1902 // If this is request for a new MediaStream, a device is only opened once
1903 // per render frame. This is so that the permission to use a device can be
1904 // revoked by a single call to StopStreamDevice regardless of how many
1905 // MediaStreams it is being used in.
1906 if (request->request_type == MEDIA_GENERATE_STREAM) {
1907 MediaRequestState state;
1908 if (FindExistingRequestedDeviceInfo(*request,
1912 request->devices.push_back(device_info);
1913 request->SetState(device_info.device.type, state);
1914 DVLOG(1) << "HandleAccessRequestResponse - device already opened "
1915 << ", {label = " << label << "}"
1916 << ", device_id = " << device_it->id << "}";
1920 device_info.session_id =
1921 GetDeviceManager(device_info.device.type)->Open(device_info);
1922 TranslateDeviceIdToSourceId(request, &device_info.device);
1923 request->devices.push_back(device_info);
1925 request->SetState(device_info.device.type, MEDIA_REQUEST_STATE_OPENING);
1926 DVLOG(1) << "HandleAccessRequestResponse - opening device "
1927 << ", {label = " << label << "}"
1928 << ", {device_id = " << device_info.device.id << "}"
1929 << ", {session_id = " << device_info.session_id << "}";
1932 // Check whether we've received all stream types requested.
1933 if (!found_audio && IsAudioInputMediaType(request->audio_type())) {
1934 request->SetState(request->audio_type(), MEDIA_REQUEST_STATE_ERROR);
1935 DVLOG(1) << "Set no audio found label " << label;
1938 if (!found_video && IsVideoMediaType(request->video_type()))
1939 request->SetState(request->video_type(), MEDIA_REQUEST_STATE_ERROR);
1941 if (RequestDone(*request))
1942 HandleRequestDone(label, request);
1945 void MediaStreamManager::StopMediaStreamFromBrowser(const std::string& label) {
1946 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1948 DeviceRequest* request = FindRequest(label);
1952 // Notify renderers that the devices in the stream will be stopped.
1953 if (request->requester) {
1954 for (StreamDeviceInfoArray::iterator device_it = request->devices.begin();
1955 device_it != request->devices.end(); ++device_it) {
1956 request->requester->DeviceStopped(request->requesting_frame_id,
1962 CancelRequest(label);
1965 void MediaStreamManager::UseFakeUI(scoped_ptr<FakeMediaStreamUIProxy> fake_ui) {
1966 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1967 use_fake_ui_ = true;
1968 fake_ui_ = fake_ui.Pass();
1971 void MediaStreamManager::WillDestroyCurrentMessageLoop() {
1972 DVLOG(3) << "MediaStreamManager::WillDestroyCurrentMessageLoop()";
1973 DCHECK_EQ(base::MessageLoop::current(), io_loop_);
1974 DCHECK(requests_.empty());
1975 if (device_task_runner_.get()) {
1978 video_capture_manager_->Unregister();
1979 audio_input_device_manager_->Unregister();
1980 device_task_runner_ = NULL;
1983 audio_input_device_manager_ = NULL;
1984 video_capture_manager_ = NULL;
1987 void MediaStreamManager::NotifyDevicesChanged(
1988 MediaStreamType stream_type,
1989 const StreamDeviceInfoArray& devices) {
1990 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1991 MediaObserver* media_observer =
1992 GetContentClient()->browser()->GetMediaObserver();
1994 // Map the devices to MediaStreamDevices.
1995 MediaStreamDevices new_devices;
1996 for (StreamDeviceInfoArray::const_iterator it = devices.begin();
1997 it != devices.end(); ++it) {
1998 new_devices.push_back(it->device);
2001 if (IsAudioInputMediaType(stream_type)) {
2002 MediaCaptureDevicesImpl::GetInstance()->OnAudioCaptureDevicesChanged(
2005 media_observer->OnAudioCaptureDevicesChanged();
2006 } else if (IsVideoMediaType(stream_type)) {
2007 MediaCaptureDevicesImpl::GetInstance()->OnVideoCaptureDevicesChanged(
2010 media_observer->OnVideoCaptureDevicesChanged();
2016 bool MediaStreamManager::RequestDone(const DeviceRequest& request) const {
2017 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2019 const bool requested_audio = IsAudioInputMediaType(request.audio_type());
2020 const bool requested_video = IsVideoMediaType(request.video_type());
2022 const bool audio_done =
2024 request.state(request.audio_type()) == MEDIA_REQUEST_STATE_DONE ||
2025 request.state(request.audio_type()) == MEDIA_REQUEST_STATE_ERROR;
2029 const bool video_done =
2031 request.state(request.video_type()) == MEDIA_REQUEST_STATE_DONE ||
2032 request.state(request.video_type()) == MEDIA_REQUEST_STATE_ERROR;
2039 MediaStreamProvider* MediaStreamManager::GetDeviceManager(
2040 MediaStreamType stream_type) {
2041 if (IsVideoMediaType(stream_type)) {
2042 return video_capture_manager();
2043 } else if (IsAudioInputMediaType(stream_type)) {
2044 return audio_input_device_manager();
2050 void MediaStreamManager::OnDevicesChanged(
2051 base::SystemMonitor::DeviceType device_type) {
2052 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2054 // NOTE: This method is only called in response to physical audio/video device
2055 // changes (from the operating system).
2057 MediaStreamType stream_type;
2058 if (device_type == base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE) {
2059 stream_type = MEDIA_DEVICE_AUDIO_CAPTURE;
2060 } else if (device_type == base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE) {
2061 stream_type = MEDIA_DEVICE_VIDEO_CAPTURE;
2063 return; // Uninteresting device change.
2066 // Always do enumeration even though some enumeration is in progress,
2067 // because those enumeration commands could be sent before these devices
2069 ++active_enumeration_ref_count_[stream_type];
2070 GetDeviceManager(stream_type)->EnumerateDevices(stream_type);
2073 void MediaStreamManager::OnMediaStreamUIWindowId(MediaStreamType video_type,
2074 StreamDeviceInfoArray devices,
2075 gfx::NativeViewId window_id) {
2076 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2080 // Pass along for desktop capturing. Ignored for other stream types.
2081 if (video_type == MEDIA_DESKTOP_VIDEO_CAPTURE) {
2082 for (StreamDeviceInfoArray::iterator it = devices.begin();
2083 it != devices.end();
2085 if (it->device.type == MEDIA_DESKTOP_VIDEO_CAPTURE) {
2086 video_capture_manager_->SetDesktopCaptureWindowId(it->session_id,
2094 #if defined(OS_CHROMEOS)
2095 void MediaStreamManager::EnsureKeyboardMicChecked() {
2096 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2097 if (!has_checked_keyboard_mic_) {
2098 has_checked_keyboard_mic_ = true;
2099 BrowserThread::PostTask(
2100 BrowserThread::UI, FROM_HERE,
2101 base::Bind(&MediaStreamManager::CheckKeyboardMicOnUIThread,
2102 base::Unretained(this)));
2106 void MediaStreamManager::CheckKeyboardMicOnUIThread() {
2107 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2109 // We will post this on the device thread before the media media access
2110 // request is posted on the UI thread, so setting the keyboard mic info will
2111 // be done before any stream is created.
2112 if (chromeos::CrasAudioHandler::Get()->HasKeyboardMic()) {
2113 device_task_runner_->PostTask(
2115 base::Bind(&MediaStreamManager::SetKeyboardMicOnDeviceThread,
2116 base::Unretained(this)));
2120 void MediaStreamManager::SetKeyboardMicOnDeviceThread() {
2121 DCHECK(device_task_runner_->BelongsToCurrentThread());
2122 audio_manager_->SetHasKeyboardMic();
2126 } // namespace content