summaryrefslogtreecommitdiff
path: root/chromium/media/video/capture/mac/video_capture_device_qtkit_mac.mm
blob: fa2d7c3be68e980a5d765cb3a29d51670f415275 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "media/video/capture/mac/video_capture_device_qtkit_mac.h"

#import <QTKit/QTKit.h>

#include "base/debug/crash_logging.h"
#include "base/logging.h"
#include "base/mac/scoped_nsexception_enabler.h"
#include "media/video/capture/mac/video_capture_device_mac.h"
#include "media/video/capture/video_capture_device.h"
#include "media/video/capture/video_capture_types.h"

@implementation VideoCaptureDeviceQTKit

#pragma mark Class methods

+ (void)getDeviceNames:(NSMutableDictionary*)deviceNames {
  // Third-party drivers often throw exceptions, which are fatal in
  // Chromium (see comments in scoped_nsexception_enabler.h).  The
  // following catches any exceptions and continues in an orderly
  // fashion with no devices detected.
  NSArray* captureDevices =
      base::mac::RunBlockIgnoringExceptions(^{
          return [QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo];
      });

  for (QTCaptureDevice* device in captureDevices) {
    [deviceNames setObject:[device localizedDisplayName]
                    forKey:[device uniqueID]];
  }
}

+ (NSDictionary*)deviceNames {
  NSMutableDictionary* deviceNames =
      [[[NSMutableDictionary alloc] init] autorelease];

  // TODO(shess): Post to the main thread to see if that helps
  // http://crbug.com/139164
  [self performSelectorOnMainThread:@selector(getDeviceNames:)
                         withObject:deviceNames
                      waitUntilDone:YES];
  return deviceNames;
}

#pragma mark Public methods

- (id)initWithFrameReceiver:(media::VideoCaptureDeviceMac *)frameReceiver {
  self = [super init];
  if (self) {
    frameReceiver_ = frameReceiver;
    lock_ = [[NSLock alloc] init];
  }
  return self;
}

- (void)dealloc {
  [captureSession_ release];
  [captureDeviceInput_ release];
  [super dealloc];
}

- (void)setFrameReceiver:(media::VideoCaptureDeviceMac *)frameReceiver {
  [lock_ lock];
  frameReceiver_ = frameReceiver;
  [lock_ unlock];
}

- (BOOL)setCaptureDevice:(NSString *)deviceId {
  if (deviceId) {
    // Set the capture device.
    if (captureDeviceInput_) {
      DLOG(ERROR) << "Video capture device already set.";
      return NO;
    }

    NSArray *captureDevices =
        [QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo];
    NSArray *captureDevicesNames =
        [captureDevices valueForKey:@"uniqueID"];
    NSUInteger index = [captureDevicesNames indexOfObject:deviceId];
    if (index == NSNotFound) {
      DLOG(ERROR) << "Video capture device not found.";
      return NO;
    }
    QTCaptureDevice *device = [captureDevices objectAtIndex:index];
    NSError *error;
    if (![device open:&error]) {
      DLOG(ERROR) << "Could not open video capture device."
                  << [[error localizedDescription] UTF8String];
      return NO;
    }
    captureDeviceInput_ = [[QTCaptureDeviceInput alloc] initWithDevice:device];
    captureSession_ = [[QTCaptureSession alloc] init];

    QTCaptureDecompressedVideoOutput *captureDecompressedOutput =
        [[[QTCaptureDecompressedVideoOutput alloc] init] autorelease];
    [captureDecompressedOutput setDelegate:self];
    if (![captureSession_ addOutput:captureDecompressedOutput error:&error]) {
      DLOG(ERROR) << "Could not connect video capture output."
                  << [[error localizedDescription] UTF8String];
      return NO;
    }

    // This key can be used to check if video capture code was related to a
    // particular crash.
    base::debug::SetCrashKeyValue("VideoCaptureDeviceQTKit", "OpenedDevice");

    return YES;
  } else {
    // Remove the previously set capture device.
    if (!captureDeviceInput_) {
      DLOG(ERROR) << "No video capture device set.";
      return YES;
    }
    if ([[captureSession_ inputs] count] > 0) {
      // The device is still running.
      [self stopCapture];
    }
    if ([[captureSession_ outputs] count] > 0) {
      // Only one output is set for |captureSession_|.
      id output = [[captureSession_ outputs] objectAtIndex:0];
      [output setDelegate:nil];

      // TODO(shess): QTKit achieves thread safety by posting messages
      // to the main thread.  As part of -addOutput:, it posts a
      // message to the main thread which in turn posts a notification
      // which will run in a future spin after the original method
      // returns.  -removeOutput: can post a main-thread message in
      // between while holding a lock which the notification handler
      // will need.  Posting either -addOutput: or -removeOutput: to
      // the main thread should fix it, remove is likely safer.
      // http://crbug.com/152757
      [captureSession_ performSelectorOnMainThread:@selector(removeOutput:)
                                        withObject:output
                                     waitUntilDone:YES];
    }
    [captureSession_ release];
    captureSession_ = nil;
    [captureDeviceInput_ release];
    captureDeviceInput_ = nil;
    return YES;
  }
}

- (BOOL)setCaptureHeight:(int)height width:(int)width frameRate:(int)frameRate {
  if (!captureDeviceInput_) {
    DLOG(ERROR) << "No video capture device set.";
    return NO;
  }
  if ([[captureSession_ outputs] count] != 1) {
    DLOG(ERROR) << "Video capture capabilities already set.";
    return NO;
  }
  if (frameRate <= 0) {
    DLOG(ERROR) << "Wrong frame rate.";
    return NO;
  }

  frameWidth_ = width;
  frameHeight_ = height;
  frameRate_ = frameRate;

  // Set up desired output properties.
  NSDictionary *captureDictionary =
      [NSDictionary dictionaryWithObjectsAndKeys:
          [NSNumber numberWithDouble:frameWidth_],
          (id)kCVPixelBufferWidthKey,
          [NSNumber numberWithDouble:frameHeight_],
          (id)kCVPixelBufferHeightKey,
          [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA],
          (id)kCVPixelBufferPixelFormatTypeKey,
          nil];
  [[[captureSession_ outputs] objectAtIndex:0]
      setPixelBufferAttributes:captureDictionary];

  [[[captureSession_ outputs] objectAtIndex:0]
      setMinimumVideoFrameInterval:(NSTimeInterval)1/(float)frameRate];
  return YES;
}

- (BOOL)startCapture {
  if ([[captureSession_ outputs] count] == 0) {
    // Capture properties not set.
    DLOG(ERROR) << "Video capture device not initialized.";
    return NO;
  }
  if ([[captureSession_ inputs] count] == 0) {
    NSError *error;
    if (![captureSession_ addInput:captureDeviceInput_ error:&error]) {
      DLOG(ERROR) << "Could not connect video capture device."
                  << [[error localizedDescription] UTF8String];
      return NO;
    }
    [captureSession_ startRunning];
  }
  return YES;
}

- (void)stopCapture {
  if ([[captureSession_ inputs] count] == 1) {
    [captureSession_ removeInput:captureDeviceInput_];
    [captureSession_ stopRunning];
  }
}

// |captureOutput| is called by the capture device to deliver a new frame.
- (void)captureOutput:(QTCaptureOutput *)captureOutput
  didOutputVideoFrame:(CVImageBufferRef)videoFrame
     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection {
  [lock_ lock];
  if(!frameReceiver_) {
    [lock_ unlock];
    return;
  }

  // Lock the frame and calculate frame size.
  const int kLockFlags = 0;
  if (CVPixelBufferLockBaseAddress(videoFrame, kLockFlags)
      == kCVReturnSuccess) {
    void *baseAddress = CVPixelBufferGetBaseAddress(videoFrame);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(videoFrame);
    int frameHeight = CVPixelBufferGetHeight(videoFrame);
    int frameSize = bytesPerRow * frameHeight;

    // TODO(shess): bytesPerRow may not correspond to frameWidth_*4,
    // but VideoCaptureController::OnIncomingCapturedFrame() requires
    // it to do so.  Plumbing things through is intrusive, for now
    // just deliver an adjusted buffer.
    // TODO(nick): This workaround could probably be eliminated by using
    // VideoCaptureController::OnIncomingCapturedVideoFrame, which supports
    // pitches.
    UInt8* addressToPass = static_cast<UInt8*>(baseAddress);
    size_t expectedBytesPerRow = frameWidth_ * 4;
    if (bytesPerRow > expectedBytesPerRow) {
      // TODO(shess): frameHeight and frameHeight_ are not the same,
      // try to do what the surrounding code seems to assume.
      // Ironically, captureCapability and frameSize are ignored
      // anyhow.
      adjustedFrame_.resize(expectedBytesPerRow * frameHeight);
      // std::vector is contiguous according to standard.
      UInt8* adjustedAddress = &adjustedFrame_[0];

      for (int y = 0; y < frameHeight; ++y) {
        memcpy(adjustedAddress + y * expectedBytesPerRow,
               addressToPass + y * bytesPerRow,
               expectedBytesPerRow);
      }

      addressToPass = adjustedAddress;
      frameSize = frameHeight * expectedBytesPerRow;
    }
    media::VideoCaptureCapability captureCapability;
    captureCapability.width = frameWidth_;
    captureCapability.height = frameHeight_;
    captureCapability.frame_rate = frameRate_;
    captureCapability.color = media::VideoCaptureCapability::kARGB;
    captureCapability.expected_capture_delay = 0;
    captureCapability.interlaced = false;

    // Deliver the captured video frame.
    frameReceiver_->ReceiveFrame(addressToPass, frameSize, captureCapability);

    CVPixelBufferUnlockBaseAddress(videoFrame, kLockFlags);
  }
  [lock_ unlock];
}

@end