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 /* 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 (requires drawable-nsobject)"))
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");
148 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."));
150 msg_Dbg (this, "Quartz Extreme acceleration is active");
157 /* Get the drawable object */
158 id container = var_CreateGetAddress (vd, "drawable-nsobject");
160 vout_display_DeleteWindow (vd, NULL);
162 vout_window_cfg_t wnd_cfg;
164 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
165 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
166 wnd_cfg.x = var_InheritInteger (vd, "video-x");
167 wnd_cfg.y = var_InheritInteger (vd, "video-y");
168 wnd_cfg.width = vd->cfg->display.width;
169 wnd_cfg.height = vd->cfg->display.height;
171 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
173 container = sys->embed->handle.nsobject;
176 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
181 /* This will be released in Close(), on
182 * main thread, after we are done using it. */
183 sys->container = [container retain];
185 /* Get our main view*/
186 nsPool = [[NSAutoreleasePool alloc] init];
188 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
192 [sys->glView setVoutDisplay:vd];
194 /* We don't wait, that means that we'll have to be careful about releasing
196 * That's why we'll release on main thread in Close(). */
197 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
198 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
199 else if ([container isKindOfClass:[NSView class]]) {
200 NSView *parentView = container;
201 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
202 [sys->glView performSelectorOnMainThread:@selector(setFrameToBoundsOfView:) withObject:[NSValue valueWithPointer:parentView] waitUntilDone:NO];
204 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
212 /* Initialize common OpenGL video display */
213 sys->gl.lock = OpenglLock;
214 sys->gl.unlock = OpenglUnlock;
215 sys->gl.swap = OpenglSwap;
216 sys->gl.getProcAddress = OurGetProcAddress;
218 const vlc_fourcc_t *subpicture_chromas;
219 video_format_t fmt = vd->fmt;
221 sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
228 vout_display_info_t info = vd->info;
229 info.has_pictures_invalid = false;
230 info.has_event_thread = true;
231 info.subpicture_chromas = subpicture_chromas;
232 info.has_hide_mouse = true;
234 /* Setup vout_display_t once everything is fine */
238 vd->prepare = PictureRender;
239 vd->display = PictureDisplay;
240 vd->control = Control;
243 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
253 void Close (vlc_object_t *this)
255 vout_display_t *vd = (vout_display_t *)this;
256 vout_display_sys_t *sys = vd->sys;
258 [sys->glView setVoutDisplay:nil];
260 var_Destroy (vd, "drawable-nsobject");
261 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
262 /* This will retain sys->glView */
263 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
265 /* release on main thread as explained in Open() */
266 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
267 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
269 [sys->glView release];
271 if (sys->gl.sys != NULL)
272 vout_display_opengl_Delete (sys->vgl);
275 vout_display_DeleteWindow (vd, sys->embed);
279 /*****************************************************************************
280 * vout display callbacks
281 *****************************************************************************/
283 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
285 vout_display_sys_t *sys = vd->sys;
288 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
293 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
296 vout_display_sys_t *sys = vd->sys;
298 vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
301 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
303 vout_display_sys_t *sys = vd->sys;
304 [sys->glView setVoutFlushing:YES];
305 vout_display_opengl_Display (sys->vgl, &vd->source);
306 [sys->glView setVoutFlushing:NO];
307 picture_Release (pic);
308 sys->has_first_frame = true;
311 subpicture_Delete(subpicture);
314 static int Control (vout_display_t *vd, int query, va_list ap)
316 vout_display_sys_t *sys = vd->sys;
320 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
322 const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
323 if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
328 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
330 unsigned state = va_arg (ap, unsigned);
331 return vout_window_SetState (sys->embed, state);
333 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
334 case VOUT_DISPLAY_CHANGE_ZOOM:
335 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
336 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
337 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
342 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
344 id o_window = [sys->glView window];
346 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
348 NSSize windowMinSize = [o_window minSize];
350 const vout_display_cfg_t *cfg;
351 const video_format_t *source;
352 bool is_forced = false;
354 if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP) {
355 source = (const video_format_t *)va_arg (ap, const video_format_t *);
358 source = &vd->source;
359 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
360 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
361 is_forced = (bool)va_arg (ap, int);
364 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
365 && (cfg->display.width != vd->cfg->display.width
366 || cfg->display.height != vd->cfg->display.height)
367 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
370 /* we always use our current frame here, because we have some size constraints
371 in the ui vout provider */
372 vout_display_cfg_t cfg_tmp = *cfg;
374 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
376 bounds = [sys->glView convertRectToBacking:[sys->glView bounds]];
378 bounds = [sys->glView bounds];
379 cfg_tmp.display.width = bounds.size.width;
380 cfg_tmp.display.height = bounds.size.height;
382 vout_display_place_t place;
383 vout_display_PlacePicture (&place, source, &cfg_tmp, false);
384 @synchronized (sys->glView) {
388 /* For resize, we call glViewport in reshape and not here.
389 This has the positive side effect that we avoid erratic sizing as we animate every resize. */
390 if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
391 // x / y are top left corner, but we need the lower left one
392 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
399 case VOUT_DISPLAY_HIDE_MOUSE:
401 [NSCursor setHiddenUntilMouseMoves: YES];
405 case VOUT_DISPLAY_GET_OPENGL:
407 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
412 case VOUT_DISPLAY_RESET_PICTURES:
415 msg_Err (vd, "Unknown request in Mac OS X vout display");
420 /*****************************************************************************
421 * vout opengl callbacks
422 *****************************************************************************/
423 static int OpenglLock (vlc_gl_t *gl)
425 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
426 if (!sys->glView || ![sys->glView respondsToSelector:@selector(openGLContext)])
429 NSOpenGLContext *context = [sys->glView openGLContext];
430 CGLError err = CGLLockContext ([context CGLContextObj]);
431 if (kCGLNoError == err) {
432 [context makeCurrentContext];
438 static void OpenglUnlock (vlc_gl_t *gl)
440 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
441 CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
444 static void OpenglSwap (vlc_gl_t *gl)
446 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
447 [[sys->glView openGLContext] flushBuffer];
450 /*****************************************************************************
452 *****************************************************************************/
453 @implementation VLCOpenGLVideoView
455 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
458 + (void)getNewView:(NSValue *)value
460 id *ret = [value pointerValue];
461 *ret = [[self alloc] init];
465 * Gets called by the Open() method.
469 VLCAssertMainThread();
471 /* Warning - this may be called on non main thread */
473 NSOpenGLPixelFormatAttribute attribs[] =
475 NSOpenGLPFADoubleBuffer,
476 NSOpenGLPFAAccelerated,
477 NSOpenGLPFANoRecovery,
478 NSOpenGLPFAColorSize, 24,
479 NSOpenGLPFAAlphaSize, 8,
480 NSOpenGLPFADepthSize, 24,
485 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
490 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
496 /* enable HiDPI support on OS X 10.7 and later */
498 [self setWantsBestResolutionOpenGLSurface:YES];
500 /* Swap buffers only during the vertical retrace of the monitor.
501 http://developer.apple.com/documentation/GraphicsImaging/
502 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
503 GLint params[] = { 1 };
504 CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
506 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
511 * Gets called by the Open() method.
513 - (void)setFrameToBoundsOfView:(NSValue *)value
515 NSView *parentView = [value pointerValue];
516 [self setFrame:[parentView bounds]];
520 * Gets called by the Close and Open methods.
523 - (void)setVoutDisplay:(vout_display_t *)aVd
525 @synchronized(self) {
531 * Gets called when the vout will aquire the lock and flush.
534 - (void)setVoutFlushing:(BOOL)flushing
538 @synchronized(self) {
539 _hasPendingReshape = NO;
544 * Can -drawRect skip rendering?.
546 - (BOOL)canSkipRendering
548 VLCAssertMainThread();
550 @synchronized(self) {
551 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
552 return !_hasPendingReshape && hasFirstFrame;
558 * Local method that locks the gl context.
562 VLCAssertMainThread();
563 NSOpenGLContext *context = [self openGLContext];
564 CGLError err = CGLLockContext ([context CGLContextObj]);
565 if (err == kCGLNoError)
566 [context makeCurrentContext];
567 return err == kCGLNoError;
571 * Local method that unlocks the gl context.
575 VLCAssertMainThread();
576 CGLUnlockContext ([[self openGLContext] CGLContextObj]);
580 * Local method that force a rendering of a frame.
581 * This will get called if Cocoa forces us to redraw (via -drawRect).
585 VLCAssertMainThread();
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])
593 @synchronized(self) { // vd can be accessed from multiple threads
594 hasFirstFrame = vd && vd->sys->has_first_frame;
598 // This will lock gl.
599 vout_display_opengl_Display (vd->sys->vgl, &vd->source);
601 glClear (GL_COLOR_BUFFER_BIT);
605 * Method called by Cocoa when the view is resized.
609 VLCAssertMainThread();
612 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
614 bounds = [self convertRectToBacking:[self bounds]];
616 bounds = [self bounds];
617 vout_display_place_t place;
619 @synchronized(self) {
621 vout_display_cfg_t cfg_tmp = *(vd->cfg);
622 cfg_tmp.display.width = bounds.size.width;
623 cfg_tmp.display.height = bounds.size.height;
625 vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
626 vd->sys->place = place;
627 vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
632 // x / y are top left corner, but we need the lower left one
633 glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
635 @synchronized(self) {
636 // This may be cleared before -drawRect is being called,
637 // in this case we'll skip the rendering.
638 // This will save us for rendering two frames (or more) for nothing
639 // (one by the vout, one (or more) by drawRect)
640 _hasPendingReshape = YES;
650 * Method called by Cocoa when the view is resized or the location has changed.
651 * We just need to make sure we are locking here.
655 VLCAssertMainThread();
656 BOOL success = [self lockgl];
666 * Method called by Cocoa to force redraw.
668 - (void)drawRect:(NSRect) rect
670 VLCAssertMainThread();
672 if ([self canSkipRendering])
675 BOOL success = [self lockgl];
686 NSWindow *window = [self window];
688 // Remove flashes with splitter view.
689 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
690 [window disableScreenUpdatesUntilFlush];
701 #pragma mark Mouse handling
703 - (void)mouseDown:(NSEvent *)o_event
705 if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] & NSControlKeyMask)) {
706 if ([o_event clickCount] <= 1)
707 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
710 [super mouseDown:o_event];
713 - (void)otherMouseDown:(NSEvent *)o_event
715 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
717 [super otherMouseDown: o_event];
720 - (void)mouseUp:(NSEvent *)o_event
722 if ([o_event type] == NSLeftMouseUp)
723 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
725 [super mouseUp: o_event];
728 - (void)otherMouseUp:(NSEvent *)o_event
730 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
732 [super otherMouseUp: o_event];
735 - (void)mouseMoved:(NSEvent *)o_event
741 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
743 s_rect = [self convertRectToBacking:[self bounds]];
745 s_rect = [self bounds];
746 ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
747 b_inside = [self mouse: ml inRect: s_rect];
750 @synchronized (self) {
752 vout_display_place_t place = vd->sys->place;
754 if (place.width > 0 && place.height > 0) {
755 const int x = vd->source.i_x_offset +
756 (int64_t)(ml.x - place.x) * vd->source.i_visible_width / place.width;
757 const int y = vd->source.i_y_offset +
758 (int64_t)((int)s_rect.size.height - (int)ml.y - place.y) * vd->source.i_visible_height / place.height;
760 vout_display_SendEventMouseMoved (vd, x, y);
766 [super mouseMoved: o_event];
769 - (void)mouseDragged:(NSEvent *)o_event
771 [self mouseMoved: o_event];
772 [super mouseDragged: o_event];
775 - (void)otherMouseDragged:(NSEvent *)o_event
777 [self mouseMoved: o_event];
778 [super otherMouseDragged: o_event];
781 - (void)rightMouseDragged:(NSEvent *)o_event
783 [self mouseMoved: o_event];
784 [super rightMouseDragged: o_event];
787 - (BOOL)acceptsFirstResponder
792 - (BOOL)mouseDownCanMoveWindow