]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
macosx: implemented the 'autoscale' feature and fixed some resizing bugs
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * voutgl.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2011 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 "opengl.h"
48
49 /**
50  * Forward declarations
51  */
52 static int Open(vlc_object_t *);
53 static void Close(vlc_object_t *);
54
55 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count);
56 static void PictureRender(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
57 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
58 static int Control (vout_display_t *vd, int query, va_list ap);
59
60 static int OpenglLock(vlc_gl_t *gl);
61 static void OpenglUnlock(vlc_gl_t *gl);
62 static void OpenglSwap(vlc_gl_t *gl);
63
64 /**
65  * Module declaration
66  */
67 vlc_module_begin ()
68     /* Will be loaded even without interface module. see voutgl.m */
69     set_shortname("Mac OS X")
70     set_description( N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
71     set_category(CAT_VIDEO)
72     set_subcategory(SUBCAT_VIDEO_VOUT )
73     set_capability("vout display", 300)
74     set_callbacks(Open, Close)
75
76     add_shortcut("macosx", "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_window_t *embed;
103     vlc_gl_t gl;
104     vout_display_opengl_t *vgl;
105
106     picture_pool_t *pool;
107     picture_t *current;
108     bool has_first_frame;
109 };
110
111 static int Open(vlc_object_t *this)
112 {
113     vout_display_t *vd = (vout_display_t *)this;
114     vout_display_sys_t *sys = calloc(1, sizeof(*sys));
115     NSAutoreleasePool *nsPool = nil;
116
117     if (!sys)
118         return VLC_ENOMEM;
119
120     vd->sys = sys;
121     sys->pool = NULL;
122     sys->gl.sys = NULL;
123     sys->embed = NULL;
124
125     /* Get the drawable object */
126     id container = var_CreateGetAddress(vd, "drawable-nsobject");
127     if (container)
128     {
129         vout_display_DeleteWindow(vd, NULL);
130     }
131     else
132     {
133         vout_window_cfg_t wnd_cfg;
134
135         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
136         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
137         wnd_cfg.x = var_InheritInteger (vd, "video-x");
138         wnd_cfg.y = var_InheritInteger (vd, "video-y");
139         wnd_cfg.width  = vd->cfg->display.width;
140         wnd_cfg.height = vd->cfg->display.height;
141
142         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
143         if (sys->embed)
144             container = sys->embed->handle.nsobject;
145
146         if (!container)
147         {
148             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
149             goto error;
150         }
151     }
152
153     /* This will be released in Close(), on
154      * main thread, after we are done using it. */
155     sys->container = [container retain];
156
157     /* Get our main view*/
158     nsPool = [[NSAutoreleasePool alloc] init];
159
160     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
161     if (!sys->glView)
162         goto error;
163
164     [sys->glView setVoutDisplay:vd];
165
166     /* We don't wait, that means that we'll have to be careful about releasing
167      * container.
168      * That's why we'll release on main thread in Close(). */
169     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
170         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
171     else if ([container isKindOfClass:[NSView class]])
172     {
173         NSView *parentView = container;
174         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
175         [sys->glView performSelectorOnMainThread:@selector(setFrameWithValue:) withObject:[NSValue valueWithRect:[parentView bounds]] waitUntilDone:NO];
176     }
177     else
178     {
179         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
180         goto error;
181     }
182
183
184     [nsPool release];
185     nsPool = nil;
186
187     /* Initialize common OpenGL video display */
188     sys->gl.lock = OpenglLock;
189     sys->gl.unlock = OpenglUnlock;
190     sys->gl.swap = OpenglSwap;
191     sys->gl.getProcAddress = NULL;
192     sys->gl.sys = sys;
193
194         sys->vgl = vout_display_opengl_New(&vd->fmt, NULL, &sys->gl);
195         if (!sys->vgl)
196     {
197         sys->gl.sys = NULL;
198         goto error;
199     }
200
201     /* */
202     vout_display_info_t info = vd->info;
203     info.has_pictures_invalid = false;
204
205     /* Setup vout_display_t once everything is fine */
206     vd->info = info;
207
208     vd->pool = Pool;
209     vd->prepare = PictureRender;
210     vd->display = PictureDisplay;
211     vd->control = Control;
212
213     /* */
214     vout_display_SendEventFullscreen (vd, false);
215     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
216
217     return VLC_SUCCESS;
218
219 error:
220     [nsPool release];
221     Close(this);
222     return VLC_EGENERIC;
223 }
224
225 void Close(vlc_object_t *this)
226 {
227     vout_display_t *vd = (vout_display_t *)this;
228     vout_display_sys_t *sys = vd->sys;
229
230     [sys->glView setVoutDisplay:nil];
231
232     var_Destroy(vd, "drawable-nsobject");
233     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
234     {
235         /* This will retain sys->glView */
236         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
237     }
238     /* release on main thread as explained in Open() */
239     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
240     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
241
242     [sys->glView release];
243
244     if (sys->gl.sys != NULL)
245         vout_display_opengl_Delete(sys->vgl);
246
247     if (sys->embed)
248         vout_display_DeleteWindow(vd, sys->embed);
249     free (sys);
250 }
251
252 /*****************************************************************************
253  * vout display callbacks
254  *****************************************************************************/
255
256 static picture_pool_t *Pool(vout_display_t *vd, unsigned requested_count)
257 {
258     vout_display_sys_t *sys = vd->sys;
259
260     if (!sys->pool)
261         sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
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, subpicture );
272 }
273
274 static void PictureDisplay(vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
275 {
276     vout_display_sys_t *sys = vd->sys;
277     [sys->glView setVoutFlushing:YES];
278     vout_display_opengl_Display(sys->vgl, &vd->fmt );
279     [sys->glView setVoutFlushing:NO];
280     picture_Release (pic);
281     sys->has_first_frame = true;
282         (void)subpicture;
283 }
284
285 static int Control (vout_display_t *vd, int query, va_list ap)
286 {
287     vout_display_sys_t *sys = vd->sys;
288
289     switch (query)
290     {
291         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
292         {
293             /* todo */
294             return VLC_EGENERIC;
295         }
296         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
297         {
298             unsigned state = va_arg (ap, unsigned);
299             if( (state & VOUT_WINDOW_STATE_ABOVE) != 0)
300                 [[sys->glView window] setLevel: NSStatusWindowLevel];
301             else
302                 [[sys->glView window] setLevel: NSNormalWindowLevel];
303             return VLC_SUCCESS;
304         }
305         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
306         {
307             [[sys->glView window] performZoom: nil];
308             return VLC_SUCCESS;
309         }
310         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
311         case VOUT_DISPLAY_CHANGE_ZOOM:
312         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
313         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
314         {
315             NSPoint topleftbase;
316             NSPoint topleftscreen;
317             NSRect new_frame;
318             const vout_display_cfg_t *cfg;
319
320             id o_window = [sys->glView window];
321             NSRect windowFrame = [o_window frame];
322             NSRect glViewFrame = [sys->glView frame];
323             NSSize windowMinSize = [o_window minSize];
324
325             topleftbase.x = 0;
326             topleftbase.y = windowFrame.size.height;
327             topleftscreen = [o_window convertBaseToScreen: topleftbase];
328             cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
329             int i_width = cfg->display.width;
330             int i_height = cfg->display.height;
331
332             /* Calculate the window's new size, if it is larger than our minimal size */
333             if (i_width < windowMinSize.width)
334                 i_width = windowMinSize.width;
335             if (i_height < windowMinSize.height)
336                 i_height = windowMinSize.height;
337
338             if( i_height != glViewFrame.size.height || i_width != glViewFrame.size.width )
339             {
340                 new_frame.size.width = windowFrame.size.width - glViewFrame.size.width + i_width;
341                 new_frame.size.height = windowFrame.size.height - glViewFrame.size.height + i_height;
342
343                 new_frame.origin.x = topleftscreen.x;
344                 new_frame.origin.y = topleftscreen.y - new_frame.size.height;
345
346                 [o_window setFrame:new_frame display:YES animate:YES];
347             }
348             return VLC_SUCCESS;
349         }
350
351         case VOUT_DISPLAY_HIDE_MOUSE:
352         {
353             [NSCursor setHiddenUntilMouseMoves: YES];
354             return VLC_SUCCESS;
355         }
356
357         case VOUT_DISPLAY_GET_OPENGL:
358         {
359             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
360             *gl = &sys->gl;
361             return VLC_SUCCESS;
362         }
363
364         case VOUT_DISPLAY_RESET_PICTURES:
365             assert (0);
366         default:
367             msg_Err (vd, "Unknown request in Mac OS X vout display");
368             return VLC_EGENERIC;
369     }
370 }
371
372 /*****************************************************************************
373  * vout opengl callbacks
374  *****************************************************************************/
375 static int OpenglLock(vlc_gl_t *gl)
376 {
377     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
378     NSOpenGLContext *context = [sys->glView openGLContext];
379     CGLError err = CGLLockContext([context CGLContextObj]);
380     if (kCGLNoError == err)
381     {
382         [context makeCurrentContext];
383         return 0;
384     }
385     return 1;
386 }
387
388 static void OpenglUnlock(vlc_gl_t *gl)
389 {
390     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
391     CGLUnlockContext([[sys->glView openGLContext] CGLContextObj]);
392 }
393
394 static void OpenglSwap(vlc_gl_t *gl)
395 {
396     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
397     [[sys->glView openGLContext] flushBuffer];
398 }
399
400 /*****************************************************************************
401  * Our NSView object
402  *****************************************************************************/
403 @implementation VLCOpenGLVideoView
404
405 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
406
407 + (void)getNewView:(NSValue *)value
408 {
409     id *ret = [value pointerValue];
410     *ret = [[self alloc] init];
411 }
412
413 /**
414  * Gets called by the Open() method.
415  */
416 - (id)init
417 {
418     VLCAssertMainThread();
419
420     /* Warning - this may be called on non main thread */
421
422     NSOpenGLPixelFormatAttribute attribs[] =
423     {
424         NSOpenGLPFADoubleBuffer,
425         NSOpenGLPFAAccelerated,
426         NSOpenGLPFANoRecovery,
427         NSOpenGLPFAColorSize, 24,
428         NSOpenGLPFAAlphaSize, 8,
429         NSOpenGLPFADepthSize, 24,
430         NSOpenGLPFAWindow,
431         0
432     };
433
434     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
435
436     if (!fmt)
437         return nil;
438
439     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
440     [fmt release];
441
442     if (!self)
443         return nil;
444
445     /* Swap buffers only during the vertical retrace of the monitor.
446      http://developer.apple.com/documentation/GraphicsImaging/
447      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
448     GLint params[] = { 1 };
449     CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
450
451     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
452     return self;
453 }
454
455 /**
456  * Gets called by the Open() method.
457  */
458 - (void)setFrameWithValue:(NSValue *)value
459 {
460     [self setFrame:[value rectValue]];
461 }
462
463 /**
464  * Gets called by the Close and Open methods.
465  * (Non main thread).
466  */
467 - (void)setVoutDisplay:(vout_display_t *)aVd
468 {
469     @synchronized(self) {
470         vd = aVd;
471     }
472 }
473
474
475 /**
476  * Gets called when the vout will aquire the lock and flush.
477  * (Non main thread).
478  */
479 - (void)setVoutFlushing:(BOOL)flushing
480 {
481     if (!flushing)
482         return;
483     @synchronized(self) {
484         _hasPendingReshape = NO;
485     }
486 }
487
488 /**
489  * Can -drawRect skip rendering?.
490  */
491 - (BOOL)canSkipRendering
492 {
493     VLCAssertMainThread();
494
495     @synchronized(self) {
496         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
497         return !_hasPendingReshape && hasFirstFrame;
498     }
499 }
500
501
502 /**
503  * Local method that locks the gl context.
504  */
505 - (BOOL)lockgl
506 {
507     VLCAssertMainThread();
508     NSOpenGLContext *context = [self openGLContext];
509     CGLError err = CGLLockContext([context CGLContextObj]);
510     if (err == kCGLNoError)
511         [context makeCurrentContext];
512     return err == kCGLNoError;
513 }
514
515 /**
516  * Local method that unlocks the gl context.
517  */
518 - (void)unlockgl
519 {
520     VLCAssertMainThread();
521     CGLUnlockContext([[self openGLContext] CGLContextObj]);
522 }
523
524 /**
525  * Local method that force a rendering of a frame.
526  * This will get called if Cocoa forces us to redraw (via -drawRect).
527  */
528 - (void)render
529 {
530     VLCAssertMainThread();
531
532     // We may have taken some times to take the opengl Lock.
533     // Check here to see if we can just skip the frame as well.
534     if ([self canSkipRendering])
535         return;
536
537     BOOL hasFirstFrame;
538     @synchronized(self) { // vd can be accessed from multiple threads
539         hasFirstFrame = vd && vd->sys->has_first_frame;
540     }
541
542     if (hasFirstFrame) {
543         // This will lock gl.
544         vout_display_opengl_Display( vd->sys->vgl, &vd->source );
545     }
546     else
547         glClear(GL_COLOR_BUFFER_BIT);
548 }
549
550 /**
551  * Method called by Cocoa when the view is resized.
552  */
553 - (void)reshape
554 {
555     VLCAssertMainThread();
556
557     NSRect bounds = [self bounds];
558
559     CGFloat height = bounds.size.height;
560     CGFloat width = bounds.size.width;
561
562     GLint x = width, y = height;
563
564     @synchronized(self) {
565         if (vd) {
566             CGFloat videoHeight = vd->source.i_visible_height;
567             CGFloat videoWidth = vd->source.i_visible_width;
568
569             GLint sarNum = vd->source.i_sar_num;
570             GLint sarDen = vd->source.i_sar_den;
571
572             if (height * videoWidth * sarNum < width * videoHeight * sarDen)
573             {
574                 x = (height * videoWidth * sarNum) / (videoHeight * sarDen);
575                 y = height;
576             }
577             else
578             {
579                 x = width;
580                 y = (width * videoHeight * sarDen) / (videoWidth * sarNum);
581             }
582         }
583     }
584
585     if ([self lockgl]) {
586         glViewport((width - x) / 2, (height - y) / 2, x, y);
587
588         @synchronized(self) {
589             // This may be cleared before -drawRect is being called,
590             // in this case we'll skip the rendering.
591             // This will save us for rendering two frames (or more) for nothing
592             // (one by the vout, one (or more) by drawRect)
593             _hasPendingReshape = YES;
594         }
595
596         [self unlockgl];
597
598         [super reshape];
599     }
600 }
601
602 /**
603  * Method called by Cocoa when the view is resized or the location has changed.
604  * We just need to make sure we are locking here.
605  */
606 - (void)update
607 {
608     VLCAssertMainThread();
609     BOOL success = [self lockgl];
610     if (!success)
611         return;
612
613     [super update];
614
615     [self unlockgl];
616 }
617
618 /**
619  * Method called by Cocoa to force redraw.
620  */
621 - (void)drawRect:(NSRect) rect
622 {
623     VLCAssertMainThread();
624
625     if ([self canSkipRendering])
626         return;
627
628     BOOL success = [self lockgl];
629     if (!success)
630         return;
631
632     [self render];
633
634     [self unlockgl];
635 }
636
637 - (void)renewGState
638 {
639     NSWindow *window = [self window];
640
641     // Remove flashes with splitter view.
642         if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
643                 [window disableScreenUpdatesUntilFlush];
644
645     [super renewGState];
646 }
647
648 - (BOOL)mouseDownCanMoveWindow
649 {
650     return YES;
651 }
652
653 - (BOOL)isOpaque
654 {
655     return YES;
656 }
657 @end