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