1 /*****************************************************************************
2 * macosx.m: MacOS X OpenGL provider
3 *****************************************************************************
4 * Copyright (C) 2001-2013 VLC authors and VideoLAN
7 * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8 * Eric Petit <titer@m0k.org>
9 * Benjamin Pracht <bigben at videolan dot org>
10 * Damien Fouilleul <damienf at videolan dot org>
11 * Pierre d'Herbemont <pdherbemont at videolan dot org>
12 * Felix Paul Kühne <fkuehne at videolan dot org>
13 * David Fuhrmann <david dot fuhrmann at googlemail dot com>
15 * Juho Vähä-Herttua <juhovh at iki dot fi>
16 * Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
18 * This program is free software; you can redistribute it and/or modify it
19 * under the terms of the GNU Lesser General Public License as published by
20 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
28 * You should have received a copy of the GNU Lesser General Public License
29 * along with this program; if not, write to the Free Software Foundation,
30 * 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 /* compilation support for 10.5 and 10.6 */
53 #define OSX_LION NSAppKitVersionNumber >= 1115.2
54 #ifndef MAC_OS_X_VERSION_10_7
56 @interface NSView (IntroducedInLion)
57 - (NSRect)convertRectToBacking:(NSRect)aRect;
58 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
64 * Forward declarations
66 static int Open (vlc_object_t *);
67 static void Close (vlc_object_t *);
69 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
70 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
71 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
72 static int Control (vout_display_t *vd, int query, va_list ap);
74 static void *OurGetProcAddress(vlc_gl_t *, const char *);
76 static int OpenglLock (vlc_gl_t *gl);
77 static void OpenglUnlock (vlc_gl_t *gl);
78 static void OpenglSwap (vlc_gl_t *gl);
84 /* Will be loaded even without interface module. see voutgl.m */
85 set_shortname ("Mac OS X")
86 set_description (N_("Mac OS X OpenGL video output"))
87 set_category (CAT_VIDEO)
88 set_subcategory (SUBCAT_VIDEO_VOUT)
89 set_capability ("vout display", 300)
90 set_callbacks (Open, Close)
92 add_shortcut ("macosx", "vout_macosx")
96 * Obj-C protocol declaration that drawable-nsobject should follow
98 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
99 - (void)addVoutSubview:(NSView *)view;
100 - (void)removeVoutSubview:(NSView *)view;
103 @interface VLCOpenGLVideoView : NSOpenGLView
106 BOOL _hasPendingReshape;
108 - (void)setVoutDisplay:(vout_display_t *)vd;
109 - (void)setVoutFlushing:(BOOL)flushing;
113 struct vout_display_sys_t
115 VLCOpenGLVideoView *glView;
116 id<VLCOpenGLVideoViewEmbedding> container;
118 vout_window_t *embed;
120 vout_display_opengl_t *vgl;
122 picture_pool_t *pool;
124 bool has_first_frame;
126 vout_display_place_t place;
130 static void *OurGetProcAddress(vlc_gl_t *gl, const char *name)
134 return dlsym(RTLD_DEFAULT, name);
137 static int Open (vlc_object_t *this)
139 vout_display_t *vd = (vout_display_t *)this;
140 vout_display_sys_t *sys = calloc (1, sizeof(*sys));
141 NSAutoreleasePool *nsPool = nil;
146 if (!CGDisplayUsesOpenGLAcceleration (kCGDirectMainDisplay))
147 msg_Err (this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results");
154 /* Get the drawable object */
155 id container = var_CreateGetAddress (vd, "drawable-nsobject");
157 vout_display_DeleteWindow (vd, NULL);
159 sys->embed = vout_display_NewWindow (vd, VOUT_WINDOW_TYPE_NSOBJECT);
161 container = sys->embed->handle.nsobject;
164 msg_Err(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
169 /* This will be released in Close(), on
170 * main thread, after we are done using it. */
171 sys->container = [container retain];
173 /* Get our main view*/
174 nsPool = [[NSAutoreleasePool alloc] init];
176 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
178 msg_Err(vd, "Initialization of open gl view failed");
182 [sys->glView setVoutDisplay:vd];
184 /* We don't wait, that means that we'll have to be careful about releasing
186 * That's why we'll release on main thread in Close(). */
187 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
188 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
189 else if ([container isKindOfClass:[NSView class]]) {
190 NSView *parentView = container;
191 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
192 [sys->glView performSelectorOnMainThread:@selector(setFrameToBoundsOfView:) withObject:[NSValue valueWithPointer:parentView] waitUntilDone:NO];
194 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
202 /* Initialize common OpenGL video display */
203 sys->gl.lock = OpenglLock;
204 sys->gl.unlock = OpenglUnlock;
205 sys->gl.swap = OpenglSwap;
206 sys->gl.getProcAddress = OurGetProcAddress;
208 const vlc_fourcc_t *subpicture_chromas;
210 sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
212 msg_Err(vd, "Error while initializing opengl display.");
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 info.has_hide_mouse = true;
224 /* Setup vout_display_t once everything is fine */
228 vd->prepare = PictureRender;
229 vd->display = PictureDisplay;
230 vd->control = Control;
233 vout_display_SendEventDisplaySize (vd, vd->fmt.i_visible_width, vd->fmt.i_visible_height);
243 void Close (vlc_object_t *this)
245 vout_display_t *vd = (vout_display_t *)this;
246 vout_display_sys_t *sys = vd->sys;
248 [sys->glView setVoutDisplay:nil];
250 var_Destroy (vd, "drawable-nsobject");
251 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
252 /* This will retain sys->glView */
253 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
255 /* release on main thread as explained in Open() */
256 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
257 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
259 if (sys->gl.sys != NULL)
260 vout_display_opengl_Delete (sys->vgl);
262 [sys->glView release];
265 vout_display_DeleteWindow (vd, sys->embed);
269 /*****************************************************************************
270 * vout display callbacks
271 *****************************************************************************/
273 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
275 vout_display_sys_t *sys = vd->sys;
278 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
283 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
286 vout_display_sys_t *sys = vd->sys;
288 vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
291 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
293 vout_display_sys_t *sys = vd->sys;
294 [sys->glView setVoutFlushing:YES];
295 vout_display_opengl_Display (sys->vgl, &vd->source);
296 [sys->glView setVoutFlushing:NO];
297 picture_Release (pic);
298 sys->has_first_frame = true;
301 subpicture_Delete(subpicture);
304 static int Control (vout_display_t *vd, int query, va_list ap)
306 vout_display_sys_t *sys = vd->sys;
316 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
317 case VOUT_DISPLAY_CHANGE_ZOOM:
318 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
319 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
320 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
322 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
324 id o_window = [sys->glView window];
327 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
330 NSSize windowMinSize = [o_window minSize];
332 const vout_display_cfg_t *cfg;
333 const video_format_t *source;
335 if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP) {
336 source = (const video_format_t *)va_arg (ap, const video_format_t *);
339 source = &vd->source;
340 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
343 /* we always use our current frame here, because we have some size constraints
344 in the ui vout provider */
345 vout_display_cfg_t cfg_tmp = *cfg;
347 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
349 bounds = [sys->glView convertRectToBacking:[sys->glView bounds]];
351 bounds = [sys->glView bounds];
352 cfg_tmp.display.width = bounds.size.width;
353 cfg_tmp.display.height = bounds.size.height;
355 vout_display_place_t place;
356 vout_display_PlacePicture (&place, source, &cfg_tmp, false);
357 @synchronized (sys->glView) {
361 /* For resize, we call glViewport in reshape and not here.
362 This has the positive side effect that we avoid erratic sizing as we animate every resize. */
363 if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
364 // x / y are top left corner, but we need the lower left one
365 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
372 case VOUT_DISPLAY_HIDE_MOUSE:
374 [NSCursor setHiddenUntilMouseMoves: YES];
378 case VOUT_DISPLAY_RESET_PICTURES:
379 vlc_assert_unreachable ();
381 msg_Err (vd, "Unknown request in Mac OS X vout display");
386 /*****************************************************************************
387 * vout opengl callbacks
388 *****************************************************************************/
389 static int OpenglLock (vlc_gl_t *gl)
391 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
392 if (!sys->glView || ![sys->glView respondsToSelector:@selector(openGLContext)])
395 NSOpenGLContext *context = [sys->glView openGLContext];
396 CGLError err = CGLLockContext ([context CGLContextObj]);
397 if (kCGLNoError == err) {
398 [context makeCurrentContext];
404 static void OpenglUnlock (vlc_gl_t *gl)
406 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
407 CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
410 static void OpenglSwap (vlc_gl_t *gl)
412 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
413 [[sys->glView openGLContext] flushBuffer];
416 /*****************************************************************************
418 *****************************************************************************/
419 @implementation VLCOpenGLVideoView
421 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
424 + (void)getNewView:(NSValue *)value
426 id *ret = [value pointerValue];
427 *ret = [[self alloc] init];
431 * Gets called by the Open() method.
435 VLCAssertMainThread();
437 /* Warning - this may be called on non main thread */
439 NSOpenGLPixelFormatAttribute attribs[] =
441 NSOpenGLPFADoubleBuffer,
442 NSOpenGLPFAAccelerated,
443 NSOpenGLPFANoRecovery,
444 NSOpenGLPFAColorSize, 24,
445 NSOpenGLPFAAlphaSize, 8,
446 NSOpenGLPFADepthSize, 24,
448 NSOpenGLPFAAllowOfflineRenderers,
452 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
457 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
463 /* enable HiDPI support on OS X 10.7 and later */
465 [self setWantsBestResolutionOpenGLSurface:YES];
467 /* Swap buffers only during the vertical retrace of the monitor.
468 http://developer.apple.com/documentation/GraphicsImaging/
469 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
470 GLint params[] = { 1 };
471 CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
473 [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidChangeScreenParametersNotification
474 object:[NSApplication sharedApplication]
476 usingBlock:^(NSNotification *notification) {
477 [self performSelectorOnMainThread:@selector(reshape)
482 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
488 [[NSNotificationCenter defaultCenter] removeObserver:self];
493 * Gets called by the Open() method.
495 - (void)setFrameToBoundsOfView:(NSValue *)value
497 NSView *parentView = [value pointerValue];
498 [self setFrame:[parentView bounds]];
502 * Gets called by the Close and Open methods.
505 - (void)setVoutDisplay:(vout_display_t *)aVd
507 @synchronized(self) {
513 * Gets called when the vout will aquire the lock and flush.
516 - (void)setVoutFlushing:(BOOL)flushing
520 @synchronized(self) {
521 _hasPendingReshape = NO;
526 * Can -drawRect skip rendering?.
528 - (BOOL)canSkipRendering
530 VLCAssertMainThread();
532 @synchronized(self) {
533 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
534 return !_hasPendingReshape && hasFirstFrame;
540 * Local method that locks the gl context.
544 VLCAssertMainThread();
545 NSOpenGLContext *context = [self openGLContext];
546 CGLError err = CGLLockContext ([context CGLContextObj]);
547 if (err == kCGLNoError)
548 [context makeCurrentContext];
549 return err == kCGLNoError;
553 * Local method that unlocks the gl context.
557 VLCAssertMainThread();
558 CGLUnlockContext ([[self openGLContext] CGLContextObj]);
562 * Local method that force a rendering of a frame.
563 * This will get called if Cocoa forces us to redraw (via -drawRect).
567 VLCAssertMainThread();
569 // We may have taken some times to take the opengl Lock.
570 // Check here to see if we can just skip the frame as well.
571 if ([self canSkipRendering])
575 @synchronized(self) { // vd can be accessed from multiple threads
576 hasFirstFrame = vd && vd->sys->has_first_frame;
580 // This will lock gl.
581 vout_display_opengl_Display (vd->sys->vgl, &vd->source);
583 glClear (GL_COLOR_BUFFER_BIT);
587 * Method called by Cocoa when the view is resized.
591 VLCAssertMainThread();
594 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
596 bounds = [self convertRectToBacking:[self bounds]];
598 bounds = [self bounds];
599 vout_display_place_t place;
601 @synchronized(self) {
603 vout_display_cfg_t cfg_tmp = *(vd->cfg);
604 cfg_tmp.display.width = bounds.size.width;
605 cfg_tmp.display.height = bounds.size.height;
607 vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
608 vd->sys->place = place;
609 vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height);
614 // x / y are top left corner, but we need the lower left one
615 glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
617 @synchronized(self) {
618 // This may be cleared before -drawRect is being called,
619 // in this case we'll skip the rendering.
620 // This will save us for rendering two frames (or more) for nothing
621 // (one by the vout, one (or more) by drawRect)
622 _hasPendingReshape = YES;
632 * Method called by Cocoa when the view is resized or the location has changed.
633 * We just need to make sure we are locking here.
637 VLCAssertMainThread();
638 BOOL success = [self lockgl];
648 * Method called by Cocoa to force redraw.
650 - (void)drawRect:(NSRect) rect
652 VLCAssertMainThread();
654 if ([self canSkipRendering])
657 BOOL success = [self lockgl];
668 NSWindow *window = [self window];
670 // Remove flashes with splitter view.
671 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
672 [window disableScreenUpdatesUntilFlush];
683 #pragma mark Mouse handling
685 - (void)mouseDown:(NSEvent *)o_event
687 @synchronized (self) {
689 if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] & NSControlKeyMask)) {
690 if ([o_event clickCount] <= 1)
691 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
696 [super mouseDown:o_event];
699 - (void)otherMouseDown:(NSEvent *)o_event
701 @synchronized (self) {
703 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
706 [super otherMouseDown: o_event];
709 - (void)mouseUp:(NSEvent *)o_event
711 @synchronized (self) {
713 if ([o_event type] == NSLeftMouseUp)
714 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
718 [super mouseUp: o_event];
721 - (void)otherMouseUp:(NSEvent *)o_event
723 @synchronized (self) {
725 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
728 [super otherMouseUp: o_event];
731 - (void)mouseMoved:(NSEvent *)o_event
733 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
734 NSPoint ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
735 NSRect videoRect = [self bounds];
736 BOOL b_inside = [self mouse: ml inRect: videoRect];
739 ml = [self convertPointToBacking: ml];
740 videoRect = [self convertRectToBacking: videoRect];
744 @synchronized (self) {
746 vout_display_SendMouseMovedDisplayCoordinates(vd, ORIENT_NORMAL,
747 (int)ml.x, videoRect.size.height - (int)ml.y,
753 [super mouseMoved: o_event];
756 - (void)mouseDragged:(NSEvent *)o_event
758 [self mouseMoved: o_event];
759 [super mouseDragged: o_event];
762 - (void)otherMouseDragged:(NSEvent *)o_event
764 [self mouseMoved: o_event];
765 [super otherMouseDragged: o_event];
768 - (void)rightMouseDragged:(NSEvent *)o_event
770 [self mouseMoved: o_event];
771 [super rightMouseDragged: o_event];
774 - (BOOL)acceptsFirstResponder
779 - (BOOL)mouseDownCanMoveWindow