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