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 // MediaStreamManager is used to open/enumerate media capture devices (video
6 // supported now). Call flow:
7 // 1. GenerateStream is called when a render process wants to use a capture
9 // 2. MediaStreamManager will ask MediaStreamUIController for permission to
10 // use devices and for which device to use.
11 // 3. MediaStreamManager will request the corresponding media device manager(s)
12 // to enumerate available devices. The result will be given to
13 // MediaStreamUIController.
14 // 4. MediaStreamUIController will, by posting the request to UI, let the
15 // users to select which devices to use and send callback to
16 // MediaStreamManager with the result.
17 // 5. MediaStreamManager will call the proper media device manager to open the
18 // device and let the MediaStreamRequester know it has been done.
20 // If either user or test harness selects --use-fake-device-for-media-stream,
21 // a fake video device or devices are used instead of real ones.
23 // When enumeration and open are done in separate operations,
24 // MediaStreamUIController is not involved as in steps.
26 #ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
27 #define CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
33 #include "base/basictypes.h"
34 #include "base/memory/ref_counted.h"
35 #include "base/memory/scoped_ptr.h"
36 #include "base/message_loop/message_loop.h"
37 #include "base/power_monitor/power_observer.h"
38 #include "base/system_monitor/system_monitor.h"
39 #include "content/browser/renderer_host/media/media_stream_provider.h"
40 #include "content/common/content_export.h"
41 #include "content/common/media/media_stream_options.h"
42 #include "content/public/browser/media_request_state.h"
43 #include "content/public/browser/resource_context.h"
51 class AudioInputDeviceManager
;
52 class FakeMediaStreamUIProxy
;
53 class MediaStreamDeviceSettings
;
54 class MediaStreamRequester
;
55 class MediaStreamUIProxy
;
56 class VideoCaptureManager
;
58 // MediaStreamManager is used to generate and close new media devices, not to
59 // start the media flow. The classes requesting new media streams are answered
60 // using MediaStreamRequester.
61 class CONTENT_EXPORT MediaStreamManager
62 : public MediaStreamProviderListener
,
63 public base::MessageLoop::DestructionObserver
,
64 public base::PowerObserver
,
65 public base::SystemMonitor::DevicesChangedObserver
{
67 // Callback to deliver the result of a media request.
68 typedef base::Callback
<void(const MediaStreamDevices
& devices
,
69 scoped_ptr
<MediaStreamUIProxy
> ui
)>
70 MediaRequestResponseCallback
;
72 explicit MediaStreamManager(media::AudioManager
* audio_manager
);
73 virtual ~MediaStreamManager();
75 // Used to access VideoCaptureManager.
76 VideoCaptureManager
* video_capture_manager();
78 // Used to access AudioInputDeviceManager.
79 AudioInputDeviceManager
* audio_input_device_manager();
81 // Creates a new media access request which is identified by a unique string
82 // that's returned to the caller. This will trigger the infobar and ask users
83 // for access to the device. |render_process_id| and |render_view_id| refer
84 // to the view where the infobar will appear to the user. |callback| is
85 // used to send the selected device to the clients. An empty list of device
86 // will be returned if the users deny the access.
87 std::string
MakeMediaAccessRequest(
88 int render_process_id
,
91 const StreamOptions
& options
,
92 const GURL
& security_origin
,
93 const MediaRequestResponseCallback
& callback
);
95 // GenerateStream opens new media devices according to |components|. It
96 // creates a new request which is identified by a unique string that's
97 // returned to the caller. |render_process_id| and |render_view_id| refer to
98 // the view where the infobar will appear to the user.
99 void GenerateStream(MediaStreamRequester
* requester
,
100 int render_process_id
,
102 const ResourceContext::SaltCallback
& sc
,
104 const StreamOptions
& components
,
105 const GURL
& security_origin
,
108 void CancelRequest(int render_process_id
,
110 int page_request_id
);
112 // Cancel an open request identified by |label|.
113 virtual void CancelRequest(const std::string
& label
);
115 // Cancel all requests for the given |render_process_id|.
116 void CancelAllRequests(int render_process_id
);
118 // Closes the stream device for a certain render view. The stream must have
119 // been opened by a call to GenerateStream.
120 void StopStreamDevice(int render_process_id
,
122 const std::string
& device_id
);
124 // Gets a list of devices of |type|, which must be MEDIA_DEVICE_AUDIO_CAPTURE
125 // or MEDIA_DEVICE_VIDEO_CAPTURE.
126 // The request is identified using the string returned to the caller.
127 // When the |requester| is NULL, MediaStreamManager will enumerate both audio
128 // and video devices and also start monitoring device changes, such as
129 // plug/unplug. The new device lists will be delivered via media observer to
130 // MediaCaptureDevicesDispatcher.
131 virtual std::string
EnumerateDevices(MediaStreamRequester
* requester
,
132 int render_process_id
,
134 const ResourceContext::SaltCallback
& sc
,
136 MediaStreamType type
,
137 const GURL
& security_origin
);
139 // Open a device identified by |device_id|. |type| must be either
140 // MEDIA_DEVICE_AUDIO_CAPTURE or MEDIA_DEVICE_VIDEO_CAPTURE.
141 // The request is identified using string returned to the caller.
142 void OpenDevice(MediaStreamRequester
* requester
,
143 int render_process_id
,
145 const ResourceContext::SaltCallback
& sc
,
147 const std::string
& device_id
,
148 MediaStreamType type
,
149 const GURL
& security_origin
);
151 // Finds and returns the device id corresponding to the given
152 // |source_id|. Returns true if there was a raw device id that matched the
153 // given |source_id|, false if nothing matched it.
154 bool TranslateSourceIdToDeviceId(
155 MediaStreamType stream_type
,
156 const ResourceContext::SaltCallback
& rc
,
157 const GURL
& security_origin
,
158 const std::string
& source_id
,
159 std::string
* device_id
) const;
161 // Called by UI to make sure the device monitor is started so that UI receive
162 // notifications about device changes.
163 void EnsureDeviceMonitorStarted();
165 // Implements MediaStreamProviderListener.
166 virtual void Opened(MediaStreamType stream_type
,
167 int capture_session_id
) OVERRIDE
;
168 virtual void Closed(MediaStreamType stream_type
,
169 int capture_session_id
) OVERRIDE
;
170 virtual void DevicesEnumerated(MediaStreamType stream_type
,
171 const StreamDeviceInfoArray
& devices
) OVERRIDE
;
172 virtual void Aborted(MediaStreamType stream_type
,
173 int capture_session_id
) OVERRIDE
;
175 // Implements base::SystemMonitor::DevicesChangedObserver.
176 virtual void OnDevicesChanged(
177 base::SystemMonitor::DeviceType device_type
) OVERRIDE
;
179 // Called by the tests to specify a fake UI that should be used for next
180 // generated stream (or when using --use-fake-ui-for-media-stream).
181 void UseFakeUI(scoped_ptr
<FakeMediaStreamUIProxy
> fake_ui
);
183 // Returns all devices currently opened by a request with label |label|.
184 // If no request with |label| exist, an empty array is returned.
185 StreamDeviceInfoArray
GetDevicesOpenedByRequest(
186 const std::string
& label
) const;
188 // This object gets deleted on the UI thread after the IO thread has been
189 // destroyed. So we need to know when IO thread is being destroyed so that
190 // we can delete VideoCaptureManager and AudioInputDeviceManager. Normally
191 // this is handled by
192 // base::MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop.
193 // But for some tests which use TestBrowserThreadBundle, we need to call
194 // WillDestroyCurrentMessageLoop explicitly because the notification happens
195 // too late. (see http://crbug.com/247525#c14).
196 virtual void WillDestroyCurrentMessageLoop() OVERRIDE
;
198 // Sends log messages to the render process hosts whose corresponding render
199 // processes are making device requests, to be used by the
200 // webrtcLoggingPrivate API if requested.
201 void AddLogMessageOnIOThread(const std::string
& message
);
203 // Adds |message| to native logs for outstanding device requests, for use by
204 // render processes hosts whose corresponding render processes are requesting
205 // logging from webrtcLoggingPrivate API. Safe to call from any thread.
206 static void SendMessageToNativeLog(const std::string
& message
);
208 // base::PowerObserver overrides.
209 virtual void OnSuspend() OVERRIDE
;
210 virtual void OnResume() OVERRIDE
;
214 MediaStreamManager();
217 // Contains all data needed to keep track of requests.
220 // Cache enumerated device list.
221 struct EnumerationCache
{
226 StreamDeviceInfoArray devices
;
229 typedef std::map
<std::string
, DeviceRequest
*> DeviceRequests
;
231 // Initializes the device managers on IO thread. Auto-starts the device
232 // thread and registers this as a listener with the device managers.
233 void InitializeDeviceManagersOnIOThread();
235 // Helper for sending up-to-date device lists to media observer when a
236 // capture device is plugged in or unplugged.
237 void NotifyDevicesChanged(MediaStreamType stream_type
,
238 const StreamDeviceInfoArray
& devices
);
240 void HandleAccessRequestResponse(const std::string
& label
,
241 const MediaStreamDevices
& devices
,
242 content::MediaStreamRequestResult result
);
243 void StopMediaStreamFromBrowser(const std::string
& label
);
245 void DoEnumerateDevices(const std::string
& label
);
248 // Checks if all devices that was requested in the request identififed by
249 // |label| has been opened and set the request state accordingly.
250 void HandleRequestDone(const std::string
& label
,
251 DeviceRequest
* request
);
252 // Stop the use of the device associated with |session_id| of type |type| in
253 // all |requests_|. The device is removed from the request. If a request
254 /// doesn't use any devices as a consequence, the request is deleted.
255 void StopDevice(MediaStreamType type
, int session_id
);
256 // Calls the correct capture manager and close the device with |session_id|.
257 // All requests that uses the device are updated.
258 void CloseDevice(MediaStreamType type
, int session_id
);
259 // Returns true if a request for devices has been completed and the devices
260 // has either been opened or an error has occurred.
261 bool RequestDone(const DeviceRequest
& request
) const;
262 MediaStreamProvider
* GetDeviceManager(MediaStreamType stream_type
);
263 void StartEnumeration(DeviceRequest
* request
);
264 std::string
AddRequest(DeviceRequest
* request
);
265 DeviceRequest
* FindRequest(const std::string
& label
) const;
266 void DeleteRequest(const std::string
& label
);
267 void ClearEnumerationCache(EnumerationCache
* cache
);
268 // Returns true if the |cache| is invalid, false if it's invalid or if
269 // the |stream_type| is MEDIA_NO_SERVICE.
270 // On Android, this function will always return true for
271 // MEDIA_DEVICE_AUDIO_CAPTURE since we don't have a SystemMonitor to tell
272 // us about audio device changes.
273 bool EnumerationRequired(EnumerationCache
* cache
, MediaStreamType type
);
274 // Prepare the request with label |label| by starting device enumeration if
276 void SetupRequest(const std::string
& label
);
277 // Prepare |request| of type MEDIA_DEVICE_AUDIO_CAPTURE and/or
278 // MEDIA_DEVICE_VIDEO_CAPTURE for being posted to the UI by parsing
279 // StreamOptions::Constraints for requested device IDs.
280 bool SetupDeviceCaptureRequest(DeviceRequest
* request
);
281 // Prepare |request| of type MEDIA_TAB_AUDIO_CAPTURE and/or
282 // MEDIA_TAB_VIDEO_CAPTURE for being posted to the UI by parsing
283 // StreamOptions::Constraints for requested tab capture IDs.
284 bool SetupTabCaptureRequest(DeviceRequest
* request
);
285 // Prepare |request| of type MEDIA_LOOPBACK_AUDIO_CAPTURE and/or
286 // MEDIA_DESKTOP_VIDEO_CAPTURE for being posted to the UI by parsing
287 // StreamOptions::Constraints for the requested desktop ID.
288 bool SetupScreenCaptureRequest(DeviceRequest
* request
);
289 // Called when a request has been setup and devices have been enumerated if
291 void PostRequestToUI(const std::string
& label
, DeviceRequest
* request
);
292 // Returns true if a device with |device_id| has already been requested with
293 // a render procecss_id and render_view_id and type equal to the the values
294 // in |request|. If it has been requested, |device_info| contain information
296 bool FindExistingRequestedDeviceInfo(
297 const DeviceRequest
& new_request
,
298 const MediaStreamDevice
& new_device_info
,
299 StreamDeviceInfo
* existing_device_info
,
300 MediaRequestState
* existing_request_state
) const;
302 void FinalizeGenerateStream(const std::string
& label
,
303 DeviceRequest
* request
);
304 void FinalizeRequestFailed(const std::string
& label
,
305 DeviceRequest
* request
,
306 content::MediaStreamRequestResult result
);
307 void FinalizeOpenDevice(const std::string
& label
,
308 DeviceRequest
* request
);
309 void FinalizeMediaAccessRequest(const std::string
& label
,
310 DeviceRequest
* request
,
311 const MediaStreamDevices
& devices
);
312 void FinalizeEnumerateDevices(const std::string
& label
,
313 DeviceRequest
* request
);
315 // This method is called when an audio or video device is plugged in or
316 // removed. It make sure all MediaStreams that use a removed device is
317 // stopped and that the render process is notified. |old_devices| is the list
318 // of previously available devices. |new_devices| is the new
319 // list of currently available devices.
320 void StopRemovedDevices(const StreamDeviceInfoArray
& old_devices
,
321 const StreamDeviceInfoArray
& new_devices
);
322 // Helper method used by StopRemovedDevices to stop the use of a certain
324 void StopRemovedDevice(const MediaStreamDevice
& device
);
326 // Helpers to start and stop monitoring devices.
327 void StartMonitoring();
328 void StopMonitoring();
329 #if defined(OS_MACOSX)
330 void StartMonitoringOnUIThread();
333 // Finds the requested device id from constraints. The requested device type
334 // must be MEDIA_DEVICE_AUDIO_CAPTURE or MEDIA_DEVICE_VIDEO_CAPTURE.
335 bool GetRequestedDeviceCaptureId(const DeviceRequest
* request
,
336 MediaStreamType type
,
337 std::string
* device_id
) const;
339 void TranslateDeviceIdToSourceId(DeviceRequest
* request
,
340 MediaStreamDevice
* device
);
342 // Helper method that sends log messages to the render process hosts whose
343 // corresponding render processes are in |render_process_ids|, to be used by
344 // the webrtcLoggingPrivate API if requested.
345 void AddLogMessageOnUIThread(const std::set
<int>& render_process_ids
,
346 const std::string
& message
);
348 // Handles the callback from MediaStreamUIProxy to receive the UI window id,
349 // used for excluding the notification window in desktop capturing.
350 void OnMediaStreamUIWindowId(MediaStreamType video_type
,
351 StreamDeviceInfoArray devices
,
352 gfx::NativeViewId window_id
);
354 // Task runner shared by VideoCaptureManager and AudioInputDeviceManager.
355 // Note: Enumeration tasks may take seconds to complete so must never be run
356 // on any of the BrowserThreads (UI, IO, etc). See http://crbug.com/256945.
357 scoped_refptr
<base::SingleThreadTaskRunner
> device_task_runner_
;
359 media::AudioManager
* const audio_manager_
; // not owned
360 scoped_refptr
<AudioInputDeviceManager
> audio_input_device_manager_
;
361 scoped_refptr
<VideoCaptureManager
> video_capture_manager_
;
363 // Indicator of device monitoring state.
364 bool monitoring_started_
;
366 // Stores most recently enumerated device lists. The cache is cleared when
367 // monitoring is stopped or there is no request for that type of device.
368 EnumerationCache audio_enumeration_cache_
;
369 EnumerationCache video_enumeration_cache_
;
371 // Keeps track of live enumeration commands sent to VideoCaptureManager or
372 // AudioInputDeviceManager, in order to only enumerate when necessary.
373 int active_enumeration_ref_count_
[NUM_MEDIA_TYPES
];
375 // All non-closed request. Must be accessed on IO thread.
376 DeviceRequests requests_
;
378 // Hold a pointer to the IO loop to check we delete the device thread and
379 // managers on the right thread.
380 base::MessageLoop
* io_loop_
;
383 scoped_ptr
<FakeMediaStreamUIProxy
> fake_ui_
;
385 DISALLOW_COPY_AND_ASSIGN(MediaStreamManager
);
388 } // namespace content
390 #endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_