1 /*****************************************************************************
2 * macosx.m: MacOS X OpenGL provider
3 *****************************************************************************
4 * Copyright (C) 2001-2012 the VideoLAN team
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 * David Fuhrmann <david dot fuhrmann at googlemail dot com>
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
31 *****************************************************************************/
33 /*****************************************************************************
35 *****************************************************************************/
37 #import <Cocoa/Cocoa.h>
38 #import <OpenGL/OpenGL.h>
45 #include <vlc_common.h>
46 #include <vlc_plugin.h>
47 #include <vlc_vout_display.h>
48 #include <vlc_opengl.h>
49 #include <vlc_dialog.h>
52 @interface NSWindow (VLCCustomCode)
56 /* compilation support for 10.5 and 10.6 */
57 #define OSX_LION NSAppKitVersionNumber >= 1115.2
58 #ifndef MAC_OS_X_VERSION_10_7
60 @interface NSView (IntroducedInLion)
61 - (NSRect)convertRectToBacking:(NSRect)aRect;
62 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
68 * Forward declarations
70 static int Open (vlc_object_t *);
71 static void Close (vlc_object_t *);
73 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
74 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
75 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
76 static int Control (vout_display_t *vd, int query, va_list ap);
78 static void *OurGetProcAddress(vlc_gl_t *, const char *);
80 static int OpenglLock (vlc_gl_t *gl);
81 static void OpenglUnlock (vlc_gl_t *gl);
82 static void OpenglSwap (vlc_gl_t *gl);
88 /* Will be loaded even without interface module. see voutgl.m */
89 set_shortname ("Mac OS X")
90 set_description (N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
91 set_category (CAT_VIDEO)
92 set_subcategory (SUBCAT_VIDEO_VOUT )
93 set_capability ("vout display", 300)
94 set_callbacks (Open, Close)
96 add_shortcut ("macosx", "vout_macosx")
100 * Obj-C protocol declaration that drawable-nsobject should follow
102 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
103 - (void)addVoutSubview:(NSView *)view;
104 - (void)removeVoutSubview:(NSView *)view;
107 @interface VLCOpenGLVideoView : NSOpenGLView
110 BOOL _hasPendingReshape;
112 - (void)setVoutDisplay:(vout_display_t *)vd;
113 - (void)setVoutFlushing:(BOOL)flushing;
117 struct vout_display_sys_t
119 VLCOpenGLVideoView *glView;
120 id<VLCOpenGLVideoViewEmbedding> container;
122 vout_window_t *embed;
124 vout_display_opengl_t *vgl;
126 picture_pool_t *pool;
128 bool has_first_frame;
130 vout_display_place_t place;
134 static void *OurGetProcAddress(vlc_gl_t *gl, const char *name)
138 return dlsym(RTLD_DEFAULT, name);
141 static int Open (vlc_object_t *this)
143 vout_display_t *vd = (vout_display_t *)this;
144 vout_display_sys_t *sys = calloc (1, sizeof(*sys));
145 NSAutoreleasePool *nsPool = nil;
150 if (!CGDisplayUsesOpenGLAcceleration (kCGDirectMainDisplay))
152 msg_Err (this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results");
153 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."));
156 msg_Dbg (this, "Quartz Extreme acceleration is active");
163 /* Get the drawable object */
164 id container = var_CreateGetAddress (vd, "drawable-nsobject");
167 vout_display_DeleteWindow (vd, NULL);
171 vout_window_cfg_t wnd_cfg;
173 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
174 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
175 wnd_cfg.x = var_InheritInteger (vd, "video-x");
176 wnd_cfg.y = var_InheritInteger (vd, "video-y");
177 wnd_cfg.width = vd->cfg->display.width;
178 wnd_cfg.height = vd->cfg->display.height;
180 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
182 container = sys->embed->handle.nsobject;
186 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
191 /* This will be released in Close(), on
192 * main thread, after we are done using it. */
193 sys->container = [container retain];
195 /* Get our main view*/
196 nsPool = [[NSAutoreleasePool alloc] init];
198 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
202 [sys->glView setVoutDisplay:vd];
204 /* We don't wait, that means that we'll have to be careful about releasing
206 * That's why we'll release on main thread in Close(). */
207 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
208 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
209 else if ([container isKindOfClass:[NSView class]])
211 NSView *parentView = container;
212 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
213 [sys->glView performSelectorOnMainThread:@selector(setFrameToBoundsOfView:) withObject:[NSValue valueWithPointer:parentView] waitUntilDone:NO];
217 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
225 /* Initialize common OpenGL video display */
226 sys->gl.lock = OpenglLock;
227 sys->gl.unlock = OpenglUnlock;
228 sys->gl.swap = OpenglSwap;
229 sys->gl.getProcAddress = OurGetProcAddress;
231 const vlc_fourcc_t *subpicture_chromas;
232 video_format_t fmt = vd->fmt;
234 sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
242 vout_display_info_t info = vd->info;
243 info.has_pictures_invalid = false;
244 info.has_event_thread = true;
245 info.subpicture_chromas = subpicture_chromas;
247 /* Setup vout_display_t once everything is fine */
251 vd->prepare = PictureRender;
252 vd->display = PictureDisplay;
253 vd->control = Control;
256 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
266 void Close (vlc_object_t *this)
268 vout_display_t *vd = (vout_display_t *)this;
269 vout_display_sys_t *sys = vd->sys;
271 [sys->glView setVoutDisplay:nil];
273 var_Destroy (vd, "drawable-nsobject");
274 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
276 /* This will retain sys->glView */
277 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
279 /* release on main thread as explained in Open() */
280 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
281 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
283 [sys->glView release];
285 if (sys->gl.sys != NULL)
286 vout_display_opengl_Delete (sys->vgl);
289 vout_display_DeleteWindow (vd, sys->embed);
293 /*****************************************************************************
294 * vout display callbacks
295 *****************************************************************************/
297 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
299 vout_display_sys_t *sys = vd->sys;
302 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
307 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
310 vout_display_sys_t *sys = vd->sys;
312 vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
315 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
317 vout_display_sys_t *sys = vd->sys;
318 [sys->glView setVoutFlushing:YES];
319 vout_display_opengl_Display (sys->vgl, &vd->source);
320 [sys->glView setVoutFlushing:NO];
321 picture_Release (pic);
322 sys->has_first_frame = true;
325 subpicture_Delete(subpicture);
328 static int Control (vout_display_t *vd, int query, va_list ap)
330 vout_display_sys_t *sys = vd->sys;
334 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
336 const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
337 if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
342 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
344 unsigned state = va_arg (ap, unsigned);
345 return vout_window_SetState (sys->embed, state);
347 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
348 case VOUT_DISPLAY_CHANGE_ZOOM:
349 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
350 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
351 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
356 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
358 id o_window = [sys->glView window];
360 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
362 NSSize windowMinSize = [o_window minSize];
364 const vout_display_cfg_t *cfg;
365 const video_format_t *source;
366 bool is_forced = false;
368 if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP)
370 source = (const video_format_t *)va_arg (ap, const video_format_t *);
375 source = &vd->source;
376 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
377 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
378 is_forced = (bool)va_arg (ap, int);
381 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
382 && (cfg->display.width != vd->cfg->display.width
383 || cfg->display.height != vd->cfg->display.height)
384 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
387 /* we always use our current frame here, because we have some size constraints
388 in the ui vout provider */
389 vout_display_cfg_t cfg_tmp = *cfg;
391 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
393 bounds = [sys->glView convertRectToBacking:[sys->glView bounds]];
395 bounds = [sys->glView bounds];
396 cfg_tmp.display.width = bounds.size.width;
397 cfg_tmp.display.height = bounds.size.height;
399 vout_display_place_t place;
400 vout_display_PlacePicture (&place, source, &cfg_tmp, false);
401 @synchronized (sys->glView) {
405 /* For resize, we call glViewport in reshape and not here.
406 This has the positive side effect that we avoid erratic sizing as we animate every resize. */
407 if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
409 // x / y are top left corner, but we need the lower left one
410 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
417 case VOUT_DISPLAY_HIDE_MOUSE:
419 [NSCursor setHiddenUntilMouseMoves: YES];
423 case VOUT_DISPLAY_GET_OPENGL:
425 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
430 case VOUT_DISPLAY_RESET_PICTURES:
433 msg_Err (vd, "Unknown request in Mac OS X vout display");
438 /*****************************************************************************
439 * vout opengl callbacks
440 *****************************************************************************/
441 static int OpenglLock (vlc_gl_t *gl)
443 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
444 NSOpenGLContext *context = [sys->glView openGLContext];
445 CGLError err = CGLLockContext ([context CGLContextObj]);
446 if (kCGLNoError == err)
448 [context makeCurrentContext];
454 static void OpenglUnlock (vlc_gl_t *gl)
456 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
457 CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
460 static void OpenglSwap (vlc_gl_t *gl)
462 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
463 [[sys->glView openGLContext] flushBuffer];
466 /*****************************************************************************
468 *****************************************************************************/
469 @implementation VLCOpenGLVideoView
471 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
474 + (void)getNewView:(NSValue *)value
476 id *ret = [value pointerValue];
477 *ret = [[self alloc] init];
481 * Gets called by the Open() method.
485 VLCAssertMainThread();
487 /* Warning - this may be called on non main thread */
489 NSOpenGLPixelFormatAttribute attribs[] =
491 NSOpenGLPFADoubleBuffer,
492 NSOpenGLPFAAccelerated,
493 NSOpenGLPFANoRecovery,
494 NSOpenGLPFAColorSize, 24,
495 NSOpenGLPFAAlphaSize, 8,
496 NSOpenGLPFADepthSize, 24,
501 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
506 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
512 /* enable HiDPI support on OS X 10.7 and later */
514 [self setWantsBestResolutionOpenGLSurface:YES];
516 /* Swap buffers only during the vertical retrace of the monitor.
517 http://developer.apple.com/documentation/GraphicsImaging/
518 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
519 GLint params[] = { 1 };
520 CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
522 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
527 * Gets called by the Open() method.
529 - (void)setFrameToBoundsOfView:(NSValue *)value
531 NSView *parentView = [value pointerValue];
532 [self setFrame:[parentView bounds]];
536 * Gets called by the Close and Open methods.
539 - (void)setVoutDisplay:(vout_display_t *)aVd
541 @synchronized(self) {
547 * Gets called when the vout will aquire the lock and flush.
550 - (void)setVoutFlushing:(BOOL)flushing
554 @synchronized(self) {
555 _hasPendingReshape = NO;
560 * Can -drawRect skip rendering?.
562 - (BOOL)canSkipRendering
564 VLCAssertMainThread();
566 @synchronized(self) {
567 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
568 return !_hasPendingReshape && hasFirstFrame;
574 * Local method that locks the gl context.
578 VLCAssertMainThread();
579 NSOpenGLContext *context = [self openGLContext];
580 CGLError err = CGLLockContext ([context CGLContextObj]);
581 if (err == kCGLNoError)
582 [context makeCurrentContext];
583 return err == kCGLNoError;
587 * Local method that unlocks the gl context.
591 VLCAssertMainThread();
592 CGLUnlockContext ([[self openGLContext] CGLContextObj]);
596 * Local method that force a rendering of a frame.
597 * This will get called if Cocoa forces us to redraw (via -drawRect).
601 VLCAssertMainThread();
603 // We may have taken some times to take the opengl Lock.
604 // Check here to see if we can just skip the frame as well.
605 if ([self canSkipRendering])
609 @synchronized(self) { // vd can be accessed from multiple threads
610 hasFirstFrame = vd && vd->sys->has_first_frame;
614 // This will lock gl.
615 vout_display_opengl_Display (vd->sys->vgl, &vd->source);
618 glClear (GL_COLOR_BUFFER_BIT);
622 * Method called by Cocoa when the view is resized.
626 VLCAssertMainThread();
629 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
631 bounds = [self convertRectToBacking:[self bounds]];
633 bounds = [self bounds];
634 vout_display_place_t place;
636 @synchronized(self) {
638 vout_display_cfg_t cfg_tmp = *(vd->cfg);
639 cfg_tmp.display.width = bounds.size.width;
640 cfg_tmp.display.height = bounds.size.height;
642 vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
643 vd->sys->place = place;
644 vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
649 // x / y are top left corner, but we need the lower left one
650 glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
652 @synchronized(self) {
653 // This may be cleared before -drawRect is being called,
654 // in this case we'll skip the rendering.
655 // This will save us for rendering two frames (or more) for nothing
656 // (one by the vout, one (or more) by drawRect)
657 _hasPendingReshape = YES;
667 * Method called by Cocoa when the view is resized or the location has changed.
668 * We just need to make sure we are locking here.
672 VLCAssertMainThread();
673 BOOL success = [self lockgl];
683 * Method called by Cocoa to force redraw.
685 - (void)drawRect:(NSRect) rect
687 VLCAssertMainThread();
689 if ([self canSkipRendering])
692 BOOL success = [self lockgl];
703 NSWindow *window = [self window];
705 // Remove flashes with splitter view.
706 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
707 [window disableScreenUpdatesUntilFlush];
718 #pragma mark Mouse handling
720 - (void)mouseDown:(NSEvent *)o_event
722 if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] & NSControlKeyMask))
724 if ([o_event clickCount] <= 1)
725 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
728 [super mouseDown:o_event];
731 - (void)otherMouseDown:(NSEvent *)o_event
733 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
735 [super otherMouseDown: o_event];
738 - (void)mouseUp:(NSEvent *)o_event
740 if ([o_event type] == NSLeftMouseUp)
741 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
743 [super mouseUp: o_event];
746 - (void)otherMouseUp:(NSEvent *)o_event
748 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
750 [super otherMouseUp: o_event];
753 - (void)mouseMoved:(NSEvent *)o_event
759 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
761 s_rect = [self convertRectToBacking:[self bounds]];
763 s_rect = [self bounds];
764 ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
765 b_inside = [self mouse: ml inRect: s_rect];
773 vout_display_place_t place = vd->sys->place;
775 if (place.width > 0 && place.height > 0)
777 const int x = vd->source.i_x_offset +
778 (int64_t)(ml.x - place.x) * vd->source.i_visible_width / place.width;
779 const int y = vd->source.i_y_offset +
780 (int64_t)((int)s_rect.size.height - (int)ml.y - place.y) * vd->source.i_visible_height / place.height;
782 vout_display_SendEventMouseMoved (vd, x, y);
788 [super mouseMoved: o_event];
791 - (void)mouseDragged:(NSEvent *)o_event
793 [self mouseMoved: o_event];
794 [super mouseDragged: o_event];
797 - (void)otherMouseDragged:(NSEvent *)o_event
799 [self mouseMoved: o_event];
800 [super otherMouseDragged: o_event];
803 - (void)rightMouseDragged:(NSEvent *)o_event
805 [self mouseMoved: o_event];
806 [super rightMouseDragged: o_event];
809 - (BOOL)acceptsFirstResponder
814 - (BOOL)mouseDownCanMoveWindow