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