]> git.sesse.net Git - vlc/blob - modules/access/qtcapture.m
Use the actual pts in qtcapture.
[vlc] / modules / access / qtcapture.m
1 /*****************************************************************************
2 * qtcapture.m: qtkit (Mac OS X) based capture module
3 *****************************************************************************
4 * Copyright (C) 2008 the VideoLAN team
5 *
6 * Authors: Pierre d'Herbemont <pdherbemont@videolan.org>
7 *
8 *****************************************************************************
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation;
12 * version 2 of the License.
13 *
14 * This library 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 GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22 *
23 *****************************************************************************/
24
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_input.h>
36 #include <vlc_vout.h>
37 #include <vlc_demux.h>
38 #include <vlc_interface.h>
39
40 #import <QTKit/QTKit.h>
41
42 /*****************************************************************************
43 * Local prototypes
44 *****************************************************************************/
45 static int Open( vlc_object_t *p_this );
46 static void Close( vlc_object_t *p_this );
47 static int Demux( demux_t *p_demux );
48 static int Control( demux_t *, int, va_list );
49
50 /*****************************************************************************
51 * Module descriptor
52 *****************************************************************************/
53 vlc_module_begin();
54    set_shortname( N_("Quicktime Capture") );
55    set_description( N_("Quicktime Capture") );
56    set_category( CAT_INPUT );
57    set_subcategory( SUBCAT_INPUT_ACCESS );
58    add_shortcut( "qtcapture" );
59    set_capability( "access_demux", 10 );
60    set_callbacks( Open, Close );
61 vlc_module_end();
62
63
64 /*****************************************************************************
65 * QTKit Bridge
66 *****************************************************************************/
67 @interface VLCDecompressedVideoOutput : QTCaptureDecompressedVideoOutput
68 {
69     CVImageBufferRef currentImageBuffer;
70     mtime_t currentPts;
71 }
72 - (id)init;
73 - (void)outputVideoFrame:(CVImageBufferRef)videoFrame withSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection;
74 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer;
75 @end
76
77 /* Apple sample code */
78 @implementation VLCDecompressedVideoOutput : QTCaptureDecompressedVideoOutput
79 - (id)init
80 {
81     if( self = [super init] )
82     {
83         currentImageBuffer = nil;
84         currentPts = 0;
85     }
86     return self;
87 }
88 - (void)dealloc
89 {
90     @synchronized (self)
91     {
92         CVBufferRelease(currentImageBuffer);
93         currentImageBuffer = nil;
94     }
95     [super dealloc];
96 }
97
98 - (void)outputVideoFrame:(CVImageBufferRef)videoFrame withSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection
99 {
100     // Store the latest frame
101     // This must be done in a @synchronized block because this delegate method is not called on the main thread
102     CVImageBufferRef imageBufferToRelease;
103
104     CVBufferRetain(videoFrame);
105
106     @synchronized (self)
107     {
108         imageBufferToRelease = currentImageBuffer;
109         currentImageBuffer = videoFrame;
110         currentPts = 1000000L / [sampleBuffer presentationTime].timeScale * [sampleBuffer presentationTime].timeValue;
111     }
112     CVBufferRelease(imageBufferToRelease);
113 }
114
115 - (mtime_t)copyCurrentFrameToBuffer:(void *)buffer
116 {
117     CVImageBufferRef imageBuffer;
118     mtime_t pts;
119
120     if(!currentImageBuffer)
121         return 0;
122
123     @synchronized (self)
124     {
125         imageBuffer = CVBufferRetain(currentImageBuffer);
126         pts = currentPts;
127
128         CVPixelBufferLockBaseAddress(imageBuffer, 0);
129         void * pixels = CVPixelBufferGetBaseAddress(imageBuffer);
130         memcpy( buffer, pixels, CVPixelBufferGetBytesPerRow(imageBuffer) * CVPixelBufferGetHeight(imageBuffer) );
131         CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
132     }
133
134     CVBufferRelease(imageBuffer);
135
136     return currentPts;
137 }
138
139 @end
140
141 /*****************************************************************************
142 * Struct
143 *****************************************************************************/
144
145 struct demux_sys_t {
146     QTCaptureSession * session;
147     QTCaptureDevice * device;
148     VLCDecompressedVideoOutput * output;
149     int height, width;
150     es_out_id_t * p_es_video;
151 };
152
153
154 /*****************************************************************************
155 * qtchroma_to_fourcc
156 *****************************************************************************/
157 static int qtchroma_to_fourcc( int i_qt )
158 {
159     static struct
160     {
161         unsigned int i_qt;
162         int i_fourcc;
163     } qtchroma_to_fourcc[] =
164     {
165         /* Raw data types */
166         { k422YpCbCr8CodecType,    VLC_FOURCC('U','Y','V','Y') },
167         { 0, 0 }
168     };
169     int i;
170     for( i = 0; qtchroma_to_fourcc[i].i_qt; i++ )
171     {
172         if( qtchroma_to_fourcc[i].i_qt == i_qt )
173             return qtchroma_to_fourcc[i].i_fourcc;
174     }
175     return 0;
176 }
177
178 /*****************************************************************************
179 * Open:
180 *****************************************************************************/
181 static int Open( vlc_object_t *p_this )
182 {
183     demux_t     *p_demux = (demux_t*)p_this;
184     demux_sys_t *p_sys = NULL;
185     es_format_t fmt;
186     int i;
187     int i_width;
188     int i_height;
189     int i_aspect;
190     int result = 0;
191
192     /* Only when selected */
193     if( *p_demux->psz_access == '\0' )
194         return VLC_EGENERIC;
195     
196     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
197
198     /* Set up p_demux */
199     p_demux->pf_demux = Demux;
200     p_demux->pf_control = Control;
201     p_demux->info.i_update = 0;
202     p_demux->info.i_title = 0;
203     p_demux->info.i_seekpoint = 0;
204     
205     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
206     if( !p_sys ) return VLC_ENOMEM;
207     
208     memset( p_sys, 0, sizeof( demux_sys_t ) );
209     memset( &fmt, 0, sizeof( es_format_t ) );    
210     
211     msg_Dbg( p_demux, "QTCapture Probed" );
212
213     QTCaptureDeviceInput * input = nil;
214     NSError *o_returnedError;
215
216     p_sys->device = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeVideo];
217     if( !p_sys->device )
218     {
219         intf_UserFatal( p_demux, true, _("No Input device found"),
220                         _("Your Mac does not seem to be equipped with a suitable input device. "
221                           "Please check your connectors and drivers.") );
222         msg_Err( p_demux, "Can't find any Video device" );
223         
224         goto error;
225     }
226
227     if( ![p_sys->device open: &o_returnedError] )
228     {
229         msg_Err( p_demux, "Unable to open the capture device (%i)", [o_returnedError code] );
230         goto error;
231     }
232
233     if( [p_sys->device isInUseByAnotherApplication] == YES )
234     {
235         msg_Err( p_demux, "default capture device is exclusively in use by another application" );
236         goto error;
237     }
238
239     input = [[QTCaptureDeviceInput alloc] initWithDevice: p_sys->device];
240     if( !input )
241     {
242         msg_Err( p_demux, "can't create a valid capture input facility" );
243         goto error;
244     }
245
246     p_sys->output = [[VLCDecompressedVideoOutput alloc] init];
247
248     /* Hack - This will lower CPU consumption for some reason */
249     [p_sys->output setPixelBufferAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
250         [NSNumber numberWithInt:480], kCVPixelBufferHeightKey,
251         [NSNumber numberWithInt:640], kCVPixelBufferWidthKey, nil]];
252
253     p_sys->session = [[QTCaptureSession alloc] init];
254
255     bool ret = [p_sys->session addInput:input error: &o_returnedError];
256     if( !ret )
257     {
258         msg_Err( p_demux, "default video capture device could not be added to capture session (%i)", [o_returnedError code] );
259         goto error;
260     }
261
262     ret = [p_sys->session addOutput:p_sys->output error: &o_returnedError];
263     if( !ret )
264     {
265         msg_Err( p_demux, "output could not be added to capture session (%i)", [o_returnedError code] );
266         goto error;
267     }
268
269     [p_sys->session startRunning];
270
271
272     int qtchroma = [[[p_sys->device formatDescriptions] objectAtIndex: 0] formatType]; /* FIXME */
273     int chroma = qtchroma_to_fourcc( qtchroma );
274     if( !chroma )
275     {
276         msg_Err( p_demux, "Unknown qt chroma %4.4s provided by camera", (char*)&qtchroma );
277         goto error;
278     }
279
280     /* Now we can init */
281
282     es_format_Init( &fmt, VIDEO_ES, chroma );
283
284     NSSize size = [[p_sys->device attributeForKey:QTFormatDescriptionVideoEncodedPixelsSizeAttribute] sizeValue];
285     p_sys->width = fmt.video.i_width = 640;/* size.width; FIXME */
286     p_sys->height = fmt.video.i_height = 480;/* size.height; FIXME */
287
288     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
289             (char*)&fmt.i_codec, fmt.video.i_width, fmt.video.i_height );
290
291     p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
292
293     [input release];
294     [pool release];
295
296     msg_Dbg( p_demux, "QTCapture: We have a video device ready!" );
297
298     return VLC_SUCCESS;
299 error:
300     [input release];
301     [pool release];
302
303     free( p_sys );
304
305     return VLC_EGENERIC;
306 }
307
308 /*****************************************************************************
309 * Close:
310 *****************************************************************************/
311 static void Close( vlc_object_t *p_this )
312 {
313     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
314
315     demux_t     *p_demux = (demux_t*)p_this;
316     demux_sys_t *p_sys = p_demux->p_sys;
317
318     [p_sys->session stopRunning];
319     [p_sys->output release];
320     [p_sys->session release];
321     [p_sys->device release];
322     free( p_sys );
323
324     [pool release];
325 }
326
327
328 /*****************************************************************************
329 * Demux:
330 *****************************************************************************/
331 static int Demux( demux_t *p_demux )
332 {
333     demux_sys_t *p_sys = p_demux->p_sys;
334     block_t *p_block;
335
336     p_block = block_New( p_demux, p_sys->width *
337                             p_sys->height * 2 /* FIXME */ );
338     if( !p_block )
339     {
340         msg_Err( p_demux, "cannot get block" );
341         return 0;
342     }
343
344     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
345
346     @synchronized (p_sys->output)
347     {
348     p_block->i_pts = [p_sys->output copyCurrentFrameToBuffer: p_block->p_buffer];
349     }
350
351     if( !p_block->i_pts )
352     {
353         /* Nothing to display yet, just forget */
354         block_Release( p_block );
355         [pool release];
356         return 1;
357     }
358
359     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
360     es_out_Send( p_demux->out, p_sys->p_es_video, p_block );
361
362     [pool release];
363     return 1;
364 }
365
366 /*****************************************************************************
367 * Control:
368 *****************************************************************************/
369 static int Control( demux_t *p_demux, int i_query, va_list args )
370 {
371     bool *pb;
372     int64_t    *pi64;
373
374     switch( i_query )
375     {
376         /* Special for access_demux */
377         case DEMUX_CAN_PAUSE:
378         case DEMUX_CAN_SEEK:
379         case DEMUX_SET_PAUSE_STATE:
380         case DEMUX_CAN_CONTROL_PACE:
381            pb = (bool*)va_arg( args, bool * );
382            *pb = false;
383            return VLC_SUCCESS;
384
385         case DEMUX_GET_PTS_DELAY:
386            pi64 = (int64_t*)va_arg( args, int64_t * );
387            *pi64 = (int64_t)DEFAULT_PTS_DELAY;
388            return VLC_SUCCESS;
389
390         default:
391            return VLC_EGENERIC;
392     }
393     return VLC_EGENERIC;
394 }