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>
50 * Forward declarations
52 static int Open(vlc_object_t *);
53 static void Close(vlc_object_t *);
55 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
56 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
57 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
58 static int Control (vout_display_t *vd, int query, va_list ap);
60 static int OpenglLock(vlc_gl_t *gl);
61 static void OpenglUnlock(vlc_gl_t *gl);
62 static void OpenglSwap(vlc_gl_t *gl);
68 /* Will be loaded even without interface module. see voutgl.m */
69 set_shortname("Mac OS X")
70 set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
71 set_category(CAT_VIDEO)
72 set_subcategory(SUBCAT_VIDEO_VOUT )
73 set_capability("vout display", 300)
74 set_callbacks(Open, Close)
76 add_shortcut("macosx", "vout_macosx")
80 * Obj-C protocol declaration that drawable-nsobject should follow
82 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
83 - (void)addVoutSubview:(NSView *)view;
84 - (void)removeVoutSubview:(NSView *)view;
87 @interface VLCOpenGLVideoView : NSOpenGLView
90 BOOL _hasPendingReshape;
92 - (void)setVoutDisplay:(vout_display_t *)vd;
93 - (void)setVoutFlushing:(BOOL)flushing;
97 struct vout_display_sys_t
99 VLCOpenGLVideoView *glView;
100 id<VLCOpenGLVideoViewEmbedding> container;
102 vout_window_t *embed;
104 vout_display_opengl_t *vgl;
106 picture_pool_t *pool;
108 bool has_first_frame;
111 static int Open(vlc_object_t *this)
113 vout_display_t *vd = (vout_display_t *)this;
114 vout_display_sys_t *sys = calloc(1, sizeof(*sys));
115 NSAutoreleasePool *nsPool = nil;
125 /* Get the drawable object */
126 id container = var_CreateGetAddress(vd, "drawable-nsobject");
129 vout_display_DeleteWindow(vd, NULL);
133 vout_window_cfg_t wnd_cfg;
135 memset (&wnd_cfg, 0, sizeof (wnd_cfg));
136 wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
137 wnd_cfg.x = var_InheritInteger (vd, "video-x");
138 wnd_cfg.y = var_InheritInteger (vd, "video-y");
139 wnd_cfg.width = vd->cfg->display.width;
140 wnd_cfg.height = vd->cfg->display.height;
142 sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
144 container = sys->embed->handle.nsobject;
148 msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
153 /* This will be released in Close(), on
154 * main thread, after we are done using it. */
155 sys->container = [container retain];
157 /* Get our main view*/
158 nsPool = [[NSAutoreleasePool alloc] init];
160 [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
164 [sys->glView setVoutDisplay:vd];
166 /* We don't wait, that means that we'll have to be careful about releasing
168 * That's why we'll release on main thread in Close(). */
169 if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
170 [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
171 else if ([container isKindOfClass:[NSView class]])
173 NSView *parentView = container;
174 [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
175 [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
179 msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
187 /* Initialize common OpenGL video display */
188 sys->gl.lock = OpenglLock;
189 sys->gl.unlock = OpenglUnlock;
190 sys->gl.swap = OpenglSwap;
191 sys->gl.getProcAddress = NULL;
194 sys->vgl = vout_display_opengl_New(&vd->fmt, NULL, &sys->gl);
202 vout_display_info_t info = vd->info;
203 info.has_pictures_invalid = false;
205 /* Setup vout_display_t once everything is fine */
209 vd->prepare = PictureRender;
210 vd->display = PictureDisplay;
211 vd->control = Control;
214 vout_display_SendEventFullscreen (vd, false);
215 vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
225 void Close(vlc_object_t *this)
227 vout_display_t *vd = (vout_display_t *)this;
228 vout_display_sys_t *sys = vd->sys;
230 [sys->glView setVoutDisplay:nil];
232 var_Destroy(vd, "drawable-nsobject");
233 if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
235 /* This will retain sys->glView */
236 [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
238 /* release on main thread as explained in Open() */
239 [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
240 [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
242 [sys->glView release];
244 if (sys->gl.sys != NULL)
245 vout_display_opengl_Delete(sys->vgl);
248 vout_display_DeleteWindow(vd, sys->embed);
252 /*****************************************************************************
253 * vout display callbacks
254 *****************************************************************************/
256 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
258 vout_display_sys_t *sys = vd->sys;
261 sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
266 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
269 vout_display_sys_t *sys = vd->sys;
271 vout_display_opengl_Prepare( sys->vgl, pic, subpicture );
274 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
276 vout_display_sys_t *sys = vd->sys;
277 [sys->glView setVoutFlushing:YES];
278 vout_display_opengl_Display(sys->vgl, &vd->fmt );
279 [sys->glView setVoutFlushing:NO];
280 picture_Release (pic);
281 sys->has_first_frame = true;
285 static int Control (vout_display_t *vd, int query, va_list ap)
287 vout_display_sys_t *sys = vd->sys;
291 case VOUT_DISPLAY_CHANGE_FULLSCREEN:
296 case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
298 unsigned state = va_arg (ap, unsigned);
299 if( (state & VOUT_WINDOW_STATE_ABOVE) != 0)
300 [[sys->glView window] setLevel: NSStatusWindowLevel];
302 [[sys->glView window] setLevel: NSNormalWindowLevel];
305 case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
307 [[sys->glView window] performZoom: nil];
310 case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
311 case VOUT_DISPLAY_CHANGE_ZOOM:
312 case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
313 case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
316 NSPoint topleftscreen;
318 const vout_display_cfg_t *cfg;
320 id o_window = [sys->glView window];
321 NSRect windowFrame = [o_window frame];
322 NSRect glViewFrame = [sys->glView frame];
323 NSSize windowMinSize = [o_window minSize];
326 topleftbase.y = windowFrame.size.height;
327 topleftscreen = [o_window convertBaseToScreen: topleftbase];
328 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
329 int i_width = cfg->display.width;
330 int i_height = cfg->display.height;
332 /* Calculate the window's new size, if it is larger than our minimal size */
333 if (i_width < windowMinSize.width)
334 i_width = windowMinSize.width;
335 if (i_height < windowMinSize.height)
336 i_height = windowMinSize.height;
338 if( i_height != glViewFrame.size.height || i_width != glViewFrame.size.width )
340 new_frame.size.width = windowFrame.size.width - glViewFrame.size.width + i_width;
341 new_frame.size.height = windowFrame.size.height - glViewFrame.size.height + i_height;
343 new_frame.origin.x = topleftscreen.x;
344 new_frame.origin.y = topleftscreen.y - new_frame.size.height;
346 [o_window setFrame:new_frame display:YES animate:YES];
351 case VOUT_DISPLAY_HIDE_MOUSE:
353 [NSCursor setHiddenUntilMouseMoves: YES];
357 case VOUT_DISPLAY_GET_OPENGL:
359 vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
364 case VOUT_DISPLAY_RESET_PICTURES:
367 msg_Err (vd, "Unknown request in Mac OS X vout display");
372 /*****************************************************************************
373 * vout opengl callbacks
374 *****************************************************************************/
375 static int OpenglLock(vlc_gl_t *gl)
377 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
378 NSOpenGLContext *context = [sys->glView openGLContext];
379 CGLError err = CGLLockContext([context CGLContextObj]);
380 if (kCGLNoError == err)
382 [context makeCurrentContext];
388 static void OpenglUnlock(vlc_gl_t *gl)
390 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
391 CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
394 static void OpenglSwap(vlc_gl_t *gl)
396 vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
397 [[sys->glView openGLContext] flushBuffer];
400 /*****************************************************************************
402 *****************************************************************************/
403 @implementation VLCOpenGLVideoView
405 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
407 + (void)getNewView:(NSValue *)value
409 id *ret = [value pointerValue];
410 *ret = [[self alloc] init];
414 * Gets called by the Open() method.
418 VLCAssertMainThread();
420 /* Warning - this may be called on non main thread */
422 NSOpenGLPixelFormatAttribute attribs[] =
424 NSOpenGLPFADoubleBuffer,
425 NSOpenGLPFAAccelerated,
426 NSOpenGLPFANoRecovery,
427 NSOpenGLPFAColorSize, 24,
428 NSOpenGLPFAAlphaSize, 8,
429 NSOpenGLPFADepthSize, 24,
434 NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
439 self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
445 /* Swap buffers only during the vertical retrace of the monitor.
446 http://developer.apple.com/documentation/GraphicsImaging/
447 Conceptual/OpenGL/chap5/chapter_5_section_44.html */
448 GLint params[] = { 1 };
449 CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
451 [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
456 * Gets called by the Open() method.
458 - (void)setFrameWithValue:(NSValue *)value
460 [self setFrame:[value rectValue]];
464 * Gets called by the Close and Open methods.
467 - (void)setVoutDisplay:(vout_display_t *)aVd
469 @synchronized(self) {
476 * Gets called when the vout will aquire the lock and flush.
479 - (void)setVoutFlushing:(BOOL)flushing
483 @synchronized(self) {
484 _hasPendingReshape = NO;
489 * Can -drawRect skip rendering?.
491 - (BOOL)canSkipRendering
493 VLCAssertMainThread();
495 @synchronized(self) {
496 BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
497 return !_hasPendingReshape && hasFirstFrame;
503 * Local method that locks the gl context.
507 VLCAssertMainThread();
508 NSOpenGLContext *context = [self openGLContext];
509 CGLError err = CGLLockContext([context CGLContextObj]);
510 if (err == kCGLNoError)
511 [context makeCurrentContext];
512 return err == kCGLNoError;
516 * Local method that unlocks the gl context.
520 VLCAssertMainThread();
521 CGLUnlockContext([[self openGLContext] CGLContextObj]);
525 * Local method that force a rendering of a frame.
526 * This will get called if Cocoa forces us to redraw (via -drawRect).
530 VLCAssertMainThread();
532 // We may have taken some times to take the opengl Lock.
533 // Check here to see if we can just skip the frame as well.
534 if ([self canSkipRendering])
538 @synchronized(self) { // vd can be accessed from multiple threads
539 hasFirstFrame = vd && vd->sys->has_first_frame;
543 // This will lock gl.
544 vout_display_opengl_Display( vd->sys->vgl, &vd->source );
547 glClear(GL_COLOR_BUFFER_BIT);
551 * Method called by Cocoa when the view is resized.
555 VLCAssertMainThread();
557 NSRect bounds = [self bounds];
559 CGFloat height = bounds.size.height;
560 CGFloat width = bounds.size.width;
562 GLint x = width, y = height;
564 @synchronized(self) {
566 CGFloat videoHeight = vd->source.i_visible_height;
567 CGFloat videoWidth = vd->source.i_visible_width;
569 GLint sarNum = vd->source.i_sar_num;
570 GLint sarDen = vd->source.i_sar_den;
572 if (height * videoWidth * sarNum < width * videoHeight * sarDen)
574 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
580 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
586 glViewport((width - x) / 2, (height - y) / 2, x, y);
588 @synchronized(self) {
589 // This may be cleared before -drawRect is being called,
590 // in this case we'll skip the rendering.
591 // This will save us for rendering two frames (or more) for nothing
592 // (one by the vout, one (or more) by drawRect)
593 _hasPendingReshape = YES;
603 * Method called by Cocoa when the view is resized or the location has changed.
604 * We just need to make sure we are locking here.
608 VLCAssertMainThread();
609 BOOL success = [self lockgl];
619 * Method called by Cocoa to force redraw.
621 - (void)drawRect:(NSRect) rect
623 VLCAssertMainThread();
625 if ([self canSkipRendering])
628 BOOL success = [self lockgl];
639 NSWindow *window = [self window];
641 // Remove flashes with splitter view.
642 if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
643 [window disableScreenUpdatesUntilFlush];
648 - (BOOL)mouseDownCanMoveWindow