]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
300a60ad1fc8f804090e713fc0aa2fa2eaff50c7
[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_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, subpicture_t *subpicture);
56 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
57 static int Control (vout_display_t *vd, int query, va_list ap);
58
59 static int OpenglLock(vlc_gl_t *gl);
60 static void OpenglUnlock(vlc_gl_t *gl);
61 static void OpenglSwap(vlc_gl_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     vlc_gl_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.getProcAddress = NULL;
191     sys->gl.sys = sys;
192
193         sys->vgl = vout_display_opengl_New(&vd->fmt, &sys->gl);
194         if (!sys->vgl)
195     {
196         sys->gl.sys = NULL;
197         goto error;
198     }
199
200     /* */
201     vout_display_info_t info = vd->info;
202     info.has_pictures_invalid = false;
203
204     /* Setup vout_display_t once everything is fine */
205     vd->info = info;
206
207     vd->pool = Pool;
208     vd->prepare = PictureRender;
209     vd->display = PictureDisplay;
210     vd->control = Control;
211
212     /* */
213     vout_display_SendEventFullscreen (vd, false);
214     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
215
216     return VLC_SUCCESS;
217
218 error:
219     [nsPool release];
220     Close(this);
221     return VLC_EGENERIC;
222 }
223
224 void Close(vlc_object_t *this)
225 {
226     vout_display_t *vd = (vout_display_t *)this;
227     vout_display_sys_t *sys = vd->sys;
228
229     [sys->glView setVoutDisplay:nil];
230
231     var_Destroy(vd, "drawable-nsobject");
232     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
233     {
234         /* This will retain sys->glView */
235         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
236     }
237     /* release on main thread as explained in Open() */
238     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
239     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
240
241     [sys->glView release];
242
243     if (sys->gl.sys != NULL)
244         vout_display_opengl_Delete(sys->vgl);
245
246     if (sys->embed)
247         vout_display_DeleteWindow(vd, sys->embed);
248     free (sys);
249 }
250
251 /*****************************************************************************
252  * vout display callbacks
253  *****************************************************************************/
254
255 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
256 {
257     vout_display_sys_t *sys = vd->sys;
258     VLC_UNUSED(requested_count);
259
260     if (!sys->pool)
261         sys->pool = vout_display_opengl_GetPool (sys->vgl);
262     assert(sys->pool);
263     return sys->pool;
264 }
265
266 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
267 {
268
269     vout_display_sys_t *sys = vd->sys;
270
271     vout_display_opengl_Prepare( sys->vgl, pic );
272         (void)subpicture;
273 }
274
275 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
276 {
277     vout_display_sys_t *sys = vd->sys;
278     [sys->glView setVoutFlushing:YES];
279     vout_display_opengl_Display(sys->vgl, &vd->fmt );
280     [sys->glView setVoutFlushing:NO];
281     picture_Release (pic);
282     sys->has_first_frame = true;
283         (void)subpicture;
284 }
285
286 static int Control (vout_display_t *vd, int query, va_list ap)
287 {
288     vout_display_sys_t *sys = vd->sys;
289
290     switch (query)
291     {
292         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
293         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
294         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
295         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
296         case VOUT_DISPLAY_CHANGE_ZOOM:
297         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
298         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
299         {
300             /* todo */
301             return VLC_EGENERIC;
302         }
303         case VOUT_DISPLAY_HIDE_MOUSE:
304             return VLC_SUCCESS;
305
306         case VOUT_DISPLAY_GET_OPENGL:
307         {
308             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
309             *gl = &sys->gl;
310             return VLC_SUCCESS;
311         }
312
313         case VOUT_DISPLAY_RESET_PICTURES:
314             assert (0);
315         default:
316             msg_Err (vd, "Unknown request in Mac OS X vout display");
317             return VLC_EGENERIC;
318     }
319 }
320
321 /*****************************************************************************
322  * vout opengl callbacks
323  *****************************************************************************/
324 static int OpenglLock(vlc_gl_t *gl)
325 {
326     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
327     NSOpenGLContext *context = [sys->glView openGLContext];
328     CGLError err = CGLLockContext([context CGLContextObj]);
329     if (kCGLNoError == err)
330     {
331         [context makeCurrentContext];
332         return 0;
333     }
334     return 1;
335 }
336
337 static void OpenglUnlock(vlc_gl_t *gl)
338 {
339     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
340     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
341 }
342
343 static void OpenglSwap(vlc_gl_t *gl)
344 {
345     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
346     [[sys->glView openGLContext] flushBuffer];
347 }
348
349 /*****************************************************************************
350  * Our NSView object
351  *****************************************************************************/
352 @implementation VLCOpenGLVideoView
353
354 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
355
356 + (void)getNewView:(NSValue *)value
357 {
358     id *ret = [value pointerValue];
359     *ret = [[self alloc] init];
360 }
361
362 /**
363  * Gets called by the Open() method.
364  */
365 - (id)init
366 {
367     VLCAssertMainThread();
368
369     /* Warning - this may be called on non main thread */
370
371     NSOpenGLPixelFormatAttribute attribs[] =
372     {
373         NSOpenGLPFADoubleBuffer,
374         NSOpenGLPFAAccelerated,
375         NSOpenGLPFANoRecovery,
376         NSOpenGLPFAColorSize, 24,
377         NSOpenGLPFAAlphaSize, 8,
378         NSOpenGLPFADepthSize, 24,
379         NSOpenGLPFAWindow,
380         0
381     };
382
383     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
384
385     if (!fmt)
386         return nil;
387
388     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
389     [fmt release];
390
391     if (!self)
392         return nil;
393
394     /* Swap buffers only during the vertical retrace of the monitor.
395      http://developer.apple.com/documentation/GraphicsImaging/
396      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
397     GLint params[] = { 1 };
398     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
399
400     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
401     return self;
402 }
403
404 /**
405  * Gets called by the Open() method.
406  */
407 - (void)setFrameWithValue:(NSValue *)value
408 {
409     [self setFrame:[value rectValue]];
410 }
411
412 /**
413  * Gets called by the Close and Open methods.
414  * (Non main thread).
415  */
416 - (void)setVoutDisplay:(vout_display_t *)aVd
417 {
418     @synchronized(self) {
419         vd = aVd;
420     }
421 }
422
423
424 /**
425  * Gets called when the vout will aquire the lock and flush.
426  * (Non main thread).
427  */
428 - (void)setVoutFlushing:(BOOL)flushing
429 {
430     if (!flushing)
431         return;
432     @synchronized(self) {
433         _hasPendingReshape = NO;
434     }
435 }
436
437 /**
438  * Can -drawRect skip rendering?.
439  */
440 - (BOOL)canSkipRendering
441 {
442     VLCAssertMainThread();
443
444     @synchronized(self) {
445         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
446         return !_hasPendingReshape && hasFirstFrame;
447     }
448 }
449
450
451 /**
452  * Local method that locks the gl context.
453  */
454 - (BOOL)lockgl
455 {
456     VLCAssertMainThread();
457     NSOpenGLContext *context = [self openGLContext];
458     CGLError err = CGLLockContext([context CGLContextObj]);
459     if (err == kCGLNoError)
460         [context makeCurrentContext];
461     return err == kCGLNoError;
462 }
463
464 /**
465  * Local method that unlocks the gl context.
466  */
467 - (void)unlockgl
468 {
469     VLCAssertMainThread();
470     CGLUnlockContext([[self openGLContext] CGLContextObj]);
471 }
472
473 /**
474  * Local method that force a rendering of a frame.
475  * This will get called if Cocoa forces us to redraw (via -drawRect).
476  */
477 - (void)render
478 {
479     VLCAssertMainThread();
480
481     // We may have taken some times to take the opengl Lock.
482     // Check here to see if we can just skip the frame as well.
483     if ([self canSkipRendering])
484         return;
485
486     BOOL hasFirstFrame;
487     @synchronized(self) { // vd can be accessed from multiple threads
488         hasFirstFrame = vd && vd->sys->has_first_frame;
489     }
490
491     if (hasFirstFrame) {
492         // This will lock gl.
493         vout_display_opengl_Display( vd->sys->vgl, &vd->source );
494     }
495     else
496         glClear(GL_COLOR_BUFFER_BIT);
497 }
498
499 /**
500  * Method called by Cocoa when the view is resized.
501  */
502 - (void)reshape
503 {
504     VLCAssertMainThread();
505
506     NSRect bounds = [self bounds];
507
508     CGFloat height = bounds.size.height;
509     CGFloat width = bounds.size.width;
510
511     GLint x = width, y = height;
512
513     @synchronized(self) {
514         if (vd) {
515             CGFloat videoHeight = vd->source.i_visible_height;
516             CGFloat videoWidth = vd->source.i_visible_width;
517
518             GLint sarNum = vd->source.i_sar_num;
519             GLint sarDen = vd->source.i_sar_den;
520
521             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
522             {
523                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
524                 y = height;
525             }
526             else
527             {
528                 x = width;
529                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
530             }
531         }
532     }
533
534     if ([self lockgl]) {
535         glViewport((width - x) / 2, (height - y) / 2, x, y);
536
537         @synchronized(self) {
538             // This may be cleared before -drawRect is being called,
539             // in this case we'll skip the rendering.
540             // This will save us for rendering two frames (or more) for nothing
541             // (one by the vout, one (or more) by drawRect)
542             _hasPendingReshape = YES;
543         }
544
545         [self unlockgl];
546
547         [super reshape];
548     }
549 }
550
551 /**
552  * Method called by Cocoa when the view is resized or the location has changed.
553  * We just need to make sure we are locking here.
554  */
555 - (void)update
556 {
557     VLCAssertMainThread();
558     BOOL success = [self lockgl];
559     if (!success)
560         return;
561
562     [super update];
563
564     [self unlockgl];
565 }
566
567 /**
568  * Method called by Cocoa to force redraw.
569  */
570 - (void)drawRect:(NSRect) rect
571 {
572     VLCAssertMainThread();
573
574     if ([self canSkipRendering])
575         return;
576
577     BOOL success = [self lockgl];
578     if (!success)
579         return;
580
581     [self render];
582
583     [self unlockgl];
584 }
585
586 - (void)renewGState
587 {
588     NSWindow *window = [self window];
589
590     // Remove flashes with splitter view.
591         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
592                 [window disableScreenUpdatesUntilFlush];
593
594     [super renewGState];
595 }
596
597 - (BOOL)mouseDownCanMoveWindow
598 {
599     return YES;
600 }
601
602 - (BOOL)isOpaque
603 {
604     return YES;
605 }
606 @end