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