]> git.sesse.net Git - vlc/blob - modules/video_output/caopengllayer.m
caopengllayer: Use the same gl context during modules lifetime
[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     [VLCCAOpenGLLayer performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->cgLayer] waitUntilDone:YES];
146     if (!sys->cgLayer)
147         goto bailout;
148
149     [sys->cgLayer setVoutDisplay:vd];
150
151     // TODO: Find a better way to wait until we get a context
152     [sys->cgLayer performSelectorOnMainThread:@selector(display)
153                                    withObject:nil waitUntilDone:YES];
154     assert(sys->glContext);
155
156     if ([container respondsToSelector:@selector(addVoutLayer:)]) {
157         msg_Dbg(vd, "container implements implicit protocol");
158         [container addVoutLayer:sys->cgLayer];
159     } else if ([container respondsToSelector:@selector(addSublayer:)] || [container isKindOfClass:[CALayer class]]) {
160         msg_Dbg(vd, "container doesn't implement implicit protocol, fallback mode used");
161         [container addSublayer:sys->cgLayer];
162     } else {
163         msg_Err(vd, "Provided NSObject container isn't compatible");
164         goto bailout;
165     }
166
167     /* Initialize common OpenGL video display */
168     sys->gl.lock = OpenglLock;
169     sys->gl.unlock = OpenglUnlock;
170     sys->gl.swap = OpenglSwap;
171     sys->gl.getProcAddress = OurGetProcAddress;
172     sys->gl.sys = sys;
173
174     const vlc_fourcc_t *subpicture_chromas;
175     video_format_t fmt = vd->fmt;
176     sys->vgl = vout_display_opengl_New(&vd->fmt, &subpicture_chromas, &sys->gl);
177     if (!sys->vgl) {
178         msg_Err(vd, "Error while initializing opengl display.");
179         sys->gl.sys = NULL;
180         goto bailout;
181     }
182
183     /* setup vout display */
184     vout_display_info_t info = vd->info;
185     info.subpicture_chromas = subpicture_chromas;
186     info.has_hide_mouse = false;
187     vd->info = info;
188
189     vd->pool    = Pool;
190     vd->prepare = PictureRender;
191     vd->display = PictureDisplay;
192     vd->control = Control;
193
194     /* setup initial state */
195     CGSize outputSize;
196     if ([container respondsToSelector:@selector(currentOutputSize)])
197         outputSize = [container currentOutputSize];
198     else
199         outputSize = [sys->container visibleRect].size;
200     vout_display_SendEventFullscreen(vd, false);
201     vout_display_SendEventDisplaySize(vd, (int)outputSize.width, (int)outputSize.height, false);
202
203
204     [pool release];
205     return VLC_SUCCESS;
206
207 bailout:
208     [pool release];
209     Close(p_this);
210     return VLC_EGENERIC;
211 }
212
213 static void Close (vlc_object_t *p_this)
214 {
215     vout_display_t *vd = (vout_display_t *)p_this;
216     vout_display_sys_t *sys = vd->sys;
217
218     if (sys->cgLayer) {
219         if ([sys->container respondsToSelector:@selector(removeVoutLayer:)])
220             [sys->container removeVoutLayer:sys->cgLayer];
221         else
222             [sys->cgLayer removeFromSuperlayer];
223         [sys->cgLayer release];
224     }
225
226     if (sys->container)
227         [sys->container release];
228
229     if (sys->embed)
230         vout_display_DeleteWindow(vd, sys->embed);
231
232     if (sys->gl.sys != NULL)
233         vout_display_opengl_Delete(sys->vgl);
234
235     if (sys->glContext)
236         CGLReleaseContext(sys->glContext);
237
238     free(sys);
239 }
240
241 static picture_pool_t *Pool (vout_display_t *vd, unsigned count)
242 {
243     vout_display_sys_t *sys = vd->sys;
244
245     if (!sys->pool)
246         sys->pool = vout_display_opengl_GetPool(sys->vgl, count);
247     assert(sys->pool);
248     return sys->pool;
249 }
250
251 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
252 {
253     vout_display_sys_t *sys = vd->sys;
254
255     @synchronized (sys->cgLayer) {
256         vout_display_opengl_Prepare(sys->vgl, pic, subpicture);
257     }
258 }
259
260 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
261 {
262     vout_display_sys_t *sys = vd->sys;
263
264     @synchronized (sys->cgLayer) {
265         sys->b_frame_available = YES;
266
267         /* Calling display on the non-main thread is not officially supported, but
268          * its suggested at several places and works fine here. Flush is thread-safe
269          * and makes sure the picture is actually displayed. */
270         [sys->cgLayer display];
271         [CATransaction flush];
272         sys->b_frame_available = NO;
273     }
274
275     picture_Release(pic);
276
277     if (subpicture)
278         subpicture_Delete(subpicture);
279 }
280
281 static int Control (vout_display_t *vd, int query, va_list ap)
282 {
283     vout_display_sys_t *sys = vd->sys;
284
285     if (!vd->sys)
286         return VLC_EGENERIC;
287
288     switch (query)
289     {
290         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
291         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
292         case VOUT_DISPLAY_CHANGE_ZOOM:
293         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
294         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
295         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
296         {
297             const vout_display_cfg_t *cfg;
298             const video_format_t *source;
299
300             if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP) {
301                 source = (const video_format_t *)va_arg (ap, const video_format_t *);
302                 cfg = vd->cfg;
303             } else {
304                 source = &vd->source;
305                 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
306             }
307
308             /* we always use our current frame here */
309             vout_display_cfg_t cfg_tmp = *cfg;
310             CGRect bounds = [sys->cgLayer bounds];
311             cfg_tmp.display.width = bounds.size.width;
312             cfg_tmp.display.height = bounds.size.height;
313
314             vout_display_place_t place;
315             vout_display_PlacePicture (&place, source, &cfg_tmp, false);
316             sys->place = place;
317
318             return VLC_SUCCESS;
319         }
320
321         case VOUT_DISPLAY_GET_OPENGL:
322         {
323             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
324             *gl = &sys->gl;
325             return VLC_SUCCESS;
326         }
327
328         case VOUT_DISPLAY_RESET_PICTURES:
329             assert (0);
330         default:
331             msg_Err (vd, "Unhandled request %d", query);
332             return VLC_EGENERIC;
333     }
334
335     return VLC_SUCCESS;
336 }
337
338 #pragma mark -
339 #pragma mark OpenGL callbacks
340
341 static int OpenglLock (vlc_gl_t *gl)
342 {
343     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
344
345     if(!sys->glContext) {
346         return 1;
347     }
348
349     CGLError err = CGLLockContext(sys->glContext);
350     if (kCGLNoError == err) {
351         CGLSetCurrentContext(sys->glContext);
352         return 0;
353     }
354     return 1;
355 }
356
357 static void OpenglUnlock (vlc_gl_t *gl)
358 {
359     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
360
361     if (!sys->glContext) {
362         return;
363     }
364
365     CGLUnlockContext(sys->glContext);
366 }
367
368 static void OpenglSwap (vlc_gl_t *gl)
369 {
370     glFlush();
371 }
372
373 static void *OurGetProcAddress (vlc_gl_t *gl, const char *name)
374 {
375     VLC_UNUSED(gl);
376
377     return dlsym(RTLD_DEFAULT, name);
378 }
379
380 #pragma mark -
381 #pragma mark CA layer
382
383 /*****************************************************************************
384  * @implementation VLCCAOpenGLLayer
385  *****************************************************************************/
386 @implementation VLCCAOpenGLLayer
387
388 + (void)getNewView:(NSValue *)value
389 {
390     id *ret = [value pointerValue];
391     *ret = [[self alloc] init];
392 }
393
394 - (id)init {
395
396     self = [super init];
397     if (self) {
398         [CATransaction begin];
399         [self setAutoresizingMask: kCALayerWidthSizable | kCALayerHeightSizable];
400         [self setAsynchronous: NO];
401         [CATransaction commit];
402     }
403
404     return self;
405 }
406
407 - (void)setVoutDisplay:(vout_display_t *)aVd
408 {
409     _vd = aVd;
410 }
411
412 - (void)resizeWithOldSuperlayerSize:(CGSize)size
413 {
414     [super resizeWithOldSuperlayerSize: size];
415
416     if (_vd)
417         vout_display_SendEventDisplaySize(_vd, self.bounds.size.width, self.bounds.size.height, _vd->cfg->is_fullscreen);
418 }
419
420 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
421 {
422     /* Only draw the frame if we have a frame that was previously rendered */
423     if (!_vd)
424         return false;
425
426     return _vd->sys->b_frame_available;
427 }
428
429 - (void)drawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
430 {
431     if (!_vd)
432         return;
433     vout_display_sys_t *sys = _vd->sys;
434
435     if (!sys->vgl)
436         return;
437
438     CGRect bounds = [self bounds];
439     // x / y are top left corner, but we need the lower left one
440     glViewport (sys->place.x, bounds.size.height - (sys->place.y + sys->place.height), sys->place.width, sys->place.height);
441
442     // flush is also done by this method, no need to call super
443     vout_display_opengl_Display (sys->vgl, &_vd->source);
444 }
445
446 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat
447 {
448     // Only one opengl context is allowed for the module lifetime
449     if(_vd->sys->glContext) {
450         msg_Dbg(_vd, "Return existing context: %p", _vd->sys->glContext);
451         return _vd->sys->glContext;
452     }
453
454     CGLContextObj context = [super copyCGLContextForPixelFormat:pixelFormat];
455
456     // Swap buffers only during the vertical retrace of the monitor.
457     //http://developer.apple.com/documentation/GraphicsImaging/
458     //Conceptual/OpenGL/chap5/chapter_5_section_44.html /
459
460     GLint params = 1;
461     CGLSetParameter( CGLGetCurrentContext(), kCGLCPSwapInterval,
462                      &params );
463
464     @synchronized (self) {
465         _vd->sys->glContext = context;
466     }
467
468     return context;
469 }
470
471 - (void)releaseCGLContext:(CGLContextObj)glContext
472 {
473     // do not release anything here, we do that when closing the module
474 }
475
476 @end