macosx: fixed video output
[vlc.git] / modules / gui / macosx / voutgl.m
1 /*****************************************************************************
2  * voutgl.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2004, 2007-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Colin Delacroix <colin@zoy.org>
8  *          Florian G. Pflug <fgp@phlo.org>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          Eric Petit <titer@m0k.org>
12  *          Benjamin Pracht <bigben at videolan dot org>
13  *          Damien Fouilleul <damienf at videolan dot 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 #include <stdlib.h>                                                /* free() */
35 #include <string.h>
36
37 #include <vlc_keys.h>
38
39 #include "intf.h"
40 #include "vout.h"
41
42 #include <OpenGL/OpenGL.h>
43 #include <OpenGL/gl.h>
44
45 #include <AGL/agl.h>
46
47 /*****************************************************************************
48  * VLCGLView interface
49  *****************************************************************************/
50 @interface VLCGLView : NSOpenGLView <VLCVoutViewResetting>
51 {
52     vout_thread_t * p_vout;
53 }
54
55 + (void)resetVout: (NSValue *) voutValue;
56 - (id) initWithVout: (vout_thread_t *) p_vout;
57 @end
58
59 struct vout_sys_t
60 {
61     VLCGLView         * o_glview;
62     VLCVoutView       * o_vout_view;
63     bool                b_saved_frame;
64     NSRect              s_frame;
65     bool                b_got_frame;
66
67     /* Mozilla plugin-related variables (not 64bit compatible) */
68     bool                b_embedded;
69 #ifndef __x86_64__
70     AGLContext          agl_ctx;
71     AGLDrawable         agl_drawable;
72     int                 i_offx, i_offy;
73     int                 i_width, i_height;
74     WindowRef           theWindow;
75     WindowGroupRef      winGroup;
76     bool                b_clipped_out;
77     Rect                clipBounds, viewBounds;
78 #endif
79 };
80
81 /*****************************************************************************
82  * Local prototypes
83  *****************************************************************************/
84
85 static int  Init   ( vout_thread_t * p_vout );
86 static void End    ( vout_thread_t * p_vout );
87 static int  Manage ( vout_thread_t * p_vout );
88 static int  Control( vout_thread_t *, int, va_list );
89 static void Swap   ( vout_thread_t * p_vout );
90 static int  Lock   ( vout_thread_t * p_vout );
91 static void Unlock ( vout_thread_t * p_vout );
92
93 #ifndef __x86_64__
94 static int  aglInit   ( vout_thread_t * p_vout );
95 static void aglEnd    ( vout_thread_t * p_vout );
96 static int  aglManage ( vout_thread_t * p_vout );
97 static int  aglControl( vout_thread_t *, int, va_list );
98 static void aglSwap   ( vout_thread_t * p_vout );
99 static int  aglLock   ( vout_thread_t * p_vout );
100 static void aglUnlock ( vout_thread_t * p_vout );
101 #endif
102
103 int OpenVideoGL  ( vlc_object_t * p_this )
104 {
105     vout_thread_t * p_vout = (vout_thread_t *) p_this;
106
107     if( !CGDisplayUsesOpenGLAcceleration( kCGDirectMainDisplay ) )
108     {
109         msg_Warn( p_vout, "no OpenGL hardware acceleration found. "
110                           "Video display might be slow" );
111     }
112     msg_Dbg( p_vout, "display is Quartz Extreme accelerated" );
113
114     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
115     if( p_vout->p_sys == NULL )
116         return VLC_ENOMEM;
117
118     memset( p_vout->p_sys, 0, sizeof( vout_sys_t ) );
119
120 #ifndef __x86_64__
121     int i_drawable_agl;
122     i_drawable_agl = var_GetInteger( p_vout->p_libvlc, "drawable-agl" );
123     if( i_drawable_agl > 0 )
124     {
125         static const GLint ATTRIBUTES[] = {
126             AGL_WINDOW,
127             AGL_RGBA,
128             AGL_NO_RECOVERY,
129             AGL_ACCELERATED,
130             AGL_DOUBLEBUFFER,
131             AGL_RED_SIZE,   8,
132             AGL_GREEN_SIZE, 8,
133             AGL_BLUE_SIZE,  8,
134             AGL_ALPHA_SIZE, 8,
135             AGL_DEPTH_SIZE, 24,
136             AGL_NONE };
137
138         AGLPixelFormat pixFormat;
139
140         p_vout->p_sys->b_embedded = true;
141
142         pixFormat = aglChoosePixelFormat(NULL, 0, ATTRIBUTES);
143         if( NULL == pixFormat )
144         {
145             msg_Err( p_vout, "no screen renderer available for required attributes." );
146             free( p_vout->p_sys );
147             return VLC_EGENERIC;
148         }
149  
150         p_vout->p_sys->agl_ctx = aglCreateContext(pixFormat, NULL);
151         aglDestroyPixelFormat(pixFormat);
152         if( NULL == p_vout->p_sys->agl_ctx )
153         {
154             msg_Err( p_vout, "cannot create AGL context." );
155             free( p_vout->p_sys );
156             return VLC_EGENERIC;
157         }
158         else
159         {
160             // tell opengl not to sync buffer swap with vertical retrace (too inefficient)
161             GLint param = 0;
162             aglSetInteger(p_vout->p_sys->agl_ctx, AGL_SWAP_INTERVAL, &param);
163             aglEnable(p_vout->p_sys->agl_ctx, AGL_SWAP_INTERVAL);
164         }
165
166         p_vout->pf_init             = aglInit;
167         p_vout->pf_end              = aglEnd;
168         p_vout->pf_manage           = aglManage;
169         p_vout->pf_control          = aglControl;
170         p_vout->pf_swap             = aglSwap;
171         p_vout->pf_lock             = aglLock;
172         p_vout->pf_unlock           = aglUnlock;
173     }
174     else
175     {
176 #endif
177         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
178
179         p_vout->p_sys->b_embedded = false;
180
181         [VLCGLView performSelectorOnMainThread:@selector(initVout:) withObject:[NSValue valueWithPointer:p_vout] waitUntilDone:YES];
182
183         [o_pool release];
184
185         /* Check to see if initVout: was successfull */
186         if( !p_vout->p_sys->o_vout_view )
187         {
188             free( p_vout->p_sys );
189             return VLC_EGENERIC;
190         }
191
192         p_vout->pf_init   = Init;
193         p_vout->pf_end    = End;
194         p_vout->pf_manage = Manage;
195         p_vout->pf_control= Control;
196         p_vout->pf_swap   = Swap;
197         p_vout->pf_lock   = Lock;
198         p_vout->pf_unlock = Unlock;
199 #ifndef __x86_64__
200     }
201 #endif
202     p_vout->p_sys->b_got_frame = false;
203
204     return VLC_SUCCESS;
205 }
206
207 void CloseVideoGL ( vlc_object_t * p_this )
208 {
209     vout_thread_t * p_vout = (vout_thread_t *) p_this;
210
211
212 #ifndef __x86_64__
213     if( p_vout->p_sys->b_embedded )
214     {
215         /* If the fullscreen window is still open, close it */
216         if( p_vout->b_fullscreen )
217         {
218             p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
219             aglManage( p_vout );
220             var_SetBool( p_vout->p_parent, "fullscreen", false );
221         }
222         if( p_vout->p_sys->agl_ctx )
223         {
224             aglEnd( p_vout );
225             aglDestroyContext(p_vout->p_sys->agl_ctx);
226         }
227     }
228     else
229 #endif
230     if(VLCIntf && vlc_object_alive (VLCIntf))
231     {
232         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
233
234         /* Close the window */
235         [p_vout->p_sys->o_vout_view performSelectorOnMainThread:@selector(closeVout) withObject:NULL waitUntilDone:YES];
236
237         [o_pool release];
238     }
239     /* Clean up */
240     free( p_vout->p_sys );
241 }
242
243 static int Init( vout_thread_t * p_vout )
244 {
245     [[p_vout->p_sys->o_glview openGLContext] makeCurrentContext];
246     return VLC_SUCCESS;
247 }
248
249 static void End( vout_thread_t * p_vout )
250 {
251     [[p_vout->p_sys->o_glview openGLContext] makeCurrentContext];
252 }
253
254 static int Manage( vout_thread_t * p_vout )
255 {
256     if( p_vout->i_changes & VOUT_ASPECT_CHANGE )
257     {
258         [p_vout->p_sys->o_glview reshape];
259         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
260     }
261     if( p_vout->i_changes & VOUT_CROP_CHANGE )
262     {
263         [p_vout->p_sys->o_glview reshape];
264         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
265     }
266
267     if( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
268     {
269         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
270
271         p_vout->b_fullscreen = !p_vout->b_fullscreen;
272
273         if( p_vout->b_fullscreen )
274             [p_vout->p_sys->o_vout_view enterFullscreen];
275         else
276             [p_vout->p_sys->o_vout_view leaveFullscreen];
277
278         [o_pool release];
279
280         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
281     }
282
283     if( p_vout->p_sys->o_vout_view )
284         [p_vout->p_sys->o_vout_view manage];
285     return VLC_SUCCESS;
286 }
287
288 /*****************************************************************************
289  * Control: control facility for the vout
290  *****************************************************************************/
291 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
292 {
293     bool b_arg;
294
295     switch( i_query )
296     {
297         case VOUT_SET_STAY_ON_TOP:
298             b_arg = (bool) va_arg( args, int );
299             [p_vout->p_sys->o_vout_view setOnTop: b_arg];
300             return VLC_SUCCESS;
301
302         default:
303             return VLC_EGENERIC;
304     }
305 }
306
307 static void Swap( vout_thread_t * p_vout )
308 {
309     p_vout->p_sys->b_got_frame = true;
310     [[p_vout->p_sys->o_glview openGLContext] flushBuffer];
311 }
312
313 static int Lock( vout_thread_t * p_vout )
314 {
315     if( kCGLNoError == CGLLockContext([[p_vout->p_sys->o_glview openGLContext] CGLContextObj]) )
316     {
317         [[p_vout->p_sys->o_glview openGLContext] makeCurrentContext];
318         return 0;
319     }
320     return 1;
321 }
322
323 static void Unlock( vout_thread_t * p_vout )
324 {
325     CGLUnlockContext([[p_vout->p_sys->o_glview openGLContext] CGLContextObj]);
326 }
327
328 /*****************************************************************************
329  * VLCGLView implementation
330  *****************************************************************************/
331 @implementation VLCGLView
332 + (void)initVout:(NSValue *)arg
333 {
334     vout_thread_t * p_vout = [arg pointerValue];
335
336     /* Create the GL view */
337     p_vout->p_sys->o_glview = [[VLCGLView alloc] initWithVout: p_vout];
338     [p_vout->p_sys->o_glview autorelease];
339
340     /* Spawn the window */
341     id old_vout = p_vout->p_sys->o_vout_view;
342     p_vout->p_sys->o_vout_view = [[VLCVoutView voutView: p_vout
343                                                 subView: p_vout->p_sys->o_glview frame: nil] retain];
344     [old_vout release];
345 }
346
347 /* This function will reset the o_vout_view. It's useful to go fullscreen. */
348 + (void)resetVout:(NSValue *) voutValue
349 {
350     vout_thread_t * p_vout = [voutValue pointerValue];
351     if( p_vout->b_fullscreen )
352     {
353         /* Save window size and position */
354         p_vout->p_sys->s_frame.size =
355             [p_vout->p_sys->o_vout_view frame].size;
356         p_vout->p_sys->s_frame.origin =
357             [[p_vout->p_sys->o_vout_view voutWindow]frame].origin;
358         p_vout->p_sys->b_saved_frame = true;
359     }
360
361     [p_vout->p_sys->o_vout_view closeVout];
362
363 #define o_glview p_vout->p_sys->o_glview
364     o_glview = [[VLCGLView alloc] initWithVout: p_vout];
365     [o_glview autorelease];
366  
367     if( p_vout->p_sys->b_saved_frame )
368     {
369         id old_vout = p_vout->p_sys->o_vout_view;
370         p_vout->p_sys->o_vout_view = [[VLCVoutView voutView: p_vout
371                                                     subView: o_glview
372                                                       frame: &p_vout->p_sys->s_frame] retain];
373         [old_vout release];
374     }
375     else
376     {
377         id old_vout = p_vout->p_sys->o_vout_view;
378         p_vout->p_sys->o_vout_view = [[VLCVoutView voutView: p_vout
379                                                     subView: o_glview frame: nil] retain];
380         [old_vout release];
381     }
382 #undef o_glview
383 }
384
385 - (id) initWithVout: (vout_thread_t *) vout
386 {
387     /* Must be called from main thread:
388      * "The NSView class is generally thread-safe, with a few exceptions. You
389      * should create, destroy, resize, move, and perform other operations on NSView
390      * objects only from the main thread of an application. Drawing from secondary
391      * threads is thread-safe as long as you bracket drawing calls with calls to
392      * lockFocusIfCanDraw and unlockFocus." Cocoa Thread Safety */
393
394     p_vout = vout;
395
396     NSOpenGLPixelFormatAttribute attribs[] =
397     {
398         NSOpenGLPFADoubleBuffer,
399         NSOpenGLPFAAccelerated,
400         NSOpenGLPFANoRecovery,
401         NSOpenGLPFAColorSize, 24,
402         NSOpenGLPFAAlphaSize, 8,
403         NSOpenGLPFADepthSize, 24,
404         NSOpenGLPFAWindow,
405         0
406     };
407
408     NSOpenGLPixelFormat * fmt = [[NSOpenGLPixelFormat alloc]
409         initWithAttributes: attribs];
410
411     if( !fmt )
412     {
413         msg_Warn( p_vout, "could not create OpenGL video output" );
414         return nil;
415     }
416
417     self = [super initWithFrame: NSMakeRect(0,0,10,10) pixelFormat: fmt];
418     [fmt release];
419
420     [[self openGLContext] makeCurrentContext];
421     [[self openGLContext] update];
422
423     /* Swap buffers only during the vertical retrace of the monitor.
424        http://developer.apple.com/documentation/GraphicsImaging/
425        Conceptual/OpenGL/chap5/chapter_5_section_44.html */
426     GLint params[] = { 1 };
427     CGLSetParameter( CGLGetCurrentContext(), kCGLCPSwapInterval, params );
428     return self;
429 }
430
431 - (BOOL)mouseDownCanMoveWindow
432 {
433     return YES;
434 }
435
436 - (void) reshape
437 {
438     int x, y;
439
440     Lock( p_vout );
441     NSRect bounds = [self bounds];
442
443     if( var_GetBool( p_vout, "macosx-stretch" ) )
444     {
445         x = bounds.size.width;
446         y = bounds.size.height;
447     }
448     else if( bounds.size.height * p_vout->fmt_in.i_visible_width *
449              p_vout->fmt_in.i_sar_num <
450              bounds.size.width * p_vout->fmt_in.i_visible_height *
451              p_vout->fmt_in.i_sar_den )
452     {
453         x = ( bounds.size.height * p_vout->fmt_in.i_visible_width *
454               p_vout->fmt_in.i_sar_num ) /
455             ( p_vout->fmt_in.i_visible_height * p_vout->fmt_in.i_sar_den);
456
457         y = bounds.size.height;
458     }
459     else
460     {
461         x = bounds.size.width;
462         y = ( bounds.size.width * p_vout->fmt_in.i_visible_height *
463               p_vout->fmt_in.i_sar_den) /
464             ( p_vout->fmt_in.i_visible_width * p_vout->fmt_in.i_sar_num  );
465     }
466
467     glViewport( ( bounds.size.width - x ) / 2,
468                 ( bounds.size.height - y ) / 2, x, y );
469
470     [super reshape];
471
472     if( p_vout->p_sys->b_got_frame )
473     {
474         /* Ask the opengl module to redraw */
475         vout_thread_t * p_parent;
476         p_parent = (vout_thread_t *) p_vout->p_parent;
477         Unlock( p_vout );
478         if( p_parent && p_parent->pf_display )
479         {
480             p_parent->pf_display( p_parent, NULL );
481         }
482     }
483     else
484     {
485         glClear( GL_COLOR_BUFFER_BIT );
486         Unlock( p_vout );
487     }
488 }
489
490 - (void) update
491 {
492     Lock( p_vout );
493     [super update];
494     Unlock( p_vout );
495 }
496
497 - (void) drawRect: (NSRect) rect
498 {
499     Lock( p_vout );
500     [[p_vout->p_sys->o_glview openGLContext] flushBuffer];
501     [super drawRect:rect];
502     Unlock( p_vout );
503 }
504
505 @end
506
507 /*****************************************************************************
508  * embedded AGL context implementation
509  *****************************************************************************/
510
511 #ifndef __x86_64__
512
513 static void aglSetViewport( vout_thread_t *p_vout, Rect viewBounds, Rect clipBounds );
514 static void aglReshape( vout_thread_t * p_vout );
515 static OSStatus WindowEventHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData);
516
517 static int aglInit( vout_thread_t * p_vout )
518 {
519     Rect viewBounds;
520     Rect clipBounds;
521  
522     p_vout->p_sys->agl_drawable = (AGLDrawable)
523             var_GetInteger( p_vout->p_libvlc, "drawable-agl" );
524     aglSetDrawable(p_vout->p_sys->agl_ctx, p_vout->p_sys->agl_drawable);
525
526     viewBounds.top = var_GetInteger( p_vout->p_libvlc, "drawable-view-top" );
527     viewBounds.left = var_GetInteger( p_vout->p_libvlc, "drawable-view-left" );
528     viewBounds.bottom = var_GetInteger( p_vout->p_libvlc, "drawable-view-bottom" );
529     viewBounds.right = var_GetInteger( p_vout->p_libvlc, "drawable-view-right" );
530     clipBounds.top = var_GetInteger( p_vout->p_libvlc, "drawable-clip-top" );
531     clipBounds.left = var_GetInteger( p_vout->p_libvlc, "drawable-clip-left" );
532     clipBounds.bottom = var_GetInteger( p_vout->p_libvlc, "drawable-clip-bottom" );
533     clipBounds.right = var_GetInteger( p_vout->p_libvlc, "drawable-clip-right" );
534
535     p_vout->p_sys->b_clipped_out = (clipBounds.top == clipBounds.bottom)
536                                  || (clipBounds.left == clipBounds.right);
537     if( ! p_vout->p_sys->b_clipped_out )
538     {
539         aglLock(p_vout);
540         aglSetViewport(p_vout, viewBounds, clipBounds);
541         aglReshape(p_vout);
542         aglUnlock(p_vout);
543     }
544     p_vout->p_sys->clipBounds = clipBounds;
545     p_vout->p_sys->viewBounds = viewBounds;
546
547     return VLC_SUCCESS;
548 }
549
550 static void aglEnd( vout_thread_t * p_vout )
551 {
552     aglSetCurrentContext(NULL);
553     if( p_vout->p_sys->theWindow )
554     {
555         DisposeWindow( p_vout->p_sys->theWindow );
556         p_vout->p_sys->theWindow = NULL;
557     }
558 }
559
560 static void aglReshape( vout_thread_t * p_vout )
561 {
562     unsigned int x, y;
563     unsigned int i_height = p_vout->p_sys->i_height;
564     unsigned int i_width  = p_vout->p_sys->i_width;
565
566     vout_PlacePicture(p_vout, i_width, i_height, &x, &y, &i_width, &i_height);
567
568     glViewport( p_vout->p_sys->i_offx + x, p_vout->p_sys->i_offy + y, i_width, i_height );
569
570     if( p_vout->p_sys->b_got_frame )
571     {
572         /* Ask the opengl module to redraw */
573         vout_thread_t * p_parent;
574         p_parent = (vout_thread_t *) p_vout->p_parent;
575         if( p_parent && p_parent->pf_display )
576         {
577             p_parent->pf_display( p_parent, NULL );
578         }
579     }
580     else
581     {
582         glClear( GL_COLOR_BUFFER_BIT );
583     }
584 }
585
586 /* private event class */
587 enum
588 {
589     kEventClassVLCPlugin = 'vlcp',
590 };
591 /* private event kinds */
592 enum
593 {
594     kEventVLCPluginShowFullscreen = 32768,
595     kEventVLCPluginHideFullscreen,
596 };
597
598 static void sendEventToMainThread(EventTargetRef target, UInt32 class, UInt32 kind)
599 {
600     EventRef myEvent;
601     if( noErr == CreateEvent(NULL, class, kind, 0, kEventAttributeNone, &myEvent) )
602     {
603         if( noErr == SetEventParameter(myEvent, kEventParamPostTarget, typeEventTargetRef, sizeof(EventTargetRef), &target) )
604         {
605             PostEventToQueue(GetMainEventQueue(), myEvent, kEventPriorityStandard);
606         }
607         ReleaseEvent(myEvent);
608     }
609 }
610
611 static int aglManage( vout_thread_t * p_vout )
612 {
613     if( p_vout->i_changes & VOUT_ASPECT_CHANGE )
614     {
615         aglLock( p_vout );
616         aglReshape(p_vout);
617         aglUnlock( p_vout );
618         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
619     }
620     if( p_vout->i_changes & VOUT_CROP_CHANGE )
621     {
622         aglLock( p_vout );
623         aglReshape(p_vout);
624         aglUnlock( p_vout );
625         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
626     }
627     if( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
628     {
629         aglSetDrawable(p_vout->p_sys->agl_ctx, NULL);
630         aglLock( p_vout );
631         if( p_vout->b_fullscreen )
632         {
633             /* Close the fullscreen window and resume normal drawing */
634             Rect viewBounds;
635             Rect clipBounds;
636
637             p_vout->p_sys->agl_drawable = (AGLDrawable)
638                     var_GetInteger( p_vout->p_libvlc, "drawable-agl" );
639
640             aglSetDrawable(p_vout->p_sys->agl_ctx, p_vout->p_sys->agl_drawable);
641
642             viewBounds.top = var_GetInteger( p_vout->p_libvlc, "drawable-view-top" );
643             viewBounds.left = var_GetInteger( p_vout->p_libvlc, "drawable-view-left" );
644             viewBounds.bottom = var_GetInteger( p_vout->p_libvlc, "drawable-view-bottom" );
645             viewBounds.right = var_GetInteger( p_vout->p_libvlc, "drawable-view-right" );
646             clipBounds.top = var_GetInteger( p_vout->p_libvlc, "drawable-clip-top" );
647             clipBounds.left = var_GetInteger( p_vout->p_libvlc, "drawable-clip-left" );
648             clipBounds.bottom = var_GetInteger( p_vout->p_libvlc, "drawable-clip-bottom" );
649             clipBounds.right = var_GetInteger( p_vout->p_libvlc, "drawable-clip-right" );
650
651             aglSetCurrentContext(p_vout->p_sys->agl_ctx);
652             aglSetViewport(p_vout, viewBounds, clipBounds);
653
654             if( p_vout->p_sys->theWindow )
655             {
656                 /* Most Carbon APIs are not thread-safe, therefore delagate some GUI visibilty
657                  * update to the main thread */
658                 sendEventToMainThread(GetWindowEventTarget(p_vout->p_sys->theWindow),
659                                       kEventClassVLCPlugin, kEventVLCPluginHideFullscreen);
660             }
661         }
662         else
663         {
664             /* Go into fullscreen */
665             Rect deviceRect;
666  
667             GDHandle deviceHdl = GetMainDevice();
668             deviceRect = (*deviceHdl)->gdRect;
669  
670             if( !p_vout->p_sys->theWindow )
671             {
672                 /* Create a window */
673                 WindowAttributes windowAttrs;
674
675                 windowAttrs = kWindowStandardDocumentAttributes
676                             | kWindowStandardHandlerAttribute
677                             | kWindowLiveResizeAttribute
678                             | kWindowNoShadowAttribute;
679  
680                 windowAttrs &= (~kWindowResizableAttribute);
681
682                 CreateNewWindow(kDocumentWindowClass, windowAttrs, &deviceRect, &p_vout->p_sys->theWindow);
683                 if( !p_vout->p_sys->winGroup )
684                 {
685                     CreateWindowGroup(0, &p_vout->p_sys->winGroup);
686                     SetWindowGroup(p_vout->p_sys->theWindow, p_vout->p_sys->winGroup);
687                     SetWindowGroupParent( p_vout->p_sys->winGroup, GetWindowGroupOfClass(kDocumentWindowClass) ) ;
688                 }
689  
690                 // Window title
691                 CFStringRef titleKey    = CFSTR("Fullscreen VLC media plugin");
692                 CFStringRef windowTitle = CFCopyLocalizedString(titleKey, NULL);
693                 SetWindowTitleWithCFString(p_vout->p_sys->theWindow, windowTitle);
694                 CFRelease(titleKey);
695                 CFRelease(windowTitle);
696  
697                 //Install event handler
698                 static const EventTypeSpec win_events[] = {
699                     { kEventClassMouse, kEventMouseDown },
700                     { kEventClassMouse, kEventMouseMoved },
701                     { kEventClassMouse, kEventMouseUp },
702                     { kEventClassWindow, kEventWindowClosed },
703                     { kEventClassWindow, kEventWindowBoundsChanged },
704                     { kEventClassCommand, kEventCommandProcess },
705                     { kEventClassVLCPlugin, kEventVLCPluginShowFullscreen },
706                     { kEventClassVLCPlugin, kEventVLCPluginHideFullscreen },
707                 };
708                 InstallWindowEventHandler (p_vout->p_sys->theWindow, NewEventHandlerUPP (WindowEventHandler), GetEventTypeCount(win_events), win_events, p_vout, NULL);
709             }
710             else
711             {
712                 /* just in case device resolution changed */
713                 SetWindowBounds(p_vout->p_sys->theWindow, kWindowContentRgn, &deviceRect);
714             }
715             glClear( GL_COLOR_BUFFER_BIT );
716             p_vout->p_sys->agl_drawable = (AGLDrawable)GetWindowPort(p_vout->p_sys->theWindow);
717             aglSetDrawable(p_vout->p_sys->agl_ctx, p_vout->p_sys->agl_drawable);
718             aglSetCurrentContext(p_vout->p_sys->agl_ctx);
719             aglSetViewport(p_vout, deviceRect, deviceRect);
720             //aglSetFullScreen(p_vout->p_sys->agl_ctx, device_width, device_height, 0, 0);
721
722             if( p_vout->p_sys->theWindow )
723             {
724                 /* Most Carbon APIs are not thread-safe, therefore delagate some GUI visibilty
725                  * update to the main thread */
726                 sendEventToMainThread(GetWindowEventTarget(p_vout->p_sys->theWindow),
727                                       kEventClassVLCPlugin, kEventVLCPluginShowFullscreen);
728             }
729         }
730         aglReshape(p_vout);
731         aglUnlock( p_vout );
732         p_vout->b_fullscreen = !p_vout->b_fullscreen;
733         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
734     }
735     return VLC_SUCCESS;
736 }
737
738 static int aglControl( vout_thread_t *p_vout, int i_query, va_list args )
739 {
740     switch( i_query )
741     {
742         case VOUT_SET_VIEWPORT:
743         {
744             Rect viewBounds, clipBounds;
745             viewBounds.top = va_arg( args, int);
746             viewBounds.left = va_arg( args, int);
747             viewBounds.bottom = va_arg( args, int);
748             viewBounds.right = va_arg( args, int);
749             clipBounds.top = va_arg( args, int);
750             clipBounds.left = va_arg( args, int);
751             clipBounds.bottom = va_arg( args, int);
752             clipBounds.right = va_arg( args, int);
753  
754             if( !p_vout->b_fullscreen )
755             {
756                 /*
757                 ** check that the clip rect is not empty, as this is used
758                 ** by Firefox to prevent a plugin from displaying during
759                 ** a scrolling event. In this case we just prevent buffers
760                 ** from being swapped and ignore clipping as this is less
761                 ** disruptive than a GL geometry change
762                 */
763
764                 p_vout->p_sys->b_clipped_out = (clipBounds.top == clipBounds.bottom)
765                                              || (clipBounds.left == clipBounds.right);
766                 if( ! p_vout->p_sys->b_clipped_out )
767                 {
768                     /* ignore consecutive viewport update with identical parameters */
769                     if( memcmp(&clipBounds, &(p_vout->p_sys->clipBounds), sizeof(clipBounds) )
770                      && memcmp(&viewBounds, &(p_vout->p_sys->viewBounds), sizeof(viewBounds)) )
771                     {
772                         aglLock( p_vout );
773                         aglSetViewport(p_vout, viewBounds, clipBounds);
774                         aglReshape( p_vout );
775                         aglUnlock( p_vout );
776                         p_vout->p_sys->clipBounds = clipBounds;
777                         p_vout->p_sys->viewBounds = viewBounds;
778                     }
779                 }
780             }
781             return VLC_SUCCESS;
782         }
783
784         case VOUT_REDRAW_RECT:
785         {
786             vout_thread_t * p_parent;
787             Rect areaBounds;
788
789             areaBounds.top = va_arg( args, int);
790             areaBounds.left = va_arg( args, int);
791             areaBounds.bottom = va_arg( args, int);
792             areaBounds.right = va_arg( args, int);
793
794             /* Ask the opengl module to redraw */
795             p_parent = (vout_thread_t *) p_vout->p_parent;
796             if( p_parent && p_parent->pf_display )
797             {
798                 p_parent->pf_display( p_parent, NULL );
799             }
800             return VLC_SUCCESS;
801         }
802
803         default:
804             return VLC_EGENERIC;
805     }
806 }
807
808 static void aglSwap( vout_thread_t * p_vout )
809 {
810     if( ! p_vout->p_sys->b_clipped_out )
811     {
812         p_vout->p_sys->b_got_frame = true;
813         aglSwapBuffers(p_vout->p_sys->agl_ctx);
814     }
815     else
816     {
817         /* drop frame */
818         glFlush();
819     }
820 }
821
822 /* Enter this function with the p_vout locked */
823 static void aglSetViewport( vout_thread_t *p_vout, Rect viewBounds, Rect clipBounds )
824 {
825     // mozilla plugin provides coordinates based on port bounds
826     // however AGL coordinates are based on window structure region
827     // and are vertically flipped
828     GLint rect[4];
829     CGrafPtr port = (CGrafPtr)p_vout->p_sys->agl_drawable;
830     Rect winBounds, clientBounds;
831
832     GetWindowBounds(GetWindowFromPort(port),
833         kWindowStructureRgn, &winBounds);
834     GetWindowBounds(GetWindowFromPort(port),
835         kWindowContentRgn, &clientBounds);
836
837     /* update video clipping bounds in drawable */
838     rect[0] = (clientBounds.left-winBounds.left)
839             + clipBounds.left;                  // from window left edge
840     rect[1] = (winBounds.bottom-winBounds.top)
841             - (clientBounds.top-winBounds.top)
842             - clipBounds.bottom;                // from window bottom edge
843     rect[2] = clipBounds.right-clipBounds.left; // width
844     rect[3] = clipBounds.bottom-clipBounds.top; // height
845
846     aglSetInteger(p_vout->p_sys->agl_ctx, AGL_BUFFER_RECT, rect);
847     aglEnable(p_vout->p_sys->agl_ctx, AGL_BUFFER_RECT);
848
849     /* update video internal bounds in drawable */
850     p_vout->p_sys->i_width  = viewBounds.right-viewBounds.left;
851     p_vout->p_sys->i_height = viewBounds.bottom-viewBounds.top;
852     p_vout->p_sys->i_offx   = -clipBounds.left - viewBounds.left;
853     p_vout->p_sys->i_offy   = clipBounds.bottom + viewBounds.top
854                             - p_vout->p_sys->i_height;
855
856     aglUpdateContext(p_vout->p_sys->agl_ctx);
857 }
858
859 //default window event handler
860 static pascal OSStatus WindowEventHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData)
861 {
862     OSStatus result = noErr;
863     UInt32 class = GetEventClass (event);
864     UInt32 kind = GetEventKind (event);
865     vout_thread_t *p_vout = (vout_thread_t *)userData;
866
867     result = CallNextEventHandler(nextHandler, event);
868     if(class == kEventClassCommand)
869     {
870         HICommand theHICommand;
871         GetEventParameter( event, kEventParamDirectObject, typeHICommand, NULL, sizeof( HICommand ), NULL, &theHICommand );
872  
873         switch ( theHICommand.commandID )
874         {
875             default:
876                 result = eventNotHandledErr;
877         }
878     }
879     else if(class == kEventClassWindow)
880     {
881         WindowRef     window;
882         Rect          rectPort = {0,0,0,0};
883  
884         GetEventParameter(event, kEventParamDirectObject, typeWindowRef, NULL, sizeof(WindowRef), NULL, &window);
885
886         if(window)
887         {
888             GetPortBounds(GetWindowPort(window), &rectPort);
889         }
890
891         switch (kind)
892         {
893             case kEventWindowClosed:
894             case kEventWindowZoomed:
895             case kEventWindowBoundsChanged:
896                 break;
897  
898             default:
899                 result = eventNotHandledErr;
900         }
901     }
902     else if(class == kEventClassMouse)
903     {
904         switch (kind)
905         {
906             case kEventMouseDown:
907             {
908                 UInt16     button;
909  
910                 GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL, sizeof(button), NULL, &button);
911                 switch (button)
912                 {
913                     case kEventMouseButtonPrimary:
914                     {
915                         vlc_value_t val;
916
917                         var_Get( p_vout, "mouse-button-down", &val );
918                         val.i_int |= 1;
919                         var_Set( p_vout, "mouse-button-down", val );
920                         break;
921                     }
922                     case kEventMouseButtonSecondary:
923                     {
924                         vlc_value_t val;
925
926                         var_Get( p_vout, "mouse-button-down", &val );
927                         val.i_int |= 2;
928                         var_Set( p_vout, "mouse-button-down", val );
929                         break;
930                     }
931                     case kEventMouseButtonTertiary:
932                     {
933                         vlc_value_t val;
934
935                         var_Get( p_vout, "mouse-button-down", &val );
936                         val.i_int |= 4;
937                         var_Set( p_vout, "mouse-button-down", val );
938                         break;
939                     }
940                     default:
941                         result = eventNotHandledErr;
942                 }
943                 break;
944             }
945
946             case kEventMouseUp:
947             {
948                 UInt16     button;
949  
950                 GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL, sizeof(button), NULL, &button);
951                 switch (button)
952                 {
953                     case kEventMouseButtonPrimary:
954                     {
955                         UInt32 clickCount = 0;
956                         GetEventParameter(event, kEventParamClickCount, typeUInt32, NULL, sizeof(clickCount), NULL, &clickCount);
957                         if( clickCount > 1 )
958                         {
959                             vlc_value_t val;
960
961                             val.b_bool = false;
962                             var_Set((vout_thread_t *) p_vout->p_parent, "fullscreen", val);
963                         }
964                         else
965                         {
966                             vlc_value_t val;
967
968                             var_SetBool( p_vout, "mouse-clicked", true );
969
970                             var_Get( p_vout, "mouse-button-down", &val );
971                             val.i_int &= ~1;
972                             var_Set( p_vout, "mouse-button-down", val );
973                         }
974                         break;
975                     }
976                     case kEventMouseButtonSecondary:
977                     {
978                         vlc_value_t val;
979
980                         var_Get( p_vout, "mouse-button-down", &val );
981                         val.i_int &= ~2;
982                         var_Set( p_vout, "mouse-button-down", val );
983                         break;
984                     }
985                     case kEventMouseButtonTertiary:
986                     {
987                         vlc_value_t val;
988
989                         var_Get( p_vout, "mouse-button-down", &val );
990                         val.i_int &= ~2;
991                         var_Set( p_vout, "mouse-button-down", val );
992                         break;
993                     }
994                     default:
995                         result = eventNotHandledErr;
996                 }
997                 break;
998             }
999
1000             case kEventMouseMoved:
1001             {
1002                 Point ml;
1003                 vlc_value_t val;
1004
1005                 unsigned int i_x, i_y;
1006                 unsigned int i_height = p_vout->p_sys->i_height;
1007                 unsigned int i_width  = p_vout->p_sys->i_width;
1008
1009                 vout_PlacePicture(p_vout, i_width, i_height, &i_x, &i_y, &i_width, &i_height);
1010
1011                 GetEventParameter(event, kEventParamWindowMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &ml);
1012  
1013                 val.i_int = ( ((int)ml.h) - i_x ) *
1014                             p_vout->render.i_width / i_width;
1015                 var_Set( p_vout, "mouse-x", val );
1016
1017                 val.i_int = ( ((int)ml.v) - i_y ) *
1018                             p_vout->render.i_height / i_height;
1019
1020                 var_Set( p_vout, "mouse-y", val );
1021
1022                 val.b_bool = true;
1023                 var_Set( p_vout, "mouse-moved", val );
1024
1025                 break;
1026             }
1027  
1028             default:
1029                 result = eventNotHandledErr;
1030         }
1031     }
1032     else if(class == kEventClassTextInput)
1033     {
1034         switch (kind)
1035         {
1036             case kEventTextInputUnicodeForKeyEvent:
1037             {
1038                 break;
1039             }
1040             default:
1041                 result = eventNotHandledErr;
1042         }
1043     }
1044     else if(class == kEventClassVLCPlugin)
1045     {
1046         switch (kind)
1047         {
1048             case kEventVLCPluginShowFullscreen:
1049                 ShowWindow (p_vout->p_sys->theWindow);
1050                 SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
1051                 //CGDisplayHideCursor(kCGDirectMainDisplay);
1052                 break;
1053             case kEventVLCPluginHideFullscreen:
1054                 HideWindow (p_vout->p_sys->theWindow);
1055                 SetSystemUIMode( kUIModeNormal, 0);
1056                 CGDisplayShowCursor(kCGDirectMainDisplay);
1057                 break;
1058             default:
1059                 result = eventNotHandledErr;
1060                 break;
1061         }
1062     }
1063     return result;
1064 }
1065
1066 static int aglLock( vout_thread_t * p_vout )
1067 {
1068         /* get the underlying CGL context */
1069     CGLContextObj cglContext;
1070     if( aglGetCGLContext(p_vout->p_sys->agl_ctx, (void**)&cglContext) )
1071     {
1072         if( kCGLNoError == CGLLockContext( cglContext ) )
1073         {
1074             aglSetCurrentContext(p_vout->p_sys->agl_ctx);
1075             return 0;
1076         }
1077     }
1078     return 1;
1079 }
1080
1081 static void aglUnlock( vout_thread_t * p_vout )
1082 {
1083         /* get the underlying CGL context */
1084     CGLContextObj cglContext;
1085     if( aglGetCGLContext(p_vout->p_sys->agl_ctx, (void**)&cglContext) )
1086     {
1087         CGLUnlockContext( cglContext );
1088     }
1089 }
1090
1091 #endif