Revert of Update mojo sdk to rev 8af2ccff2eee4bfca1043015abee30482a030b30 (patchset...
[chromium-blink-merge.git] / content / browser / device_monitor_mac.mm
blobc437426bbe4c9927efa78589648ac2f00bbcd246
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/device_monitor_mac.h"
7 #import <QTKit/QTKit.h>
9 #include <set>
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/mac/bind_objc_block.h"
14 #include "base/mac/scoped_nsobject.h"
15 #include "base/threading/thread_checker.h"
16 #include "content/public/browser/browser_thread.h"
17 #import "media/base/mac/avfoundation_glue.h"
19 using content::BrowserThread;
21 namespace {
23 // This class is used to keep track of system devices names and their types.
24 class DeviceInfo {
25  public:
26   enum DeviceType {
27     kAudio,
28     kVideo,
29     kMuxed,
30     kUnknown,
31     kInvalid
32   };
34   DeviceInfo(std::string unique_id, DeviceType type)
35       : unique_id_(unique_id), type_(type) {}
37   // Operator== is needed here to use this class in a std::find. A given
38   // |unique_id_| always has the same |type_| so for comparison purposes the
39   // latter can be safely ignored.
40   bool operator==(const DeviceInfo& device) const {
41     return unique_id_ == device.unique_id_;
42   }
44   const std::string& unique_id() const { return unique_id_; }
45   DeviceType type() const { return type_; }
47  private:
48   std::string unique_id_;
49   DeviceType type_;
50   // Allow generated copy constructor and assignment.
53 // Base abstract class used by DeviceMonitorMac to interact with either a QTKit
54 // or an AVFoundation implementation of events and notifications.
55 class DeviceMonitorMacImpl {
56  public:
57   explicit DeviceMonitorMacImpl(content::DeviceMonitorMac* monitor)
58       : monitor_(monitor),
59         cached_devices_(),
60         device_arrival_(nil),
61         device_removal_(nil) {
62     DCHECK(monitor);
63     // Initialise the devices_cache_ with a not-valid entry. For the case in
64     // which there is one single device in the system and we get notified when
65     // it gets removed, this will prevent the system from thinking that no
66     // devices were added nor removed and not notifying the |monitor_|.
67     cached_devices_.push_back(DeviceInfo("invalid", DeviceInfo::kInvalid));
68   }
69   virtual ~DeviceMonitorMacImpl() {}
71   virtual void OnDeviceChanged() = 0;
73   // Method called by the default notification center when a device is removed
74   // or added to the system. It will compare the |cached_devices_| with the
75   // current situation, update it, and, if there's an update, signal to
76   // |monitor_| with the appropriate device type.
77   void ConsolidateDevicesListAndNotify(
78       const std::vector<DeviceInfo>& snapshot_devices);
80  protected:
81   content::DeviceMonitorMac* monitor_;
82   std::vector<DeviceInfo> cached_devices_;
84   // Handles to NSNotificationCenter block observers.
85   id device_arrival_;
86   id device_removal_;
88  private:
89   DISALLOW_COPY_AND_ASSIGN(DeviceMonitorMacImpl);
92 void DeviceMonitorMacImpl::ConsolidateDevicesListAndNotify(
93     const std::vector<DeviceInfo>& snapshot_devices) {
94   bool video_device_added = false;
95   bool audio_device_added = false;
96   bool video_device_removed = false;
97   bool audio_device_removed = false;
99   // Compare the current system devices snapshot with the ones cached to detect
100   // additions, present in the former but not in the latter. If we find a device
101   // in snapshot_devices entry also present in cached_devices, we remove it from
102   // the latter vector.
103   std::vector<DeviceInfo>::const_iterator it;
104   for (it = snapshot_devices.begin(); it != snapshot_devices.end(); ++it) {
105     std::vector<DeviceInfo>::iterator cached_devices_iterator =
106         std::find(cached_devices_.begin(), cached_devices_.end(), *it);
107     if (cached_devices_iterator == cached_devices_.end()) {
108       video_device_added |= ((it->type() == DeviceInfo::kVideo) ||
109                              (it->type() == DeviceInfo::kMuxed));
110       audio_device_added |= ((it->type() == DeviceInfo::kAudio) ||
111                              (it->type() == DeviceInfo::kMuxed));
112       DVLOG(1) << "Device has been added, id: " << it->unique_id();
113     } else {
114       cached_devices_.erase(cached_devices_iterator);
115     }
116   }
117   // All the remaining entries in cached_devices are removed devices.
118   for (it = cached_devices_.begin(); it != cached_devices_.end(); ++it) {
119     video_device_removed |= ((it->type() == DeviceInfo::kVideo) ||
120                              (it->type() == DeviceInfo::kMuxed) ||
121                              (it->type() == DeviceInfo::kInvalid));
122     audio_device_removed |= ((it->type() == DeviceInfo::kAudio) ||
123                              (it->type() == DeviceInfo::kMuxed) ||
124                              (it->type() == DeviceInfo::kInvalid));
125     DVLOG(1) << "Device has been removed, id: " << it->unique_id();
126   }
127   // Update the cached devices with the current system snapshot.
128   cached_devices_ = snapshot_devices;
130   if (video_device_added || video_device_removed)
131     monitor_->NotifyDeviceChanged(base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE);
132   if (audio_device_added || audio_device_removed)
133     monitor_->NotifyDeviceChanged(base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE);
136 class QTKitMonitorImpl : public DeviceMonitorMacImpl {
137  public:
138   explicit QTKitMonitorImpl(content::DeviceMonitorMac* monitor);
139   ~QTKitMonitorImpl() override;
141   void OnDeviceChanged() override;
143  private:
144   void CountDevices();
145   void OnAttributeChanged(NSNotification* notification);
147   id device_change_;
150 QTKitMonitorImpl::QTKitMonitorImpl(content::DeviceMonitorMac* monitor)
151     : DeviceMonitorMacImpl(monitor) {
152   NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
153   device_arrival_ =
154       [nc addObserverForName:QTCaptureDeviceWasConnectedNotification
155                       object:nil
156                        queue:nil
157                   usingBlock:^(NSNotification* notification) {
158                       OnDeviceChanged();}];
159   device_removal_ =
160       [nc addObserverForName:QTCaptureDeviceWasDisconnectedNotification
161                       object:nil
162                        queue:nil
163                   usingBlock:^(NSNotification* notification) {
164                       OnDeviceChanged();}];
165   device_change_ =
166       [nc addObserverForName:QTCaptureDeviceAttributeDidChangeNotification
167                       object:nil
168                        queue:nil
169                   usingBlock:^(NSNotification* notification) {
170                       OnAttributeChanged(notification);}];
173 QTKitMonitorImpl::~QTKitMonitorImpl() {
174   NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
175   [nc removeObserver:device_arrival_];
176   [nc removeObserver:device_removal_];
177   [nc removeObserver:device_change_];
180 void QTKitMonitorImpl::OnAttributeChanged(
181     NSNotification* notification) {
182   if ([[[notification userInfo]
183          objectForKey:QTCaptureDeviceChangedAttributeKey]
184       isEqualToString:QTCaptureDeviceSuspendedAttribute]) {
185     OnDeviceChanged();
186   }
189 void QTKitMonitorImpl::OnDeviceChanged() {
190   std::vector<DeviceInfo> snapshot_devices;
192   NSArray* devices = [QTCaptureDevice inputDevices];
193   for (QTCaptureDevice* device in devices) {
194     DeviceInfo::DeviceType device_type = DeviceInfo::kUnknown;
195     // Act as if suspended video capture devices are not attached.  For
196     // example, a laptop's internal webcam is suspended when the lid is closed.
197     if ([device hasMediaType:QTMediaTypeVideo] &&
198         ![[device attributeForKey:QTCaptureDeviceSuspendedAttribute]
199         boolValue]) {
200       device_type = DeviceInfo::kVideo;
201     } else if ([device hasMediaType:QTMediaTypeMuxed] &&
202         ![[device attributeForKey:QTCaptureDeviceSuspendedAttribute]
203         boolValue]) {
204       device_type = DeviceInfo::kMuxed;
205     } else if ([device hasMediaType:QTMediaTypeSound] &&
206         ![[device attributeForKey:QTCaptureDeviceSuspendedAttribute]
207         boolValue]) {
208       device_type = DeviceInfo::kAudio;
209     }
210     snapshot_devices.push_back(
211         DeviceInfo([[device uniqueID] UTF8String], device_type));
212   }
213   ConsolidateDevicesListAndNotify(snapshot_devices);
216 // Forward declaration for use by CrAVFoundationDeviceObserver.
217 class SuspendObserverDelegate;
219 }  // namespace
221 // This class is a Key-Value Observer (KVO) shim. It is needed because C++
222 // classes cannot observe Key-Values directly. Created, manipulated, and
223 // destroyed on the UI Thread by SuspendObserverDelegate.
224 @interface CrAVFoundationDeviceObserver : NSObject {
225  @private
226   // Callback for device changed, has to run on Device Thread.
227   base::Closure onDeviceChangedCallback_;
229   // Member to keep track of the devices we are already monitoring.
230   std::set<base::scoped_nsobject<CrAVCaptureDevice> > monitoredDevices_;
233 - (id)initWithOnChangedCallback:(const base::Closure&)callback;
234 - (void)startObserving:(base::scoped_nsobject<CrAVCaptureDevice>)device;
235 - (void)stopObserving:(CrAVCaptureDevice*)device;
236 - (void)clearOnDeviceChangedCallback;
238 @end
240 namespace {
242 // This class owns and manages the lifetime of a CrAVFoundationDeviceObserver.
243 // It is created and destroyed in UI thread by AVFoundationMonitorImpl, and it
244 // operates on this thread except for the expensive device enumerations which
245 // are run on Device Thread.
246 class SuspendObserverDelegate :
247     public base::RefCountedThreadSafe<SuspendObserverDelegate> {
248  public:
249   explicit SuspendObserverDelegate(DeviceMonitorMacImpl* monitor);
251   // Create |suspend_observer_| for all devices and register OnDeviceChanged()
252   // as its change callback. Schedule bottom half in DoStartObserver().
253   void StartObserver(
254       const scoped_refptr<base::SingleThreadTaskRunner>& device_thread);
255   // Enumerate devices in |device_thread| and run the bottom half in
256   // DoOnDeviceChange(). |suspend_observer_| calls back here on suspend event,
257   // and our parent AVFoundationMonitorImpl calls on connect/disconnect device.
258   void OnDeviceChanged(
259       const scoped_refptr<base::SingleThreadTaskRunner>& device_thread);
260   // Remove the device monitor's weak reference. Remove ourselves as suspend
261   // notification observer from |suspend_observer_|.
262   void ResetDeviceMonitor();
264  private:
265   friend class base::RefCountedThreadSafe<SuspendObserverDelegate>;
267   virtual ~SuspendObserverDelegate();
269   // Bottom half of StartObserver(), starts |suspend_observer_| for all devices.
270   // Assumes that |devices| has been retained prior to being called, and
271   // releases it internally.
272   void DoStartObserver(NSArray* devices);
273   // Bottom half of OnDeviceChanged(), starts |suspend_observer_| for current
274   // devices and composes a snapshot of them to send it to
275   // |avfoundation_monitor_impl_|. Assumes that |devices| has been retained
276   // prior to being called, and releases it internally.
277   void DoOnDeviceChanged(NSArray* devices);
279   base::scoped_nsobject<CrAVFoundationDeviceObserver> suspend_observer_;
280   DeviceMonitorMacImpl* avfoundation_monitor_impl_;
283 SuspendObserverDelegate::SuspendObserverDelegate(DeviceMonitorMacImpl* monitor)
284     : avfoundation_monitor_impl_(monitor) {
285   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
288 void SuspendObserverDelegate::StartObserver(
289       const scoped_refptr<base::SingleThreadTaskRunner>& device_thread) {
290   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
292   base::Closure on_device_changed_callback =
293       base::Bind(&SuspendObserverDelegate::OnDeviceChanged,
294                  this, device_thread);
295   suspend_observer_.reset([[CrAVFoundationDeviceObserver alloc]
296       initWithOnChangedCallback:on_device_changed_callback]);
298   // Enumerate the devices in Device thread and post the observers start to be
299   // done on UI thread. The devices array is retained in |device_thread| and
300   // released in DoStartObserver().
301   base::PostTaskAndReplyWithResult(
302       device_thread.get(),
303       FROM_HERE,
304       base::BindBlock(^{ return [[AVCaptureDeviceGlue devices] retain]; }),
305       base::Bind(&SuspendObserverDelegate::DoStartObserver, this));
308 void SuspendObserverDelegate::OnDeviceChanged(
309       const scoped_refptr<base::SingleThreadTaskRunner>& device_thread) {
310   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
311   // Enumerate the devices in Device thread and post the consolidation of the
312   // new devices and the old ones to be done on UI thread. The devices array
313   // is retained in |device_thread| and released in DoOnDeviceChanged().
314   PostTaskAndReplyWithResult(
315       device_thread.get(),
316       FROM_HERE,
317       base::BindBlock(^{ return [[AVCaptureDeviceGlue devices] retain]; }),
318       base::Bind(&SuspendObserverDelegate::DoOnDeviceChanged, this));
321 void SuspendObserverDelegate::ResetDeviceMonitor() {
322   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
323   avfoundation_monitor_impl_ = NULL;
324   [suspend_observer_ clearOnDeviceChangedCallback];
327 SuspendObserverDelegate::~SuspendObserverDelegate() {
328   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
331 void SuspendObserverDelegate::DoStartObserver(NSArray* devices) {
332   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
333   base::scoped_nsobject<NSArray> auto_release(devices);
334   for (CrAVCaptureDevice* device in devices) {
335     base::scoped_nsobject<CrAVCaptureDevice> device_ptr([device retain]);
336     [suspend_observer_ startObserving:device_ptr];
337   }
340 void SuspendObserverDelegate::DoOnDeviceChanged(NSArray* devices) {
341   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
342   base::scoped_nsobject<NSArray> auto_release(devices);
343   std::vector<DeviceInfo> snapshot_devices;
344   for (CrAVCaptureDevice* device in devices) {
345     base::scoped_nsobject<CrAVCaptureDevice> device_ptr([device retain]);
346     [suspend_observer_ startObserving:device_ptr];
348     BOOL suspended = [device respondsToSelector:@selector(isSuspended)] &&
349         [device isSuspended];
350     DeviceInfo::DeviceType device_type = DeviceInfo::kUnknown;
351     if ([device hasMediaType:AVFoundationGlue::AVMediaTypeVideo()]) {
352       if (suspended)
353         continue;
354       device_type = DeviceInfo::kVideo;
355     } else if ([device hasMediaType:AVFoundationGlue::AVMediaTypeMuxed()]) {
356       device_type = suspended ? DeviceInfo::kAudio : DeviceInfo::kMuxed;
357     } else if ([device hasMediaType:AVFoundationGlue::AVMediaTypeAudio()]) {
358       device_type = DeviceInfo::kAudio;
359     }
360     snapshot_devices.push_back(DeviceInfo([[device uniqueID] UTF8String],
361                                           device_type));
362   }
363   // Make sure no references are held to |devices| when
364   // ConsolidateDevicesListAndNotify is called since the VideoCaptureManager
365   // and AudioCaptureManagers also enumerates the available devices but on
366   // another thread.
367   auto_release.reset();
368   // |avfoundation_monitor_impl_| might have been NULLed asynchronously before
369   // arriving at this line.
370   if (avfoundation_monitor_impl_) {
371     avfoundation_monitor_impl_->ConsolidateDevicesListAndNotify(
372         snapshot_devices);
373   }
376 // AVFoundation implementation of the Mac Device Monitor, registers as a global
377 // device connect/disconnect observer and plugs suspend/wake up device observers
378 // per device. This class is created and lives in UI thread. Owns a
379 // SuspendObserverDelegate that notifies when a device is suspended/resumed.
380 class AVFoundationMonitorImpl : public DeviceMonitorMacImpl {
381  public:
382   AVFoundationMonitorImpl(
383       content::DeviceMonitorMac* monitor,
384       const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner);
385   ~AVFoundationMonitorImpl() override;
387   void OnDeviceChanged() override;
389  private:
390   // {Video,AudioInput}DeviceManager's "Device" thread task runner used for
391   // posting tasks to |suspend_observer_delegate_|; valid after
392   // MediaStreamManager calls StartMonitoring().
393   const scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_;
395   scoped_refptr<SuspendObserverDelegate> suspend_observer_delegate_;
397   DISALLOW_COPY_AND_ASSIGN(AVFoundationMonitorImpl);
400 AVFoundationMonitorImpl::AVFoundationMonitorImpl(
401     content::DeviceMonitorMac* monitor,
402     const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner)
403     : DeviceMonitorMacImpl(monitor),
404       device_task_runner_(device_task_runner),
405       suspend_observer_delegate_(new SuspendObserverDelegate(this)) {
406   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
407   NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
408   device_arrival_ =
409       [nc addObserverForName:AVFoundationGlue::
410           AVCaptureDeviceWasConnectedNotification()
411                       object:nil
412                        queue:nil
413                   usingBlock:^(NSNotification* notification) {
414                       OnDeviceChanged();}];
415   device_removal_ =
416       [nc addObserverForName:AVFoundationGlue::
417           AVCaptureDeviceWasDisconnectedNotification()
418                       object:nil
419                        queue:nil
420                   usingBlock:^(NSNotification* notification) {
421                       OnDeviceChanged();}];
422   suspend_observer_delegate_->StartObserver(device_task_runner_);
425 AVFoundationMonitorImpl::~AVFoundationMonitorImpl() {
426   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
427   suspend_observer_delegate_->ResetDeviceMonitor();
428   NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
429   [nc removeObserver:device_arrival_];
430   [nc removeObserver:device_removal_];
433 void AVFoundationMonitorImpl::OnDeviceChanged() {
434   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
435   suspend_observer_delegate_->OnDeviceChanged(device_task_runner_);
438 }  // namespace
440 @implementation CrAVFoundationDeviceObserver
442 - (id)initWithOnChangedCallback:(const base::Closure&)callback {
443   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
444   if ((self = [super init])) {
445     DCHECK(!callback.is_null());
446     onDeviceChangedCallback_ = callback;
447   }
448   return self;
451 - (void)dealloc {
452   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
453   std::set<base::scoped_nsobject<CrAVCaptureDevice> >::iterator it =
454       monitoredDevices_.begin();
455   while (it != monitoredDevices_.end())
456     [self removeObservers:*(it++)];
457   [super dealloc];
460 - (void)startObserving:(base::scoped_nsobject<CrAVCaptureDevice>)device {
461   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
462   DCHECK(device != nil);
463   // Skip this device if there are already observers connected to it.
464   if (std::find(monitoredDevices_.begin(), monitoredDevices_.end(), device) !=
465       monitoredDevices_.end()) {
466     return;
467   }
468   [device addObserver:self
469            forKeyPath:@"suspended"
470               options:0
471               context:device.get()];
472   [device addObserver:self
473            forKeyPath:@"connected"
474               options:0
475               context:device.get()];
476   monitoredDevices_.insert(device);
479 - (void)stopObserving:(CrAVCaptureDevice*)device {
480   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
481   DCHECK(device != nil);
483   std::set<base::scoped_nsobject<CrAVCaptureDevice> >::iterator found =
484       std::find(monitoredDevices_.begin(), monitoredDevices_.end(), device);
485   DCHECK(found != monitoredDevices_.end());
486   [self removeObservers:*found];
487   monitoredDevices_.erase(found);
490 - (void)clearOnDeviceChangedCallback {
491   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
492   onDeviceChangedCallback_.Reset();
495 - (void)removeObservers:(CrAVCaptureDevice*)device {
496   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
497   // Check sanity of |device| via its -observationInfo. http://crbug.com/371271.
498   if ([device observationInfo]) {
499     [device removeObserver:self
500                 forKeyPath:@"suspended"];
501     [device removeObserver:self
502                 forKeyPath:@"connected"];
503   }
506 - (void)observeValueForKeyPath:(NSString*)keyPath
507                       ofObject:(id)object
508                         change:(NSDictionary*)change
509                        context:(void*)context {
510   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
511   if ([keyPath isEqual:@"suspended"])
512     onDeviceChangedCallback_.Run();
513   if ([keyPath isEqual:@"connected"])
514     [self stopObserving:static_cast<CrAVCaptureDevice*>(context)];
517 @end  // @implementation CrAVFoundationDeviceObserver
519 namespace content {
521 DeviceMonitorMac::DeviceMonitorMac() {
522   // Both QTKit and AVFoundation do not need to be fired up until the user
523   // exercises a GetUserMedia. Bringing up either library and enumerating the
524   // devices in the system is an operation taking in the range of hundred of ms,
525   // so it is triggered explicitly from MediaStreamManager::StartMonitoring().
528 DeviceMonitorMac::~DeviceMonitorMac() {}
530 void DeviceMonitorMac::StartMonitoring(
531     const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner) {
532   DCHECK(thread_checker_.CalledOnValidThread());
533   if (AVFoundationGlue::IsAVFoundationSupported()) {
534     DVLOG(1) << "Monitoring via AVFoundation";
535     device_monitor_impl_.reset(new AVFoundationMonitorImpl(this,
536                                                            device_task_runner));
537   } else {
538     DVLOG(1) << "Monitoring via QTKit";
539     device_monitor_impl_.reset(new QTKitMonitorImpl(this));
540   }
543 void DeviceMonitorMac::NotifyDeviceChanged(
544     base::SystemMonitor::DeviceType type) {
545   DCHECK(thread_checker_.CalledOnValidThread());
546   // TODO(xians): Remove the global variable for SystemMonitor.
547   base::SystemMonitor::Get()->ProcessDevicesChanged(type);
550 }  // namespace content