]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
ios2: clean opengl buffers only in active state
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * macosx.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8  *          Eric Petit <titer@m0k.org>
9  *          Benjamin Pracht <bigben at videolan dot org>
10  *          Damien Fouilleul <damienf at videolan dot org>
11  *          Pierre d'Herbemont <pdherbemont at videolan dot org>
12  *          Felix Paul Kühne <fkuehne at videolan dot org>
13  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
14  *          Rémi Denis-Courmont
15  *          Juho Vähä-Herttua <juhovh at iki dot fi>
16  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
17  *
18  * This program is free software; you can redistribute it and/or modify it
19  * under the terms of the GNU Lesser General Public License as published by
20  * the Free Software Foundation; either version 2.1 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU Lesser General Public License for more details.
27  *
28  * You should have received a copy of the GNU Lesser General Public License
29  * along with this program; if not, write to the Free Software Foundation,
30  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
31  *****************************************************************************/
32
33 /*****************************************************************************
34  * Preamble
35  *****************************************************************************/
36
37 #import <Cocoa/Cocoa.h>
38 #import <OpenGL/OpenGL.h>
39 #import <dlfcn.h>
40
41 #ifdef HAVE_CONFIG_H
42 # include "config.h"
43 #endif
44
45 #include <vlc_common.h>
46 #include <vlc_plugin.h>
47 #include <vlc_vout_display.h>
48 #include <vlc_opengl.h>
49 #include <vlc_dialog.h>
50 #include "opengl.h"
51
52 /* compilation support for 10.5 and 10.6 */
53 #define OSX_LION NSAppKitVersionNumber >= 1115.2
54 #ifndef MAC_OS_X_VERSION_10_7
55
56 @interface NSView (IntroducedInLion)
57 - (NSRect)convertRectToBacking:(NSRect)aRect;
58 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
59 @end
60
61 #endif
62
63 /**
64  * Forward declarations
65  */
66 static int Open (vlc_object_t *);
67 static void Close (vlc_object_t *);
68
69 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
70 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
71 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
72 static int Control (vout_display_t *vd, int query, va_list ap);
73
74 static void *OurGetProcAddress(vlc_gl_t *, const char *);
75
76 static int OpenglLock (vlc_gl_t *gl);
77 static void OpenglUnlock (vlc_gl_t *gl);
78 static void OpenglSwap (vlc_gl_t *gl);
79
80 /**
81  * Module declaration
82  */
83 vlc_module_begin ()
84     /* Will be loaded even without interface module. see voutgl.m */
85     set_shortname ("Mac OS X")
86     set_description (N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
87     set_category (CAT_VIDEO)
88     set_subcategory (SUBCAT_VIDEO_VOUT)
89     set_capability ("vout display", 300)
90     set_callbacks (Open, Close)
91
92     add_shortcut ("macosx", "vout_macosx")
93 vlc_module_end ()
94
95 /**
96  * Obj-C protocol declaration that drawable-nsobject should follow
97  */
98 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
99 - (void)addVoutSubview:(NSView *)view;
100 - (void)removeVoutSubview:(NSView *)view;
101 @end
102
103 @interface VLCOpenGLVideoView : NSOpenGLView
104 {
105     vout_display_t *vd;
106     BOOL _hasPendingReshape;
107 }
108 - (void)setVoutDisplay:(vout_display_t *)vd;
109 - (void)setVoutFlushing:(BOOL)flushing;
110 @end
111
112
113 struct vout_display_sys_t
114 {
115     VLCOpenGLVideoView *glView;
116     id<VLCOpenGLVideoViewEmbedding> container;
117
118     vout_window_t *embed;
119     vlc_gl_t gl;
120     vout_display_opengl_t *vgl;
121
122     picture_pool_t *pool;
123     picture_t *current;
124     bool has_first_frame;
125
126     vout_display_place_t place;
127 };
128
129
130 static void *OurGetProcAddress(vlc_gl_t *gl, const char *name)
131 {
132     VLC_UNUSED(gl);
133
134     return dlsym(RTLD_DEFAULT, name);
135 }
136
137 static int Open (vlc_object_t *this)
138 {
139     vout_display_t *vd = (vout_display_t *)this;
140     vout_display_sys_t *sys = calloc (1, sizeof(*sys));
141     NSAutoreleasePool *nsPool = nil;
142
143     if (!sys)
144         return VLC_ENOMEM;
145
146     if (!CGDisplayUsesOpenGLAcceleration (kCGDirectMainDisplay)) {
147         msg_Err (this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results");
148         dialog_Fatal (this, _("OpenGL acceleration is not supported on your Mac"), _("Your Mac lacks Quartz Extreme acceleration, which is required for video output. It will still work, but much slower and with possibly unexpected results."));
149     } else
150         msg_Dbg (this, "Quartz Extreme acceleration is active");
151
152     vd->sys = sys;
153     sys->pool = NULL;
154     sys->gl.sys = NULL;
155     sys->embed = NULL;
156
157     /* Get the drawable object */
158     id container = var_CreateGetAddress (vd, "drawable-nsobject");
159     if (container)
160         vout_display_DeleteWindow (vd, NULL);
161     else {
162         vout_window_cfg_t wnd_cfg;
163
164         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
165         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
166         wnd_cfg.x = var_InheritInteger (vd, "video-x");
167         wnd_cfg.y = var_InheritInteger (vd, "video-y");
168         wnd_cfg.width  = vd->cfg->display.width;
169         wnd_cfg.height = vd->cfg->display.height;
170
171         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
172         if (sys->embed)
173             container = sys->embed->handle.nsobject;
174
175         if (!container) {
176             msg_Err(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
177             goto error;
178         }
179     }
180
181     /* This will be released in Close(), on
182      * main thread, after we are done using it. */
183     sys->container = [container retain];
184
185     /* Get our main view*/
186     nsPool = [[NSAutoreleasePool alloc] init];
187
188     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
189     if (!sys->glView)
190         goto error;
191
192     [sys->glView setVoutDisplay:vd];
193
194     /* We don't wait, that means that we'll have to be careful about releasing
195      * container.
196      * That's why we'll release on main thread in Close(). */
197     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
198         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
199     else if ([container isKindOfClass:[NSView class]]) {
200         NSView *parentView = container;
201         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
202         [sys->glView performSelectorOnMainThread:@selector(setFrameToBoundsOfView:) withObject:[NSValue valueWithPointer:parentView] waitUntilDone:NO];
203     } else {
204         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
205         goto error;
206     }
207
208
209     [nsPool release];
210     nsPool = nil;
211
212     /* Initialize common OpenGL video display */
213     sys->gl.lock = OpenglLock;
214     sys->gl.unlock = OpenglUnlock;
215     sys->gl.swap = OpenglSwap;
216     sys->gl.getProcAddress = OurGetProcAddress;
217     sys->gl.sys = sys;
218     const vlc_fourcc_t *subpicture_chromas;
219     video_format_t fmt = vd->fmt;
220
221     sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
222     if (!sys->vgl) {
223         msg_Err(vd, "Error while initializing opengl display.");
224         sys->gl.sys = NULL;
225         goto error;
226     }
227
228     /* */
229     vout_display_info_t info = vd->info;
230     info.has_pictures_invalid = false;
231     info.has_event_thread = true;
232     info.subpicture_chromas = subpicture_chromas;
233     info.has_hide_mouse = true;
234
235     /* Setup vout_display_t once everything is fine */
236     vd->info = info;
237
238     vd->pool = Pool;
239     vd->prepare = PictureRender;
240     vd->display = PictureDisplay;
241     vd->control = Control;
242
243     /* */
244     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
245
246     return VLC_SUCCESS;
247
248 error:
249     [nsPool release];
250     Close(this);
251     return VLC_EGENERIC;
252 }
253
254 void Close (vlc_object_t *this)
255 {
256     vout_display_t *vd = (vout_display_t *)this;
257     vout_display_sys_t *sys = vd->sys;
258
259     [sys->glView setVoutDisplay:nil];
260
261     var_Destroy (vd, "drawable-nsobject");
262     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
263         /* This will retain sys->glView */
264         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
265
266     /* release on main thread as explained in Open() */
267     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
268     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
269
270     if (sys->gl.sys != NULL)
271         vout_display_opengl_Delete (sys->vgl);
272
273     [sys->glView release];
274
275     if (sys->embed)
276         vout_display_DeleteWindow (vd, sys->embed);
277     free (sys);
278 }
279
280 /*****************************************************************************
281  * vout display callbacks
282  *****************************************************************************/
283
284 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
285 {
286     vout_display_sys_t *sys = vd->sys;
287
288     if (!sys->pool)
289         sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
290     assert(sys->pool);
291     return sys->pool;
292 }
293
294 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
295 {
296
297     vout_display_sys_t *sys = vd->sys;
298
299     vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
300 }
301
302 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
303 {
304     vout_display_sys_t *sys = vd->sys;
305     [sys->glView setVoutFlushing:YES];
306     vout_display_opengl_Display (sys->vgl, &vd->source);
307     [sys->glView setVoutFlushing:NO];
308     picture_Release (pic);
309     sys->has_first_frame = true;
310
311     if (subpicture)
312         subpicture_Delete(subpicture);
313 }
314
315 static int Control (vout_display_t *vd, int query, va_list ap)
316 {
317     vout_display_sys_t *sys = vd->sys;
318
319     if (!vd->sys)
320         return VLC_EGENERIC;
321
322     if (!sys->embed)
323         return VLC_EGENERIC;
324
325     switch (query)
326     {
327         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
328         {
329             const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
330             if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
331                 return VLC_EGENERIC;
332
333             return VLC_SUCCESS;
334         }
335         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
336         {
337             unsigned state = va_arg (ap, unsigned);
338             return vout_window_SetState (sys->embed, state);            
339         }
340         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
341         case VOUT_DISPLAY_CHANGE_ZOOM:
342         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
343         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
344         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
345         {
346             NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
347
348             id o_window = [sys->glView window];
349             if (!o_window) {
350                 [o_pool release];
351                 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
352             }
353
354             NSSize windowMinSize = [o_window minSize];
355
356             const vout_display_cfg_t *cfg;
357             const video_format_t *source;
358             bool is_forced = false;
359
360             if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP) {
361                 source = (const video_format_t *)va_arg (ap, const video_format_t *);
362                 cfg = vd->cfg;
363             } else {
364                 source = &vd->source;
365                 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
366                 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
367                     is_forced = (bool)va_arg (ap, int);
368             }
369
370             if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
371                 && (cfg->display.width != vd->cfg->display.width
372                     || cfg->display.height != vd->cfg->display.height)
373                 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height)) {
374                 [o_pool release];
375                 return VLC_EGENERIC;
376             }
377  
378             /* we always use our current frame here, because we have some size constraints
379                in the ui vout provider */
380             vout_display_cfg_t cfg_tmp = *cfg;
381             NSRect bounds;
382             /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
383             if (OSX_LION)
384                 bounds = [sys->glView convertRectToBacking:[sys->glView bounds]];
385             else
386                 bounds = [sys->glView bounds];
387             cfg_tmp.display.width = bounds.size.width;
388             cfg_tmp.display.height = bounds.size.height;
389
390             vout_display_place_t place;
391             vout_display_PlacePicture (&place, source, &cfg_tmp, false);
392             @synchronized (sys->glView) {
393                 sys->place = place;
394             }
395
396             /* For resize, we call glViewport in reshape and not here.
397                This has the positive side effect that we avoid erratic sizing as we animate every resize. */
398             if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
399                 // x / y are top left corner, but we need the lower left one
400                 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
401
402
403             [o_pool release];
404             return VLC_SUCCESS;
405         }
406
407         case VOUT_DISPLAY_HIDE_MOUSE:
408         {
409             [NSCursor setHiddenUntilMouseMoves: YES];
410             return VLC_SUCCESS;
411         }
412
413         case VOUT_DISPLAY_GET_OPENGL:
414         {
415             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
416             *gl = &sys->gl;
417             return VLC_SUCCESS;
418         }
419
420         case VOUT_DISPLAY_RESET_PICTURES:
421             assert (0);
422         default:
423             msg_Err (vd, "Unknown request in Mac OS X vout display");
424             return VLC_EGENERIC;
425     }
426 }
427
428 /*****************************************************************************
429  * vout opengl callbacks
430  *****************************************************************************/
431 static int OpenglLock (vlc_gl_t *gl)
432 {
433     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
434     if (!sys->glView || ![sys->glView respondsToSelector:@selector(openGLContext)])
435         return 1;
436
437     NSOpenGLContext *context = [sys->glView openGLContext];
438     CGLError err = CGLLockContext ([context CGLContextObj]);
439     if (kCGLNoError == err) {
440         [context makeCurrentContext];
441         return 0;
442     }
443     return 1;
444 }
445
446 static void OpenglUnlock (vlc_gl_t *gl)
447 {
448     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
449     CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
450 }
451
452 static void OpenglSwap (vlc_gl_t *gl)
453 {
454     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
455     [[sys->glView openGLContext] flushBuffer];
456 }
457
458 /*****************************************************************************
459  * Our NSView object
460  *****************************************************************************/
461 @implementation VLCOpenGLVideoView
462
463 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
464
465
466 + (void)getNewView:(NSValue *)value
467 {
468     id *ret = [value pointerValue];
469     *ret = [[self alloc] init];
470 }
471
472 /**
473  * Gets called by the Open() method.
474  */
475 - (id)init
476 {
477     VLCAssertMainThread();
478
479     /* Warning - this may be called on non main thread */
480
481     NSOpenGLPixelFormatAttribute attribs[] =
482     {
483         NSOpenGLPFADoubleBuffer,
484         NSOpenGLPFAAccelerated,
485         NSOpenGLPFANoRecovery,
486         NSOpenGLPFAColorSize, 24,
487         NSOpenGLPFAAlphaSize, 8,
488         NSOpenGLPFADepthSize, 24,
489         NSOpenGLPFAWindow,
490         NSOpenGLPFAAllowOfflineRenderers,
491         0
492     };
493
494     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
495
496     if (!fmt)
497         return nil;
498
499     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
500     [fmt release];
501
502     if (!self)
503         return nil;
504
505     /* enable HiDPI support on OS X 10.7 and later */
506     if (OSX_LION)
507         [self setWantsBestResolutionOpenGLSurface:YES];
508
509     /* Swap buffers only during the vertical retrace of the monitor.
510      http://developer.apple.com/documentation/GraphicsImaging/
511      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
512     GLint params[] = { 1 };
513     CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
514
515     [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidChangeScreenParametersNotification
516                                                       object:[NSApplication sharedApplication]
517                                                        queue:nil
518                                                   usingBlock:^(NSNotification *notification) {
519                                                       [self performSelectorOnMainThread:@selector(reshape)
520                                                                              withObject:nil
521                                                                           waitUntilDone:NO];
522                                                   }];
523
524     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
525     return self;
526 }
527
528 - (void)dealloc
529 {
530     [[NSNotificationCenter defaultCenter] removeObserver:self];
531     [super dealloc];
532 }
533
534 /**
535  * Gets called by the Open() method.
536  */
537 - (void)setFrameToBoundsOfView:(NSValue *)value
538 {
539     NSView *parentView = [value pointerValue];
540     [self setFrame:[parentView bounds]];
541 }
542
543 /**
544  * Gets called by the Close and Open methods.
545  * (Non main thread).
546  */
547 - (void)setVoutDisplay:(vout_display_t *)aVd
548 {
549     @synchronized(self) {
550         vd = aVd;
551     }
552 }
553
554 /**
555  * Gets called when the vout will aquire the lock and flush.
556  * (Non main thread).
557  */
558 - (void)setVoutFlushing:(BOOL)flushing
559 {
560     if (!flushing)
561         return;
562     @synchronized(self) {
563         _hasPendingReshape = NO;
564     }
565 }
566
567 /**
568  * Can -drawRect skip rendering?.
569  */
570 - (BOOL)canSkipRendering
571 {
572     VLCAssertMainThread();
573
574     @synchronized(self) {
575         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
576         return !_hasPendingReshape && hasFirstFrame;
577     }
578 }
579
580
581 /**
582  * Local method that locks the gl context.
583  */
584 - (BOOL)lockgl
585 {
586     VLCAssertMainThread();
587     NSOpenGLContext *context = [self openGLContext];
588     CGLError err = CGLLockContext ([context CGLContextObj]);
589     if (err == kCGLNoError)
590         [context makeCurrentContext];
591     return err == kCGLNoError;
592 }
593
594 /**
595  * Local method that unlocks the gl context.
596  */
597 - (void)unlockgl
598 {
599     VLCAssertMainThread();
600     CGLUnlockContext ([[self openGLContext] CGLContextObj]);
601 }
602
603 /**
604  * Local method that force a rendering of a frame.
605  * This will get called if Cocoa forces us to redraw (via -drawRect).
606  */
607 - (void)render
608 {
609     VLCAssertMainThread();
610
611     // We may have taken some times to take the opengl Lock.
612     // Check here to see if we can just skip the frame as well.
613     if ([self canSkipRendering])
614         return;
615
616     BOOL hasFirstFrame;
617     @synchronized(self) { // vd can be accessed from multiple threads
618         hasFirstFrame = vd && vd->sys->has_first_frame;
619     }
620
621     if (hasFirstFrame)
622         // This will lock gl.
623         vout_display_opengl_Display (vd->sys->vgl, &vd->source);
624     else
625         glClear (GL_COLOR_BUFFER_BIT);
626 }
627
628 /**
629  * Method called by Cocoa when the view is resized.
630  */
631 - (void)reshape
632 {
633     VLCAssertMainThread();
634
635     NSRect bounds;
636     /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
637     if (OSX_LION)
638         bounds = [self convertRectToBacking:[self bounds]];
639     else
640         bounds = [self bounds];
641     vout_display_place_t place;
642     
643     @synchronized(self) {
644         if (vd) {
645             vout_display_cfg_t cfg_tmp = *(vd->cfg);
646             cfg_tmp.display.width  = bounds.size.width;
647             cfg_tmp.display.height = bounds.size.height;
648
649             vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
650             vd->sys->place = place;
651             vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
652         }
653     }
654
655     if ([self lockgl]) {
656         // x / y are top left corner, but we need the lower left one
657         glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
658
659         @synchronized(self) {
660             // This may be cleared before -drawRect is being called,
661             // in this case we'll skip the rendering.
662             // This will save us for rendering two frames (or more) for nothing
663             // (one by the vout, one (or more) by drawRect)
664             _hasPendingReshape = YES;
665         }
666
667         [self unlockgl];
668
669         [super reshape];
670     }
671 }
672
673 /**
674  * Method called by Cocoa when the view is resized or the location has changed.
675  * We just need to make sure we are locking here.
676  */
677 - (void)update
678 {
679     VLCAssertMainThread();
680     BOOL success = [self lockgl];
681     if (!success)
682         return;
683
684     [super update];
685
686     [self unlockgl];
687 }
688
689 /**
690  * Method called by Cocoa to force redraw.
691  */
692 - (void)drawRect:(NSRect) rect
693 {
694     VLCAssertMainThread();
695
696     if ([self canSkipRendering])
697         return;
698
699     BOOL success = [self lockgl];
700     if (!success)
701         return;
702
703     [self render];
704
705     [self unlockgl];
706 }
707
708 - (void)renewGState
709 {
710     NSWindow *window = [self window];
711
712     // Remove flashes with splitter view.
713     if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
714         [window disableScreenUpdatesUntilFlush];
715
716     [super renewGState];
717 }
718
719 - (BOOL)isOpaque
720 {
721     return YES;
722 }
723
724 #pragma mark -
725 #pragma mark Mouse handling
726
727 - (void)mouseDown:(NSEvent *)o_event
728 {
729     @synchronized (self) {
730         if (vd) {
731             if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] &  NSControlKeyMask)) {
732                 if ([o_event clickCount] <= 1)
733                     vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
734             }
735         }
736     }
737
738     [super mouseDown:o_event];
739 }
740
741 - (void)otherMouseDown:(NSEvent *)o_event
742 {
743     @synchronized (self) {
744         if (vd)
745             vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
746     }
747
748     [super otherMouseDown: o_event];
749 }
750
751 - (void)mouseUp:(NSEvent *)o_event
752 {
753     @synchronized (self) {
754         if (vd) {
755             if ([o_event type] == NSLeftMouseUp)
756                 vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
757         }
758     }
759
760     [super mouseUp: o_event];
761 }
762
763 - (void)otherMouseUp:(NSEvent *)o_event
764 {
765     @synchronized (self) {
766         if (vd)
767             vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
768     }
769
770     [super otherMouseUp: o_event];
771 }
772
773 - (void)mouseMoved:(NSEvent *)o_event
774 {
775     NSPoint ml;
776     NSRect s_rect;
777     BOOL b_inside;
778
779     /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
780     if (OSX_LION)
781         s_rect = [self convertRectToBacking:[self bounds]];
782     else
783         s_rect = [self bounds];
784     ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
785     b_inside = [self mouse: ml inRect: s_rect];
786     
787     if (b_inside) {
788         @synchronized (self) {
789             if (vd) {
790                 vout_display_place_t place = vd->sys->place;
791
792                 if (place.width > 0 && place.height > 0) {
793                     const int x = vd->source.i_x_offset +
794                     (int64_t)(ml.x - place.x) * vd->source.i_visible_width / place.width;
795                     const int y = vd->source.i_y_offset +
796                     (int64_t)((int)s_rect.size.height - (int)ml.y - place.y) * vd->source.i_visible_height / place.height;
797
798                     vout_display_SendEventMouseMoved (vd, x, y);
799                 }
800             }
801         }
802     }
803
804     [super mouseMoved: o_event];
805 }
806
807 - (void)mouseDragged:(NSEvent *)o_event
808 {
809     [self mouseMoved: o_event];
810     [super mouseDragged: o_event];
811 }
812
813 - (void)otherMouseDragged:(NSEvent *)o_event
814 {
815     [self mouseMoved: o_event];
816     [super otherMouseDragged: o_event];
817 }
818
819 - (void)rightMouseDragged:(NSEvent *)o_event
820 {
821     [self mouseMoved: o_event];
822     [super rightMouseDragged: o_event];
823 }
824
825 - (BOOL)acceptsFirstResponder
826 {
827     return YES;
828 }
829
830 - (BOOL)mouseDownCanMoveWindow
831 {
832     return YES;
833 }
834
835 @end