4951fc14d329afac289fe801f83e857de163caf2
[vlc.git] / modules / video_output / opengllayer.m
1 /*****************************************************************************
2  * opengl.c: CAOpenGLLayer (Mac OS X) video output. Display a video output in
3  * a layer. The layer will register itself to the drawable object stored in 
4  * the "drawable" variable. 
5  *****************************************************************************
6  * Copyright (C) 2004 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Cyril Deguet <asmax@videolan.org>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *          Eric Petit <titer@m0k.org>
12  *          Cedric Cocquebert <cedric.cocquebert@supelec.fr>
13  *          Pierre d'Herbemont <pdherbemont # videolan.org>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #include <errno.h>                                                 /* ENOMEM */
34
35 #include <vlc/vlc.h>
36 #include <vlc_vout.h>
37
38 #import <QuartzCore/QuartzCore.h>
39 #import <Cocoa/Cocoa.h>
40 #import <OpenGL/OpenGL.h>
41
42 /* On OS X, use GL_TEXTURE_RECTANGLE_EXT instead of GL_TEXTURE_2D.
43    This allows sizes which are not powers of 2 */
44 #define VLCGL_TARGET GL_TEXTURE_RECTANGLE_EXT
45
46 /* OS X OpenGL supports YUV. Hehe. */
47 #define VLCGL_FORMAT GL_YCBCR_422_APPLE
48 #define VLCGL_TYPE   GL_UNSIGNED_SHORT_8_8_APPLE
49
50 /* RV32 */
51 #define VLCGL_RGB_FORMAT GL_RGBA
52 #define VLCGL_RGB_TYPE GL_UNSIGNED_BYTE
53
54 /* YUY2 */
55 #ifndef YCBCR_MESA
56 #define YCBCR_MESA 0x8757
57 #endif
58 #ifndef UNSIGNED_SHORT_8_8_MESA
59 #define UNSIGNED_SHORT_8_8_MESA 0x85BA
60 #endif
61 #define VLCGL_YUV_FORMAT YCBCR_MESA
62 #define VLCGL_YUV_TYPE UNSIGNED_SHORT_8_8_MESA
63
64
65 #ifndef GL_CLAMP_TO_EDGE
66 #   define GL_CLAMP_TO_EDGE 0x812F
67 #endif
68
69 @interface VLCVideoView : NSObject
70 - (void)addVoutLayer:(CALayer *)layer;
71 @end
72
73 /*****************************************************************************
74  * Vout interface
75  *****************************************************************************/
76 static int  CreateVout   ( vlc_object_t * );
77 static void DestroyVout  ( vlc_object_t * );
78 static int  Init         ( vout_thread_t * );
79 static void End          ( vout_thread_t * );
80 static int  Manage       ( vout_thread_t * );
81 static void Render       ( vout_thread_t *, picture_t * );
82 static void DisplayVideo ( vout_thread_t *, picture_t * );
83 static int  Control      ( vout_thread_t *, int, va_list );
84
85 static int InitTextures  ( vout_thread_t * );
86
87 vlc_module_begin();
88     set_shortname( "OpenGLLayer" );
89     set_category( CAT_VIDEO );
90     set_subcategory( SUBCAT_VIDEO_VOUT );
91     set_description( _("Core Animation OpenGL Layer (Mac OS X)") );
92     set_capability( "video output", 20 );
93     add_shortcut( "opengllayer" );
94     set_callbacks( CreateVout, DestroyVout );
95 vlc_module_end();
96
97 @interface VLCVoutLayer : CAOpenGLLayer {
98     vout_thread_t * p_vout;
99 }
100 + (id)layerWithVout:(vout_thread_t*)_p_vout; 
101 @end
102
103 /*****************************************************************************
104  * vout_sys_t: video output method descriptor
105  *****************************************************************************
106  * This structure is part of the video output thread descriptor.
107  * It describes the OpenGL specific properties of the output thread.
108  *****************************************************************************/
109 struct vout_sys_t
110 {
111     vout_thread_t * p_vout;
112
113     uint8_t    *pp_buffer[3]; /* one last rendered, one to be rendered */
114     int         i_rendering_index;
115     int         i_rendered_index;
116     int         i_on_screen_index;
117     vlc_bool_t  b_frame_available;
118
119     int         i_tex_width;
120     int         i_tex_height;
121     GLuint      p_textures[3];
122
123     NSAutoreleasePool *autorealease_pool;
124     VLCVoutLayer * o_layer;
125     id          o_cocoa_container;
126 };
127
128 /*****************************************************************************
129  * CreateVout: This function allocates and initializes the OpenGL vout method.
130  *****************************************************************************/
131 static int CreateVout( vlc_object_t *p_this )
132 {
133     vout_thread_t *p_vout = (vout_thread_t *)p_this;
134     vout_sys_t *p_sys;
135     char * psz;
136
137     /* Allocate structure */
138     p_vout->p_sys = p_sys = calloc( sizeof( vout_sys_t ), 1 );
139     if( p_sys == NULL )
140     {
141         msg_Err( p_vout, "out of memory" );
142         return VLC_EGENERIC;
143     }
144
145     p_sys->i_tex_width  = p_vout->fmt_in.i_width;
146     p_sys->i_tex_height = p_vout->fmt_in.i_height;
147
148     msg_Dbg( p_vout, "Texture size: %dx%d", p_sys->i_tex_width,
149              p_sys->i_tex_height );
150
151     p_vout->pf_init = Init;
152     p_vout->pf_end = End;
153     p_vout->pf_manage = Manage;
154     p_vout->pf_render = Render;
155     p_vout->pf_display = DisplayVideo;
156     p_vout->pf_control = Control;
157
158     return VLC_SUCCESS;
159 }
160
161 /*****************************************************************************
162  * Init: initialize the OpenGL video thread output method
163  *****************************************************************************/
164 static int Init( vout_thread_t *p_vout )
165 {
166     vout_sys_t *p_sys = p_vout->p_sys;
167     int i_pixel_pitch;
168     vlc_value_t val;
169
170 #if ( defined( WORDS_BIGENDIAN ) && VLCGL_FORMAT == GL_YCBCR_422_APPLE ) || (VLCGL_FORMAT == YCBCR_MESA)
171     p_vout->output.i_chroma = VLC_FOURCC('Y','U','Y','2');
172     i_pixel_pitch = 2;
173 #elif (VLCGL_FORMAT == GL_YCBCR_422_APPLE)
174     p_vout->output.i_chroma = VLC_FOURCC('U','Y','V','Y');
175     i_pixel_pitch = 2;
176 #endif
177
178     /* Since OpenGL can do rescaling for us, stick to the default
179      * coordinates and aspect. */
180     p_vout->output.i_width  = p_vout->render.i_width;
181     p_vout->output.i_height = p_vout->render.i_height;
182     p_vout->output.i_aspect = p_vout->render.i_aspect;
183
184     /* We do need a drawable to work properly */
185     vlc_value_t value_drawable;
186     var_Create( p_vout, "drawable", VLC_VAR_DOINHERIT );
187     var_Get( p_vout, "drawable", &value_drawable );
188
189     p_vout->p_sys->o_cocoa_container = (id) value_drawable.i_int;
190     
191     p_vout->fmt_out = p_vout->fmt_in;
192     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
193
194     /* We know the chroma, allocate two buffer which will be used
195      * directly by the decoder */
196     int i;
197     for( i = 0; i < 3; i++ )
198     {
199         p_sys->pp_buffer[i] =
200             malloc( p_sys->i_tex_width * p_sys->i_tex_height * i_pixel_pitch );
201         if( !p_sys->pp_buffer[i] )
202         {
203             msg_Err( p_vout, "out of memory" );
204             return VLC_EGENERIC;
205         }
206     }
207     p_sys->b_frame_available = VLC_FALSE;
208     p_sys->i_on_screen_index = 0;
209     p_sys->i_rendered_index = 1;
210     p_sys->i_rendering_index = 2;
211
212     p_vout->p_picture[0].i_planes = 1;
213     p_vout->p_picture[0].p->p_pixels = p_sys->pp_buffer[p_sys->i_rendering_index];
214     p_vout->p_picture[0].p->i_lines = p_vout->output.i_height;
215     p_vout->p_picture[0].p->i_visible_lines = p_vout->output.i_height;
216     p_vout->p_picture[0].p->i_pixel_pitch = i_pixel_pitch;
217     p_vout->p_picture[0].p->i_pitch = p_vout->output.i_width *
218         p_vout->p_picture[0].p->i_pixel_pitch;
219     p_vout->p_picture[0].p->i_visible_pitch = p_vout->output.i_width *
220         p_vout->p_picture[0].p->i_pixel_pitch;
221
222     p_vout->p_picture[0].i_status = DESTROYED_PICTURE;
223     p_vout->p_picture[0].i_type   = DIRECT_PICTURE;
224
225     PP_OUTPUTPICTURE[ 0 ] = &p_vout->p_picture[0];
226
227     I_OUTPUTPICTURES = 1;
228     p_sys->autorealease_pool = [[NSAutoreleasePool alloc] init];
229
230     [VLCVoutLayer performSelectorOnMainThread:@selector(autoinitInVout:)
231                              withObject:[NSValue valueWithPointer:p_vout]
232                              waitUntilDone:YES];
233
234     return 0;
235 }
236
237 /*****************************************************************************
238  * End: terminate GLX video thread output method
239  *****************************************************************************/
240 static void End( vout_thread_t *p_vout )
241 {
242     vout_sys_t *p_sys = p_vout->p_sys;
243
244     p_vout->p_sys->b_frame_available = VLC_FALSE;
245
246     [CATransaction performSelectorOnMainThread:@selector(begin)
247                     withObject:nil waitUntilDone:YES];
248
249     [p_sys->o_layer performSelectorOnMainThread:@selector(removeFromSuperlayer)
250                     withObject:nil waitUntilDone:YES];
251     [CATransaction performSelectorOnMainThread:@selector(commit)
252                     withObject:nil waitUntilDone:YES];
253
254     // Should be done automatically
255     [p_sys->o_layer release];
256     [p_sys->autorealease_pool release];
257
258     /* Free the texture buffer*/
259     free( p_sys->pp_buffer[0] );
260     free( p_sys->pp_buffer[1] );
261     if( p_sys->pp_buffer[2] ) free( p_sys->pp_buffer[2] );
262 }
263
264 /*****************************************************************************
265  * Destroy: destroy GLX video thread output method
266  *****************************************************************************
267  * Terminate an output method created by CreateVout
268  *****************************************************************************/
269 static void DestroyVout( vlc_object_t *p_this )
270 {
271     vout_thread_t *p_vout = (vout_thread_t *)p_this;
272     vout_sys_t *p_sys = p_vout->p_sys;
273     free( p_sys );
274 }
275
276 /*****************************************************************************
277  * Manage: handle Sys events
278  *****************************************************************************
279  * This function should be called regularly by video output thread. It returns
280  * a non null value if an error occurred.
281  *****************************************************************************/
282 static int Manage( vout_thread_t *p_vout )
283 {
284     vout_sys_t *p_sys = p_vout->p_sys;
285
286     return VLC_SUCCESS;
287 }
288
289 /*****************************************************************************
290  * Render: render previously calculated output
291  *****************************************************************************/
292 static void Render( vout_thread_t *p_vout, picture_t *p_pic )
293 {
294     vout_sys_t *p_sys = p_vout->p_sys;
295
296     /* Make sure we never draw to the currently on screen buffer */
297     assert(p_sys->i_rendering_index != p_sys->i_on_screen_index );
298
299     /* Give a buffer where the image will be rendered */
300     p_pic->p->p_pixels = p_sys->pp_buffer[p_sys->i_rendering_index];
301
302
303 }
304
305 /*****************************************************************************
306  * DisplayVideo: displays previously rendered output
307  *****************************************************************************/
308 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
309 {
310     vout_sys_t *p_sys = p_vout->p_sys;
311
312     /* Swap the buffer */
313     @synchronized(p_sys->o_layer)
314     {
315         int temp = p_sys->i_rendered_index;
316         p_sys->i_rendered_index = p_sys->i_rendering_index;
317         p_sys->i_rendering_index = temp;
318         p_sys->b_frame_available = VLC_TRUE;
319         assert(p_sys->i_rendering_index != p_sys->i_on_screen_index );
320     }
321
322 }
323
324 /*****************************************************************************
325  * Control: control facility for the vout
326  *****************************************************************************/
327 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
328 {
329     vout_sys_t *p_sys = p_vout->p_sys;
330
331     switch( i_query )
332     {
333     case VOUT_SNAPSHOT:
334         return vout_vaControlDefault( p_vout, i_query, args );
335
336     default:
337         if( p_sys->p_vout->pf_control )
338             return p_sys->p_vout->pf_control( p_sys->p_vout, i_query, args );
339         else
340             return vout_vaControlDefault( p_vout, i_query, args );
341     }
342 }
343
344 /*****************************************************************************
345  * InitTextures
346  *****************************************************************************/
347 static int InitTextures( vout_thread_t *p_vout )
348 {
349     vout_sys_t *p_sys = p_vout->p_sys;
350     int i_index;
351
352     glDeleteTextures( 3, p_sys->p_textures );
353     glGenTextures( 3, p_sys->p_textures );
354
355     for( i_index = 0; i_index < 3; i_index++ )
356     {
357         glBindTexture( VLCGL_TARGET, p_sys->p_textures[i_index] );
358
359         /* Set the texture parameters */
360         glTexParameterf( VLCGL_TARGET, GL_TEXTURE_PRIORITY, 1.0 );
361
362         glTexParameteri( VLCGL_TARGET, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
363         glTexParameteri( VLCGL_TARGET, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
364
365         glTexParameteri( VLCGL_TARGET, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
366         glTexParameteri( VLCGL_TARGET, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
367
368         glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
369
370         /* Note: It seems that we can't bypass those, and even
371          * disabled they are used. They are the cause of the flickering */
372
373         /* Tell the driver not to make a copy of the texture but to use
374            our buffer */
375         glEnable( GL_UNPACK_CLIENT_STORAGE_APPLE );
376         glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE );
377
378         /* Use AGP texturing */
379         glTexParameteri( VLCGL_TARGET, GL_TEXTURE_STORAGE_HINT_APPLE,
380                          GL_STORAGE_SHARED_APPLE );
381
382         /* Call glTexImage2D only once, and use glTexSubImage2D later */
383         glTexImage2D( VLCGL_TARGET, 0, 4, p_sys->i_tex_width,
384                       p_sys->i_tex_height, 0, VLCGL_FORMAT, VLCGL_TYPE,
385                       p_sys->pp_buffer[i_index] );
386     }
387
388     return 0;
389 }
390
391 /*****************************************************************************
392  * @implementation VLCVoutLayer
393  */
394 @implementation VLCVoutLayer
395
396 /*****************************************************************************
397  * autoinitInVout: Called from the video thread to create a layer.
398  * The created layer is stored in the p_vout. We do that way because, cocoa
399  * doesn't support layer creation on non-main thread.
400  *****************************************************************************/
401 + (void)autoinitInVout:(NSValue*)arg
402 {
403     vout_thread_t * p_vout = [arg pointerValue];
404     p_vout->p_sys->o_layer = [[VLCVoutLayer layerWithVout:p_vout] retain];
405     [p_vout->p_sys->o_cocoa_container addVoutLayer:p_vout->p_sys->o_layer];
406 }
407
408 + (id)layerWithVout:(vout_thread_t*)_p_vout 
409 {
410     VLCVoutLayer* me = [[[self alloc] init] autorelease];
411     if( me )
412     {
413         me->p_vout = _p_vout;
414         me.asynchronous = YES;
415         me.bounds = CGRectMake( 0.0, 0.0, 
416                                 (float)_p_vout->fmt_in.i_visible_width * _p_vout->fmt_in.i_sar_num,
417                                 (float)_p_vout->fmt_in.i_visible_height * _p_vout->fmt_in.i_sar_den );
418     }
419     return me;
420 }
421
422 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
423 {
424     /* Only draw the frame if we have a frame that was previously rendered */
425         return p_vout->p_sys->b_frame_available; // Flag is cleared by drawInCGLContext:pixelFormat:forLayerTime:displayTime:
426 }
427
428 - (void)drawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
429 {
430     /* Init */
431     CGLLockContext( glContext );
432     CGLSetCurrentContext( glContext );
433
434     float f_width, f_height, f_x, f_y;
435
436     f_x = (float)p_vout->fmt_out.i_x_offset;
437     f_y = (float)p_vout->fmt_out.i_y_offset;
438     f_width = (float)p_vout->fmt_out.i_x_offset +
439               (float)p_vout->fmt_out.i_visible_width;
440     f_height = (float)p_vout->fmt_out.i_y_offset +
441                (float)p_vout->fmt_out.i_visible_height;
442
443     assert(p_vout->p_sys->i_rendering_index != p_vout->p_sys->i_on_screen_index );
444
445     @synchronized(self)
446     {
447         /* Swap the buffers */
448         if( p_vout->p_sys->b_frame_available )
449         {
450             int temp;
451             temp = p_vout->p_sys->i_on_screen_index;
452             p_vout->p_sys->i_on_screen_index = p_vout->p_sys->i_rendered_index;
453             p_vout->p_sys->i_rendered_index = temp;
454             p_vout->p_sys->b_frame_available = VLC_FALSE;
455         }
456     
457         glBindTexture( VLCGL_TARGET, p_vout->p_sys->p_textures[p_vout->p_sys->i_on_screen_index] );
458
459         glTexSubImage2D( VLCGL_TARGET, 0, 0, 0,
460                      p_vout->fmt_out.i_width,
461                      p_vout->fmt_out.i_height,
462                      VLCGL_FORMAT, VLCGL_TYPE, p_vout->p_sys->pp_buffer[p_vout->p_sys->i_on_screen_index] );
463
464         /* Make sure the that there is no old reference of the pointer old texture kept around */
465         glFinishObjectAPPLE(GL_TEXTURE_RECTANGLE_EXT, p_vout->p_sys->p_textures[p_vout->p_sys->i_on_screen_index]);
466
467         glClear( GL_COLOR_BUFFER_BIT );
468
469         glEnable( VLCGL_TARGET );
470         glBegin( GL_POLYGON );
471         glTexCoord2f( f_x, f_y ); glVertex2f( -1.0, 1.0 );
472         glTexCoord2f( f_width, f_y ); glVertex2f( 1.0, 1.0 );
473         glTexCoord2f( f_width, f_height ); glVertex2f( 1.0, -1.0 );
474         glTexCoord2f( f_x, f_height ); glVertex2f( -1.0, -1.0 );
475         glEnd();
476
477         glDisable( VLCGL_TARGET );
478
479         glFlush();
480         
481         CGLUnlockContext( glContext );
482
483         p_vout->p_sys->b_frame_available = VLC_FALSE;
484     }
485 }
486
487 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat
488 {
489     CGLContextObj context = [super copyCGLContextForPixelFormat:pixelFormat];
490
491     CGLLockContext( context );
492
493     CGLSetCurrentContext( context );
494
495     /* Swap buffers only during the vertical retrace of the monitor.
496     http://developer.apple.com/documentation/GraphicsImaging/
497     Conceptual/OpenGL/chap5/chapter_5_section_44.html */
498
499     GLint params = 1;
500     CGLSetParameter( CGLGetCurrentContext(), kCGLCPSwapInterval,
501                      &params );
502
503     InitTextures( p_vout );
504
505     glDisable( GL_BLEND );
506     glDisable( GL_DEPTH_TEST );
507     glDepthMask( GL_FALSE );
508     glDisable( GL_CULL_FACE) ;
509     glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
510     glClear( GL_COLOR_BUFFER_BIT );
511
512     CGLUnlockContext( context );
513
514     return context;
515 }
516
517 - (void)releaseCGLContext:(CGLContextObj)glContext
518 {
519     CGLLockContext( glContext );
520     CGLSetCurrentContext( glContext );
521
522     glDeleteTextures( 3, p_vout->p_sys->p_textures );
523
524     CGLUnlockContext( glContext );
525 }
526 @end