]> git.sesse.net Git - vlc/blob - modules/video_output/caopengllayer.m
hotkeys: use "zoom" rather than "scale" (like the GUI do)
[vlc] / modules / video_output / caopengllayer.m
1 /*****************************************************************************
2  * caopengllayer.m: CAOpenGLLayer (Mac OS X) video output
3  *****************************************************************************
4  * Copyright (C) 2014 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: David Fuhrmann <david dot fuhrmann at googlemail dot com>
8  *          Felix Paul Kühne <fkuehne at videolan dot org>
9  *          Pierre d'Herbemont <pdherbemont at videolan dot org>
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_vout_display.h>
37 #include <vlc_opengl.h>
38
39 #import <QuartzCore/QuartzCore.h>
40 #import <Cocoa/Cocoa.h>
41 #import <OpenGL/OpenGL.h>
42 #import <dlfcn.h>               /* dlsym */
43
44 #include "opengl.h"
45
46 /*****************************************************************************
47  * Vout interface
48  *****************************************************************************/
49 static int  Open   (vlc_object_t *);
50 static void Close  (vlc_object_t *);
51
52 vlc_module_begin()
53     set_description(N_("Core Animation OpenGL Layer (Mac OS X)"))
54     set_capability("vout display", 0)
55     set_category(CAT_VIDEO)
56     set_subcategory(SUBCAT_VIDEO_VOUT)
57     set_callbacks(Open, Close)
58 vlc_module_end()
59
60
61 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
62 static void PictureRender   (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
63 static void PictureDisplay  (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
64 static int Control          (vout_display_t *vd, int query, va_list ap);
65
66 static void *OurGetProcAddress (vlc_gl_t *gl, const char *name);
67 static int OpenglLock         (vlc_gl_t *gl);
68 static void OpenglUnlock       (vlc_gl_t *gl);
69 static void OpenglSwap         (vlc_gl_t *gl);
70
71 @protocol VLCCoreAnimationVideoLayerEmbedding <NSObject>
72 - (void)addVoutLayer:(CALayer *)aLayer;
73 - (void)removeVoutLayer:(CALayer *)aLayer;
74 - (CGSize)currentOutputSize;
75 @end
76
77 @interface VLCCAOpenGLLayer : CAOpenGLLayer {
78     vout_display_t *_vd;
79 }
80
81 - (void)setVoutDisplay:(vout_display_t *)aVd;
82 @end
83
84
85 struct vout_display_sys_t {
86
87     picture_pool_t *pool;
88     picture_resource_t resource;
89
90     CALayer <VLCCoreAnimationVideoLayerEmbedding> *container;
91     vout_window_t *embed;
92     VLCCAOpenGLLayer *cgLayer;
93
94     CGLContextObj glContext;
95
96     vlc_gl_t gl;
97     vout_display_opengl_t *vgl;
98
99     vout_display_place_t place;
100
101     bool  b_frame_available;
102 };
103
104 /*****************************************************************************
105  * Open: This function allocates and initializes the OpenGL vout method.
106  *****************************************************************************/
107 static int Open (vlc_object_t *p_this)
108 {
109     vout_display_t *vd = (vout_display_t *)p_this;
110     vout_display_sys_t *sys;
111
112     /* Allocate structure */
113     vd->sys = sys = calloc(1, sizeof(vout_display_sys_t));
114     if (sys == NULL)
115         return VLC_EGENERIC;
116
117     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
118
119     id container = var_CreateGetAddress(vd, "drawable-nsobject");
120     if (container)
121         vout_display_DeleteWindow(vd, NULL);
122     else {
123         vout_window_cfg_t wnd_cfg;
124
125         memset(&wnd_cfg, 0, sizeof(wnd_cfg));
126         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
127         wnd_cfg.x = var_InheritInteger(vd, "video-x");
128         wnd_cfg.y = var_InheritInteger(vd, "video-y");
129         wnd_cfg.height = vd->cfg->display.height;
130         wnd_cfg.width = vd->cfg->display.width;
131
132         sys->embed = vout_display_NewWindow(vd, &wnd_cfg);
133         if (sys->embed)
134             container = sys->embed->handle.nsobject;
135
136         if (!container) {
137             msg_Err(vd, "No drawable-nsobject found!");
138             goto bailout;
139         }
140     }
141
142     /* store for later, released in Close() */
143     sys->container = [container retain];
144
145     [CATransaction begin];
146     sys->cgLayer = [[VLCCAOpenGLLayer alloc] init];
147     [sys->cgLayer setVoutDisplay:vd];
148
149     [sys->cgLayer performSelectorOnMainThread:@selector(display) withObject:nil waitUntilDone:YES];
150
151     if ([container respondsToSelector:@selector(addVoutLayer:)]) {
152         msg_Dbg(vd, "container implements implicit protocol");
153         [container addVoutLayer:sys->cgLayer];
154     } else if ([container respondsToSelector:@selector(addSublayer:)] || [container isKindOfClass:[CALayer class]]) {
155         msg_Dbg(vd, "container doesn't implement implicit protocol, fallback mode used");
156         [container addSublayer:sys->cgLayer];
157     } else {
158         msg_Err(vd, "Provided NSObject container isn't compatible");
159         [sys->cgLayer release];
160         sys->cgLayer = nil;
161         [CATransaction commit];
162         goto bailout;
163     }
164     [CATransaction commit];
165
166     if (!sys->cgLayer)
167         goto bailout;
168
169     if (!sys->glContext)
170         msg_Warn(vd, "we might not have an OpenGL context yet");
171
172     /* Initialize common OpenGL video display */
173     sys->gl.lock = OpenglLock;
174     sys->gl.unlock = OpenglUnlock;
175     sys->gl.swap = OpenglSwap;
176     sys->gl.getProcAddress = OurGetProcAddress;
177     sys->gl.sys = sys;
178
179     const vlc_fourcc_t *subpicture_chromas;
180     video_format_t fmt = vd->fmt;
181     sys->vgl = vout_display_opengl_New(&vd->fmt, &subpicture_chromas, &sys->gl);
182     if (!sys->vgl) {
183         msg_Err(vd, "Error while initializing opengl display.");
184         sys->gl.sys = NULL;
185         goto bailout;
186     }
187
188     /* setup vout display */
189     vout_display_info_t info = vd->info;
190     info.subpicture_chromas = subpicture_chromas;
191     info.has_hide_mouse = true;
192     vd->info = info;
193
194     vd->pool    = Pool;
195     vd->prepare = PictureRender;
196     vd->display = PictureDisplay;
197     vd->control = Control;
198
199     /* setup initial state */
200     CGSize outputSize;
201     if ([container respondsToSelector:@selector(currentOutputSize)])
202         outputSize = [container currentOutputSize];
203     else
204         outputSize = [sys->container visibleRect].size;
205     vout_display_SendEventFullscreen(vd, false);
206     vout_display_SendEventDisplaySize(vd, (int)outputSize.width, (int)outputSize.height);
207
208     [pool release];
209     return VLC_SUCCESS;
210
211 bailout:
212     [pool release];
213     Close(p_this);
214     return VLC_EGENERIC;
215 }
216
217 static void Close (vlc_object_t *p_this)
218 {
219     vout_display_t *vd = (vout_display_t *)p_this;
220     vout_display_sys_t *sys = vd->sys;
221
222     if (sys->cgLayer) {
223         if ([sys->container respondsToSelector:@selector(removeVoutLayer:)])
224             [sys->container removeVoutLayer:sys->cgLayer];
225         else
226             [sys->cgLayer removeFromSuperlayer];
227         [sys->cgLayer release];
228     }
229
230     if (sys->container)
231         [sys->container release];
232
233     if (sys->embed)
234         vout_display_DeleteWindow(vd, sys->embed);
235
236     if (sys->gl.sys != NULL)
237         vout_display_opengl_Delete(sys->vgl);
238
239     if (sys->glContext)
240         CGLReleaseContext(sys->glContext);
241
242     free(sys);
243 }
244
245 static picture_pool_t *Pool (vout_display_t *vd, unsigned count)
246 {
247     vout_display_sys_t *sys = vd->sys;
248
249     if (!sys->pool)
250         sys->pool = vout_display_opengl_GetPool(sys->vgl, count);
251     assert(sys->pool);
252     return sys->pool;
253 }
254
255 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
256 {
257     vout_display_sys_t *sys = vd->sys;
258
259     if (pic == NULL) {
260         msg_Warn(vd, "invalid pic, skipping frame");
261         return;
262     }
263
264     @synchronized (sys->cgLayer) {
265         vout_display_opengl_Prepare(sys->vgl, pic, subpicture);
266     }
267 }
268
269 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
270 {
271     vout_display_sys_t *sys = vd->sys;
272
273     @synchronized (sys->cgLayer) {
274         sys->b_frame_available = YES;
275
276         /* Calling display on the non-main thread is not officially supported, but
277          * its suggested at several places and works fine here. Flush is thread-safe
278          * and makes sure the picture is actually displayed. */
279         [sys->cgLayer display];
280         [CATransaction flush];
281     }
282
283     picture_Release(pic);
284
285     if (subpicture)
286         subpicture_Delete(subpicture);
287 }
288
289 static int Control (vout_display_t *vd, int query, va_list ap)
290 {
291     vout_display_sys_t *sys = vd->sys;
292
293     if (!vd->sys)
294         return VLC_EGENERIC;
295
296     switch (query)
297     {
298         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
299         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
300         case VOUT_DISPLAY_CHANGE_ZOOM:
301         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
302         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
303         {
304             const vout_display_cfg_t *cfg;
305             const video_format_t *source;
306
307             if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP) {
308                 source = (const video_format_t *)va_arg (ap, const video_format_t *);
309                 cfg = vd->cfg;
310             } else {
311                 source = &vd->source;
312                 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
313             }
314
315             /* we always use our current frame here */
316             vout_display_cfg_t cfg_tmp = *cfg;
317             [CATransaction lock];
318             CGRect bounds = [sys->cgLayer bounds];
319             [CATransaction unlock];
320             cfg_tmp.display.width = bounds.size.width;
321             cfg_tmp.display.height = bounds.size.height;
322
323             vout_display_place_t place;
324             vout_display_PlacePicture (&place, source, &cfg_tmp, false);
325             sys->place = place;
326
327             return VLC_SUCCESS;
328         }
329
330         case VOUT_DISPLAY_HIDE_MOUSE:
331         {
332             [NSCursor setHiddenUntilMouseMoves: YES];
333             return VLC_SUCCESS;
334         }
335
336         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
337         {
338             return VLC_SUCCESS;
339         }
340
341         case VOUT_DISPLAY_RESET_PICTURES:
342             assert (0);
343         default:
344             msg_Err (vd, "Unhandled request %d", query);
345         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
346             return VLC_EGENERIC;
347     }
348
349     return VLC_SUCCESS;
350 }
351
352 #pragma mark -
353 #pragma mark OpenGL callbacks
354
355 static int OpenglLock (vlc_gl_t *gl)
356 {
357     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
358
359     if(!sys->glContext) {
360         return 1;
361     }
362
363     CGLError err = CGLLockContext(sys->glContext);
364     if (kCGLNoError == err) {
365         CGLSetCurrentContext(sys->glContext);
366         return 0;
367     }
368     return 1;
369 }
370
371 static void OpenglUnlock (vlc_gl_t *gl)
372 {
373     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
374
375     if (!sys->glContext) {
376         return;
377     }
378
379     CGLUnlockContext(sys->glContext);
380 }
381
382 static void OpenglSwap (vlc_gl_t *gl)
383 {
384     glFlush();
385 }
386
387 static void *OurGetProcAddress (vlc_gl_t *gl, const char *name)
388 {
389     VLC_UNUSED(gl);
390
391     return dlsym(RTLD_DEFAULT, name);
392 }
393
394 #pragma mark -
395 #pragma mark CA layer
396
397 /*****************************************************************************
398  * @implementation VLCCAOpenGLLayer
399  *****************************************************************************/
400 @implementation VLCCAOpenGLLayer
401
402 - (id)init {
403
404     self = [super init];
405     if (self) {
406         [CATransaction lock];
407         [self setAutoresizingMask: kCALayerWidthSizable | kCALayerHeightSizable];
408         self.asynchronous = NO;
409         [CATransaction unlock];
410     }
411
412     return self;
413 }
414
415 - (void)setVoutDisplay:(vout_display_t *)aVd
416 {
417     _vd = aVd;
418 }
419
420 - (void)resizeWithOldSuperlayerSize:(CGSize)size
421 {
422     [super resizeWithOldSuperlayerSize: size];
423
424     CGSize boundsSize = self.bounds.size;
425     if (_vd)
426         vout_display_SendEventDisplaySize(_vd, boundsSize.width, boundsSize.height);
427 }
428
429 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
430 {
431     /* Only draw the frame if we have a frame that was previously rendered */
432     if (!_vd)
433         return false;
434
435     return _vd->sys->b_frame_available;
436 }
437
438 - (void)drawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
439 {
440     if (!_vd)
441         return;
442     vout_display_sys_t *sys = _vd->sys;
443
444     if (!sys->vgl)
445         return;
446
447     CGRect bounds = [self bounds];
448     // x / y are top left corner, but we need the lower left one
449     glViewport (sys->place.x, bounds.size.height - (sys->place.y + sys->place.height), sys->place.width, sys->place.height);
450
451     // flush is also done by this method, no need to call super
452     vout_display_opengl_Display (sys->vgl, &_vd->source);
453     sys->b_frame_available = NO;
454 }
455
456 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat
457 {
458     // Only one opengl context is allowed for the module lifetime
459     if(_vd->sys->glContext) {
460         msg_Dbg(_vd, "Return existing context: %p", _vd->sys->glContext);
461         return _vd->sys->glContext;
462     }
463
464     CGLContextObj context = [super copyCGLContextForPixelFormat:pixelFormat];
465
466     // Swap buffers only during the vertical retrace of the monitor.
467     //http://developer.apple.com/documentation/GraphicsImaging/
468     //Conceptual/OpenGL/chap5/chapter_5_section_44.html /
469
470     GLint params = 1;
471     CGLSetParameter( CGLGetCurrentContext(), kCGLCPSwapInterval,
472                      &params );
473
474     @synchronized (self) {
475         _vd->sys->glContext = context;
476     }
477
478     return context;
479 }
480
481 - (void)releaseCGLContext:(CGLContextObj)glContext
482 {
483     // do not release anything here, we do that when closing the module
484 }
485
486 - (void)mouseButtonDown:(int)buttonNumber
487 {
488     @synchronized (self) {
489         if (_vd) {
490             if (buttonNumber == 0)
491                 vout_display_SendEventMousePressed (_vd, MOUSE_BUTTON_LEFT);
492             else if (buttonNumber == 1)
493                 vout_display_SendEventMousePressed (_vd, MOUSE_BUTTON_RIGHT);
494             else
495                 vout_display_SendEventMousePressed (_vd, MOUSE_BUTTON_CENTER);
496         }
497     }
498 }
499
500 - (void)mouseButtonUp:(int)buttonNumber
501 {
502     @synchronized (self) {
503         if (_vd) {
504             if (buttonNumber == 0)
505                 vout_display_SendEventMouseReleased (_vd, MOUSE_BUTTON_LEFT);
506             else if (buttonNumber == 1)
507                 vout_display_SendEventMouseReleased (_vd, MOUSE_BUTTON_RIGHT);
508             else
509                 vout_display_SendEventMouseReleased (_vd, MOUSE_BUTTON_CENTER);
510         }
511     }
512 }
513
514 - (void)mouseMovedToX:(double)xValue Y:(double)yValue
515 {
516     @synchronized (self) {
517         if (_vd) {
518             vout_display_SendMouseMovedDisplayCoordinates (_vd,
519                                                            ORIENT_NORMAL,
520                                                            xValue,
521                                                            yValue,
522                                                            &_vd->sys->place);
523         }
524     }
525 }
526
527 @end