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