]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
vout_macosx: Backport 9c21b7ec34ef07a4f4c6b5e9dc4625ad02456bfb. (Suppress flashes...
[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 }
91 - (void)setVoutDisplay:(vout_display_t *)vd;
92 @end
93  
94
95 struct vout_display_sys_t
96 {
97     VLCOpenGLVideoView *glView;
98     id<VLCOpenGLVideoViewEmbedding> container;
99
100     vout_opengl_t gl;
101     vout_display_opengl_t vgl;
102     
103     picture_pool_t *pool;
104     picture_t *current;
105     bool has_first_frame;
106 };
107
108 static int Open(vlc_object_t *this)
109 {
110     vout_display_t *vd = (vout_display_t *)this;
111     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
112     NSAutoreleasePool *nsPool = nil;
113
114     if (!sys)
115         return VLC_ENOMEM;
116
117     vd->sys = sys;
118     sys->pool = NULL;
119     sys->gl.sys = NULL;
120     
121     /* Get the drawable object */
122     id container = var_CreateGetAddress(vd, "drawable-nsobject");
123     if (!container)
124     {
125         msg_Dbg(vd, "No drawable-nsobject, passing over.");
126         goto error;
127     }
128
129     /* This will be released in Close(), on
130      * main thread, after we are done using it. */
131     sys->container = [container retain];
132
133     /* Get our main view*/
134     nsPool = [[NSAutoreleasePool alloc] init];
135     
136     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
137     if (!sys->glView)
138         goto error;
139
140     [sys->glView setVoutDisplay:vd];
141
142     /* We don't wait, that means that we'll have to be careful about releasing
143      * container.
144      * That's why we'll release on main thread in Close(). */
145     [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
146     [nsPool release];
147     nsPool = nil;
148
149     /* Initialize common OpenGL video display */
150     sys->gl.lock = OpenglLock;
151     sys->gl.unlock = OpenglUnlock;
152     sys->gl.swap = OpenglSwap;
153     sys->gl.sys = sys;
154     
155     if (vout_display_opengl_Init(&sys->vgl, &vd->fmt, &sys->gl))
156     {
157         sys->gl.sys = NULL;
158         goto error;
159     }
160
161     /* */
162     vout_display_info_t info = vd->info;
163     info.has_pictures_invalid = false;
164     
165     /* Setup vout_display_t once everything is fine */
166     vd->info = info;
167     
168     vd->pool = Pool;
169     vd->prepare = PictureRender;
170     vd->display = PictureDisplay;
171     vd->control = Control;
172
173     /* */
174     vout_display_SendEventFullscreen (vd, false);
175     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
176
177     return VLC_SUCCESS;
178
179 error:
180     [nsPool release];
181     Close(this);
182     return VLC_EGENERIC;
183 }
184
185 void Close(vlc_object_t *this)
186 {
187     vout_display_t *vd = (vout_display_t *)this;
188     vout_display_sys_t *sys = vd->sys;
189
190     [sys->glView setVoutDisplay:nil];
191
192     var_Destroy(vd, "drawable-nsobject");
193     /* This will retain sys->glView */
194     [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
195     /* release on main thread as explained in Open() */
196     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
197     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
198     
199     [sys->glView release];
200
201     if (sys->gl.sys != NULL)
202         vout_display_opengl_Clean(&sys->vgl);
203
204     free (sys);
205 }
206
207 /*****************************************************************************
208  * vout display callbacks
209  *****************************************************************************/
210
211 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
212 {
213     vout_display_sys_t *sys = vd->sys;
214     VLC_UNUSED(requested_count);
215
216     if (!sys->pool)
217         sys->pool = vout_display_opengl_GetPool (&sys->vgl);
218     assert(sys->pool);
219     return sys->pool;
220 }
221
222 static void PictureRender(vout_display_t *vd, picture_t *pic)
223 {
224
225     vout_display_sys_t *sys = vd->sys;
226     
227     vout_display_opengl_Prepare( &sys->vgl, pic );
228 }
229
230 static void PictureDisplay(vout_display_t *vd, picture_t *pic)
231 {
232     vout_display_sys_t *sys = vd->sys;
233     vout_display_opengl_Display(&sys->vgl, &vd->fmt );
234     picture_Release (pic);
235     sys->has_first_frame = true;
236 }
237
238 static int Control (vout_display_t *vd, int query, va_list ap)
239 {
240     vout_display_sys_t *sys = vd->sys;
241     
242     switch (query)
243     {
244         case VOUT_DISPLAY_CHANGE_FULLSCREEN:            
245         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
246         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
247         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
248         case VOUT_DISPLAY_CHANGE_ZOOM:
249         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
250         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
251         {
252             /* todo */
253             return VLC_EGENERIC;
254         }
255         case VOUT_DISPLAY_HIDE_MOUSE:
256             return VLC_SUCCESS;
257             
258         case VOUT_DISPLAY_GET_OPENGL:
259         {
260             vout_opengl_t **gl = va_arg (ap, vout_opengl_t **);
261             *gl = &sys->gl;
262             return VLC_SUCCESS;
263         }
264             
265         case VOUT_DISPLAY_RESET_PICTURES:
266             assert (0);
267         default:
268             msg_Err (vd, "Unknown request in Mac OS X vout display");
269             return VLC_EGENERIC;
270     }
271     printf("query %d\n", query);
272 }
273
274 /*****************************************************************************
275  * vout opengl callbacks
276  *****************************************************************************/
277 static int OpenglLock(vout_opengl_t *gl)
278 {
279     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
280     NSOpenGLContext *context = [sys->glView openGLContext];
281     CGLError err = CGLLockContext([context CGLContextObj]);
282     if (kCGLNoError == err)
283     {
284         [context makeCurrentContext];
285         return 0;
286     }
287     return 1;    
288 }
289
290 static void OpenglUnlock(vout_opengl_t *gl)
291 {
292     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
293     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
294 }
295
296 static void OpenglSwap(vout_opengl_t *gl)
297 {
298     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
299     [[sys->glView openGLContext] flushBuffer];
300 }
301
302 /*****************************************************************************
303  * Our NSView object
304  *****************************************************************************/
305 @implementation VLCOpenGLVideoView
306
307 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
308
309 + (void)getNewView:(NSValue *)value
310 {
311     id *ret = [value pointerValue];
312     *ret = [[self alloc] init];
313 }
314
315 /**
316  * Gets called by the Open() method.
317  */
318 - (id)init
319 {
320     VLCAssertMainThread();
321
322     /* Warning - this may be called on non main thread */
323
324     NSOpenGLPixelFormatAttribute attribs[] =
325     {
326         NSOpenGLPFADoubleBuffer,
327         NSOpenGLPFAAccelerated,
328         NSOpenGLPFANoRecovery,
329         NSOpenGLPFAColorSize, 24,
330         NSOpenGLPFAAlphaSize, 8,
331         NSOpenGLPFADepthSize, 24,
332         NSOpenGLPFAWindow,
333         0
334     };
335     
336     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
337     
338     if (!fmt)
339         return nil;
340
341     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
342     if (!self)
343         return nil;
344
345     /* Swap buffers only during the vertical retrace of the monitor.
346      http://developer.apple.com/documentation/GraphicsImaging/
347      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
348     GLint params[] = { 1 };
349     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
350
351     return self;
352 }
353
354 /**
355  * Gets called by the Close and Open methods.
356  * (Non main thread).
357  */
358 - (void)setVoutDisplay:(vout_display_t *)aVd
359 {
360     @synchronized(self) {
361         vd = aVd;
362     }
363 }
364
365 /**
366  * Local method that locks the gl context.
367  */
368 - (BOOL)lockgl
369 {
370     VLCAssertMainThread();
371     CGLError err = CGLLockContext([[self openGLContext] CGLContextObj]);
372     return err == kCGLNoError;
373 }
374
375 /**
376  * Local method that unlocks the gl context.
377  */
378 - (void)unlockgl
379 {
380     VLCAssertMainThread();
381     CGLUnlockContext([[self openGLContext] CGLContextObj]);
382 }
383
384 /**
385  * Local method that force a rendering of a frame.
386  * This will get called if Cocoa forces us to redraw (via -drawRect).
387  */
388 - (void)render
389 {
390     VLCAssertMainThread();
391
392     @synchronized(self) { // vd can be accessed from multiple threads
393         if (vd && vd->sys->has_first_frame)
394         {
395             // This will lock gl.
396             vout_display_opengl_Display( &vd->sys->vgl, &vd->source );
397         }
398         else {
399             glClear(GL_COLOR_BUFFER_BIT);
400         }
401         
402     }    
403 }
404
405 /**
406  * Method called by Cocoa when the view is resized.
407  */
408 - (void)reshape
409 {
410     VLCAssertMainThread();
411     
412     NSRect bounds = [self bounds];
413
414     CGFloat height = bounds.size.height;
415     CGFloat width = bounds.size.width;
416
417     GLint x = width, y = height;
418
419     @synchronized(self) {
420         if (vd) {
421             CGFloat videoHeight = vd->source.i_visible_height;
422             CGFloat videoWidth = vd->source.i_visible_width;
423             
424             GLint sarNum = vd->source.i_sar_num;
425             GLint sarDen = vd->source.i_sar_den;
426             
427             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
428             {
429                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
430                 y = height;
431             }
432             else
433             {
434                 x = width;
435                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
436             }            
437         }
438     }
439     
440     [self lockgl];
441     glClearColor(0, 0, 0, 1);
442     glViewport((width - x) / 2, (height - y) / 2, x, y);
443     [self unlockgl];
444
445     [super reshape];
446 }
447
448 /**
449  * Method called by Cocoa when the view is resized or the location has changed.
450  * We just need to make sure we are locking here.
451  */
452 - (void)update
453 {
454     VLCAssertMainThread();
455     BOOL success = [self lockgl];
456     if (!success)
457         return;
458
459     [super update];
460
461     [self unlockgl];
462 }
463
464 /**
465  * Method called by Cocoa to force redraw.
466  */
467 - (void)drawRect:(NSRect) rect
468 {
469     VLCAssertMainThread();
470     BOOL success = [self lockgl];
471     if (!success)
472         return;
473
474     [self render];
475
476     [self unlockgl];
477 }
478
479 - (void)renewGState
480 {
481     NSWindow *window = [self window];
482
483     // Remove flashes with splitter view.
484         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
485                 [window disableScreenUpdatesUntilFlush];
486
487     [super renewGState];
488 }
489
490 - (BOOL)mouseDownCanMoveWindow
491 {
492     return YES;
493 }
494
495 - (BOOL)isOpaque
496 {
497     return YES;
498 }
499 @end