Remove legacy parameter from add_string()
[vlc/asuraparaju-public.git] / modules / video_output / macosx.m
blob6d6feadd072f98599630a18459a24a83d1609bf5
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  *****************************************************************************/
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
35 #import <Cocoa/Cocoa.h>
36 #import <OpenGL/OpenGL.h>
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
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"
48 /**
49  * Forward declarations
50  */
51 static int Open(vlc_object_t *);
52 static void Close(vlc_object_t *);
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);
59 static int OpenglLock(vout_opengl_t *gl);
60 static void OpenglUnlock(vout_opengl_t *gl);
61 static void OpenglSwap(vout_opengl_t *gl);
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)
75     add_shortcut("macosx", "vout_macosx")
76 vlc_module_end ()
78 /**
79  * Obj-C protocol declaration that drawable-nsobject should follow
80  */
81 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
82 - (void)addVoutSubview:(NSView *)view;
83 - (void)removeVoutSubview:(NSView *)view;
84 @end
86 @interface VLCOpenGLVideoView : NSOpenGLView
88     vout_display_t *vd;
89     BOOL _hasPendingReshape;
91 - (void)setVoutDisplay:(vout_display_t *)vd;
92 - (void)setVoutFlushing:(BOOL)flushing;
93 @end
96 struct vout_display_sys_t
98     VLCOpenGLVideoView *glView;
99     id<VLCOpenGLVideoViewEmbedding> container;
101     vout_window_t *embed;
102     vout_opengl_t gl;
103     vout_display_opengl_t vgl;
105     picture_pool_t *pool;
106     picture_t *current;
107     bool has_first_frame;
110 static int Open(vlc_object_t *this)
112     vout_display_t *vd = (vout_display_t *)this;
113     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
114     NSAutoreleasePool *nsPool = nil;
116     if (!sys)
117         return VLC_ENOMEM;
119     vd->sys = sys;
120     sys->pool = NULL;
121     sys->gl.sys = NULL;
122     sys->embed = NULL;
124     /* Get the drawable object */
125     id container = var_CreateGetAddress(vd, "drawable-nsobject");
126     if (container)
127     {
128         vout_display_DeleteWindow(vd, NULL);
129     }
130     else
131     {
132         vout_window_cfg_t wnd_cfg;
134         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
135         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
136         wnd_cfg.x = var_InheritInteger (vd, "video-x");
137         wnd_cfg.y = var_InheritInteger (vd, "video-y");
138         wnd_cfg.width  = vd->cfg->display.width;
139         wnd_cfg.height = vd->cfg->display.height;
141         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
142         if (sys->embed)
143             container = sys->embed->handle.nsobject;
145         if (!container)
146         {
147             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
148             goto error;
149         }
150     }
152     /* This will be released in Close(), on
153      * main thread, after we are done using it. */
154     sys->container = [container retain];
156     /* Get our main view*/
157     nsPool = [[NSAutoreleasePool alloc] init];
159     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
160     if (!sys->glView)
161         goto error;
163     [sys->glView setVoutDisplay:vd];
165     /* We don't wait, that means that we'll have to be careful about releasing
166      * container.
167      * That's why we'll release on main thread in Close(). */
168     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
169         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
170     else if ([container isKindOfClass:[NSView class]])
171     {
172         NSView *parentView = container;
173         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
174         [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
175     }
176     else
177     {
178         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
179         goto error;
180     }
183     [nsPool release];
184     nsPool = nil;
186     /* Initialize common OpenGL video display */
187     sys->gl.lock = OpenglLock;
188     sys->gl.unlock = OpenglUnlock;
189     sys->gl.swap = OpenglSwap;
190     sys->gl.sys = sys;
192     if (vout_display_opengl_Init(&sys->vgl, &vd->fmt, &sys->gl))
193     {
194         sys->gl.sys = NULL;
195         goto error;
196     }
198     /* */
199     vout_display_info_t info = vd->info;
200     info.has_pictures_invalid = false;
202     /* Setup vout_display_t once everything is fine */
203     vd->info = info;
205     vd->pool = Pool;
206     vd->prepare = PictureRender;
207     vd->display = PictureDisplay;
208     vd->control = Control;
210     /* */
211     vout_display_SendEventFullscreen (vd, false);
212     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
214     return VLC_SUCCESS;
216 error:
217     [nsPool release];
218     Close(this);
219     return VLC_EGENERIC;
222 void Close(vlc_object_t *this)
224     vout_display_t *vd = (vout_display_t *)this;
225     vout_display_sys_t *sys = vd->sys;
227     [sys->glView setVoutDisplay:nil];
229     var_Destroy(vd, "drawable-nsobject");
230     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
231     {
232         /* This will retain sys->glView */
233         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
234     }
235     /* release on main thread as explained in Open() */
236     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
237     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
239     [sys->glView release];
241     if (sys->gl.sys != NULL)
242         vout_display_opengl_Clean(&sys->vgl);
244     if (sys->embed)
245         vout_display_DeleteWindow(vd, sys->embed);
246     free (sys);
249 /*****************************************************************************
250  * vout display callbacks
251  *****************************************************************************/
253 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
255     vout_display_sys_t *sys = vd->sys;
256     VLC_UNUSED(requested_count);
258     if (!sys->pool)
259         sys->pool = vout_display_opengl_GetPool (&sys->vgl);
260     assert(sys->pool);
261     return sys->pool;
264 static void PictureRender(vout_display_t *vd, picture_t *pic)
267     vout_display_sys_t *sys = vd->sys;
269     vout_display_opengl_Prepare( &sys->vgl, pic );
272 static void PictureDisplay(vout_display_t *vd, picture_t *pic)
274     vout_display_sys_t *sys = vd->sys;
275     [sys->glView setVoutFlushing:YES];
276     vout_display_opengl_Display(&sys->vgl, &vd->fmt );
277     [sys->glView setVoutFlushing:NO];
278     picture_Release (pic);
279     sys->has_first_frame = true;
282 static int Control (vout_display_t *vd, int query, va_list ap)
284     vout_display_sys_t *sys = vd->sys;
286     switch (query)
287     {
288         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
289         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
290         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
291         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
292         case VOUT_DISPLAY_CHANGE_ZOOM:
293         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
294         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
295         {
296             /* todo */
297             return VLC_EGENERIC;
298         }
299         case VOUT_DISPLAY_HIDE_MOUSE:
300             return VLC_SUCCESS;
302         case VOUT_DISPLAY_GET_OPENGL:
303         {
304             vout_opengl_t **gl = va_arg (ap, vout_opengl_t **);
305             *gl = &sys->gl;
306             return VLC_SUCCESS;
307         }
309         case VOUT_DISPLAY_RESET_PICTURES:
310             assert (0);
311         default:
312             msg_Err (vd, "Unknown request in Mac OS X vout display");
313             return VLC_EGENERIC;
314     }
317 /*****************************************************************************
318  * vout opengl callbacks
319  *****************************************************************************/
320 static int OpenglLock(vout_opengl_t *gl)
322     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
323     NSOpenGLContext *context = [sys->glView openGLContext];
324     CGLError err = CGLLockContext([context CGLContextObj]);
325     if (kCGLNoError == err)
326     {
327         [context makeCurrentContext];
328         return 0;
329     }
330     return 1;
333 static void OpenglUnlock(vout_opengl_t *gl)
335     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
336     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
339 static void OpenglSwap(vout_opengl_t *gl)
341     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
342     [[sys->glView openGLContext] flushBuffer];
345 /*****************************************************************************
346  * Our NSView object
347  *****************************************************************************/
348 @implementation VLCOpenGLVideoView
350 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
352 + (void)getNewView:(NSValue *)value
354     id *ret = [value pointerValue];
355     *ret = [[self alloc] init];
359  * Gets called by the Open() method.
360  */
361 - (id)init
363     VLCAssertMainThread();
365     /* Warning - this may be called on non main thread */
367     NSOpenGLPixelFormatAttribute attribs[] =
368     {
369         NSOpenGLPFADoubleBuffer,
370         NSOpenGLPFAAccelerated,
371         NSOpenGLPFANoRecovery,
372         NSOpenGLPFAColorSize, 24,
373         NSOpenGLPFAAlphaSize, 8,
374         NSOpenGLPFADepthSize, 24,
375         NSOpenGLPFAWindow,
376         0
377     };
379     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
381     if (!fmt)
382         return nil;
384     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
385     [fmt release];
387     if (!self)
388         return nil;
390     /* Swap buffers only during the vertical retrace of the monitor.
391      http://developer.apple.com/documentation/GraphicsImaging/
392      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
393     GLint params[] = { 1 };
394     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
396     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
397     return self;
401  * Gets called by the Open() method.
402  */
403 - (void)setFrameWithValue:(NSValue *)value
405     [self setFrame:[value rectValue]];
409  * Gets called by the Close and Open methods.
410  * (Non main thread).
411  */
412 - (void)setVoutDisplay:(vout_display_t *)aVd
414     @synchronized(self) {
415         vd = aVd;
416     }
421  * Gets called when the vout will aquire the lock and flush.
422  * (Non main thread).
423  */
424 - (void)setVoutFlushing:(BOOL)flushing
426     if (!flushing)
427         return;
428     @synchronized(self) {
429         _hasPendingReshape = NO;
430     }
434  * Can -drawRect skip rendering?.
435  */
436 - (BOOL)canSkipRendering
438     VLCAssertMainThread();
440     @synchronized(self) {
441         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
442         return !_hasPendingReshape && hasFirstFrame;
443     }
448  * Local method that locks the gl context.
449  */
450 - (BOOL)lockgl
452     VLCAssertMainThread();
453     NSOpenGLContext *context = [self openGLContext];
454     CGLError err = CGLLockContext([context CGLContextObj]);
455     if (err == kCGLNoError)
456         [context makeCurrentContext];
457     return err == kCGLNoError;
461  * Local method that unlocks the gl context.
462  */
463 - (void)unlockgl
465     VLCAssertMainThread();
466     CGLUnlockContext([[self openGLContext] CGLContextObj]);
470  * Local method that force a rendering of a frame.
471  * This will get called if Cocoa forces us to redraw (via -drawRect).
472  */
473 - (void)render
475     VLCAssertMainThread();
477     // We may have taken some times to take the opengl Lock.
478     // Check here to see if we can just skip the frame as well.
479     if ([self canSkipRendering])
480         return;
482     BOOL hasFirstFrame;
483     @synchronized(self) { // vd can be accessed from multiple threads
484         hasFirstFrame = vd && vd->sys->has_first_frame;
485     }
487     if (hasFirstFrame) {
488         // This will lock gl.
489         vout_display_opengl_Display( &vd->sys->vgl, &vd->source );
490     }
491     else
492         glClear(GL_COLOR_BUFFER_BIT);
496  * Method called by Cocoa when the view is resized.
497  */
498 - (void)reshape
500     VLCAssertMainThread();
502     NSRect bounds = [self bounds];
504     CGFloat height = bounds.size.height;
505     CGFloat width = bounds.size.width;
507     GLint x = width, y = height;
509     @synchronized(self) {
510         if (vd) {
511             CGFloat videoHeight = vd->source.i_visible_height;
512             CGFloat videoWidth = vd->source.i_visible_width;
514             GLint sarNum = vd->source.i_sar_num;
515             GLint sarDen = vd->source.i_sar_den;
517             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
518             {
519                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
520                 y = height;
521             }
522             else
523             {
524                 x = width;
525                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
526             }
527         }
528     }
530     if ([self lockgl]) {
531         glViewport((width - x) / 2, (height - y) / 2, x, y);
533         @synchronized(self) {
534             // This may be cleared before -drawRect is being called,
535             // in this case we'll skip the rendering.
536             // This will save us for rendering two frames (or more) for nothing
537             // (one by the vout, one (or more) by drawRect)
538             _hasPendingReshape = YES;
539         }
541         [self unlockgl];
543         [super reshape];
544     }
548  * Method called by Cocoa when the view is resized or the location has changed.
549  * We just need to make sure we are locking here.
550  */
551 - (void)update
553     VLCAssertMainThread();
554     BOOL success = [self lockgl];
555     if (!success)
556         return;
558     [super update];
560     [self unlockgl];
564  * Method called by Cocoa to force redraw.
565  */
566 - (void)drawRect:(NSRect) rect
568     VLCAssertMainThread();
570     if ([self canSkipRendering])
571         return;
573     BOOL success = [self lockgl];
574     if (!success)
575         return;
577     [self render];
579     [self unlockgl];
582 - (void)renewGState
584     NSWindow *window = [self window];
586     // Remove flashes with splitter view.
587         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
588                 [window disableScreenUpdatesUntilFlush];
590     [super renewGState];
593 - (BOOL)mouseDownCanMoveWindow
595     return YES;
598 - (BOOL)isOpaque
600     return YES;
602 @end