1 /*****************************************************************************
2 * avcapture.m: AVFoundation (Mac OS X) based video capture module
3 *****************************************************************************
4 * Copyright © 2008-2013 VLC authors and VideoLAN
6 * Authors: Michael Feurstein <michael.feurstein@gmail.com>
8 ****************************************************************************
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU Lesser General Public License as published by
11 * the Free Software Foundation; either version 2.1 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
28 #define OS_OBJECT_USE_OBJC 0
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_input.h>
37 #include <vlc_demux.h>
38 #include <vlc_interface.h>
39 #include <vlc_dialog.h>
40 #include <vlc_access.h>
42 #import <AVFoundation/AVFoundation.h>
43 #import <CoreMedia/CoreMedia.h>
45 /*****************************************************************************
47 *****************************************************************************/
48 static int Open(vlc_object_t *p_this);
49 static void Close(vlc_object_t *p_this);
50 static int Demux(demux_t *p_demux);
51 static int Control(demux_t *, int, va_list);
53 /*****************************************************************************
55 *****************************************************************************/
57 set_shortname(N_("AVFoundation Video Capture"))
58 set_description(N_("AVFoundation video capture module."))
59 set_category(CAT_INPUT)
60 set_subcategory(SUBCAT_INPUT_ACCESS)
61 add_shortcut("avcapture")
62 set_capability("access_demux", 0)
63 set_callbacks(Open, Close)
67 /*****************************************************************************
69 *****************************************************************************/
70 @interface VLCAVDecompressedVideoOutput : AVCaptureVideoDataOutput
74 CVImageBufferRef currentImageBuffer;
81 BOOL videoDimensionsReady;
84 @property (readwrite) CMVideoDimensions videoDimensions;
86 - (id)initWithDemux:(demux_t *)p_demux;
89 - (void)getVideoDimensions:(CMSampleBufferRef)sampleBuffer;
90 - (mtime_t)currentPts;
91 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection;
92 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer;
95 @implementation VLCAVDecompressedVideoOutput : AVCaptureVideoDataOutput
97 - (id)initWithDemux:(demux_t *)p_demux
99 if (self = [super init])
101 p_avcapture = p_demux;
102 currentImageBuffer = nil;
107 videoDimensionsReady = NO;
116 CVBufferRelease(currentImageBuffer);
117 currentImageBuffer = nil;
119 videoDimensionsReady = NO;
130 return self.videoDimensions.width;
135 return self.videoDimensions.height;
138 - (size_t)bytesPerRow
143 - (void)getVideoDimensions:(CMSampleBufferRef)sampleBuffer
145 if (!videoDimensionsReady)
147 CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
148 self.videoDimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
149 bytesPerRow = CVPixelBufferGetBytesPerRow(CMSampleBufferGetImageBuffer(sampleBuffer));
150 videoDimensionsReady = YES;
151 msg_Dbg(p_avcapture, "Dimensionns obtained height:%i width:%i bytesPerRow:%lu", [self height], [self width], bytesPerRow);
159 if ( !currentImageBuffer || currentPts == previousPts )
164 pts = previousPts = currentPts;
170 - (void)captureOutput:(AVCaptureOutput *)captureOutput
171 didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
172 fromConnection:(AVCaptureConnection *)connection
175 CVImageBufferRef imageBufferToRelease;
176 CMTime presentationtimestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
177 CVImageBufferRef videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
178 CVBufferRetain(videoFrame);
179 [self getVideoDimensions:sampleBuffer];
181 @synchronized (self) {
182 imageBufferToRelease = currentImageBuffer;
183 currentImageBuffer = videoFrame;
184 currentPts = (mtime_t)presentationtimestamp.value;
185 timeScale = (long)presentationtimestamp.timescale;
188 CVBufferRelease(imageBufferToRelease);
192 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer
194 CVImageBufferRef imageBuffer;
199 if ( !currentImageBuffer || currentPts == previousPts )
204 imageBuffer = CVBufferRetain(currentImageBuffer);
207 pts = previousPts = currentPts;
208 CVPixelBufferLockBaseAddress(imageBuffer, 0);
209 pixels = CVPixelBufferGetBaseAddress(imageBuffer);
212 memcpy(buffer, pixels, CVPixelBufferGetHeight(imageBuffer) * CVPixelBufferGetBytesPerRow(imageBuffer));
214 CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
217 CVBufferRelease(imageBuffer);
227 /*****************************************************************************
229 *****************************************************************************/
233 CFTypeRef _Nullable session; // AVCaptureSession
234 CFTypeRef _Nullable device; // AVCaptureDevice
235 CFTypeRef _Nullable output; // VLCAVDecompressedVideoOutput
236 es_out_id_t *p_es_video;
242 /*****************************************************************************
244 *****************************************************************************/
245 static int Open(vlc_object_t *p_this)
247 demux_t *p_demux = (demux_t*)p_this;
248 demux_sys_t *p_sys = NULL;
250 NSString *avf_currdevice_uid;
251 NSArray *myVideoDevices;
252 NSError *o_returnedError;
254 AVCaptureDeviceInput *input = nil;
256 int i, i_width, i_height, deviceCount, ivideo;
258 char *psz_uid = NULL;
261 if (p_demux->psz_location && *p_demux->psz_location)
262 psz_uid = strdup(p_demux->psz_location);
264 msg_Dbg(p_demux, "avcapture uid = %s", psz_uid);
265 avf_currdevice_uid = [[NSString alloc] initWithFormat:@"%s", psz_uid];
268 p_demux->pf_demux = Demux;
269 p_demux->pf_control = Control;
271 p_demux->p_sys = p_sys = calloc(1, sizeof(demux_sys_t));
275 myVideoDevices = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]
276 arrayByAddingObjectsFromArray:[AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed]];
277 if ( [myVideoDevices count] == 0 )
279 vlc_dialog_display_error(p_demux, _("No video devices found"),
280 _("Your Mac does not seem to be equipped with a suitable video input device. "
281 "Please check your connectors and drivers."));
282 msg_Err(p_demux, "Can't find any suitable video device");
286 deviceCount = [myVideoDevices count];
287 for ( ivideo = 0; ivideo < deviceCount; ivideo++ )
289 AVCaptureDevice *avf_device;
290 avf_device = [myVideoDevices objectAtIndex:ivideo];
291 msg_Dbg(p_demux, "avcapture %i/%i %s %s", ivideo, deviceCount, [[avf_device modelID] UTF8String], [[avf_device uniqueID] UTF8String]);
292 if ([[[avf_device uniqueID]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:avf_currdevice_uid]) {
297 if ( ivideo < [myVideoDevices count] )
299 p_sys->device = CFBridgingRetain([myVideoDevices objectAtIndex:ivideo]);
303 msg_Dbg(p_demux, "Cannot find designated device as %s, falling back to default.", [avf_currdevice_uid UTF8String]);
304 p_sys->device = CFBridgingRetain([AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]);
306 if ( !p_sys->device )
308 vlc_dialog_display_error(p_demux, _("No video devices found"),
309 _("Your Mac does not seem to be equipped with a suitable input device. "
310 "Please check your connectors and drivers."));
311 msg_Err(p_demux, "Can't find any suitable video device");
315 if ( [(__bridge AVCaptureDevice *)p_sys->device isInUseByAnotherApplication] == YES )
317 msg_Err(p_demux, "default capture device is exclusively in use by another application");
321 input = [AVCaptureDeviceInput deviceInputWithDevice:(__bridge AVCaptureDevice *)p_sys->device error:&o_returnedError];
325 msg_Err(p_demux, "can't create a valid capture input facility (%ld)", [o_returnedError code]);
329 int chroma = VLC_CODEC_RGB32;
331 memset(&p_sys->fmt, 0, sizeof(es_format_t));
332 es_format_Init(&p_sys->fmt, VIDEO_ES, chroma);
334 p_sys->session = CFBridgingRetain([[AVCaptureSession alloc] init]);
335 [(__bridge AVCaptureSession *)p_sys->session addInput:input];
337 p_sys->output = CFBridgingRetain([[VLCAVDecompressedVideoOutput alloc] initWithDemux:p_demux]);
338 [(__bridge AVCaptureSession *)p_sys->session addOutput:(__bridge VLCAVDecompressedVideoOutput *)p_sys->output];
340 dispatch_queue_t queue = dispatch_queue_create("avCaptureQueue", NULL);
341 [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output setSampleBufferDelegate:(__bridge id)p_sys->output queue:queue];
342 dispatch_release(queue);
344 [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
345 [(__bridge AVCaptureSession *)p_sys->session startRunning];
349 msg_Dbg(p_demux, "AVCapture: Video device ready!");
353 msg_Err(p_demux, "Error");
362 /*****************************************************************************
364 *****************************************************************************/
365 static void Close(vlc_object_t *p_this)
367 demux_t *p_demux = (demux_t*)p_this;
368 demux_sys_t *p_sys = p_demux->p_sys;
371 msg_Dbg(p_demux,"Close AVCapture");
373 // Perform this on main thread, as the framework itself will sometimes try to synchronously
374 // work on main thread. And this will create a dead lock.
375 [(__bridge AVCaptureSession *)p_sys->session performSelectorOnMainThread:@selector(stopRunning) withObject:nil waitUntilDone:NO];
376 CFBridgingRelease(p_sys->output);
377 CFBridgingRelease(p_sys->session);
383 /*****************************************************************************
385 *****************************************************************************/
386 static int Demux(demux_t *p_demux)
388 demux_sys_t *p_sys = p_demux->p_sys;
392 @synchronized ( p_sys->output )
394 p_block = block_Alloc([(__bridge VLCAVDecompressedVideoOutput *)p_sys->output width] * [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output bytesPerRow]);
398 msg_Err(p_demux, "cannot get block");
402 p_block->i_pts = [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output copyCurrentFrameToBuffer: p_block->p_buffer];
404 if ( !p_block->i_pts )
406 /* Nothing to display yet, just forget */
407 block_Release(p_block);
411 else if ( !p_sys->b_es_setup )
413 p_sys->fmt.video.i_frame_rate_base = [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output timeScale];
414 msg_Dbg(p_demux, "using frame rate base: %i", p_sys->fmt.video.i_frame_rate_base);
415 p_sys->width = p_sys->fmt.video.i_width = [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output width];
416 p_sys->height = p_sys->fmt.video.i_height = [(__bridge VLCAVDecompressedVideoOutput *)p_sys->output height];
417 p_sys->p_es_video = es_out_Add(p_demux->out, &p_sys->fmt);
418 msg_Dbg(p_demux, "added new video es %4.4s %dx%d", (char*)&p_sys->fmt.i_codec, p_sys->width, p_sys->height);
419 p_sys->b_es_setup = YES;
423 es_out_SetPCR(p_demux->out, p_block->i_pts);
424 es_out_Send(p_demux->out, p_sys->p_es_video, p_block);
430 /*****************************************************************************
432 *****************************************************************************/
433 static int Control(demux_t *p_demux, int i_query, va_list args)
440 /* Special for access_demux */
441 case DEMUX_CAN_PAUSE:
443 case DEMUX_SET_PAUSE_STATE:
444 case DEMUX_CAN_CONTROL_PACE:
445 pb = va_arg(args, bool *);
449 case DEMUX_GET_PTS_DELAY:
450 pi64 = va_arg(args, int64_t *);
451 *pi64 = INT64_C(1000) * var_InheritInteger(p_demux, "live-caching");
455 pi64 = va_arg(args, int64_t *);