]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
Qt4: Tell the window manager to keep the fullscreen controller window on top.
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * voutgl.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-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  *          Pierre d'Herbemont <pdherbemont at videolan dot org>
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
29  *****************************************************************************/
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #import <Cocoa/Cocoa.h>
36 #import <OpenGL/OpenGL.h>
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_vout_display.h>
45 #include <vlc_opengl.h>
46 #include "opengl.h"
47
48 /**
49  * Forward declarations
50  */
51 static int Open(vlc_object_t *);
52 static void Close(vlc_object_t *);
53
54 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
55 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
56 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
57 static int Control (vout_display_t *vd, int query, va_list ap);
58
59 static int OpenglLock(vlc_gl_t *gl);
60 static void OpenglUnlock(vlc_gl_t *gl);
61 static void OpenglSwap(vlc_gl_t *gl);
62
63 /**
64  * Module declaration
65  */
66 vlc_module_begin ()
67     /* Will be loaded even without interface module. see voutgl.m */
68     set_shortname("Mac OS X")
69     set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
70     set_category(CAT_VIDEO)
71     set_subcategory(SUBCAT_VIDEO_VOUT )
72     set_capability("vout display", 300)
73     set_callbacks(Open, Close)
74
75     add_shortcut("macosx", "vout_macosx")
76 vlc_module_end ()
77
78 /**
79  * Obj-C protocol declaration that drawable-nsobject should follow
80  */
81 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
82 - (void)addVoutSubview:(NSView *)view;
83 - (void)removeVoutSubview:(NSView *)view;
84 @end
85
86 @interface VLCOpenGLVideoView : NSOpenGLView
87 {
88     vout_display_t *vd;
89     BOOL _hasPendingReshape;
90 }
91 - (void)setVoutDisplay:(vout_display_t *)vd;
92 - (void)setVoutFlushing:(BOOL)flushing;
93 @end
94
95
96 struct vout_display_sys_t
97 {
98     VLCOpenGLVideoView *glView;
99     id<VLCOpenGLVideoViewEmbedding> container;
100
101     vout_window_t *embed;
102     vlc_gl_t gl;
103     vout_display_opengl_t vgl;
104
105     picture_pool_t *pool;
106     picture_t *current;
107     bool has_first_frame;
108 };
109
110 static int Open(vlc_object_t *this)
111 {
112     vout_display_t *vd = (vout_display_t *)this;
113     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
114     NSAutoreleasePool *nsPool = nil;
115
116     if (!sys)
117         return VLC_ENOMEM;
118
119     vd->sys = sys;
120     sys->pool = NULL;
121     sys->gl.sys = NULL;
122     sys->embed = NULL;
123
124     /* Get the drawable object */
125     id container = var_CreateGetAddress(vd, "drawable-nsobject");
126     if (container)
127     {
128         vout_display_DeleteWindow(vd, NULL);
129     }
130     else
131     {
132         vout_window_cfg_t wnd_cfg;
133
134         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
135         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
136         wnd_cfg.x = var_InheritInteger (vd, "video-x");
137         wnd_cfg.y = var_InheritInteger (vd, "video-y");
138         wnd_cfg.width  = vd->cfg->display.width;
139         wnd_cfg.height = vd->cfg->display.height;
140
141         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
142         if (sys->embed)
143             container = sys->embed->handle.nsobject;
144
145         if (!container)
146         {
147             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
148             goto error;
149         }
150     }
151
152     /* This will be released in Close(), on
153      * main thread, after we are done using it. */
154     sys->container = [container retain];
155
156     /* Get our main view*/
157     nsPool = [[NSAutoreleasePool alloc] init];
158
159     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
160     if (!sys->glView)
161         goto error;
162
163     [sys->glView setVoutDisplay:vd];
164
165     /* We don't wait, that means that we'll have to be careful about releasing
166      * container.
167      * That's why we'll release on main thread in Close(). */
168     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
169         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
170     else if ([container isKindOfClass:[NSView class]])
171     {
172         NSView *parentView = container;
173         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
174         [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
175     }
176     else
177     {
178         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
179         goto error;
180     }
181
182
183     [nsPool release];
184     nsPool = nil;
185
186     /* Initialize common OpenGL video display */
187     sys->gl.lock = OpenglLock;
188     sys->gl.unlock = OpenglUnlock;
189     sys->gl.swap = OpenglSwap;
190     sys->gl.sys = sys;
191
192     if (vout_display_opengl_Init(&sys->vgl, &vd->fmt, &sys->gl))
193     {
194         sys->gl.sys = NULL;
195         goto error;
196     }
197
198     /* */
199     vout_display_info_t info = vd->info;
200     info.has_pictures_invalid = false;
201
202     /* Setup vout_display_t once everything is fine */
203     vd->info = info;
204
205     vd->pool = Pool;
206     vd->prepare = PictureRender;
207     vd->display = PictureDisplay;
208     vd->control = Control;
209
210     /* */
211     vout_display_SendEventFullscreen (vd, false);
212     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
213
214     return VLC_SUCCESS;
215
216 error:
217     [nsPool release];
218     Close(this);
219     return VLC_EGENERIC;
220 }
221
222 void Close(vlc_object_t *this)
223 {
224     vout_display_t *vd = (vout_display_t *)this;
225     vout_display_sys_t *sys = vd->sys;
226
227     [sys->glView setVoutDisplay:nil];
228
229     var_Destroy(vd, "drawable-nsobject");
230     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
231     {
232         /* This will retain sys->glView */
233         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
234     }
235     /* release on main thread as explained in Open() */
236     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
237     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
238
239     [sys->glView release];
240
241     if (sys->gl.sys != NULL)
242         vout_display_opengl_Clean(&sys->vgl);
243
244     if (sys->embed)
245         vout_display_DeleteWindow(vd, sys->embed);
246     free (sys);
247 }
248
249 /*****************************************************************************
250  * vout display callbacks
251  *****************************************************************************/
252
253 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
254 {
255     vout_display_sys_t *sys = vd->sys;
256     VLC_UNUSED(requested_count);
257
258     if (!sys->pool)
259         sys->pool = vout_display_opengl_GetPool (&sys->vgl);
260     assert(sys->pool);
261     return sys->pool;
262 }
263
264 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
265 {
266
267     vout_display_sys_t *sys = vd->sys;
268
269     vout_display_opengl_Prepare( &sys->vgl, pic );
270         (void)subpicture;
271 }
272
273 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
274 {
275     vout_display_sys_t *sys = vd->sys;
276     [sys->glView setVoutFlushing:YES];
277     vout_display_opengl_Display(&sys->vgl, &vd->fmt );
278     [sys->glView setVoutFlushing:NO];
279     picture_Release (pic);
280     sys->has_first_frame = true;
281         (void)subpicture;
282 }
283
284 static int Control (vout_display_t *vd, int query, va_list ap)
285 {
286     vout_display_sys_t *sys = vd->sys;
287
288     switch (query)
289     {
290         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
291         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
292         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
293         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
294         case VOUT_DISPLAY_CHANGE_ZOOM:
295         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
296         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
297         {
298             /* todo */
299             return VLC_EGENERIC;
300         }
301         case VOUT_DISPLAY_HIDE_MOUSE:
302             return VLC_SUCCESS;
303
304         case VOUT_DISPLAY_GET_OPENGL:
305         {
306             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
307             *gl = &sys->gl;
308             return VLC_SUCCESS;
309         }
310
311         case VOUT_DISPLAY_RESET_PICTURES:
312             assert (0);
313         default:
314             msg_Err (vd, "Unknown request in Mac OS X vout display");
315             return VLC_EGENERIC;
316     }
317 }
318
319 /*****************************************************************************
320  * vout opengl callbacks
321  *****************************************************************************/
322 static int OpenglLock(vlc_gl_t *gl)
323 {
324     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
325     NSOpenGLContext *context = [sys->glView openGLContext];
326     CGLError err = CGLLockContext([context CGLContextObj]);
327     if (kCGLNoError == err)
328     {
329         [context makeCurrentContext];
330         return 0;
331     }
332     return 1;
333 }
334
335 static void OpenglUnlock(vlc_gl_t *gl)
336 {
337     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
338     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
339 }
340
341 static void OpenglSwap(vlc_gl_t *gl)
342 {
343     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
344     [[sys->glView openGLContext] flushBuffer];
345 }
346
347 /*****************************************************************************
348  * Our NSView object
349  *****************************************************************************/
350 @implementation VLCOpenGLVideoView
351
352 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
353
354 + (void)getNewView:(NSValue *)value
355 {
356     id *ret = [value pointerValue];
357     *ret = [[self alloc] init];
358 }
359
360 /**
361  * Gets called by the Open() method.
362  */
363 - (id)init
364 {
365     VLCAssertMainThread();
366
367     /* Warning - this may be called on non main thread */
368
369     NSOpenGLPixelFormatAttribute attribs[] =
370     {
371         NSOpenGLPFADoubleBuffer,
372         NSOpenGLPFAAccelerated,
373         NSOpenGLPFANoRecovery,
374         NSOpenGLPFAColorSize, 24,
375         NSOpenGLPFAAlphaSize, 8,
376         NSOpenGLPFADepthSize, 24,
377         NSOpenGLPFAWindow,
378         0
379     };
380
381     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
382
383     if (!fmt)
384         return nil;
385
386     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
387     [fmt release];
388
389     if (!self)
390         return nil;
391
392     /* Swap buffers only during the vertical retrace of the monitor.
393      http://developer.apple.com/documentation/GraphicsImaging/
394      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
395     GLint params[] = { 1 };
396     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
397
398     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
399     return self;
400 }
401
402 /**
403  * Gets called by the Open() method.
404  */
405 - (void)setFrameWithValue:(NSValue *)value
406 {
407     [self setFrame:[value rectValue]];
408 }
409
410 /**
411  * Gets called by the Close and Open methods.
412  * (Non main thread).
413  */
414 - (void)setVoutDisplay:(vout_display_t *)aVd
415 {
416     @synchronized(self) {
417         vd = aVd;
418     }
419 }
420
421
422 /**
423  * Gets called when the vout will aquire the lock and flush.
424  * (Non main thread).
425  */
426 - (void)setVoutFlushing:(BOOL)flushing
427 {
428     if (!flushing)
429         return;
430     @synchronized(self) {
431         _hasPendingReshape = NO;
432     }
433 }
434
435 /**
436  * Can -drawRect skip rendering?.
437  */
438 - (BOOL)canSkipRendering
439 {
440     VLCAssertMainThread();
441
442     @synchronized(self) {
443         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
444         return !_hasPendingReshape && hasFirstFrame;
445     }
446 }
447
448
449 /**
450  * Local method that locks the gl context.
451  */
452 - (BOOL)lockgl
453 {
454     VLCAssertMainThread();
455     NSOpenGLContext *context = [self openGLContext];
456     CGLError err = CGLLockContext([context CGLContextObj]);
457     if (err == kCGLNoError)
458         [context makeCurrentContext];
459     return err == kCGLNoError;
460 }
461
462 /**
463  * Local method that unlocks the gl context.
464  */
465 - (void)unlockgl
466 {
467     VLCAssertMainThread();
468     CGLUnlockContext([[self openGLContext] CGLContextObj]);
469 }
470
471 /**
472  * Local method that force a rendering of a frame.
473  * This will get called if Cocoa forces us to redraw (via -drawRect).
474  */
475 - (void)render
476 {
477     VLCAssertMainThread();
478
479     // We may have taken some times to take the opengl Lock.
480     // Check here to see if we can just skip the frame as well.
481     if ([self canSkipRendering])
482         return;
483
484     BOOL hasFirstFrame;
485     @synchronized(self) { // vd can be accessed from multiple threads
486         hasFirstFrame = vd && vd->sys->has_first_frame;
487     }
488
489     if (hasFirstFrame) {
490         // This will lock gl.
491         vout_display_opengl_Display( &vd->sys->vgl, &vd->source );
492     }
493     else
494         glClear(GL_COLOR_BUFFER_BIT);
495 }
496
497 /**
498  * Method called by Cocoa when the view is resized.
499  */
500 - (void)reshape
501 {
502     VLCAssertMainThread();
503
504     NSRect bounds = [self bounds];
505
506     CGFloat height = bounds.size.height;
507     CGFloat width = bounds.size.width;
508
509     GLint x = width, y = height;
510
511     @synchronized(self) {
512         if (vd) {
513             CGFloat videoHeight = vd->source.i_visible_height;
514             CGFloat videoWidth = vd->source.i_visible_width;
515
516             GLint sarNum = vd->source.i_sar_num;
517             GLint sarDen = vd->source.i_sar_den;
518
519             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
520             {
521                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
522                 y = height;
523             }
524             else
525             {
526                 x = width;
527                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
528             }
529         }
530     }
531
532     if ([self lockgl]) {
533         glViewport((width - x) / 2, (height - y) / 2, x, y);
534
535         @synchronized(self) {
536             // This may be cleared before -drawRect is being called,
537             // in this case we'll skip the rendering.
538             // This will save us for rendering two frames (or more) for nothing
539             // (one by the vout, one (or more) by drawRect)
540             _hasPendingReshape = YES;
541         }
542
543         [self unlockgl];
544
545         [super reshape];
546     }
547 }
548
549 /**
550  * Method called by Cocoa when the view is resized or the location has changed.
551  * We just need to make sure we are locking here.
552  */
553 - (void)update
554 {
555     VLCAssertMainThread();
556     BOOL success = [self lockgl];
557     if (!success)
558         return;
559
560     [super update];
561
562     [self unlockgl];
563 }
564
565 /**
566  * Method called by Cocoa to force redraw.
567  */
568 - (void)drawRect:(NSRect) rect
569 {
570     VLCAssertMainThread();
571
572     if ([self canSkipRendering])
573         return;
574
575     BOOL success = [self lockgl];
576     if (!success)
577         return;
578
579     [self render];
580
581     [self unlockgl];
582 }
583
584 - (void)renewGState
585 {
586     NSWindow *window = [self window];
587
588     // Remove flashes with splitter view.
589         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
590                 [window disableScreenUpdatesUntilFlush];
591
592     [super renewGState];
593 }
594
595 - (BOOL)mouseDownCanMoveWindow
596 {
597     return YES;
598 }
599
600 - (BOOL)isOpaque
601 {
602     return YES;
603 }
604 @end