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 *****************************************************************************/
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_input.h>
35 #include <vlc_demux.h>
36 #include <vlc_interface.h>
37 #include <vlc_dialog.h>
38 #include <vlc_access.h>
40 #import <AVFoundation/AVFoundation.h>
41 #import <CoreMedia/CoreMedia.h>
43 /*****************************************************************************
45 *****************************************************************************/
46 static int Open(vlc_object_t *p_this);
47 static void Close(vlc_object_t *p_this);
48 static int Demux(demux_t *p_demux);
49 static int Control(demux_t *, int, va_list);
51 /*****************************************************************************
53 *****************************************************************************/
55 set_shortname(N_("AVFoundation Video Capture"))
56 set_description(N_("AVFoundation video capture module."))
57 set_category(CAT_INPUT)
58 set_subcategory(SUBCAT_INPUT_ACCESS)
59 add_shortcut("avcapture")
60 set_capability("access_demux", 10)
61 set_callbacks(Open, Close)
65 /*****************************************************************************
67 *****************************************************************************/
68 @interface VLCAVDecompressedVideoOutput : AVCaptureVideoDataOutput
72 CVImageBufferRef currentImageBuffer;
73 CMVideoDimensions videoDimensions;
80 BOOL videoDimensionsReady;
83 @property (readwrite) CMVideoDimensions videoDimensions;
85 - (id)initWithDemux:(demux_t *)p_demux;
88 - (void)getVideoDimensions:(CMSampleBufferRef)sampleBuffer;
89 - (mtime_t)currentPts;
90 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection;
91 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer;
94 @implementation VLCAVDecompressedVideoOutput : AVCaptureVideoDataOutput
96 @synthesize videoDimensions;
98 - (id)initWithDemux:(demux_t *)p_demux
100 if (self = [super init])
102 p_avcapture = p_demux;
103 currentImageBuffer = nil;
108 videoDimensionsReady = NO;
117 CVBufferRelease(currentImageBuffer);
118 currentImageBuffer = nil;
120 videoDimensionsReady = NO;
132 return self.videoDimensions.width;
137 return self.videoDimensions.height;
140 - (size_t)bytesPerRow
145 - (void)getVideoDimensions:(CMSampleBufferRef)sampleBuffer
147 if (!videoDimensionsReady)
149 CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
150 self.videoDimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
151 bytesPerRow = CVPixelBufferGetBytesPerRow(CMSampleBufferGetImageBuffer(sampleBuffer));
152 videoDimensionsReady = YES;
153 msg_Dbg(p_avcapture, "Dimensionns obtained height:%i width:%i bytesPerRow:%lu", [self height], [self width], bytesPerRow);
161 if ( !currentImageBuffer || currentPts == previousPts )
166 pts = previousPts = currentPts;
172 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
174 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
176 CVImageBufferRef imageBufferToRelease;
177 CMTime presentationtimestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
178 CVImageBufferRef videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
179 CVBufferRetain(videoFrame);
180 [self getVideoDimensions:sampleBuffer];
184 imageBufferToRelease = currentImageBuffer;
185 currentImageBuffer = videoFrame;
186 currentPts = (mtime_t)presentationtimestamp.value;
187 timeScale = (long)presentationtimestamp.timescale;
190 CVBufferRelease(imageBufferToRelease);
194 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer
196 CVImageBufferRef imageBuffer;
201 if ( !currentImageBuffer || currentPts == previousPts )
206 imageBuffer = CVBufferRetain(currentImageBuffer);
209 pts = previousPts = currentPts;
210 CVPixelBufferLockBaseAddress(imageBuffer, 0);
211 pixels = CVPixelBufferGetBaseAddress(imageBuffer);
214 memcpy(buffer, pixels, CVPixelBufferGetHeight(imageBuffer) * CVPixelBufferGetBytesPerRow(imageBuffer));
216 CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
219 CVBufferRelease(imageBuffer);
229 /*****************************************************************************
231 *****************************************************************************/
235 AVCaptureSession *session;
236 AVCaptureDevice *device;
237 VLCAVDecompressedVideoOutput *output;
238 es_out_id_t *p_es_video;
244 /*****************************************************************************
246 *****************************************************************************/
247 static int Open(vlc_object_t *p_this)
249 demux_t *p_demux = (demux_t*)p_this;
250 demux_sys_t *p_sys = NULL;
252 NSString *avf_currdevice_uid;
253 NSArray *myVideoDevices;
254 NSError *o_returnedError;
256 AVCaptureDeviceInput *input = nil;
258 int i, i_width, i_height, deviceCount, ivideo;
260 char *psz_uid = NULL;
262 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
264 /* Only when selected */
265 if ( *p_demux->psz_access == '\0' )
268 if ( p_demux->psz_location && *p_demux->psz_location )
269 psz_uid = strdup(p_demux->psz_location);
271 msg_Dbg(p_demux, "avcapture uid = %s", psz_uid);
272 avf_currdevice_uid = [[NSString alloc] initWithFormat:@"%s", psz_uid];
275 p_demux->pf_demux = Demux;
276 p_demux->pf_control = Control;
277 p_demux->info.i_update = 0;
278 p_demux->info.i_title = 0;
279 p_demux->info.i_seekpoint = 0;
281 p_demux->p_sys = p_sys = calloc(1, sizeof(demux_sys_t));
285 myVideoDevices = [[[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] arrayByAddingObjectsFromArray:[AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed]] retain];
286 if ( [myVideoDevices count] == 0 )
288 dialog_FatalWait(p_demux, _("No video devices found"),
289 _("Your Mac does not seem to be equipped with a suitable video input device. "
290 "Please check your connectors and drivers."));
291 msg_Err(p_demux, "Can't find any suitable video device");
295 deviceCount = [myVideoDevices count];
296 for ( ivideo = 0; ivideo < deviceCount; ivideo++ )
298 AVCaptureDevice *avf_device;
299 avf_device = [myVideoDevices objectAtIndex:ivideo];
300 msg_Dbg(p_demux, "avcapture %i/%i %s %s", ivideo, deviceCount, [[avf_device modelID] UTF8String], [[avf_device uniqueID] UTF8String]);
301 if ([[[avf_device uniqueID]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:avf_currdevice_uid]) {
306 if ( ivideo < [myVideoDevices count] )
308 p_sys->device = [myVideoDevices objectAtIndex:ivideo];
312 msg_Dbg(p_demux, "Cannot find designated device as %s, falling back to default.", [avf_currdevice_uid UTF8String]);
313 p_sys->device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
315 if ( !p_sys->device )
317 dialog_FatalWait(p_demux, _("No video devices found"),
318 _("Your Mac does not seem to be equipped with a suitable input device. "
319 "Please check your connectors and drivers."));
320 msg_Err(p_demux, "Can't find any suitable video device");
324 if ( [p_sys->device isInUseByAnotherApplication] == YES )
326 msg_Err(p_demux, "default capture device is exclusively in use by another application");
330 input = [AVCaptureDeviceInput deviceInputWithDevice:p_sys->device error:&o_returnedError];
334 msg_Err(p_demux, "can't create a valid capture input facility (%ld)", [o_returnedError code]);
338 int chroma = VLC_CODEC_RGB32;
340 memset(&p_sys->fmt, 0, sizeof(es_format_t));
341 es_format_Init(&p_sys->fmt, VIDEO_ES, chroma);
343 p_sys->session = [[AVCaptureSession alloc] init];
344 [p_sys->session addInput:input];
346 p_sys->output = [[VLCAVDecompressedVideoOutput alloc] initWithDemux:p_demux];
347 [p_sys->session addOutput:p_sys->output];
349 dispatch_queue_t queue = dispatch_queue_create("avCaptureQueue", NULL);
350 [p_sys->output setSampleBufferDelegate:(id)p_sys->output queue:queue];
351 dispatch_release(queue);
353 p_sys->output.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
354 [p_sys->session startRunning];
358 msg_Dbg(p_demux, "AVCapture: Video device ready!");
363 msg_Err(p_demux, "Error");
372 /*****************************************************************************
374 *****************************************************************************/
375 static void Close(vlc_object_t *p_this)
377 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
378 demux_t *p_demux = (demux_t*)p_this;
379 demux_sys_t *p_sys = p_demux->p_sys;
381 msg_Dbg(p_demux,"Close AVCapture");
383 if ( vlc_object_alive(p_this->p_libvlc) )
385 // Perform this on main thread, as the framework itself will sometimes try to synchronously
386 // work on main thread. And this will create a dead lock.
387 [p_sys->session performSelectorOnMainThread:@selector(stopRunning) withObject:nil waitUntilDone:NO];
388 [p_sys->output performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
389 [p_sys->session performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
397 /*****************************************************************************
399 *****************************************************************************/
400 static int Demux(demux_t *p_demux)
402 demux_sys_t *p_sys = p_demux->p_sys;
405 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
407 @synchronized ( p_sys->output )
409 p_block = block_Alloc([p_sys->output width] * [p_sys->output bytesPerRow]);
413 msg_Err(p_demux, "cannot get block");
417 p_block->i_pts = [p_sys->output copyCurrentFrameToBuffer: p_block->p_buffer];
419 if ( !p_block->i_pts )
421 /* Nothing to display yet, just forget */
422 block_Release(p_block);
427 else if ( !p_sys->b_es_setup )
429 p_sys->fmt.video.i_frame_rate_base = [p_sys->output timeScale];
430 msg_Dbg(p_demux, "using frame rate base: %i", p_sys->fmt.video.i_frame_rate_base);
431 p_sys->width = p_sys->fmt.video.i_width = [p_sys->output width];
432 p_sys->height = p_sys->fmt.video.i_height = [p_sys->output height];
433 p_sys->p_es_video = es_out_Add(p_demux->out, &p_sys->fmt);
434 msg_Dbg(p_demux, "added new video es %4.4s %dx%d", (char*)&p_sys->fmt.i_codec, p_sys->width, p_sys->height);
435 p_sys->b_es_setup = YES;
439 es_out_Control(p_demux->out, ES_OUT_SET_PCR, p_block->i_pts);
440 es_out_Send(p_demux->out, p_sys->p_es_video, p_block);
446 /*****************************************************************************
448 *****************************************************************************/
449 static int Control(demux_t *p_demux, int i_query, va_list args)
456 /* Special for access_demux */
457 case DEMUX_CAN_PAUSE:
459 case DEMUX_SET_PAUSE_STATE:
460 case DEMUX_CAN_CONTROL_PACE:
461 pb = (bool*)va_arg(args, bool *);
465 case DEMUX_GET_PTS_DELAY:
466 pi64 = (int64_t*)va_arg(args, int64_t *);
467 *pi64 = INT64_C(1000) * var_InheritInteger(p_demux, "live-caching");
471 pi64 = (int64_t*)va_arg(args, int64_t *);