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, video output will fail" );
129 dialog_Fatal( this, _("Video output is not supported"), _("Your Mac lacks Quartz Extreme acceleration, which is required for video output.") );
133 msg_Dbg( this, "Quartz Extreme acceleration is active" );
140 /* Get the drawable object */
141 id container = var_CreateGetAddress(vd, "drawable-nsobject");
144 vout_display_DeleteWindow(vd, NULL);
148 vout_window_cfg_t wnd_cfg;
150 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
151 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
152 wnd_cfg.x = var_InheritInteger (vd, "video-x");
153 wnd_cfg.y = var_InheritInteger (vd, "video-y");
154 wnd_cfg.width = vd->cfg->display.width;
155 wnd_cfg.height = vd->cfg->display.height;
157 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
159 container = sys->embed->handle.nsobject;
163 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
168 /* This will be released in Close(), on
169 * main thread, after we are done using it. */
170 sys->container = [container retain];
172 /* Get our main view*/
173 nsPool = [[NSAutoreleasePool alloc] init];
175 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
179 [sys->glView setVoutDisplay:vd];
181 /* We don't wait, that means that we'll have to be careful about releasing
183 * That's why we'll release on main thread in Close(). */
184 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
185 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
186 else if ([container isKindOfClass:[NSView class]])
188 NSView *parentView = container;
189 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
190 [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] 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 = NULL;
208 const vlc_fourcc_t *subpicture_chromas;
209 video_format_t fmt = vd->fmt;
211 sys->vgl = vout_display_opengl_New(&vd->fmt, &subpicture_chromas, &sys->gl);
219 vout_display_info_t info = vd->info;
220 info.has_pictures_invalid = false;
221 info.has_event_thread = true;
222 info.subpicture_chromas = subpicture_chromas;
224 /* Setup vout_display_t once everything is fine */
228 vd->prepare = PictureRender;
229 vd->display = PictureDisplay;
230 vd->control = Control;
233 vout_display_SendEventFullscreen (vd, false);
234 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
244 void Close(vlc_object_t *this)
246 vout_display_t *vd = (vout_display_t *)this;
247 vout_display_sys_t *sys = vd->sys;
249 if ([[sys->glView window] level] != NSNormalWindowLevel)
250 [[sys->glView window] setLevel: NSNormalWindowLevel];
252 [sys->glView setVoutDisplay:nil];
254 var_Destroy(vd, "drawable-nsobject");
255 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
257 /* This will retain sys->glView */
258 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
260 /* release on main thread as explained in Open() */
261 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
262 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
264 [sys->glView release];
266 if (sys->gl.sys != NULL)
267 vout_display_opengl_Delete(sys->vgl);
270 vout_display_DeleteWindow(vd, sys->embed);
274 /*****************************************************************************
275 * vout display callbacks
276 *****************************************************************************/
278 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
280 vout_display_sys_t *sys = vd->sys;
283 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
288 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
291 vout_display_sys_t *sys = vd->sys;
293 vout_display_opengl_Prepare( sys->vgl, pic, subpicture );
296 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
298 vout_display_sys_t *sys = vd->sys;
299 [sys->glView setVoutFlushing:YES];
300 vout_display_opengl_Display(sys->vgl, &vd->fmt );
301 [sys->glView setVoutFlushing:NO];
302 picture_Release (pic);
303 sys->has_first_frame = true;
306 subpicture_Delete(subpicture);
309 static int Control (vout_display_t *vd, int query, va_list ap)
311 vout_display_sys_t *sys = vd->sys;
315 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
317 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
318 [[sys->glView window] performSelectorOnMainThread:@selector(fullscreen:) withObject: nil waitUntilDone:NO];
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 NSPoint topleftscreen;
343 const vout_display_cfg_t *cfg;
347 id o_window = [sys->glView window];
349 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
350 NSRect windowFrame = [o_window frame];
351 NSRect glViewFrame = [sys->glView frame];
352 NSRect screenFrame = [[o_window screen] visibleFrame];
353 NSSize windowMinSize = [o_window minSize];
356 topleftbase.y = windowFrame.size.height;
357 topleftscreen = [o_window convertBaseToScreen: topleftbase];
359 if (query == VOUT_DISPLAY_CHANGE_SOURCE_CROP || query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT)
361 const video_format_t *source;
363 source = (const video_format_t *)va_arg (ap, const video_format_t *);
366 vout_display_place_t place;
367 vout_display_PlacePicture (&place, source, cfg, false);
369 vd->fmt.i_width = vd->source.i_width * place.width / vd->source.i_visible_width;
370 vd->fmt.i_height = vd->source.i_height * place.height / vd->source.i_visible_height;
371 vd->fmt.i_visible_width = vd->source.i_visible_width;
372 vd->fmt.i_visible_height = vd->source.i_visible_height;
373 vd->fmt.i_x_offset = vd->source.i_x_offset * place.width / vd->source.i_visible_width;
374 vd->fmt.i_y_offset = vd->source.i_y_offset * place.height / vd->source.i_visible_height;
376 i_width = place.width;
377 i_height = place.height;
379 if (vd->fmt.i_x_offset > 0)
381 if (vd->source.i_width / vd->fmt.i_x_offset <= 4)
383 /* hack and special case for the "Default" state
384 * The 'Default' state tries to set the dimensions with a huge x offset and a weird
385 * width / height ratio, which definitely isn't the default for the played media.
386 * That's why, we enforce the media's actual dimensions here.
387 * The quotient of 4 is a stochastic value, which isn't reached by any other crop state. */
388 vd->fmt.i_width = vd->source.i_width;
389 vd->fmt.i_height = vd->source.i_height;
390 vd->fmt.i_visible_width = vd->source.i_width;
391 vd->fmt.i_visible_height = vd->source.i_height;
392 vd->fmt.i_x_offset = 0;
393 vd->fmt.i_y_offset = 0;
394 i_width = vd->source.i_width;
395 i_height = vd->source.i_height;
399 glViewport (0, 0, i_width, i_height);
403 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
404 i_width = cfg->display.width;
405 i_height = cfg->display.height;
408 /* Calculate the window's new size, if it is larger than our minimal size */
409 if (i_width < windowMinSize.width)
410 i_width = windowMinSize.width;
411 if (i_height < windowMinSize.height)
412 i_height = windowMinSize.height;
414 // is needed in the case we do not an actual resize
415 [sys->glView performSelectorOnMainThread:@selector(reshapeView:) withObject:nil waitUntilDone:NO];
417 if (config_GetInt (vd, "macosx-video-autoresize") && query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE &&
418 (i_height != glViewFrame.size.height || i_width != glViewFrame.size.width))
420 new_frame.size.width = windowFrame.size.width - glViewFrame.size.width + i_width;
421 new_frame.size.height = windowFrame.size.height - glViewFrame.size.height + i_height;
423 new_frame.origin.x = topleftscreen.x;
424 new_frame.origin.y = topleftscreen.y - new_frame.size.height;
426 /* make sure the window doesn't exceed the screen size the window is on */
427 if( new_frame.size.width > screenFrame.size.width )
429 new_frame.size.width = screenFrame.size.width;
430 new_frame.origin.x = screenFrame.origin.x;
432 if( new_frame.size.height > screenFrame.size.height )
434 new_frame.size.height = screenFrame.size.height;
435 new_frame.origin.y = screenFrame.origin.y;
437 if( new_frame.origin.y < screenFrame.origin.y )
438 new_frame.origin.y = screenFrame.origin.y;
440 [sys->glView performSelectorOnMainThread:@selector(setWindowFrameWithValue:) withObject:[NSValue valueWithRect:new_frame] waitUntilDone:NO];
446 case VOUT_DISPLAY_HIDE_MOUSE:
448 [NSCursor setHiddenUntilMouseMoves: YES];
452 case VOUT_DISPLAY_GET_OPENGL:
454 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
459 case VOUT_DISPLAY_RESET_PICTURES:
462 msg_Err (vd, "Unknown request in Mac OS X vout display");
467 /*****************************************************************************
468 * vout opengl callbacks
469 *****************************************************************************/
470 static int OpenglLock(vlc_gl_t *gl)
472 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
473 NSOpenGLContext *context = [sys->glView openGLContext];
474 CGLError err = CGLLockContext([context CGLContextObj]);
475 if (kCGLNoError == err)
477 [context makeCurrentContext];
483 static void OpenglUnlock(vlc_gl_t *gl)
485 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
486 CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
489 static void OpenglSwap(vlc_gl_t *gl)
491 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
492 [[sys->glView openGLContext] flushBuffer];
495 /*****************************************************************************
497 *****************************************************************************/
498 @implementation VLCOpenGLVideoView
500 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
502 + (void)getNewView:(NSValue *)value
504 id *ret = [value pointerValue];
505 *ret = [[self alloc] init];
509 * Gets called by the Open() method.
513 VLCAssertMainThread();
515 /* Warning - this may be called on non main thread */
517 NSOpenGLPixelFormatAttribute attribs[] =
519 NSOpenGLPFADoubleBuffer,
520 NSOpenGLPFAAccelerated,
521 NSOpenGLPFANoRecovery,
522 NSOpenGLPFAColorSize, 24,
523 NSOpenGLPFAAlphaSize, 8,
524 NSOpenGLPFADepthSize, 24,
529 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
534 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
540 /* Swap buffers only during the vertical retrace of the monitor.
541 http://developer.apple.com/documentation/GraphicsImaging/
542 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
543 GLint params[] = { 1 };
544 CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
546 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
551 * Gets called by the Open() method.
553 - (void)setFrameWithValue:(NSValue *)value
555 [self setFrame:[value rectValue]];
559 * Gets called by Control() to make sure that we're performing on the main thread
561 - (void)setWindowFrameWithValue:(NSValue *)value
563 if (![[self window] isFullscreen])
565 NSRect frame = [value rectValue];
566 [[self window] setFrame:frame display:YES animate: YES];
571 * Gets called by the Close and Open methods.
574 - (void)setVoutDisplay:(vout_display_t *)aVd
576 @synchronized(self) {
581 - (vout_display_t *)voutDisplay
587 * Gets called when the vout will aquire the lock and flush.
590 - (void)setVoutFlushing:(BOOL)flushing
594 @synchronized(self) {
595 _hasPendingReshape = NO;
600 * Can -drawRect skip rendering?.
602 - (BOOL)canSkipRendering
604 VLCAssertMainThread();
606 @synchronized(self) {
607 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
608 return !_hasPendingReshape && hasFirstFrame;
614 * Local method that locks the gl context.
618 VLCAssertMainThread();
619 NSOpenGLContext *context = [self openGLContext];
620 CGLError err = CGLLockContext([context CGLContextObj]);
621 if (err == kCGLNoError)
622 [context makeCurrentContext];
623 return err == kCGLNoError;
627 * Local method that unlocks the gl context.
631 VLCAssertMainThread();
632 CGLUnlockContext([[self openGLContext] CGLContextObj]);
636 * Local method that force a rendering of a frame.
637 * This will get called if Cocoa forces us to redraw (via -drawRect).
641 VLCAssertMainThread();
643 // We may have taken some times to take the opengl Lock.
644 // Check here to see if we can just skip the frame as well.
645 if ([self canSkipRendering])
649 @synchronized(self) { // vd can be accessed from multiple threads
650 hasFirstFrame = vd && vd->sys->has_first_frame;
654 // This will lock gl.
655 vout_display_opengl_Display( vd->sys->vgl, &vd->source );
658 glClear(GL_COLOR_BUFFER_BIT);
661 - (void)reshapeView:(id)sender
667 * Method called by Cocoa when the view is resized.
671 VLCAssertMainThread();
673 NSRect bounds = [self bounds];
675 CGFloat height, width;
676 if( !vd || ( vd && vd->cfg->is_display_filled ))
678 height = bounds.size.height;
679 width = bounds.size.width;
683 height = vd->source.i_visible_height;
684 width = vd->source.i_visible_width;
687 GLint x = width, y = height;
689 @synchronized(self) {
691 CGFloat videoHeight = vd->source.i_visible_height;
692 CGFloat videoWidth = vd->source.i_visible_width;
694 GLint sarNum = vd->source.i_sar_num;
695 GLint sarDen = vd->source.i_sar_den;
697 if (height * videoWidth * sarNum < width * videoHeight * sarDen)
699 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
705 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
711 glViewport((bounds.size.width - x) / 2, (bounds.size.height - y) / 2, x, y);
713 @synchronized(self) {
714 // This may be cleared before -drawRect is being called,
715 // in this case we'll skip the rendering.
716 // This will save us for rendering two frames (or more) for nothing
717 // (one by the vout, one (or more) by drawRect)
718 _hasPendingReshape = YES;
728 * Method called by Cocoa when the view is resized or the location has changed.
729 * We just need to make sure we are locking here.
733 VLCAssertMainThread();
734 BOOL success = [self lockgl];
744 * Method called by Cocoa to force redraw.
746 - (void)drawRect:(NSRect) rect
748 VLCAssertMainThread();
750 if ([self canSkipRendering])
753 BOOL success = [self lockgl];
764 NSWindow *window = [self window];
766 // Remove flashes with splitter view.
767 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
768 [window disableScreenUpdatesUntilFlush];
773 - (BOOL)mouseDownCanMoveWindow
783 - (void)setWindowLevel:(NSNumber*)state
785 if( [state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE )
786 [[self window] setLevel: NSStatusWindowLevel];
788 [[self window] setLevel: NSNormalWindowLevel];