]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
7499d8e404fd2ba743e75258c4be3020105208cb
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * macosx.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2012 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 @interface NSWindow (VLCCustomCode)
51 - (BOOL)isFullscreen;
52 @end
53
54 /**
55  * Forward declarations
56  */
57 static int Open(vlc_object_t *);
58 static void Close(vlc_object_t *);
59
60 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
61 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
62 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
63 static int Control (vout_display_t *vd, int query, va_list ap);
64
65 static int OpenglLock(vlc_gl_t *gl);
66 static void OpenglUnlock(vlc_gl_t *gl);
67 static void OpenglSwap(vlc_gl_t *gl);
68
69 /**
70  * Module declaration
71  */
72 vlc_module_begin ()
73     /* Will be loaded even without interface module. see voutgl.m */
74     set_shortname("Mac OS X")
75     set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
76     set_category(CAT_VIDEO)
77     set_subcategory(SUBCAT_VIDEO_VOUT )
78     set_capability("vout display", 300)
79     set_callbacks(Open, Close)
80
81     add_shortcut("macosx", "vout_macosx")
82 vlc_module_end ()
83
84 /**
85  * Obj-C protocol declaration that drawable-nsobject should follow
86  */
87 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
88 - (void)addVoutSubview:(NSView *)view;
89 - (void)removeVoutSubview:(NSView *)view;
90 @end
91
92 @interface VLCOpenGLVideoView : NSOpenGLView
93 {
94     vout_display_t *vd;
95     BOOL _hasPendingReshape;
96 }
97 - (void)setVoutDisplay:(vout_display_t *)vd;
98 - (vout_display_t *)voutDisplay;
99 - (void)setVoutFlushing:(BOOL)flushing;
100 @end
101
102
103 struct vout_display_sys_t
104 {
105     VLCOpenGLVideoView *glView;
106     id<VLCOpenGLVideoViewEmbedding> container;
107
108     vout_window_t *embed;
109     vlc_gl_t gl;
110     vout_display_opengl_t *vgl;
111
112     picture_pool_t *pool;
113     picture_t *current;
114     bool has_first_frame;
115 };
116
117 static int Open(vlc_object_t *this)
118 {
119     vout_display_t *vd = (vout_display_t *)this;
120     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
121     NSAutoreleasePool *nsPool = nil;
122
123     if (!sys)
124         return VLC_ENOMEM;
125
126     if( !CGDisplayUsesOpenGLAcceleration( kCGDirectMainDisplay ) )
127     {
128         msg_Err( this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results" );
129         dialog_Fatal( this, _("OpenGL acceleration is not supported on your Mac"), _("Your Mac lacks Quartz Extreme acceleration, which is required for video output. It will still work, but much slower and with possibly unexpected results.") );
130     }
131     else
132         msg_Dbg( this, "Quartz Extreme acceleration is active" );
133
134     vd->sys = sys;
135     sys->pool = NULL;
136     sys->gl.sys = NULL;
137     sys->embed = NULL;
138
139     /* Get the drawable object */
140     id container = var_CreateGetAddress(vd, "drawable-nsobject");
141     if (container)
142     {
143         vout_display_DeleteWindow(vd, NULL);
144     }
145     else
146     {
147         vout_window_cfg_t wnd_cfg;
148
149         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
150         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
151         wnd_cfg.x = var_InheritInteger (vd, "video-x");
152         wnd_cfg.y = var_InheritInteger (vd, "video-y");
153         wnd_cfg.width  = vd->cfg->display.width;
154         wnd_cfg.height = vd->cfg->display.height;
155
156         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
157         if (sys->embed)
158             container = sys->embed->handle.nsobject;
159
160         if (!container)
161         {
162             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
163             goto error;
164         }
165     }
166
167     /* This will be released in Close(), on
168      * main thread, after we are done using it. */
169     sys->container = [container retain];
170
171     /* Get our main view*/
172     nsPool = [[NSAutoreleasePool alloc] init];
173
174     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
175     if (!sys->glView)
176         goto error;
177
178     [sys->glView setVoutDisplay:vd];
179
180     /* We don't wait, that means that we'll have to be careful about releasing
181      * container.
182      * That's why we'll release on main thread in Close(). */
183     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
184         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
185     else if ([container isKindOfClass:[NSView class]])
186     {
187         NSView *parentView = container;
188         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
189         [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
190     }
191     else
192     {
193         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
194         goto error;
195     }
196
197
198     [nsPool release];
199     nsPool = nil;
200
201     /* Initialize common OpenGL video display */
202     sys->gl.lock = OpenglLock;
203     sys->gl.unlock = OpenglUnlock;
204     sys->gl.swap = OpenglSwap;
205     sys->gl.getProcAddress = NULL;
206     sys->gl.sys = sys;
207     const vlc_fourcc_t *subpicture_chromas;
208     video_format_t fmt = vd->fmt;
209
210     sys->vgl = vout_display_opengl_New(&vd->fmt, &subpicture_chromas, &sys->gl);
211     if (!sys->vgl)
212     {
213         sys->gl.sys = NULL;
214         goto error;
215     }
216
217     /* */
218     vout_display_info_t info = vd->info;
219     info.has_pictures_invalid = false;
220     info.has_event_thread = true;
221     info.subpicture_chromas = subpicture_chromas;
222
223     /* Setup vout_display_t once everything is fine */
224     vd->info = info;
225
226     vd->pool = Pool;
227     vd->prepare = PictureRender;
228     vd->display = PictureDisplay;
229     vd->control = Control;
230
231     /* */
232     vout_display_SendEventFullscreen (vd, false);
233     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
234
235     return VLC_SUCCESS;
236
237 error:
238     [nsPool release];
239     Close(this);
240     return VLC_EGENERIC;
241 }
242
243 void Close(vlc_object_t *this)
244 {
245     vout_display_t *vd = (vout_display_t *)this;
246     vout_display_sys_t *sys = vd->sys;
247
248     if ([[sys->glView window] level] != NSNormalWindowLevel)
249         [[sys->glView window] setLevel: NSNormalWindowLevel];
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->source );
300     [sys->glView setVoutFlushing:NO];
301     picture_Release (pic);
302     sys->has_first_frame = true;
303
304     if (subpicture)
305         subpicture_Delete(subpicture);
306 }
307
308 static int Control (vout_display_t *vd, int query, va_list ap)
309 {
310     vout_display_sys_t *sys = vd->sys;
311
312     switch (query)
313     {
314         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
315         {
316             const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
317             if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
318                 return VLC_EGENERIC;
319
320             return VLC_SUCCESS;
321         }
322         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
323         {
324             NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
325             unsigned state = va_arg (ap, unsigned);
326             [sys->glView performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:state] waitUntilDone:NO];
327             [o_pool release];
328             return VLC_SUCCESS;
329         }
330         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
331         case VOUT_DISPLAY_CHANGE_ZOOM:
332         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
333         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
334         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
335         {
336             if (!vd->sys)
337                 return VLC_EGENERIC;
338
339             NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
340
341             id o_window = [sys->glView window];
342             if (!o_window)
343                 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
344
345             NSSize windowMinSize = [o_window minSize];
346
347             const vout_display_cfg_t *cfg;
348             const video_format_t *source;
349             bool is_forced = false;
350
351             vout_display_place_t place;
352
353             if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP)
354             {
355                 source = (const video_format_t *)va_arg (ap, const video_format_t *);
356                 cfg = vd->cfg;
357             }
358             else
359             {
360                 source = &vd->source;
361                 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
362                 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
363                     is_forced = (bool)va_arg (ap, int);
364             }
365
366             if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
367                 && (cfg->display.width != vd->cfg->display.width
368                     || cfg->display.height != vd->cfg->display.height)
369                 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
370                 return VLC_EGENERIC;
371  
372             /* for the case that the core wants to resize below minimum window size we correct the size here
373              to ensure a centered picture */
374             vout_display_cfg_t cfg_tmp = *cfg;
375             if (cfg_tmp.display.width < windowMinSize.width)
376                 cfg_tmp.display.width = windowMinSize.width;
377             if (cfg_tmp.display.height < 70)
378                 cfg_tmp.display.height = 70;
379
380             if (!config_GetInt(vd, "macosx-video-autoresize"))
381             {
382                 NSRect bounds = [sys->glView bounds];
383                 cfg_tmp.display.width = bounds.size.width;
384                 cfg_tmp.display.height = bounds.size.height;
385             }
386
387             vout_display_PlacePicture (&place, source, &cfg_tmp, false);
388
389             /* For resize, we call glViewport in reshape and not here.
390                This has the positive side effect that we avoid erratic sizing as we animate every resize. */
391             if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
392             {
393                 // x / y are top left corner, but we need the lower left one
394                 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
395             }
396
397             [o_pool release];
398             return VLC_SUCCESS;
399         }
400
401         case VOUT_DISPLAY_HIDE_MOUSE:
402         {
403             [NSCursor setHiddenUntilMouseMoves: YES];
404             return VLC_SUCCESS;
405         }
406
407         case VOUT_DISPLAY_GET_OPENGL:
408         {
409             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
410             *gl = &sys->gl;
411             return VLC_SUCCESS;
412         }
413
414         case VOUT_DISPLAY_RESET_PICTURES:
415             assert (0);
416         default:
417             msg_Err (vd, "Unknown request in Mac OS X vout display");
418             return VLC_EGENERIC;
419     }
420 }
421
422 /*****************************************************************************
423  * vout opengl callbacks
424  *****************************************************************************/
425 static int OpenglLock(vlc_gl_t *gl)
426 {
427     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
428     NSOpenGLContext *context = [sys->glView openGLContext];
429     CGLError err = CGLLockContext([context CGLContextObj]);
430     if (kCGLNoError == err)
431     {
432         [context makeCurrentContext];
433         return 0;
434     }
435     return 1;
436 }
437
438 static void OpenglUnlock(vlc_gl_t *gl)
439 {
440     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
441     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
442 }
443
444 static void OpenglSwap(vlc_gl_t *gl)
445 {
446     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
447     [[sys->glView openGLContext] flushBuffer];
448 }
449
450 /*****************************************************************************
451  * Our NSView object
452  *****************************************************************************/
453 @implementation VLCOpenGLVideoView
454
455 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
456
457
458 + (void)getNewView:(NSValue *)value
459 {
460     id *ret = [value pointerValue];
461     *ret = [[self alloc] init];
462 }
463
464 /**
465  * Gets called by the Open() method.
466  */
467 - (id)init
468 {
469     VLCAssertMainThread();
470
471     /* Warning - this may be called on non main thread */
472
473     NSOpenGLPixelFormatAttribute attribs[] =
474     {
475         NSOpenGLPFADoubleBuffer,
476         NSOpenGLPFAAccelerated,
477         NSOpenGLPFANoRecovery,
478         NSOpenGLPFAColorSize, 24,
479         NSOpenGLPFAAlphaSize, 8,
480         NSOpenGLPFADepthSize, 24,
481         NSOpenGLPFAWindow,
482         0
483     };
484
485     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
486
487     if (!fmt)
488         return nil;
489
490     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
491     [fmt release];
492
493     if (!self)
494         return nil;
495
496     /* Swap buffers only during the vertical retrace of the monitor.
497      http://developer.apple.com/documentation/GraphicsImaging/
498      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
499     GLint params[] = { 1 };
500     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
501
502     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
503     return self;
504 }
505
506 /**
507  * Gets called by the Open() method.
508  */
509 - (void)setFrameWithValue:(NSValue *)value
510 {
511     [self setFrame:[value rectValue]];
512 }
513
514 /**
515  * Gets called by the Close and Open methods.
516  * (Non main thread).
517  */
518 - (void)setVoutDisplay:(vout_display_t *)aVd
519 {
520     @synchronized(self) {
521         vd = aVd;
522     }
523 }
524
525 - (vout_display_t *)voutDisplay
526 {
527     return vd;
528 }
529
530 /**
531  * Gets called when the vout will aquire the lock and flush.
532  * (Non main thread).
533  */
534 - (void)setVoutFlushing:(BOOL)flushing
535 {
536     if (!flushing)
537         return;
538     @synchronized(self) {
539         _hasPendingReshape = NO;
540     }
541 }
542
543 /**
544  * Can -drawRect skip rendering?.
545  */
546 - (BOOL)canSkipRendering
547 {
548     VLCAssertMainThread();
549
550     @synchronized(self) {
551         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
552         return !_hasPendingReshape && hasFirstFrame;
553     }
554 }
555
556
557 /**
558  * Local method that locks the gl context.
559  */
560 - (BOOL)lockgl
561 {
562     VLCAssertMainThread();
563     NSOpenGLContext *context = [self openGLContext];
564     CGLError err = CGLLockContext([context CGLContextObj]);
565     if (err == kCGLNoError)
566         [context makeCurrentContext];
567     return err == kCGLNoError;
568 }
569
570 /**
571  * Local method that unlocks the gl context.
572  */
573 - (void)unlockgl
574 {
575     VLCAssertMainThread();
576     CGLUnlockContext([[self openGLContext] CGLContextObj]);
577 }
578
579 /**
580  * Local method that force a rendering of a frame.
581  * This will get called if Cocoa forces us to redraw (via -drawRect).
582  */
583 - (void)render
584 {
585     VLCAssertMainThread();
586
587     // We may have taken some times to take the opengl Lock.
588     // Check here to see if we can just skip the frame as well.
589     if ([self canSkipRendering])
590         return;
591
592     BOOL hasFirstFrame;
593     @synchronized(self) { // vd can be accessed from multiple threads
594         hasFirstFrame = vd && vd->sys->has_first_frame;
595     }
596
597     if (hasFirstFrame) {
598         // This will lock gl.
599         vout_display_opengl_Display( vd->sys->vgl, &vd->source );
600     }
601     else
602         glClear(GL_COLOR_BUFFER_BIT);
603 }
604
605 /**
606  * Method called by Cocoa when the view is resized.
607  */
608 - (void)reshape
609 {
610     VLCAssertMainThread();
611
612     NSRect bounds = [self bounds];
613     vout_display_place_t place;
614
615     @synchronized(self) {
616         if (vd) {
617             vout_display_cfg_t cfg_tmp = *(vd->cfg);
618             cfg_tmp.display.width  = bounds.size.width;
619             cfg_tmp.display.height = bounds.size.height;
620
621             vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
622             vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
623         }
624     }
625
626     if ([self lockgl]) {
627         // x / y are top left corner, but we need the lower left one
628         glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
629
630         @synchronized(self) {
631             // This may be cleared before -drawRect is being called,
632             // in this case we'll skip the rendering.
633             // This will save us for rendering two frames (or more) for nothing
634             // (one by the vout, one (or more) by drawRect)
635             _hasPendingReshape = YES;
636         }
637
638         [self unlockgl];
639
640         [super reshape];
641     }
642 }
643
644 /**
645  * Method called by Cocoa when the view is resized or the location has changed.
646  * We just need to make sure we are locking here.
647  */
648 - (void)update
649 {
650     VLCAssertMainThread();
651     BOOL success = [self lockgl];
652     if (!success)
653         return;
654
655     [super update];
656
657     [self unlockgl];
658 }
659
660 /**
661  * Method called by Cocoa to force redraw.
662  */
663 - (void)drawRect:(NSRect) rect
664 {
665     VLCAssertMainThread();
666
667     if ([self canSkipRendering])
668         return;
669
670     BOOL success = [self lockgl];
671     if (!success)
672         return;
673
674     [self render];
675
676     [self unlockgl];
677 }
678
679 - (void)renewGState
680 {
681     NSWindow *window = [self window];
682
683     // Remove flashes with splitter view.
684     if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
685         [window disableScreenUpdatesUntilFlush];
686
687     [super renewGState];
688 }
689
690 - (BOOL)mouseDownCanMoveWindow
691 {
692     return YES;
693 }
694
695 - (BOOL)isOpaque
696 {
697     return YES;
698 }
699
700 - (void)setWindowLevel:(NSNumber*)state
701 {
702     if( [state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE )
703         [[self window] setLevel: NSStatusWindowLevel];
704     else
705         [[self window] setLevel: NSNormalWindowLevel];
706 }
707 @end