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>
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 @interface NSWindow (VLCCustomCode)
55 * Forward declarations
57 static int Open(vlc_object_t *);
58 static void Close(vlc_object_t *);
60 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
61 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
62 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
63 static int Control (vout_display_t *vd, int query, va_list ap);
65 static int OpenglLock(vlc_gl_t *gl);
66 static void OpenglUnlock(vlc_gl_t *gl);
67 static void OpenglSwap(vlc_gl_t *gl);
73 /* Will be loaded even without interface module. see voutgl.m */
74 set_shortname("Mac OS X")
75 set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
76 set_category(CAT_VIDEO)
77 set_subcategory(SUBCAT_VIDEO_VOUT )
78 set_capability("vout display", 300)
79 set_callbacks(Open, Close)
81 add_shortcut("macosx", "vout_macosx")
85 * Obj-C protocol declaration that drawable-nsobject should follow
87 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
88 - (void)addVoutSubview:(NSView *)view;
89 - (void)removeVoutSubview:(NSView *)view;
92 @interface VLCOpenGLVideoView : NSOpenGLView
95 BOOL _hasPendingReshape;
97 - (void)setVoutDisplay:(vout_display_t *)vd;
98 - (vout_display_t *)voutDisplay;
99 - (void)setVoutFlushing:(BOOL)flushing;
103 struct vout_display_sys_t
105 VLCOpenGLVideoView *glView;
106 id<VLCOpenGLVideoViewEmbedding> container;
108 vout_window_t *embed;
110 vout_display_opengl_t *vgl;
112 picture_pool_t *pool;
114 bool has_first_frame;
117 static int Open(vlc_object_t *this)
119 vout_display_t *vd = (vout_display_t *)this;
120 vout_display_sys_t *sys = calloc(1, sizeof(*sys));
121 NSAutoreleasePool *nsPool = nil;
126 if( !CGDisplayUsesOpenGLAcceleration( kCGDirectMainDisplay ) )
128 msg_Err( this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results" );
129 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.") );
132 msg_Dbg( this, "Quartz Extreme acceleration is active" );
139 /* Get the drawable object */
140 id container = var_CreateGetAddress(vd, "drawable-nsobject");
143 vout_display_DeleteWindow(vd, NULL);
147 vout_window_cfg_t wnd_cfg;
149 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
150 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
151 wnd_cfg.x = var_InheritInteger (vd, "video-x");
152 wnd_cfg.y = var_InheritInteger (vd, "video-y");
153 wnd_cfg.width = vd->cfg->display.width;
154 wnd_cfg.height = vd->cfg->display.height;
156 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
158 container = sys->embed->handle.nsobject;
162 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
167 /* This will be released in Close(), on
168 * main thread, after we are done using it. */
169 sys->container = [container retain];
171 /* Get our main view*/
172 nsPool = [[NSAutoreleasePool alloc] init];
174 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
178 [sys->glView setVoutDisplay:vd];
180 /* We don't wait, that means that we'll have to be careful about releasing
182 * That's why we'll release on main thread in Close(). */
183 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
184 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
185 else if ([container isKindOfClass:[NSView class]])
187 NSView *parentView = container;
188 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
189 [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
193 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
201 /* Initialize common OpenGL video display */
202 sys->gl.lock = OpenglLock;
203 sys->gl.unlock = OpenglUnlock;
204 sys->gl.swap = OpenglSwap;
205 sys->gl.getProcAddress = NULL;
207 const vlc_fourcc_t *subpicture_chromas;
208 video_format_t fmt = vd->fmt;
210 sys->vgl = vout_display_opengl_New(&vd->fmt, &subpicture_chromas, &sys->gl);
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;
223 /* Setup vout_display_t once everything is fine */
227 vd->prepare = PictureRender;
228 vd->display = PictureDisplay;
229 vd->control = Control;
232 vout_display_SendEventFullscreen (vd, false);
233 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
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 if ([[sys->glView window] level] != NSNormalWindowLevel)
249 [[sys->glView window] setLevel: NSNormalWindowLevel];
251 [sys->glView setVoutDisplay:nil];
253 var_Destroy(vd, "drawable-nsobject");
254 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
256 /* This will retain sys->glView */
257 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
259 /* release on main thread as explained in Open() */
260 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
261 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
263 [sys->glView release];
265 if (sys->gl.sys != NULL)
266 vout_display_opengl_Delete(sys->vgl);
269 vout_display_DeleteWindow(vd, sys->embed);
273 /*****************************************************************************
274 * vout display callbacks
275 *****************************************************************************/
277 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
279 vout_display_sys_t *sys = vd->sys;
282 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
287 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
290 vout_display_sys_t *sys = vd->sys;
292 vout_display_opengl_Prepare( sys->vgl, pic, subpicture );
295 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
297 vout_display_sys_t *sys = vd->sys;
298 [sys->glView setVoutFlushing:YES];
299 vout_display_opengl_Display(sys->vgl, &vd->source );
300 [sys->glView setVoutFlushing:NO];
301 picture_Release (pic);
302 sys->has_first_frame = true;
305 subpicture_Delete(subpicture);
308 static int Control (vout_display_t *vd, int query, va_list ap)
310 vout_display_sys_t *sys = vd->sys;
314 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
316 const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
317 if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
322 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
324 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
325 unsigned state = va_arg (ap, unsigned);
326 [sys->glView performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:state] waitUntilDone:NO];
330 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
331 case VOUT_DISPLAY_CHANGE_ZOOM:
332 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
333 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
334 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
339 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
341 id o_window = [sys->glView window];
343 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
345 NSSize windowMinSize = [o_window minSize];
347 const vout_display_cfg_t *cfg;
348 const video_format_t *source;
349 bool is_forced = false;
351 vout_display_place_t place;
353 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 *);
360 source = &vd->source;
361 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
362 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
363 is_forced = (bool)va_arg (ap, int);
366 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
367 && (cfg->display.width != vd->cfg->display.width
368 || cfg->display.height != vd->cfg->display.height)
369 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
372 /* for the case that the core wants to resize below minimum window size we correct the size here
373 to ensure a centered picture */
374 vout_display_cfg_t cfg_tmp = *cfg;
375 if (cfg_tmp.display.width < windowMinSize.width)
376 cfg_tmp.display.width = windowMinSize.width;
377 if (cfg_tmp.display.height < 70)
378 cfg_tmp.display.height = 70;
380 if (!config_GetInt(vd, "macosx-video-autoresize"))
382 NSRect bounds = [sys->glView bounds];
383 cfg_tmp.display.width = bounds.size.width;
384 cfg_tmp.display.height = bounds.size.height;
387 vout_display_PlacePicture (&place, source, &cfg_tmp, false);
389 /* For resize, we call glViewport in reshape and not here.
390 This has the positive side effect that we avoid erratic sizing as we animate every resize. */
391 if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
393 // x / y are top left corner, but we need the lower left one
394 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
401 case VOUT_DISPLAY_HIDE_MOUSE:
403 [NSCursor setHiddenUntilMouseMoves: YES];
407 case VOUT_DISPLAY_GET_OPENGL:
409 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
414 case VOUT_DISPLAY_RESET_PICTURES:
417 msg_Err (vd, "Unknown request in Mac OS X vout display");
422 /*****************************************************************************
423 * vout opengl callbacks
424 *****************************************************************************/
425 static int OpenglLock(vlc_gl_t *gl)
427 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
428 NSOpenGLContext *context = [sys->glView openGLContext];
429 CGLError err = CGLLockContext([context CGLContextObj]);
430 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 /* Swap buffers only during the vertical retrace of the monitor.
497 http://developer.apple.com/documentation/GraphicsImaging/
498 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
499 GLint params[] = { 1 };
500 CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
502 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
507 * Gets called by the Open() method.
509 - (void)setFrameWithValue:(NSValue *)value
511 [self setFrame:[value rectValue]];
515 * Gets called by the Close and Open methods.
518 - (void)setVoutDisplay:(vout_display_t *)aVd
520 @synchronized(self) {
525 - (vout_display_t *)voutDisplay
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 );
602 glClear(GL_COLOR_BUFFER_BIT);
606 * Method called by Cocoa when the view is resized.
610 VLCAssertMainThread();
612 NSRect bounds = [self bounds];
613 vout_display_place_t place;
615 @synchronized(self) {
617 vout_display_cfg_t cfg_tmp = *(vd->cfg);
618 cfg_tmp.display.width = bounds.size.width;
619 cfg_tmp.display.height = bounds.size.height;
621 vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
622 vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
627 // x / y are top left corner, but we need the lower left one
628 glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
630 @synchronized(self) {
631 // This may be cleared before -drawRect is being called,
632 // in this case we'll skip the rendering.
633 // This will save us for rendering two frames (or more) for nothing
634 // (one by the vout, one (or more) by drawRect)
635 _hasPendingReshape = YES;
645 * Method called by Cocoa when the view is resized or the location has changed.
646 * We just need to make sure we are locking here.
650 VLCAssertMainThread();
651 BOOL success = [self lockgl];
661 * Method called by Cocoa to force redraw.
663 - (void)drawRect:(NSRect) rect
665 VLCAssertMainThread();
667 if ([self canSkipRendering])
670 BOOL success = [self lockgl];
681 NSWindow *window = [self window];
683 // Remove flashes with splitter view.
684 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
685 [window disableScreenUpdatesUntilFlush];
690 - (BOOL)mouseDownCanMoveWindow
700 - (void)setWindowLevel:(NSNumber*)state
702 if( [state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE )
703 [[self window] setLevel: NSStatusWindowLevel];
705 [[self window] setLevel: NSNormalWindowLevel];