1 /*****************************************************************************
2 * voutgl.m: MacOS X OpenGL provider
3 *****************************************************************************
4 * Copyright (C) 2001-2011 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>
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.
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.
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 *****************************************************************************/
32 /*****************************************************************************
34 *****************************************************************************/
36 #import <Cocoa/Cocoa.h>
37 #import <OpenGL/OpenGL.h>
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>
50 #ifndef MAC_OS_X_VERSION_10_7
52 NSApplicationPresentationFullScreen = (1 << 10),
53 NSApplicationPresentationAutoHideToolbar = (1 << 11)
58 * Forward declarations
60 static int Open(vlc_object_t *);
61 static void Close(vlc_object_t *);
63 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
64 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
65 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
66 static int Control (vout_display_t *vd, int query, va_list ap);
68 static int OpenglLock(vlc_gl_t *gl);
69 static void OpenglUnlock(vlc_gl_t *gl);
70 static void OpenglSwap(vlc_gl_t *gl);
76 /* Will be loaded even without interface module. see voutgl.m */
77 set_shortname("Mac OS X")
78 set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
79 set_category(CAT_VIDEO)
80 set_subcategory(SUBCAT_VIDEO_VOUT )
81 set_capability("vout display", 300)
82 set_callbacks(Open, Close)
84 add_shortcut("macosx", "vout_macosx")
88 * Obj-C protocol declaration that drawable-nsobject should follow
90 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
91 - (void)addVoutSubview:(NSView *)view;
92 - (void)removeVoutSubview:(NSView *)view;
95 @interface VLCOpenGLVideoView : NSOpenGLView
98 BOOL _hasPendingReshape;
100 - (void)setVoutDisplay:(vout_display_t *)vd;
101 - (void)setVoutFlushing:(BOOL)flushing;
105 struct vout_display_sys_t
107 VLCOpenGLVideoView *glView;
108 id<VLCOpenGLVideoViewEmbedding> container;
110 vout_window_t *embed;
112 vout_display_opengl_t *vgl;
114 picture_pool_t *pool;
116 bool has_first_frame;
119 static int Open(vlc_object_t *this)
121 vout_display_t *vd = (vout_display_t *)this;
122 vout_display_sys_t *sys = calloc(1, sizeof(*sys));
123 NSAutoreleasePool *nsPool = nil;
128 if( !CGDisplayUsesOpenGLAcceleration( kCGDirectMainDisplay ) )
130 msg_Err( this, "no OpenGL hardware acceleration found, video output will fail" );
131 dialog_Fatal( this, _("Video output is not supported"), _("Your Mac lacks Quartz Extreme acceleration, which is required for video output.") );
135 msg_Dbg( this, "Quartz Extreme acceleration is active" );
142 /* Get the drawable object */
143 id container = var_CreateGetAddress(vd, "drawable-nsobject");
146 vout_display_DeleteWindow(vd, NULL);
150 vout_window_cfg_t wnd_cfg;
152 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
153 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
154 wnd_cfg.x = var_InheritInteger (vd, "video-x");
155 wnd_cfg.y = var_InheritInteger (vd, "video-y");
156 wnd_cfg.width = vd->cfg->display.width;
157 wnd_cfg.height = vd->cfg->display.height;
159 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
161 container = sys->embed->handle.nsobject;
165 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
170 /* This will be released in Close(), on
171 * main thread, after we are done using it. */
172 sys->container = [container retain];
174 /* Get our main view*/
175 nsPool = [[NSAutoreleasePool alloc] init];
177 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
181 [sys->glView setVoutDisplay:vd];
183 /* We don't wait, that means that we'll have to be careful about releasing
185 * That's why we'll release on main thread in Close(). */
186 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
187 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
188 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(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
196 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
204 /* Initialize common OpenGL video display */
205 sys->gl.lock = OpenglLock;
206 sys->gl.unlock = OpenglUnlock;
207 sys->gl.swap = OpenglSwap;
208 sys->gl.getProcAddress = NULL;
211 sys->vgl = vout_display_opengl_New(&vd->fmt, NULL, &sys->gl);
219 vout_display_info_t info = vd->info;
220 info.has_pictures_invalid = false;
222 /* Setup vout_display_t once everything is fine */
226 vd->prepare = PictureRender;
227 vd->display = PictureDisplay;
228 vd->control = Control;
231 vout_display_SendEventFullscreen (vd, false);
232 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
242 void Close(vlc_object_t *this)
244 vout_display_t *vd = (vout_display_t *)this;
245 vout_display_sys_t *sys = vd->sys;
247 [sys->glView setVoutDisplay:nil];
249 var_Destroy(vd, "drawable-nsobject");
250 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 [sys->glView release];
261 if (sys->gl.sys != NULL)
262 vout_display_opengl_Delete(sys->vgl);
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->fmt );
296 [sys->glView setVoutFlushing:NO];
297 picture_Release (pic);
298 sys->has_first_frame = true;
302 static int Control (vout_display_t *vd, int query, va_list ap)
304 vout_display_sys_t *sys = vd->sys;
308 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
313 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
315 unsigned state = va_arg (ap, unsigned);
316 if( (state & VOUT_WINDOW_STATE_ABOVE) != 0)
317 [[sys->glView window] setLevel: NSStatusWindowLevel];
319 [[sys->glView window] setLevel: NSNormalWindowLevel];
322 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
324 [[sys->glView window] performSelectorOnMainThread:@selector(zoom:) withObject: nil waitUntilDone:NO];
327 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
328 case VOUT_DISPLAY_CHANGE_ZOOM:
329 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
330 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
333 NSPoint topleftscreen;
335 const vout_display_cfg_t *cfg;
337 id o_window = [sys->glView window];
339 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
340 NSRect windowFrame = [o_window frame];
341 NSRect glViewFrame = [sys->glView frame];
342 NSSize windowMinSize = [o_window minSize];
345 topleftbase.y = windowFrame.size.height;
346 topleftscreen = [o_window convertBaseToScreen: topleftbase];
347 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
348 int i_width = cfg->display.width;
349 int i_height = cfg->display.height;
351 /* Calculate the window's new size, if it is larger than our minimal size */
352 if (i_width < windowMinSize.width)
353 i_width = windowMinSize.width;
354 if (i_height < windowMinSize.height)
355 i_height = windowMinSize.height;
357 if( i_height != glViewFrame.size.height || i_width != glViewFrame.size.width )
359 new_frame.size.width = windowFrame.size.width - glViewFrame.size.width + i_width;
360 new_frame.size.height = windowFrame.size.height - glViewFrame.size.height + i_height;
362 new_frame.origin.x = topleftscreen.x;
363 new_frame.origin.y = topleftscreen.y - new_frame.size.height;
365 [sys->glView performSelectorOnMainThread:@selector(setWindowFrameWithValue:) withObject:[NSValue valueWithRect:new_frame] waitUntilDone:NO];
370 case VOUT_DISPLAY_HIDE_MOUSE:
372 [NSCursor setHiddenUntilMouseMoves: YES];
376 case VOUT_DISPLAY_GET_OPENGL:
378 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
383 case VOUT_DISPLAY_RESET_PICTURES:
386 msg_Err (vd, "Unknown request in Mac OS X vout display");
391 /*****************************************************************************
392 * vout opengl callbacks
393 *****************************************************************************/
394 static int OpenglLock(vlc_gl_t *gl)
396 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
397 NSOpenGLContext *context = [sys->glView openGLContext];
398 CGLError err = CGLLockContext([context CGLContextObj]);
399 if (kCGLNoError == err)
401 [context makeCurrentContext];
407 static void OpenglUnlock(vlc_gl_t *gl)
409 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
410 CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
413 static void OpenglSwap(vlc_gl_t *gl)
415 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
416 [[sys->glView openGLContext] flushBuffer];
419 /*****************************************************************************
421 *****************************************************************************/
422 @implementation VLCOpenGLVideoView
424 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
426 + (void)getNewView:(NSValue *)value
428 id *ret = [value pointerValue];
429 *ret = [[self alloc] init];
433 * Gets called by the Open() method.
437 VLCAssertMainThread();
439 /* Warning - this may be called on non main thread */
441 NSOpenGLPixelFormatAttribute attribs[] =
443 NSOpenGLPFADoubleBuffer,
444 NSOpenGLPFAAccelerated,
445 NSOpenGLPFANoRecovery,
446 NSOpenGLPFAColorSize, 24,
447 NSOpenGLPFAAlphaSize, 8,
448 NSOpenGLPFADepthSize, 24,
453 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
458 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
464 /* Swap buffers only during the vertical retrace of the monitor.
465 http://developer.apple.com/documentation/GraphicsImaging/
466 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
467 GLint params[] = { 1 };
468 CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
470 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
475 * Gets called by the Open() method.
477 - (void)setFrameWithValue:(NSValue *)value
479 [self setFrame:[value rectValue]];
483 * Gets called by Control() to make sure that we're performing on the main thread
485 - (void)setWindowFrameWithValue:(NSValue *)value
487 if (!(NSAppKitVersionNumber >= 1115.2 && [NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen))
489 NSRect frame = [value rectValue];
490 if (frame.origin.x <= 0.0 && frame.origin.y <= 0.0)
491 [[self window] center];
492 [[self window] setFrame:frame display:YES animate: YES];
497 * Gets called by the Close and Open methods.
500 - (void)setVoutDisplay:(vout_display_t *)aVd
502 @synchronized(self) {
509 * Gets called when the vout will aquire the lock and flush.
512 - (void)setVoutFlushing:(BOOL)flushing
516 @synchronized(self) {
517 _hasPendingReshape = NO;
522 * Can -drawRect skip rendering?.
524 - (BOOL)canSkipRendering
526 VLCAssertMainThread();
528 @synchronized(self) {
529 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
530 return !_hasPendingReshape && hasFirstFrame;
536 * Local method that locks the gl context.
540 VLCAssertMainThread();
541 NSOpenGLContext *context = [self openGLContext];
542 CGLError err = CGLLockContext([context CGLContextObj]);
543 if (err == kCGLNoError)
544 [context makeCurrentContext];
545 return err == kCGLNoError;
549 * Local method that unlocks the gl context.
553 VLCAssertMainThread();
554 CGLUnlockContext([[self openGLContext] CGLContextObj]);
558 * Local method that force a rendering of a frame.
559 * This will get called if Cocoa forces us to redraw (via -drawRect).
563 VLCAssertMainThread();
565 // We may have taken some times to take the opengl Lock.
566 // Check here to see if we can just skip the frame as well.
567 if ([self canSkipRendering])
571 @synchronized(self) { // vd can be accessed from multiple threads
572 hasFirstFrame = vd && vd->sys->has_first_frame;
576 // This will lock gl.
577 vout_display_opengl_Display( vd->sys->vgl, &vd->source );
580 glClear(GL_COLOR_BUFFER_BIT);
584 * Method called by Cocoa when the view is resized.
588 VLCAssertMainThread();
590 NSRect bounds = [self bounds];
592 CGFloat height = bounds.size.height;
593 CGFloat width = bounds.size.width;
595 GLint x = width, y = height;
597 @synchronized(self) {
599 CGFloat videoHeight = vd->source.i_visible_height;
600 CGFloat videoWidth = vd->source.i_visible_width;
602 GLint sarNum = vd->source.i_sar_num;
603 GLint sarDen = vd->source.i_sar_den;
605 if (height * videoWidth * sarNum < width * videoHeight * sarDen)
607 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
613 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
619 glViewport((width - x) / 2, (height - y) / 2, x, y);
621 @synchronized(self) {
622 // This may be cleared before -drawRect is being called,
623 // in this case we'll skip the rendering.
624 // This will save us for rendering two frames (or more) for nothing
625 // (one by the vout, one (or more) by drawRect)
626 _hasPendingReshape = YES;
636 * Method called by Cocoa when the view is resized or the location has changed.
637 * We just need to make sure we are locking here.
641 VLCAssertMainThread();
642 BOOL success = [self lockgl];
652 * Method called by Cocoa to force redraw.
654 - (void)drawRect:(NSRect) rect
656 VLCAssertMainThread();
658 if ([self canSkipRendering])
661 BOOL success = [self lockgl];
672 NSWindow *window = [self window];
674 // Remove flashes with splitter view.
675 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
676 [window disableScreenUpdatesUntilFlush];
681 - (BOOL)mouseDownCanMoveWindow