]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
Use var_Inherit* instead of var_CreateGet*.
[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", "vout_macosx")
76 vlc_module_end ()
77
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
85
86 @interface VLCOpenGLVideoView : NSOpenGLView
87 {
88     vout_display_t *vd;
89     BOOL _hasPendingReshape;
90 }
91 - (void)setVoutDisplay:(vout_display_t *)vd;
92 - (void)setVoutFlushing:(BOOL)flushing;
93 @end
94
95
96 struct vout_display_sys_t
97 {
98     VLCOpenGLVideoView *glView;
99     id<VLCOpenGLVideoViewEmbedding> container;
100
101     vout_window_t *embed;
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     sys->embed = NULL;
123
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;
133
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;
140
141         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
142         if (sys->embed)
143             container = sys->embed->handle.nsobject;
144
145         if (!container)
146         {
147             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
148             goto error;
149         }
150     }
151
152     /* This will be released in Close(), on
153      * main thread, after we are done using it. */
154     sys->container = [container retain];
155
156     /* Get our main view*/
157     nsPool = [[NSAutoreleasePool alloc] init];
158
159     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
160     if (!sys->glView)
161         goto error;
162
163     [sys->glView setVoutDisplay:vd];
164
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     }
181
182
183     [nsPool release];
184     nsPool = nil;
185
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;
191
192     if (vout_display_opengl_Init(&sys->vgl, &vd->fmt, &sys->gl))
193     {
194         sys->gl.sys = NULL;
195         goto error;
196     }
197
198     /* */
199     vout_display_info_t info = vd->info;
200     info.has_pictures_invalid = false;
201
202     /* Setup vout_display_t once everything is fine */
203     vd->info = info;
204
205     vd->pool = Pool;
206     vd->prepare = PictureRender;
207     vd->display = PictureDisplay;
208     vd->control = Control;
209
210     /* */
211     vout_display_SendEventFullscreen (vd, false);
212     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
213
214     return VLC_SUCCESS;
215
216 error:
217     [nsPool release];
218     Close(this);
219     return VLC_EGENERIC;
220 }
221
222 void Close(vlc_object_t *this)
223 {
224     vout_display_t *vd = (vout_display_t *)this;
225     vout_display_sys_t *sys = vd->sys;
226
227     [sys->glView setVoutDisplay:nil];
228
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];
238
239     [sys->glView release];
240
241     if (sys->gl.sys != NULL)
242         vout_display_opengl_Clean(&sys->vgl);
243
244     if (sys->embed)
245         vout_display_DeleteWindow(vd, sys->embed);
246     free (sys);
247 }
248
249 /*****************************************************************************
250  * vout display callbacks
251  *****************************************************************************/
252
253 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
254 {
255     vout_display_sys_t *sys = vd->sys;
256     VLC_UNUSED(requested_count);
257
258     if (!sys->pool)
259         sys->pool = vout_display_opengl_GetPool (&sys->vgl);
260     assert(sys->pool);
261     return sys->pool;
262 }
263
264 static void PictureRender(vout_display_t *vd, picture_t *pic)
265 {
266
267     vout_display_sys_t *sys = vd->sys;
268
269     vout_display_opengl_Prepare( &sys->vgl, pic );
270 }
271
272 static void PictureDisplay(vout_display_t *vd, picture_t *pic)
273 {
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;
280 }
281
282 static int Control (vout_display_t *vd, int query, va_list ap)
283 {
284     vout_display_sys_t *sys = vd->sys;
285
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;
301
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         }
308
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     }
315 }
316
317 /*****************************************************************************
318  * vout opengl callbacks
319  *****************************************************************************/
320 static int OpenglLock(vout_opengl_t *gl)
321 {
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;
331 }
332
333 static void OpenglUnlock(vout_opengl_t *gl)
334 {
335     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
336     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
337 }
338
339 static void OpenglSwap(vout_opengl_t *gl)
340 {
341     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
342     [[sys->glView openGLContext] flushBuffer];
343 }
344
345 /*****************************************************************************
346  * Our NSView object
347  *****************************************************************************/
348 @implementation VLCOpenGLVideoView
349
350 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
351
352 + (void)getNewView:(NSValue *)value
353 {
354     id *ret = [value pointerValue];
355     *ret = [[self alloc] init];
356 }
357
358 /**
359  * Gets called by the Open() method.
360  */
361 - (id)init
362 {
363     VLCAssertMainThread();
364
365     /* Warning - this may be called on non main thread */
366
367     NSOpenGLPixelFormatAttribute attribs[] =
368     {
369         NSOpenGLPFADoubleBuffer,
370         NSOpenGLPFAAccelerated,
371         NSOpenGLPFANoRecovery,
372         NSOpenGLPFAColorSize, 24,
373         NSOpenGLPFAAlphaSize, 8,
374         NSOpenGLPFADepthSize, 24,
375         NSOpenGLPFAWindow,
376         0
377     };
378
379     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
380
381     if (!fmt)
382         return nil;
383
384     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
385     [fmt release];
386
387     if (!self)
388         return nil;
389
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);
395
396     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
397     return self;
398 }
399
400 /**
401  * Gets called by the Open() method.
402  */
403 - setFrameWithValue:(NSValue *)value
404 {
405     [self setFrame:[value rectValue]];
406 }
407
408 /**
409  * Gets called by the Close and Open methods.
410  * (Non main thread).
411  */
412 - (void)setVoutDisplay:(vout_display_t *)aVd
413 {
414     @synchronized(self) {
415         vd = aVd;
416     }
417 }
418
419
420 /**
421  * Gets called when the vout will aquire the lock and flush.
422  * (Non main thread).
423  */
424 - (void)setVoutFlushing:(BOOL)flushing
425 {
426     if (!flushing)
427         return;
428     @synchronized(self) {
429         _hasPendingReshape = NO;
430     }
431 }
432
433 /**
434  * Can -drawRect skip rendering?.
435  */
436 - (BOOL)canSkipRendering
437 {
438     VLCAssertMainThread();
439
440     @synchronized(self) {
441         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
442         return !_hasPendingReshape && hasFirstFrame;
443     }
444 }
445
446
447 /**
448  * Local method that locks the gl context.
449  */
450 - (BOOL)lockgl
451 {
452     VLCAssertMainThread();
453     NSOpenGLContext *context = [self openGLContext];
454     CGLError err = CGLLockContext([context CGLContextObj]);
455     if (err == kCGLNoError)
456         [context makeCurrentContext];
457     return err == kCGLNoError;
458 }
459
460 /**
461  * Local method that unlocks the gl context.
462  */
463 - (void)unlockgl
464 {
465     VLCAssertMainThread();
466     CGLUnlockContext([[self openGLContext] CGLContextObj]);
467 }
468
469 /**
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
474 {
475     VLCAssertMainThread();
476
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;
481
482     BOOL hasFirstFrame;
483     @synchronized(self) { // vd can be accessed from multiple threads
484         hasFirstFrame = vd && vd->sys->has_first_frame;
485     }
486
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);
493 }
494
495 /**
496  * Method called by Cocoa when the view is resized.
497  */
498 - (void)reshape
499 {
500     VLCAssertMainThread();
501
502     NSRect bounds = [self bounds];
503
504     CGFloat height = bounds.size.height;
505     CGFloat width = bounds.size.width;
506
507     GLint x = width, y = height;
508
509     @synchronized(self) {
510         if (vd) {
511             CGFloat videoHeight = vd->source.i_visible_height;
512             CGFloat videoWidth = vd->source.i_visible_width;
513
514             GLint sarNum = vd->source.i_sar_num;
515             GLint sarDen = vd->source.i_sar_den;
516
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     }
529
530     if ([self lockgl]) {
531         glViewport((width - x) / 2, (height - y) / 2, x, y);
532
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         }
540
541         [self unlockgl];
542
543         [super reshape];
544     }
545 }
546
547 /**
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
552 {
553     VLCAssertMainThread();
554     BOOL success = [self lockgl];
555     if (!success)
556         return;
557
558     [super update];
559
560     [self unlockgl];
561 }
562
563 /**
564  * Method called by Cocoa to force redraw.
565  */
566 - (void)drawRect:(NSRect) rect
567 {
568     VLCAssertMainThread();
569
570     if ([self canSkipRendering])
571         return;
572
573     BOOL success = [self lockgl];
574     if (!success)
575         return;
576
577     [self render];
578
579     [self unlockgl];
580 }
581
582 - (void)renewGState
583 {
584     NSWindow *window = [self window];
585
586     // Remove flashes with splitter view.
587         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
588                 [window disableScreenUpdatesUntilFlush];
589
590     [super renewGState];
591 }
592
593 - (BOOL)mouseDownCanMoveWindow
594 {
595     return YES;
596 }
597
598 - (BOOL)isOpaque
599 {
600     return YES;
601 }
602 @end