]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
macosx_vout: Correctly change context after -lockgl.
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * voutgl.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
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  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
29  *****************************************************************************/
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #import <Cocoa/Cocoa.h>
36 #import <OpenGL/OpenGL.h>
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_vout_display.h>
45 #include <vlc_vout_opengl.h>
46 #include "opengl.h"
47
48 /**
49  * Forward declarations
50  */
51 static int Open(vlc_object_t *);
52 static void Close(vlc_object_t *);
53
54 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
55 static void PictureRender(vout_display_t *vd, picture_t *pic);
56 static void PictureDisplay(vout_display_t *vd, picture_t *pic);
57 static int Control (vout_display_t *vd, int query, va_list ap);
58
59 static int OpenglLock(vout_opengl_t *gl);
60 static void OpenglUnlock(vout_opengl_t *gl);
61 static void OpenglSwap(vout_opengl_t *gl);
62
63 /**
64  * Module declaration
65  */
66 vlc_module_begin ()
67     /* Will be loaded even without interface module. see voutgl.m */
68     set_shortname("Mac OS X")
69     set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
70     set_category(CAT_VIDEO)
71     set_subcategory(SUBCAT_VIDEO_VOUT )
72     set_capability("vout display", 300)
73     set_callbacks(Open, Close)
74
75     add_shortcut("macosx")
76     add_shortcut("vout_macosx")
77 vlc_module_end ()
78
79 /**
80  * Obj-C protocol declaration that drawable-nsobject should follow
81  */
82 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
83 - (void)addVoutSubview:(NSView *)view;
84 - (void)removeVoutSubview:(NSView *)view;
85 @end
86
87 @interface VLCOpenGLVideoView : NSOpenGLView
88 {
89     vout_display_t *vd;
90     BOOL _hasPendingReshape;
91 }
92 - (void)setVoutDisplay:(vout_display_t *)vd;
93 - (void)setVoutFlushing:(BOOL)flushing;
94 @end
95
96
97 struct vout_display_sys_t
98 {
99     VLCOpenGLVideoView *glView;
100     id<VLCOpenGLVideoViewEmbedding> container;
101
102     vout_opengl_t gl;
103     vout_display_opengl_t vgl;
104
105     picture_pool_t *pool;
106     picture_t *current;
107     bool has_first_frame;
108 };
109
110 static int Open(vlc_object_t *this)
111 {
112     vout_display_t *vd = (vout_display_t *)this;
113     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
114     NSAutoreleasePool *nsPool = nil;
115
116     if (!sys)
117         return VLC_ENOMEM;
118
119     vd->sys = sys;
120     sys->pool = NULL;
121     sys->gl.sys = NULL;
122
123     /* Get the drawable object */
124     id container = var_CreateGetAddress(vd, "drawable-nsobject");
125     if (!container)
126     {
127         msg_Dbg(vd, "No drawable-nsobject, passing over.");
128         goto error;
129     }
130
131     /* This will be released in Close(), on
132      * main thread, after we are done using it. */
133     sys->container = [container retain];
134
135     /* Get our main view*/
136     nsPool = [[NSAutoreleasePool alloc] init];
137
138     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
139     if (!sys->glView)
140         goto error;
141
142     [sys->glView setVoutDisplay:vd];
143
144     /* We don't wait, that means that we'll have to be careful about releasing
145      * container.
146      * That's why we'll release on main thread in Close(). */
147     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
148         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
149     else if ([container isKindOfClass:[NSView class]])
150     {
151         NSView *parentView = container;
152         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
153         [sys->glView performSelectorOnMainThread:@selector(setFrame:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
154     }
155     else
156     {
157         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
158         goto error;
159     }
160
161
162     [nsPool release];
163     nsPool = nil;
164
165     /* Initialize common OpenGL video display */
166     sys->gl.lock = OpenglLock;
167     sys->gl.unlock = OpenglUnlock;
168     sys->gl.swap = OpenglSwap;
169     sys->gl.sys = sys;
170
171     if (vout_display_opengl_Init(&sys->vgl, &vd->fmt, &sys->gl))
172     {
173         sys->gl.sys = NULL;
174         goto error;
175     }
176
177     /* */
178     vout_display_info_t info = vd->info;
179     info.has_pictures_invalid = false;
180
181     /* Setup vout_display_t once everything is fine */
182     vd->info = info;
183
184     vd->pool = Pool;
185     vd->prepare = PictureRender;
186     vd->display = PictureDisplay;
187     vd->control = Control;
188
189     /* */
190     vout_display_SendEventFullscreen (vd, false);
191     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
192
193     return VLC_SUCCESS;
194
195 error:
196     [nsPool release];
197     Close(this);
198     return VLC_EGENERIC;
199 }
200
201 void Close(vlc_object_t *this)
202 {
203     vout_display_t *vd = (vout_display_t *)this;
204     vout_display_sys_t *sys = vd->sys;
205
206     [sys->glView setVoutDisplay:nil];
207
208     var_Destroy(vd, "drawable-nsobject");
209     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
210     {
211         /* This will retain sys->glView */
212         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
213     }
214     /* release on main thread as explained in Open() */
215     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
216     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
217
218     [sys->glView release];
219
220     if (sys->gl.sys != NULL)
221         vout_display_opengl_Clean(&sys->vgl);
222
223     free (sys);
224 }
225
226 /*****************************************************************************
227  * vout display callbacks
228  *****************************************************************************/
229
230 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
231 {
232     vout_display_sys_t *sys = vd->sys;
233     VLC_UNUSED(requested_count);
234
235     if (!sys->pool)
236         sys->pool = vout_display_opengl_GetPool (&sys->vgl);
237     assert(sys->pool);
238     return sys->pool;
239 }
240
241 static void PictureRender(vout_display_t *vd, picture_t *pic)
242 {
243
244     vout_display_sys_t *sys = vd->sys;
245
246     vout_display_opengl_Prepare( &sys->vgl, pic );
247 }
248
249 static void PictureDisplay(vout_display_t *vd, picture_t *pic)
250 {
251     vout_display_sys_t *sys = vd->sys;
252     [sys->glView setVoutFlushing:YES];
253     vout_display_opengl_Display(&sys->vgl, &vd->fmt );
254     [sys->glView setVoutFlushing:NO];
255     picture_Release (pic);
256     sys->has_first_frame = true;
257 }
258
259 static int Control (vout_display_t *vd, int query, va_list ap)
260 {
261     vout_display_sys_t *sys = vd->sys;
262
263     switch (query)
264     {
265         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
266         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
267         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
268         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
269         case VOUT_DISPLAY_CHANGE_ZOOM:
270         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
271         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
272         {
273             /* todo */
274             return VLC_EGENERIC;
275         }
276         case VOUT_DISPLAY_HIDE_MOUSE:
277             return VLC_SUCCESS;
278
279         case VOUT_DISPLAY_GET_OPENGL:
280         {
281             vout_opengl_t **gl = va_arg (ap, vout_opengl_t **);
282             *gl = &sys->gl;
283             return VLC_SUCCESS;
284         }
285
286         case VOUT_DISPLAY_RESET_PICTURES:
287             assert (0);
288         default:
289             msg_Err (vd, "Unknown request in Mac OS X vout display");
290             return VLC_EGENERIC;
291     }
292 }
293
294 /*****************************************************************************
295  * vout opengl callbacks
296  *****************************************************************************/
297 static int OpenglLock(vout_opengl_t *gl)
298 {
299     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
300     NSOpenGLContext *context = [sys->glView openGLContext];
301     CGLError err = CGLLockContext([context CGLContextObj]);
302     if (kCGLNoError == err)
303     {
304         [context makeCurrentContext];
305         return 0;
306     }
307     return 1;
308 }
309
310 static void OpenglUnlock(vout_opengl_t *gl)
311 {
312     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
313     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
314 }
315
316 static void OpenglSwap(vout_opengl_t *gl)
317 {
318     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
319     [[sys->glView openGLContext] flushBuffer];
320 }
321
322 /*****************************************************************************
323  * Our NSView object
324  *****************************************************************************/
325 @implementation VLCOpenGLVideoView
326
327 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
328
329 + (void)getNewView:(NSValue *)value
330 {
331     id *ret = [value pointerValue];
332     *ret = [[self alloc] init];
333 }
334
335 /**
336  * Gets called by the Open() method.
337  */
338 - (id)init
339 {
340     VLCAssertMainThread();
341
342     /* Warning - this may be called on non main thread */
343
344     NSOpenGLPixelFormatAttribute attribs[] =
345     {
346         NSOpenGLPFADoubleBuffer,
347         NSOpenGLPFAAccelerated,
348         NSOpenGLPFANoRecovery,
349         NSOpenGLPFAColorSize, 24,
350         NSOpenGLPFAAlphaSize, 8,
351         NSOpenGLPFADepthSize, 24,
352         NSOpenGLPFAWindow,
353         0
354     };
355
356     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
357
358     if (!fmt)
359         return nil;
360
361     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
362     [fmt release];
363
364     if (!self)
365         return nil;
366
367     /* Swap buffers only during the vertical retrace of the monitor.
368      http://developer.apple.com/documentation/GraphicsImaging/
369      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
370     GLint params[] = { 1 };
371     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
372
373     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
374     return self;
375 }
376
377 /**
378  * Gets called by the Close and Open methods.
379  * (Non main thread).
380  */
381 - (void)setVoutDisplay:(vout_display_t *)aVd
382 {
383     @synchronized(self) {
384         vd = aVd;
385     }
386 }
387
388
389 /**
390  * Gets called when the vout will aquire the lock and flush.
391  * (Non main thread).
392  */
393 - (void)setVoutFlushing:(BOOL)flushing
394 {
395     if (!flushing)
396         return;
397     @synchronized(self) {
398         _hasPendingReshape = NO;
399     }
400 }
401
402 /**
403  * Can -drawRect skip rendering?.
404  */
405 - (BOOL)canSkipRendering
406 {
407     VLCAssertMainThread();
408
409     @synchronized(self) {
410         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
411         return !_hasPendingReshape && hasFirstFrame;
412     }
413 }
414
415
416 /**
417  * Local method that locks the gl context.
418  */
419 - (BOOL)lockgl
420 {
421     VLCAssertMainThread();
422     NSOpenGLContext *context = [self openGLContext];
423     CGLError err = CGLLockContext([context CGLContextObj]);
424     if (err == kCGLNoError)
425         [context makeCurrentContext];
426     return err == kCGLNoError;
427 }
428
429 /**
430  * Local method that unlocks the gl context.
431  */
432 - (void)unlockgl
433 {
434     VLCAssertMainThread();
435     CGLUnlockContext([[self openGLContext] CGLContextObj]);
436 }
437
438 /**
439  * Local method that force a rendering of a frame.
440  * This will get called if Cocoa forces us to redraw (via -drawRect).
441  */
442 - (void)render
443 {
444     VLCAssertMainThread();
445
446     // We may have taken some times to take the opengl Lock.
447     // Check here to see if we can just skip the frame as well.
448     if ([self canSkipRendering])
449         return;
450
451     BOOL hasFirstFrame;
452     @synchronized(self) { // vd can be accessed from multiple threads
453         hasFirstFrame = vd && vd->sys->has_first_frame;
454     }
455
456     if (hasFirstFrame) {
457         // This will lock gl.
458         vout_display_opengl_Display( &vd->sys->vgl, &vd->source );
459     }
460     else
461         glClear(GL_COLOR_BUFFER_BIT);
462 }
463
464 /**
465  * Method called by Cocoa when the view is resized.
466  */
467 - (void)reshape
468 {
469     VLCAssertMainThread();
470
471     NSRect bounds = [self bounds];
472
473     CGFloat height = bounds.size.height;
474     CGFloat width = bounds.size.width;
475
476     GLint x = width, y = height;
477
478     @synchronized(self) {
479         if (vd) {
480             CGFloat videoHeight = vd->source.i_visible_height;
481             CGFloat videoWidth = vd->source.i_visible_width;
482
483             GLint sarNum = vd->source.i_sar_num;
484             GLint sarDen = vd->source.i_sar_den;
485
486             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
487             {
488                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
489                 y = height;
490             }
491             else
492             {
493                 x = width;
494                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
495             }
496         }
497     }
498
499     if ([self lockgl]) {
500         glViewport((width - x) / 2, (height - y) / 2, x, y);
501
502         @synchronized(self) {
503             // This may be cleared before -drawRect is being called,
504             // in this case we'll skip the rendering.
505             // This will save us for rendering two frames (or more) for nothing
506             // (one by the vout, one (or more) by drawRect)
507             _hasPendingReshape = YES;
508         }
509
510         [self unlockgl];
511
512         [super reshape];
513     }
514 }
515
516 /**
517  * Method called by Cocoa when the view is resized or the location has changed.
518  * We just need to make sure we are locking here.
519  */
520 - (void)update
521 {
522     VLCAssertMainThread();
523     BOOL success = [self lockgl];
524     if (!success)
525         return;
526
527     [super update];
528
529     [self unlockgl];
530 }
531
532 /**
533  * Method called by Cocoa to force redraw.
534  */
535 - (void)drawRect:(NSRect) rect
536 {
537     VLCAssertMainThread();
538
539     if ([self canSkipRendering])
540         return;
541
542     BOOL success = [self lockgl];
543     if (!success)
544         return;
545
546     [self render];
547
548     [self unlockgl];
549 }
550
551 - (void)renewGState
552 {
553     NSWindow *window = [self window];
554
555     // Remove flashes with splitter view.
556         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
557                 [window disableScreenUpdatesUntilFlush];
558
559     [super renewGState];
560 }
561
562 - (BOOL)mouseDownCanMoveWindow
563 {
564     return YES;
565 }
566
567 - (BOOL)isOpaque
568 {
569     return YES;
570 }
571 @end