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