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