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)
57 * Forward declarations
59 static int Open (vlc_object_t *);
60 static void Close (vlc_object_t *);
62 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
63 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
64 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
65 static int Control (vout_display_t *vd, int query, va_list ap);
67 static void *OurGetProcAddress(vlc_gl_t *, const char *);
69 static int OpenglLock (vlc_gl_t *gl);
70 static void OpenglUnlock (vlc_gl_t *gl);
71 static void OpenglSwap (vlc_gl_t *gl);
77 /* Will be loaded even without interface module. see voutgl.m */
78 set_shortname ("Mac OS X")
79 set_description (N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
80 set_category (CAT_VIDEO)
81 set_subcategory (SUBCAT_VIDEO_VOUT )
82 set_capability ("vout display", 300)
83 set_callbacks (Open, Close)
85 add_shortcut ("macosx", "vout_macosx")
89 * Obj-C protocol declaration that drawable-nsobject should follow
91 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
92 - (void)addVoutSubview:(NSView *)view;
93 - (void)removeVoutSubview:(NSView *)view;
96 @interface VLCOpenGLVideoView : NSOpenGLView
99 BOOL _hasPendingReshape;
101 - (void)setVoutDisplay:(vout_display_t *)vd;
102 - (void)setVoutFlushing:(BOOL)flushing;
106 struct vout_display_sys_t
108 VLCOpenGLVideoView *glView;
109 id<VLCOpenGLVideoViewEmbedding> container;
111 vout_window_t *embed;
113 vout_display_opengl_t *vgl;
115 picture_pool_t *pool;
117 bool has_first_frame;
119 vout_display_place_t place;
123 static void *OurGetProcAddress(vlc_gl_t *gl, const char *name)
127 return dlsym(RTLD_DEFAULT, name);
130 static int Open (vlc_object_t *this)
132 vout_display_t *vd = (vout_display_t *)this;
133 vout_display_sys_t *sys = calloc (1, sizeof(*sys));
134 NSAutoreleasePool *nsPool = nil;
139 if (!CGDisplayUsesOpenGLAcceleration (kCGDirectMainDisplay))
141 msg_Err (this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results");
142 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."));
145 msg_Dbg (this, "Quartz Extreme acceleration is active");
152 /* Get the drawable object */
153 id container = var_CreateGetAddress (vd, "drawable-nsobject");
156 vout_display_DeleteWindow (vd, NULL);
160 vout_window_cfg_t wnd_cfg;
162 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
163 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
164 wnd_cfg.x = var_InheritInteger (vd, "video-x");
165 wnd_cfg.y = var_InheritInteger (vd, "video-y");
166 wnd_cfg.width = vd->cfg->display.width;
167 wnd_cfg.height = vd->cfg->display.height;
169 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
171 container = sys->embed->handle.nsobject;
175 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
180 /* This will be released in Close(), on
181 * main thread, after we are done using it. */
182 sys->container = [container retain];
184 /* Get our main view*/
185 nsPool = [[NSAutoreleasePool alloc] init];
187 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
191 [sys->glView setVoutDisplay:vd];
193 /* We don't wait, that means that we'll have to be careful about releasing
195 * That's why we'll release on main thread in Close(). */
196 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
197 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
198 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(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
206 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
214 /* Initialize common OpenGL video display */
215 sys->gl.lock = OpenglLock;
216 sys->gl.unlock = OpenglUnlock;
217 sys->gl.swap = OpenglSwap;
218 sys->gl.getProcAddress = OurGetProcAddress;
220 const vlc_fourcc_t *subpicture_chromas;
221 video_format_t fmt = vd->fmt;
223 sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
231 vout_display_info_t info = vd->info;
232 info.has_pictures_invalid = false;
233 info.has_event_thread = true;
234 info.subpicture_chromas = subpicture_chromas;
236 /* Setup vout_display_t once everything is fine */
240 vd->prepare = PictureRender;
241 vd->display = PictureDisplay;
242 vd->control = Control;
245 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
255 void Close (vlc_object_t *this)
257 vout_display_t *vd = (vout_display_t *)this;
258 vout_display_sys_t *sys = vd->sys;
260 if ([[sys->glView window] level] != NSNormalWindowLevel)
261 [[sys->glView window] setLevel: NSNormalWindowLevel];
263 [sys->glView setVoutDisplay:nil];
265 var_Destroy (vd, "drawable-nsobject");
266 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
268 /* This will retain sys->glView */
269 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
271 /* release on main thread as explained in Open() */
272 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
273 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
275 [sys->glView release];
277 if (sys->gl.sys != NULL)
278 vout_display_opengl_Delete (sys->vgl);
281 vout_display_DeleteWindow (vd, sys->embed);
285 /*****************************************************************************
286 * vout display callbacks
287 *****************************************************************************/
289 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
291 vout_display_sys_t *sys = vd->sys;
294 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
299 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
302 vout_display_sys_t *sys = vd->sys;
304 vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
307 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
309 vout_display_sys_t *sys = vd->sys;
310 [sys->glView setVoutFlushing:YES];
311 vout_display_opengl_Display (sys->vgl, &vd->source);
312 [sys->glView setVoutFlushing:NO];
313 picture_Release (pic);
314 sys->has_first_frame = true;
317 subpicture_Delete(subpicture);
320 static int Control (vout_display_t *vd, int query, va_list ap)
322 vout_display_sys_t *sys = vd->sys;
326 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
328 const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
329 if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
334 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
336 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
337 unsigned state = va_arg (ap, unsigned);
338 [sys->glView performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:state] waitUntilDone:NO];
342 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
343 case VOUT_DISPLAY_CHANGE_ZOOM:
344 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
345 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
346 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
351 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
353 id o_window = [sys->glView window];
355 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
357 NSSize windowMinSize = [o_window minSize];
359 const vout_display_cfg_t *cfg;
360 const video_format_t *source;
361 bool is_forced = false;
363 if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP)
365 source = (const video_format_t *)va_arg (ap, const video_format_t *);
370 source = &vd->source;
371 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
372 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
373 is_forced = (bool)va_arg (ap, int);
376 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
377 && (cfg->display.width != vd->cfg->display.width
378 || cfg->display.height != vd->cfg->display.height)
379 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
382 /* for the case that the core wants to resize below minimum window size we correct the size here
383 to ensure a centered picture */
384 vout_display_cfg_t cfg_tmp = *cfg;
385 if (cfg_tmp.display.width < windowMinSize.width)
386 cfg_tmp.display.width = windowMinSize.width;
387 if (cfg_tmp.display.height < 70)
388 cfg_tmp.display.height = 70;
390 if (!config_GetInt(vd, "macosx-video-autoresize"))
392 NSRect bounds = [sys->glView bounds];
393 cfg_tmp.display.width = bounds.size.width;
394 cfg_tmp.display.height = bounds.size.height;
396 vout_display_place_t place;
397 vout_display_PlacePicture (&place, source, &cfg_tmp, false);
398 @synchronized (sys->glView) {
402 /* For resize, we call glViewport in reshape and not here.
403 This has the positive side effect that we avoid erratic sizing as we animate every resize. */
404 if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
406 // x / y are top left corner, but we need the lower left one
407 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
414 case VOUT_DISPLAY_HIDE_MOUSE:
416 [NSCursor setHiddenUntilMouseMoves: YES];
420 case VOUT_DISPLAY_GET_OPENGL:
422 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
427 case VOUT_DISPLAY_RESET_PICTURES:
430 msg_Err (vd, "Unknown request in Mac OS X vout display");
435 /*****************************************************************************
436 * vout opengl callbacks
437 *****************************************************************************/
438 static int OpenglLock (vlc_gl_t *gl)
440 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
441 NSOpenGLContext *context = [sys->glView openGLContext];
442 CGLError err = CGLLockContext ([context CGLContextObj]);
443 if (kCGLNoError == err)
445 [context makeCurrentContext];
451 static void OpenglUnlock (vlc_gl_t *gl)
453 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
454 CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
457 static void OpenglSwap (vlc_gl_t *gl)
459 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
460 [[sys->glView openGLContext] flushBuffer];
463 /*****************************************************************************
465 *****************************************************************************/
466 @implementation VLCOpenGLVideoView
468 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
471 + (void)getNewView:(NSValue *)value
473 id *ret = [value pointerValue];
474 *ret = [[self alloc] init];
478 * Gets called by the Open() method.
482 VLCAssertMainThread();
484 /* Warning - this may be called on non main thread */
486 NSOpenGLPixelFormatAttribute attribs[] =
488 NSOpenGLPFADoubleBuffer,
489 NSOpenGLPFAAccelerated,
490 NSOpenGLPFANoRecovery,
491 NSOpenGLPFAColorSize, 24,
492 NSOpenGLPFAAlphaSize, 8,
493 NSOpenGLPFADepthSize, 24,
498 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
503 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
509 /* Swap buffers only during the vertical retrace of the monitor.
510 http://developer.apple.com/documentation/GraphicsImaging/
511 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
512 GLint params[] = { 1 };
513 CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
515 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
520 * Gets called by the Open() method.
522 - (void)setFrameWithValue:(NSValue *)value
524 [self setFrame:[value rectValue]];
528 * Gets called by the Close and Open methods.
531 - (void)setVoutDisplay:(vout_display_t *)aVd
533 @synchronized(self) {
539 * Gets called when the vout will aquire the lock and flush.
542 - (void)setVoutFlushing:(BOOL)flushing
546 @synchronized(self) {
547 _hasPendingReshape = NO;
552 * Can -drawRect skip rendering?.
554 - (BOOL)canSkipRendering
556 VLCAssertMainThread();
558 @synchronized(self) {
559 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
560 return !_hasPendingReshape && hasFirstFrame;
566 * Local method that locks the gl context.
570 VLCAssertMainThread();
571 NSOpenGLContext *context = [self openGLContext];
572 CGLError err = CGLLockContext ([context CGLContextObj]);
573 if (err == kCGLNoError)
574 [context makeCurrentContext];
575 return err == kCGLNoError;
579 * Local method that unlocks the gl context.
583 VLCAssertMainThread();
584 CGLUnlockContext ([[self openGLContext] CGLContextObj]);
588 * Local method that force a rendering of a frame.
589 * This will get called if Cocoa forces us to redraw (via -drawRect).
593 VLCAssertMainThread();
595 // We may have taken some times to take the opengl Lock.
596 // Check here to see if we can just skip the frame as well.
597 if ([self canSkipRendering])
601 @synchronized(self) { // vd can be accessed from multiple threads
602 hasFirstFrame = vd && vd->sys->has_first_frame;
606 // This will lock gl.
607 vout_display_opengl_Display (vd->sys->vgl, &vd->source);
610 glClear (GL_COLOR_BUFFER_BIT);
614 * Method called by Cocoa when the view is resized.
618 VLCAssertMainThread();
620 NSRect bounds = [self bounds];
621 vout_display_place_t place;
623 @synchronized(self) {
625 vout_display_cfg_t cfg_tmp = *(vd->cfg);
626 cfg_tmp.display.width = bounds.size.width;
627 cfg_tmp.display.height = bounds.size.height;
629 vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
630 vd->sys->place = place;
631 vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
636 // x / y are top left corner, but we need the lower left one
637 glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
639 @synchronized(self) {
640 // This may be cleared before -drawRect is being called,
641 // in this case we'll skip the rendering.
642 // This will save us for rendering two frames (or more) for nothing
643 // (one by the vout, one (or more) by drawRect)
644 _hasPendingReshape = YES;
654 * Method called by Cocoa when the view is resized or the location has changed.
655 * We just need to make sure we are locking here.
659 VLCAssertMainThread();
660 BOOL success = [self lockgl];
670 * Method called by Cocoa to force redraw.
672 - (void)drawRect:(NSRect) rect
674 VLCAssertMainThread();
676 if ([self canSkipRendering])
679 BOOL success = [self lockgl];
690 NSWindow *window = [self window];
692 // Remove flashes with splitter view.
693 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
694 [window disableScreenUpdatesUntilFlush];
704 - (void)setWindowLevel:(NSNumber*)state
706 if ([state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE)
707 [[self window] setLevel: NSStatusWindowLevel];
709 [[self window] setLevel: NSNormalWindowLevel];
713 #pragma mark Mouse handling
715 - (void)mouseDown:(NSEvent *)o_event
717 if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] & NSControlKeyMask))
719 if ([o_event clickCount] <= 1)
720 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
723 [super mouseDown:o_event];
726 - (void)otherMouseDown:(NSEvent *)o_event
728 vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
730 [super otherMouseDown: o_event];
733 - (void)mouseUp:(NSEvent *)o_event
735 if ([o_event type] == NSLeftMouseUp)
736 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
738 [super mouseUp: o_event];
741 - (void)otherMouseUp:(NSEvent *)o_event
743 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
745 [super otherMouseUp: o_event];
748 - (void)mouseMoved:(NSEvent *)o_event
754 s_rect = [self bounds];
755 ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
756 b_inside = [self mouse: ml inRect: s_rect];
764 vout_display_place_t place = vd->sys->place;
766 if (place.width > 0 && place.height > 0)
768 const int x = vd->source.i_x_offset +
769 (int64_t)(ml.x - place.x) * vd->source.i_visible_width / place.width;
770 const int y = vd->source.i_y_offset +
771 (int64_t)((int)s_rect.size.height - (int)ml.y - place.y) * vd->source.i_visible_height / place.height;
773 vout_display_SendEventMouseMoved (vd, x, y);
779 [super mouseMoved: o_event];
782 - (void)mouseDragged:(NSEvent *)o_event
784 [self mouseMoved: o_event];
785 [super mouseDragged: o_event];
788 - (void)otherMouseDragged:(NSEvent *)o_event
790 [self mouseMoved: o_event];
791 [super otherMouseDragged: o_event];
794 - (void)rightMouseDragged:(NSEvent *)o_event
796 [self mouseMoved: o_event];
797 [super rightMouseDragged: o_event];
800 - (BOOL)acceptsFirstResponder
805 - (BOOL)mouseDownCanMoveWindow