media_stream_manager.h revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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.
4
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
8//    device.
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.
19
20// When enumeration and open are done in separate operations,
21// MediaStreamUIController is not involved as in steps.
22
23#ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
24#define CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
25
26#include <map>
27#include <string>
28
29#include "base/basictypes.h"
30#include "base/memory/ref_counted.h"
31#include "base/memory/scoped_ptr.h"
32#include "base/message_loop/message_loop.h"
33#include "base/system_monitor/system_monitor.h"
34#include "content/browser/renderer_host/media/media_stream_provider.h"
35#include "content/common/content_export.h"
36#include "content/common/media/media_stream_options.h"
37
38namespace base {
39class Thread;
40}
41
42namespace media {
43class AudioManager;
44}
45
46namespace content {
47
48class AudioInputDeviceManager;
49class FakeMediaStreamUIProxy;
50class MediaStreamDeviceSettings;
51class MediaStreamRequester;
52class MediaStreamUIProxy;
53class VideoCaptureManager;
54
55// MediaStreamManager is used to generate and close new media devices, not to
56// start the media flow. The classes requesting new media streams are answered
57// using MediaStreamRequester.
58class CONTENT_EXPORT MediaStreamManager
59    : public MediaStreamProviderListener,
60      public base::MessageLoop::DestructionObserver,
61      public base::SystemMonitor::DevicesChangedObserver {
62 public:
63  // Callback to deliver the result of a media request.
64  typedef base::Callback<void(const MediaStreamDevices& devices,
65                              scoped_ptr<MediaStreamUIProxy> ui)>
66      MediaRequestResponseCallback;
67
68  explicit MediaStreamManager(media::AudioManager* audio_manager);
69  virtual ~MediaStreamManager();
70
71  // Used to access VideoCaptureManager.
72  VideoCaptureManager* video_capture_manager();
73
74  // Used to access AudioInputDeviceManager.
75  AudioInputDeviceManager* audio_input_device_manager();
76
77  // Creates a new media access request which is identified by a unique string
78  // that's returned to the caller. This will trigger the infobar and ask users
79  // for access to the device. |render_process_id| and |render_view_id| refer
80  // to the view where the infobar will appear to the user. |callback| is
81  // used to send the selected device to the clients. An empty list of device
82  // will be returned if the users deny the access.
83  std::string MakeMediaAccessRequest(
84      int render_process_id,
85      int render_view_id,
86      int page_request_id,
87      const StreamOptions& components,
88      const GURL& security_origin,
89      const MediaRequestResponseCallback& callback);
90
91  // GenerateStream opens new media devices according to |components|.  It
92  // creates a new request which is identified by a unique string that's
93  // returned to the caller.  |render_process_id| and |render_view_id| refer to
94  // the view where the infobar will appear to the user.
95  std::string GenerateStream(MediaStreamRequester* requester,
96                             int render_process_id,
97                             int render_view_id,
98                             int page_request_id,
99                             const StreamOptions& components,
100                             const GURL& security_origin);
101
102  void CancelRequest(const std::string& label);
103
104  // Closes generated stream.
105  virtual void StopGeneratedStream(const std::string& label);
106
107  // Gets a list of devices of |type|, which must be MEDIA_DEVICE_AUDIO_CAPTURE
108  // or MEDIA_DEVICE_VIDEO_CAPTURE.
109  // The request is identified using the string returned to the caller.
110  // When the |requester| is NULL, MediaStreamManager will enumerate both audio
111  // and video devices and also start monitoring device changes, such as
112  // plug/unplug. The new device lists will be delivered via media observer to
113  // MediaCaptureDevicesDispatcher.
114  virtual std::string EnumerateDevices(MediaStreamRequester* requester,
115                                       int render_process_id,
116                                       int render_view_id,
117                                       int page_request_id,
118                                       MediaStreamType type,
119                                       const GURL& security_origin);
120
121  // Open a device identified by |device_id|.  |type| must be either
122  // MEDIA_DEVICE_AUDIO_CAPTURE or MEDIA_DEVICE_VIDEO_CAPTURE.
123  // The request is identified using string returned to the caller.
124  std::string OpenDevice(MediaStreamRequester* requester,
125                         int render_process_id,
126                         int render_view_id,
127                         int page_request_id,
128                         const std::string& device_id,
129                         MediaStreamType type,
130                         const GURL& security_origin);
131
132  // Implements MediaStreamProviderListener.
133  virtual void Opened(MediaStreamType stream_type,
134                      int capture_session_id) OVERRIDE;
135  virtual void Closed(MediaStreamType stream_type,
136                      int capture_session_id) OVERRIDE;
137  virtual void DevicesEnumerated(MediaStreamType stream_type,
138                                 const StreamDeviceInfoArray& devices) OVERRIDE;
139  virtual void Error(MediaStreamType stream_type,
140                     int capture_session_id,
141                     MediaStreamProviderError error) OVERRIDE;
142
143  // Implements base::SystemMonitor::DevicesChangedObserver.
144  virtual void OnDevicesChanged(
145      base::SystemMonitor::DeviceType device_type) OVERRIDE;
146
147  // Used by unit test to make sure fake devices are used instead of a real
148  // devices, which is needed for server based testing or certain tests (which
149  // can pass --use-fake-device-for-media-stream).
150  void UseFakeDevice();
151
152  // Called by the tests to specify a fake UI that should be used for next
153  // generated stream (or when using --use-fake-ui-for-media-stream).
154  void UseFakeUI(scoped_ptr<FakeMediaStreamUIProxy> fake_ui);
155
156  // This object gets deleted on the UI thread after the IO thread has been
157  // destroyed. So we need to know when IO thread is being destroyed so that
158  // we can delete VideoCaptureManager and AudioInputDeviceManager.
159  // We also must call this function explicitly in tests which use
160  // TestBrowserThreadBundle, because the notification happens too late in that
161  // case (see http://crbug.com/247525#c14).
162  virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
163
164 protected:
165  // Used for testing.
166  MediaStreamManager();
167
168 private:
169  // Contains all data needed to keep track of requests.
170  class DeviceRequest;
171
172  // Cache enumerated device list.
173  struct EnumerationCache {
174    EnumerationCache();
175    ~EnumerationCache();
176
177    bool valid;
178    StreamDeviceInfoArray devices;
179  };
180
181  typedef std::map<std::string, DeviceRequest*> DeviceRequests;
182
183  // Initializes the device managers on IO thread.  Auto-starts the device
184  // thread and registers this as a listener with the device managers.
185  void InitializeDeviceManagersOnIOThread();
186
187  // Helper for sending up-to-date device lists to media observer when a
188  // capture device is plugged in or unplugged.
189  void NotifyDevicesChanged(MediaStreamType stream_type,
190                            const StreamDeviceInfoArray& devices);
191
192
193  void HandleAccessRequestResponse(const std::string& label,
194                                   const MediaStreamDevices& devices);
195  void StopStreamFromUI(const std::string& label);
196
197  // Helpers.
198  bool RequestDone(const DeviceRequest& request) const;
199  MediaStreamProvider* GetDeviceManager(MediaStreamType stream_type);
200  void StartEnumeration(DeviceRequest* request);
201  std::string AddRequest(DeviceRequest* request);
202  void RemoveRequest(DeviceRequests::iterator it);
203  void ClearEnumerationCache(EnumerationCache* cache);
204  void PostRequestToUI(const std::string& label);
205  void HandleRequest(const std::string& label);
206
207  // Sends cached device list to a client corresponding to the request
208  // identified by |label|.
209  void SendCachedDeviceList(EnumerationCache* cache, const std::string& label);
210
211  // Stop the request of enumerating devices indentified by |label|.
212  void StopEnumerateDevices(const std::string& label);
213
214  // Helpers to start and stop monitoring devices.
215  void StartMonitoring();
216  void StopMonitoring();
217
218  // Finds and returns the raw device id corresponding to the given
219  // |device_guid|. Returns true if there was a raw device id that matched the
220  // given |device_guid|, false if nothing matched it.
221  bool TranslateGUIDToRawId(
222      MediaStreamType stream_type,
223      const GURL& security_origin,
224      const std::string& device_guid,
225      std::string* raw_device_id);
226
227  // Device thread shared by VideoCaptureManager and AudioInputDeviceManager.
228  scoped_ptr<base::Thread> device_thread_;
229
230  media::AudioManager* const audio_manager_;  // not owned
231  scoped_refptr<AudioInputDeviceManager> audio_input_device_manager_;
232  scoped_refptr<VideoCaptureManager> video_capture_manager_;
233
234  // Indicator of device monitoring state.
235  bool monitoring_started_;
236
237  // Stores most recently enumerated device lists. The cache is cleared when
238  // monitoring is stopped or there is no request for that type of device.
239  EnumerationCache audio_enumeration_cache_;
240  EnumerationCache video_enumeration_cache_;
241
242  // Keeps track of live enumeration commands sent to VideoCaptureManager or
243  // AudioInputDeviceManager, in order to only enumerate when necessary.
244  int active_enumeration_ref_count_[NUM_MEDIA_TYPES];
245
246  // All non-closed request.
247  DeviceRequests requests_;
248
249  // Hold a pointer to the IO loop to check we delete the device thread and
250  // managers on the right thread.
251  base::MessageLoop* io_loop_;
252
253  bool screen_capture_active_;
254
255  bool use_fake_ui_;
256  scoped_ptr<FakeMediaStreamUIProxy> fake_ui_;
257
258  DISALLOW_COPY_AND_ASSIGN(MediaStreamManager);
259};
260
261}  // namespace content
262
263#endif  // CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
264