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