]> git.sesse.net Git - vlc/blob - modules/video_output/opengl.c
opengl: fix compilation for OS X
[vlc] / modules / video_output / opengl.c
1 /*****************************************************************************
2  * opengl.c: OpenGL and OpenGL ES output common code
3  *****************************************************************************
4  * Copyright (C) 2004-2012 VLC authors and VideoLAN
5  * Copyright (C) 2009, 2011 Laurent Aimar
6  *
7  * Authors: Cyril Deguet <asmax@videolan.org>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *          Eric Petit <titer@m0k.org>
10  *          Cedric Cocquebert <cedric.cocquebert@supelec.fr>
11  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
12  *          Ilkka Ollakka <ileoo@videolan.org>
13  *
14  * This program is free software; you can redistribute it and/or modify it
15  * under the terms of the GNU Lesser General Public License as published by
16  * the Free Software Foundation; either version 2.1 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22  * GNU Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public License
25  * along with this program; if not, write to the Free Software Foundation,
26  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_picture_pool.h>
34 #include <vlc_subpicture.h>
35 #include <vlc_opengl.h>
36
37 #include "opengl.h"
38
39 #ifndef GL_CLAMP_TO_EDGE
40 # define GL_CLAMP_TO_EDGE 0x812F
41 #endif
42
43 #ifdef __APPLE__
44 #   define PFNGLGETPROGRAMIVPROC             typeof(glGetProgramiv)*
45 #   define PFNGLGETPROGRAMINFOLOGPROC        typeof(glGetProgramInfoLog)*
46 #   define PFNGLGETSHADERIVPROC              typeof(glGetShaderiv)*
47 #   define PFNGLGETSHADERINFOLOGPROC         typeof(glGetShaderInfoLog)*
48 #   define PFNGLGETUNIFORMLOCATIONPROC       typeof(glGetUniformLocation)*
49 #   define PFNGLGETATTRIBLOCATIONPROC        typeof(glGetAttribLocation)*
50 #   define PFNGLVERTEXATTRIBPOINTERPROC      typeof(glVertexAttribPointer)*
51 #   define PFNGLENABLEVERTEXATTRIBARRAYPROC  typeof(glEnableVertexAttribArray)*
52 #   define PFNGLUNIFORM4FVPROC               typeof(glUniform4fv)*
53 #   define PFNGLUNIFORM4FPROC                typeof(glUniform4f)*
54 #   define PFNGLUNIFORM1IPROC                typeof(glUniform1i)*
55 #   define PFNGLCREATESHADERPROC             typeof(glCreateShader)*
56 #   define PFNGLSHADERSOURCEPROC             typeof(glShaderSource)*
57 #   define PFNGLCOMPILESHADERPROC            typeof(glCompileShader)*
58 #   define PFNGLDELETESHADERPROC             typeof(glDeleteShader)*
59 #   define PFNGLCREATEPROGRAMPROC            typeof(glCreateProgram)*
60 #   define PFNGLLINKPROGRAMPROC              typeof(glLinkProgram)*
61 #   define PFNGLUSEPROGRAMPROC               typeof(glUseProgram)*
62 #   define PFNGLDELETEPROGRAMPROC            typeof(glDeleteProgram)*
63 #   define PFNGLATTACHSHADERPROC             typeof(glAttachShader)*
64 #if USE_OPENGL_ES
65 #   define GL_UNPACK_ROW_LENGTH 0
66 #   import <CoreFoundation/CoreFoundation.h>
67 #endif
68 #endif
69
70 #if USE_OPENGL_ES
71 #   define GLSL_VERSION "100"
72 #   define VLCGL_TEXTURE_COUNT 1
73 #   define VLCGL_PICTURE_MAX 1
74 #else
75 #   define GLSL_VERSION "120"
76 #   define VLCGL_TEXTURE_COUNT 1
77 #   define VLCGL_PICTURE_MAX 128
78 #endif
79
80 static const vlc_fourcc_t gl_subpicture_chromas[] = {
81     VLC_CODEC_RGBA,
82     0
83 };
84
85 typedef struct {
86     GLuint   texture;
87     unsigned format;
88     unsigned type;
89     unsigned width;
90     unsigned height;
91
92     float    alpha;
93
94     float    top;
95     float    left;
96     float    bottom;
97     float    right;
98 } gl_region_t;
99
100 struct vout_display_opengl_t {
101
102     vlc_gl_t   *gl;
103
104     video_format_t fmt;
105     const vlc_chroma_description_t *chroma;
106
107     int        tex_target;
108     int        tex_format;
109     int        tex_internal;
110     int        tex_type;
111
112     int        tex_width[PICTURE_PLANE_MAX];
113     int        tex_height[PICTURE_PLANE_MAX];
114
115     GLuint     texture[VLCGL_TEXTURE_COUNT][PICTURE_PLANE_MAX];
116
117     int         region_count;
118     gl_region_t *region;
119
120
121     picture_pool_t *pool;
122
123     /* index 0 for normal and 1 for subtitle overlay */
124     GLuint     program[2];
125     GLint      shader[3]; //3. is for the common vertex shader
126     int        local_count;
127     GLfloat    local_value[16];
128
129     /* Shader variables commands*/
130     PFNGLGETUNIFORMLOCATIONPROC      GetUniformLocation;
131     PFNGLGETATTRIBLOCATIONPROC       GetAttribLocation;
132     PFNGLVERTEXATTRIBPOINTERPROC     VertexAttribPointer;
133     PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
134
135     PFNGLUNIFORM4FVPROC   Uniform4fv;
136     PFNGLUNIFORM4FPROC    Uniform4f;
137     PFNGLUNIFORM1IPROC    Uniform1i;
138
139     /* Shader command */
140     PFNGLCREATESHADERPROC CreateShader;
141     PFNGLSHADERSOURCEPROC ShaderSource;
142     PFNGLCOMPILESHADERPROC CompileShader;
143     PFNGLDELETESHADERPROC   DeleteShader;
144
145     PFNGLCREATEPROGRAMPROC CreateProgram;
146     PFNGLLINKPROGRAMPROC   LinkProgram;
147     PFNGLUSEPROGRAMPROC    UseProgram;
148     PFNGLDELETEPROGRAMPROC DeleteProgram;
149
150     PFNGLATTACHSHADERPROC  AttachShader;
151
152     /* Shader log commands */
153     PFNGLGETPROGRAMIVPROC  GetProgramiv;
154     PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
155     PFNGLGETSHADERIVPROC   GetShaderiv;
156     PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
157
158
159     /* multitexture */
160     bool use_multitexture;
161
162     /* Non-power-of-2 texture size support */
163     bool supports_npot;
164 };
165
166 static inline int GetAlignedSize(unsigned size)
167 {
168     /* Return the smallest larger or equal power of 2 */
169     unsigned align = 1 << (8 * sizeof (unsigned) - clz(size));
170     return ((align >> 1) == size) ? size : align;
171 }
172
173 #if !USE_OPENGL_ES
174 static bool IsLuminance16Supported(int target)
175 {
176     GLuint texture;
177
178     glGenTextures(1, &texture);
179     glBindTexture(target, texture);
180     glTexImage2D(target, 0, GL_LUMINANCE16,
181                  64, 64, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, NULL);
182     GLint size = 0;
183     glGetTexLevelParameteriv(target, 0, GL_TEXTURE_LUMINANCE_SIZE, &size);
184
185     glDeleteTextures(1, &texture);
186
187     return size == 16;
188 }
189 #endif
190
191 static void BuildVertexShader(vout_display_opengl_t *vgl,
192                               GLint *shader)
193 {
194     /* Basic vertex shader */
195     const char *vertexShader =
196         "#version " GLSL_VERSION "\n"
197         "precision highp float;"
198         "varying vec4 TexCoord0,TexCoord1, TexCoord2;"
199         "attribute vec4 MultiTexCoord0,MultiTexCoord1,MultiTexCoord2;"
200         "attribute vec4 VertexPosition;"
201         "void main() {"
202         " TexCoord0 = MultiTexCoord0;"
203         " TexCoord1 = MultiTexCoord1;"
204         " TexCoord2 = MultiTexCoord2;"
205         " gl_Position = VertexPosition;"
206         "}";
207
208     *shader = vgl->CreateShader(GL_VERTEX_SHADER);
209     vgl->ShaderSource(*shader, 1, &vertexShader, NULL);
210     vgl->CompileShader(*shader);
211 }
212
213 static void BuildYUVFragmentShader(vout_display_opengl_t *vgl,
214                                    GLint *shader,
215                                    int *local_count,
216                                    GLfloat *local_value,
217                                    const video_format_t *fmt,
218                                    float yuv_range_correction)
219
220 {
221     /* [R/G/B][Y U V O] from TV range to full range
222      * XXX we could also do hue/brightness/constrast/gamma
223      * by simply changing the coefficients
224      */
225     const float matrix_bt601_tv2full[12] = {
226         1.164383561643836,  0.0000,             1.596026785714286, -0.874202217873451 ,
227         1.164383561643836, -0.391762290094914, -0.812967647237771,  0.531667823499146 ,
228         1.164383561643836,  2.017232142857142,  0.0000,            -1.085630789302022 ,
229     };
230     const float matrix_bt709_tv2full[12] = {
231         1.164383561643836,  0.0000,             1.792741071428571, -0.972945075016308 ,
232         1.164383561643836, -0.21324861427373,  -0.532909328559444,  0.301482665475862 ,
233         1.164383561643836,  2.112401785714286,  0.0000,            -1.133402217873451 ,
234     };
235     const float (*matrix) = fmt->i_height > 576 ? matrix_bt709_tv2full
236                                                 : matrix_bt601_tv2full;
237
238     /* Basic linear YUV -> RGB conversion using bilinear interpolation */
239     const char *template_glsl_yuv =
240         "#version " GLSL_VERSION "\n"
241         "precision highp float;"
242         "uniform sampler2D Texture0;"
243         "uniform sampler2D Texture1;"
244         "uniform sampler2D Texture2;"
245         "uniform vec4      Coefficient[4];"
246         "varying vec4      TexCoord0,TexCoord1,TexCoord2;"
247
248         "void main(void) {"
249         " vec4 x,y,z,result;"
250         " x  = texture2D(Texture0, TexCoord0.st);"
251         " %c = texture2D(Texture1, TexCoord1.st);"
252         " %c = texture2D(Texture2, TexCoord2.st);"
253
254         " result = x * Coefficient[0] + Coefficient[3];"
255         " result = (y * Coefficient[1]) + result;"
256         " result = (z * Coefficient[2]) + result;"
257         " gl_FragColor = result;"
258         "}";
259     bool swap_uv = fmt->i_chroma == VLC_CODEC_YV12 ||
260                    fmt->i_chroma == VLC_CODEC_YV9;
261
262     char *code;
263     if (asprintf(&code, template_glsl_yuv,
264                  swap_uv ? 'z' : 'y',
265                  swap_uv ? 'y' : 'z') < 0)
266         code = NULL;
267
268     for (int i = 0; i < 4; i++) {
269         float correction = i < 3 ? yuv_range_correction : 1.0;
270         /* We place coefficient values for coefficient[4] in one array from matrix values.
271            Notice that we fill values from top down instead of left to right.*/
272         for (int j = 0; j < 4; j++)
273             local_value[*local_count + i*4+j] = j < 3 ? correction * matrix[j*4+i]
274                                                       : 0.0 ;
275     }
276     (*local_count) += 4;
277
278
279     *shader = vgl->CreateShader(GL_FRAGMENT_SHADER);
280     vgl->ShaderSource(*shader, 1, (const char **)&code, NULL);
281     vgl->CompileShader(*shader);
282
283     free(code);
284 }
285
286 static void BuildRGBFragmentShader(vout_display_opengl_t *vgl,
287                                    GLint *shader)
288 {
289     // Simple shader for RGB
290     const char *code =
291         "#version " GLSL_VERSION "\n"
292         "precision highp float;"
293         "uniform sampler2D Texture[3];"
294         "varying vec4 TexCoord0,TexCoord1,TexCoord2;"
295         "void main()"
296         "{ "
297         "  gl_FragColor = texture2D(Texture[0], TexCoord0.st);"
298         "}";
299     *shader = vgl->CreateShader(GL_FRAGMENT_SHADER);
300     vgl->ShaderSource(*shader, 1, &code, NULL);
301     vgl->CompileShader(*shader);
302 }
303
304 static void BuildRGBAFragmentShader(vout_display_opengl_t *vgl,
305                                    GLint *shader)
306 {
307     // Simple shader for RGBA
308     const char *code =
309         "#version " GLSL_VERSION "\n"
310         "precision highp float;"
311         "uniform sampler2D Texture;"
312         "uniform vec4 FillColor;"
313         "varying vec4 TexCoord0;"
314         "void main()"
315         "{ "
316         "  gl_FragColor = texture2D(Texture, TexCoord0.st) * FillColor;"
317         "}";
318     *shader = vgl->CreateShader(GL_FRAGMENT_SHADER);
319     vgl->ShaderSource(*shader, 1, &code, NULL);
320     vgl->CompileShader(*shader);
321 }
322
323 vout_display_opengl_t *vout_display_opengl_New(video_format_t *fmt,
324                                                const vlc_fourcc_t **subpicture_chromas,
325                                                vlc_gl_t *gl)
326 {
327     vout_display_opengl_t *vgl = calloc(1, sizeof(*vgl));
328     if (!vgl)
329         return NULL;
330
331     vgl->gl = gl;
332     if (vlc_gl_Lock(vgl->gl)) {
333         free(vgl);
334         return NULL;
335     }
336
337     if (vgl->gl->getProcAddress == NULL) {
338         fprintf(stderr, "getProcAddress not implemented, bailing out\n");
339         free(vgl);
340         return NULL;
341     }
342
343     const char *extensions = (const char *)glGetString(GL_EXTENSIONS);
344 #if !USE_OPENGL_ES
345     const unsigned char *ogl_version = glGetString(GL_VERSION);
346     bool supports_shaders = strverscmp((const char *)ogl_version, "2.0") >= 0;
347 #else
348     bool supports_shaders = false;
349 #endif
350
351     vgl->CreateShader  = (PFNGLCREATESHADERPROC)vlc_gl_GetProcAddress(vgl->gl, "glCreateShader");
352     vgl->ShaderSource  = (PFNGLSHADERSOURCEPROC)vlc_gl_GetProcAddress(vgl->gl, "glShaderSource");
353     vgl->CompileShader = (PFNGLCOMPILESHADERPROC)vlc_gl_GetProcAddress(vgl->gl, "glCompileShader");
354     vgl->AttachShader  = (PFNGLATTACHSHADERPROC)vlc_gl_GetProcAddress(vgl->gl, "glAttachShader");
355
356     vgl->GetProgramiv  = (PFNGLGETPROGRAMIVPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetProgramiv");
357     vgl->GetShaderiv   = (PFNGLGETSHADERIVPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetShaderiv");
358     vgl->GetProgramInfoLog  = (PFNGLGETPROGRAMINFOLOGPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetProgramInfoLog");
359     vgl->GetShaderInfoLog   = (PFNGLGETSHADERINFOLOGPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetShaderInfoLog");
360
361     vgl->DeleteShader  = (PFNGLDELETESHADERPROC)vlc_gl_GetProcAddress(vgl->gl, "glDeleteShader");
362
363     vgl->GetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetUniformLocation");
364     vgl->GetAttribLocation  = (PFNGLGETATTRIBLOCATIONPROC)vlc_gl_GetProcAddress(vgl->gl, "glGetAttribLocation");
365     vgl->VertexAttribPointer= (PFNGLVERTEXATTRIBPOINTERPROC)vlc_gl_GetProcAddress(vgl->gl, "glVertexAttribPointer");
366     vgl->EnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)vlc_gl_GetProcAddress(vgl->gl, "glEnableVertexAttribArray");
367     vgl->Uniform4fv    = (PFNGLUNIFORM4FVPROC)vlc_gl_GetProcAddress(vgl->gl,"glUniform4fv");
368     vgl->Uniform4f     = (PFNGLUNIFORM4FPROC)vlc_gl_GetProcAddress(vgl->gl,"glUniform4f");
369     vgl->Uniform1i     = (PFNGLUNIFORM1IPROC)vlc_gl_GetProcAddress(vgl->gl,"glUniform1i");
370
371     vgl->CreateProgram = (PFNGLCREATEPROGRAMPROC)vlc_gl_GetProcAddress(vgl->gl, "glCreateProgram");
372     vgl->LinkProgram   = (PFNGLLINKPROGRAMPROC)vlc_gl_GetProcAddress(vgl->gl, "glLinkProgram");
373     vgl->UseProgram    = (PFNGLUSEPROGRAMPROC)vlc_gl_GetProcAddress(vgl->gl, "glUseProgram");
374     vgl->DeleteProgram = (PFNGLDELETEPROGRAMPROC)vlc_gl_GetProcAddress(vgl->gl, "glDeleteProgram");
375
376     if (!vgl->CreateShader || !vgl->ShaderSource || !vgl->CreateProgram)
377         supports_shaders = false;
378
379     vgl->supports_npot = HasExtension(extensions, "GL_ARB_texture_non_power_of_two") ||
380                          HasExtension(extensions, "GL_APPLE_texture_2D_limited_npot");
381
382     GLint max_texture_units = 0;
383     glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units);
384
385 #ifdef __APPLE__
386 #if USE_OPENGL_ES
387     /* work-around an iOS 6 bug */
388     if (kCFCoreFoundationVersionNumber >= 786.)
389         max_texture_units = 8;
390     supports_shaders = true;
391 #endif
392 #endif
393
394     /* Initialize with default chroma */
395     vgl->fmt = *fmt;
396     vgl->fmt.i_chroma = VLC_CODEC_RGB32;
397 #   if defined(WORDS_BIGENDIAN)
398     vgl->fmt.i_rmask  = 0xff000000;
399     vgl->fmt.i_gmask  = 0x00ff0000;
400     vgl->fmt.i_bmask  = 0x0000ff00;
401 #   else
402     vgl->fmt.i_rmask  = 0x000000ff;
403     vgl->fmt.i_gmask  = 0x0000ff00;
404     vgl->fmt.i_bmask  = 0x00ff0000;
405 #   endif
406     vgl->tex_target   = GL_TEXTURE_2D;
407     vgl->tex_format   = GL_RGBA;
408     vgl->tex_internal = GL_RGBA;
409     vgl->tex_type     = GL_UNSIGNED_BYTE;
410     /* Use YUV if possible and needed */
411     bool need_fs_yuv = false;
412     float yuv_range_correction = 1.0;
413
414     if (max_texture_units >= 3 && supports_shaders &&
415         vlc_fourcc_IsYUV(fmt->i_chroma) && !vlc_fourcc_IsYUV(vgl->fmt.i_chroma)) {
416         printf("passed check\n");
417         const vlc_fourcc_t *list = vlc_fourcc_GetYUVFallback(fmt->i_chroma);
418         while (*list) {
419             const vlc_chroma_description_t *dsc = vlc_fourcc_GetChromaDescription(*list);
420             if (dsc && dsc->plane_count == 3 && dsc->pixel_size == 1) {
421                 need_fs_yuv       = true;
422                 vgl->fmt          = *fmt;
423                 vgl->fmt.i_chroma = *list;
424                 vgl->tex_format   = GL_LUMINANCE;
425                 vgl->tex_internal = GL_LUMINANCE;
426                 vgl->tex_type     = GL_UNSIGNED_BYTE;
427                 yuv_range_correction = 1.0;
428                 break;
429 #if !USE_OPENGL_ES
430             } else if (dsc && dsc->plane_count == 3 && dsc->pixel_size == 2 &&
431                        IsLuminance16Supported(vgl->tex_target)) {
432                 need_fs_yuv       = true;
433                 vgl->fmt          = *fmt;
434                 vgl->fmt.i_chroma = *list;
435                 vgl->tex_format   = GL_LUMINANCE;
436                 vgl->tex_internal = GL_LUMINANCE16;
437                 vgl->tex_type     = GL_UNSIGNED_SHORT;
438                 yuv_range_correction = (float)((1 << 16) - 1) / ((1 << dsc->pixel_bits) - 1);
439                 break;
440 #endif
441             }
442             list++;
443         }
444     }
445
446     vgl->chroma = vlc_fourcc_GetChromaDescription(vgl->fmt.i_chroma);
447     vgl->use_multitexture = vgl->chroma->plane_count > 1;
448
449     /* Texture size */
450     for (unsigned j = 0; j < vgl->chroma->plane_count; j++) {
451         int w = vgl->fmt.i_width  * vgl->chroma->p[j].w.num / vgl->chroma->p[j].w.den;
452         int h = vgl->fmt.i_height * vgl->chroma->p[j].h.num / vgl->chroma->p[j].h.den;
453         if (vgl->supports_npot) {
454             vgl->tex_width[j]  = w;
455             vgl->tex_height[j] = h;
456         } else {
457             vgl->tex_width[j]  = GetAlignedSize(w);
458             vgl->tex_height[j] = GetAlignedSize(h);
459         }
460     }
461
462     /* Build program if needed */
463     vgl->program[0] =
464     vgl->program[1] = 0;
465     vgl->shader[0] =
466     vgl->shader[1] =
467     vgl->shader[2] = -1;
468     vgl->local_count = 0;
469     if (supports_shaders) {
470         if (need_fs_yuv)
471             BuildYUVFragmentShader(vgl, &vgl->shader[0],
472                                    &vgl->local_count,
473                                    vgl->local_value,
474                                    fmt, yuv_range_correction);
475         else
476             BuildRGBFragmentShader(vgl, &vgl->shader[0]);
477         BuildRGBAFragmentShader(vgl, &vgl->shader[1]);
478         BuildVertexShader(vgl, &vgl->shader[2]);
479
480         /* Check shaders messages */
481         for (unsigned j = 0; j < 3; j++) {
482             int infoLength;
483             vgl->GetShaderiv(vgl->shader[j], GL_INFO_LOG_LENGTH, &infoLength);
484             if (infoLength <= 1)
485                 continue;
486
487             char *infolog = malloc(infoLength);
488             int charsWritten;
489             vgl->GetShaderInfoLog(vgl->shader[j], infoLength, &charsWritten, infolog);
490             fprintf(stderr, "shader %d: %s\n", j, infolog);
491             free(infolog);
492         }
493
494         vgl->program[0] = vgl->CreateProgram();
495         vgl->AttachShader(vgl->program[0], vgl->shader[0]);
496         vgl->AttachShader(vgl->program[0], vgl->shader[2]);
497         vgl->LinkProgram(vgl->program[0]);
498
499         vgl->program[1] = vgl->CreateProgram();
500         vgl->AttachShader(vgl->program[1], vgl->shader[1]);
501         vgl->AttachShader(vgl->program[1], vgl->shader[2]);
502         vgl->LinkProgram(vgl->program[1]);
503
504         /* Check program messages */
505         for (GLuint i = 0; i < 2; i++) {
506             int infoLength = 0;
507             vgl->GetProgramiv(vgl->program[i], GL_INFO_LOG_LENGTH, &infoLength);
508             if (infoLength <= 1)
509                 continue;
510             char *infolog = malloc(infoLength);
511             int charsWritten;
512             vgl->GetProgramInfoLog(vgl->program[i], infoLength, &charsWritten, infolog);
513             fprintf(stderr, "shader program %d: %s\n", i, infolog);
514             free(infolog);
515
516             /* If there is some message, better to check linking is ok */
517             GLint link_status = GL_TRUE;
518             vgl->GetProgramiv(vgl->program[i], GL_LINK_STATUS, &link_status);
519             if (link_status == GL_FALSE) {
520                 fprintf(stderr, "Unable to use program %d\n", i);
521                 free(vgl);
522                 return NULL;
523             }
524         }
525     }
526
527     /* */
528     glDisable(GL_BLEND);
529     glDisable(GL_DEPTH_TEST);
530     glDepthMask(GL_FALSE);
531     glDisable(GL_CULL_FACE);
532     glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
533     glClear(GL_COLOR_BUFFER_BIT);
534
535     vlc_gl_Unlock(vgl->gl);
536
537     /* */
538     for (int i = 0; i < VLCGL_TEXTURE_COUNT; i++) {
539         for (int j = 0; j < PICTURE_PLANE_MAX; j++)
540             vgl->texture[i][j] = 0;
541     }
542     vgl->region_count = 0;
543     vgl->region = NULL;
544     vgl->pool = NULL;
545
546     *fmt = vgl->fmt;
547     if (subpicture_chromas) {
548         *subpicture_chromas = gl_subpicture_chromas;
549     }
550     return vgl;
551 }
552
553 void vout_display_opengl_Delete(vout_display_opengl_t *vgl)
554 {
555     /* */
556     if (!vlc_gl_Lock(vgl->gl)) {
557         glFinish();
558         glFlush();
559         for (int i = 0; i < VLCGL_TEXTURE_COUNT; i++)
560             glDeleteTextures(vgl->chroma->plane_count, vgl->texture[i]);
561         for (int i = 0; i < vgl->region_count; i++) {
562             if (vgl->region[i].texture)
563                 glDeleteTextures(1, &vgl->region[i].texture);
564         }
565         free(vgl->region);
566
567         if (vgl->program[0]) {
568             for (int i = 0; i < 2; i++)
569                 vgl->DeleteProgram(vgl->program[i]);
570             for (int i = 0; i < 3; i++)
571                 vgl->DeleteShader(vgl->shader[i]);
572         }
573
574         vlc_gl_Unlock(vgl->gl);
575     }
576     if (vgl->pool)
577         picture_pool_Delete(vgl->pool);
578     free(vgl);
579 }
580
581 picture_pool_t *vout_display_opengl_GetPool(vout_display_opengl_t *vgl, unsigned requested_count)
582 {
583     if (vgl->pool)
584         return vgl->pool;
585
586     /* Allocate our pictures */
587     picture_t *picture[VLCGL_PICTURE_MAX] = {NULL, };
588     unsigned count;
589
590     for (count = 0; count < __MIN(VLCGL_PICTURE_MAX, requested_count); count++) {
591         picture[count] = picture_NewFromFormat(&vgl->fmt);
592         if (!picture[count])
593             break;
594     }
595     if (count <= 0)
596         return NULL;
597
598     /* Wrap the pictures into a pool */
599     picture_pool_configuration_t cfg;
600     memset(&cfg, 0, sizeof(cfg));
601     cfg.picture_count = count;
602     cfg.picture       = picture;
603     vgl->pool = picture_pool_NewExtended(&cfg);
604     if (!vgl->pool)
605         goto error;
606
607     /* Allocates our textures */
608     if (vlc_gl_Lock(vgl->gl))
609         return vgl->pool;
610
611     for (int i = 0; i < VLCGL_TEXTURE_COUNT; i++) {
612         glGenTextures(vgl->chroma->plane_count, vgl->texture[i]);
613         for (unsigned j = 0; j < vgl->chroma->plane_count; j++) {
614             if (vgl->use_multitexture) {
615                 glActiveTexture(GL_TEXTURE0 + j);
616                 glClientActiveTexture(GL_TEXTURE0 + j);
617             }
618             glBindTexture(vgl->tex_target, vgl->texture[i][j]);
619
620 #if !USE_OPENGL_ES
621             /* Set the texture parameters */
622             glTexParameterf(vgl->tex_target, GL_TEXTURE_PRIORITY, 1.0);
623             glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
624 #endif
625
626             glTexParameteri(vgl->tex_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
627             glTexParameteri(vgl->tex_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
628             glTexParameteri(vgl->tex_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
629             glTexParameteri(vgl->tex_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
630
631             /* Call glTexImage2D only once, and use glTexSubImage2D later */
632             glTexImage2D(vgl->tex_target, 0,
633                          vgl->tex_internal, vgl->tex_width[j], vgl->tex_height[j],
634                          0, vgl->tex_format, vgl->tex_type, NULL);
635         }
636     }
637
638     vlc_gl_Unlock(vgl->gl);
639
640     return vgl->pool;
641
642 error:
643     for (unsigned i = 0; i < count; i++)
644         picture_Release(picture[i]);
645     return NULL;
646 }
647
648 int vout_display_opengl_Prepare(vout_display_opengl_t *vgl,
649                                 picture_t *picture, subpicture_t *subpicture)
650 {
651     if (vlc_gl_Lock(vgl->gl))
652         return VLC_EGENERIC;
653
654     /* Update the texture */
655     for (unsigned j = 0; j < vgl->chroma->plane_count; j++) {
656         if (vgl->use_multitexture) {
657             glActiveTexture(GL_TEXTURE0 + j);
658             glClientActiveTexture(GL_TEXTURE0 + j);
659         }
660         glBindTexture(vgl->tex_target, vgl->texture[0][j]);
661         glPixelStorei(GL_UNPACK_ROW_LENGTH, picture->p[j].i_pitch / picture->p[j].i_pixel_pitch);
662         glTexSubImage2D(vgl->tex_target, 0,
663                         0, 0,
664                         vgl->fmt.i_width  * vgl->chroma->p[j].w.num / vgl->chroma->p[j].w.den,
665                         vgl->fmt.i_height * vgl->chroma->p[j].h.num / vgl->chroma->p[j].h.den,
666                         vgl->tex_format, vgl->tex_type, picture->p[j].p_pixels);
667     }
668
669     int         last_count = vgl->region_count;
670     gl_region_t *last = vgl->region;
671
672     vgl->region_count = 0;
673     vgl->region       = NULL;
674
675     if (subpicture) {
676
677         int count = 0;
678         for (subpicture_region_t *r = subpicture->p_region; r; r = r->p_next)
679             count++;
680
681         vgl->region_count = count;
682         vgl->region       = calloc(count, sizeof(*vgl->region));
683
684         if (vgl->use_multitexture) {
685             glActiveTexture(GL_TEXTURE0 + 0);
686             glClientActiveTexture(GL_TEXTURE0 + 0);
687         }
688         int i = 0;
689         for (subpicture_region_t *r = subpicture->p_region; r; r = r->p_next, i++) {
690             gl_region_t *glr = &vgl->region[i];
691
692             glr->format = GL_RGBA;
693             glr->type   = GL_UNSIGNED_BYTE;
694             glr->width  = r->fmt.i_visible_width;
695             glr->height = r->fmt.i_visible_height;
696             if (!vgl->supports_npot) {
697                 glr->width  = GetAlignedSize(glr->width);
698                 glr->height = GetAlignedSize(glr->height);
699             }
700             glr->alpha  = (float)subpicture->i_alpha * r->i_alpha / 255 / 255;
701             glr->left   =  2.0 * (r->i_x                          ) / subpicture->i_original_picture_width  - 1.0;
702             glr->top    = -2.0 * (r->i_y                          ) / subpicture->i_original_picture_height + 1.0;
703             glr->right  =  2.0 * (r->i_x + r->fmt.i_visible_width ) / subpicture->i_original_picture_width  - 1.0;
704             glr->bottom = -2.0 * (r->i_y + r->fmt.i_visible_height) / subpicture->i_original_picture_height + 1.0;
705
706             glr->texture = 0;
707             for (int j = 0; j < last_count; j++) {
708                 if (last[j].texture &&
709                     last[j].width  == glr->width &&
710                     last[j].height == glr->height &&
711                     last[j].format == glr->format &&
712                     last[j].type   == glr->type) {
713                     glr->texture = last[j].texture;
714                     memset(&last[j], 0, sizeof(last[j]));
715                     break;
716                 }
717             }
718
719             const int pixels_offset = r->fmt.i_y_offset * r->p_picture->p->i_pitch +
720                                       r->fmt.i_x_offset * r->p_picture->p->i_pixel_pitch;
721             if (glr->texture) {
722                 glBindTexture(GL_TEXTURE_2D, glr->texture);
723                 /* TODO set GL_UNPACK_ALIGNMENT */
724                 glPixelStorei(GL_UNPACK_ROW_LENGTH, r->p_picture->p->i_pitch / r->p_picture->p->i_pixel_pitch);
725                 glTexSubImage2D(GL_TEXTURE_2D, 0,
726                                 0, 0, glr->width, glr->height,
727                                 glr->format, glr->type, &r->p_picture->p->p_pixels[pixels_offset]);
728             } else {
729                 glGenTextures(1, &glr->texture);
730                 glBindTexture(GL_TEXTURE_2D, glr->texture);
731 #if !USE_OPENGL_ES
732                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 1.0);
733                 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
734 #endif
735                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
736                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
737                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
738                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
739                 /* TODO set GL_UNPACK_ALIGNMENT */
740                 glPixelStorei(GL_UNPACK_ROW_LENGTH, r->p_picture->p->i_pitch / r->p_picture->p->i_pixel_pitch);
741                 glTexImage2D(GL_TEXTURE_2D, 0, glr->format,
742                              glr->width, glr->height, 0, glr->format, glr->type,
743                              &r->p_picture->p->p_pixels[pixels_offset]);
744             }
745         }
746     }
747     for (int i = 0; i < last_count; i++) {
748         if (last[i].texture)
749             glDeleteTextures(1, &last[i].texture);
750     }
751     free(last);
752
753     vlc_gl_Unlock(vgl->gl);
754     VLC_UNUSED(subpicture);
755     return VLC_SUCCESS;
756 }
757
758 static void DrawWithoutShaders(vout_display_opengl_t *vgl,
759                                float *left, float *top, float *right, float *bottom)
760 {
761     static const GLfloat vertexCoord[] = {
762         -1.0f, -1.0f,
763          1.0f, -1.0f,
764         -1.0f,  1.0f,
765          1.0f,  1.0f,
766     };
767
768     const GLfloat textureCoord[] = {
769         left[0],  bottom[0],
770         right[0], bottom[0],
771         left[0],  top[0],
772         right[0], top[0]
773     };
774
775     glEnable(vgl->tex_target);
776     glActiveTexture(GL_TEXTURE0 + 0);
777     glClientActiveTexture(GL_TEXTURE0 + 0);
778
779     glBindTexture(vgl->tex_target, vgl->texture[0][0]);
780
781     glEnableClientState(GL_VERTEX_ARRAY);
782     glEnableClientState(GL_TEXTURE_COORD_ARRAY);
783
784     glTexCoordPointer(2, GL_FLOAT, 0, textureCoord);
785     glVertexPointer(2, GL_FLOAT, 0, vertexCoord);
786
787     glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
788
789     glDisableClientState(GL_TEXTURE_COORD_ARRAY);
790     glDisableClientState(GL_VERTEX_ARRAY);
791     glDisable(vgl->tex_target);
792 }
793
794 static void DrawWithShaders(vout_display_opengl_t *vgl,
795                             float *left, float *top, float *right, float *bottom)
796 {
797     vgl->UseProgram(vgl->program[0]);
798     vgl->Uniform4fv(vgl->GetUniformLocation(vgl->program[0], "Coefficient"), 4, vgl->local_value);
799     vgl->Uniform1i(vgl->GetUniformLocation(vgl->program[0], "Texture0"), 0);
800     vgl->Uniform1i(vgl->GetUniformLocation(vgl->program[0], "Texture1"), 1);
801     vgl->Uniform1i(vgl->GetUniformLocation(vgl->program[0], "Texture2"), 2);
802
803     static const GLfloat vertexCoord[] = {
804         -1.0,  1.0,
805         -1.0, -1.0,
806          1.0,  1.0,
807          1.0, -1.0,
808     };
809
810     for (unsigned j = 0; j < vgl->chroma->plane_count; j++) {
811         const GLfloat textureCoord[] = {
812             left[j],  top[j],
813             left[j],  bottom[j],
814             right[j], top[j],
815             right[j], bottom[j],
816         };
817         glActiveTexture(GL_TEXTURE0+j);
818         glClientActiveTexture(GL_TEXTURE0+j);
819         glEnable(vgl->tex_target);
820         glBindTexture(vgl->tex_target, vgl->texture[0][j]);
821
822         char attribute[20];
823         snprintf(attribute, sizeof(attribute), "MultiTexCoord%1d", j);
824         vgl->EnableVertexAttribArray(vgl->GetAttribLocation(vgl->program[0], attribute));
825         vgl->VertexAttribPointer(vgl->GetAttribLocation(vgl->program[0], attribute), 2, GL_FLOAT, 0, 0, textureCoord);
826     }
827     glActiveTexture(GL_TEXTURE0 + 0);
828     glClientActiveTexture(GL_TEXTURE0 + 0);
829     vgl->EnableVertexAttribArray(vgl->GetAttribLocation(vgl->program[0], "VertexPosition"));
830     vgl->VertexAttribPointer(vgl->GetAttribLocation(vgl->program[0], "VertexPosition"), 2, GL_FLOAT, 0, 0, vertexCoord);
831
832     glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
833 }
834
835 int vout_display_opengl_Display(vout_display_opengl_t *vgl,
836                                 const video_format_t *source)
837 {
838     if (vlc_gl_Lock(vgl->gl))
839         return VLC_EGENERIC;
840
841     /* Why drawing here and not in Render()? Because this way, the
842        OpenGL providers can call vout_display_opengl_Display to force redraw.i
843        Currently, the OS X provider uses it to get a smooth window resizing */
844     glClear(GL_COLOR_BUFFER_BIT);
845
846     /* Draw the picture */
847     float left[PICTURE_PLANE_MAX];
848     float top[PICTURE_PLANE_MAX];
849     float right[PICTURE_PLANE_MAX];
850     float bottom[PICTURE_PLANE_MAX];
851     for (unsigned j = 0; j < vgl->chroma->plane_count; j++) {
852         /* glTexCoord works differently with GL_TEXTURE_2D and
853            GL_TEXTURE_RECTANGLE_EXT */
854         float scale_w, scale_h;
855
856         if (vgl->tex_target == GL_TEXTURE_2D) {
857             scale_w = (float)vgl->chroma->p[j].w.num / vgl->chroma->p[j].w.den / vgl->tex_width[j];
858             scale_h = (float)vgl->chroma->p[j].h.num / vgl->chroma->p[j].h.den / vgl->tex_height[j];
859
860         } else {
861             scale_w = 1.0;
862             scale_h = 1.0;
863         }
864         left[j]   = (source->i_x_offset +                       0 ) * scale_w;
865         top[j]    = (source->i_y_offset +                       0 ) * scale_h;
866         right[j]  = (source->i_x_offset + source->i_visible_width ) * scale_w;
867         bottom[j] = (source->i_y_offset + source->i_visible_height) * scale_h;
868     }
869
870     if (vgl->program[0])
871         DrawWithShaders(vgl, left, top ,right, bottom);
872     else
873         DrawWithoutShaders(vgl, left, top, right, bottom);
874
875     /* Draw the subpictures */
876     if (vgl->program[1]) {
877         // Change the program for overlays
878         vgl->UseProgram(vgl->program[1]);
879         vgl->Uniform1i(vgl->GetUniformLocation(vgl->program[1], "Texture"), 0);
880     }
881
882     glEnable(GL_TEXTURE_2D);
883     glEnable(GL_BLEND);
884     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
885
886     glActiveTexture(GL_TEXTURE0 + 0);
887     glClientActiveTexture(GL_TEXTURE0 + 0);
888     for (int i = 0; i < vgl->region_count; i++) {
889         gl_region_t *glr = &vgl->region[i];
890         const GLfloat vertexCoord[] = {
891             glr->left,  glr->top,
892             glr->left,  glr->bottom,
893             glr->right, glr->top,
894             glr->right, glr->bottom,
895         };
896         static const GLfloat textureCoord[] = {
897             0.0, 0.0,
898             0.0, 1.0,
899             1.0, 0.0,
900             1.0, 1.0,
901         };
902
903         glBindTexture(GL_TEXTURE_2D, glr->texture);
904         if (vgl->program[1]) {
905             vgl->Uniform4f(vgl->GetUniformLocation(vgl->program[1], "FillColor"), 1.0f, 1.0f, 1.0f, glr->alpha);
906             vgl->EnableVertexAttribArray(vgl->GetAttribLocation(vgl->program[1], "MultiTexCoord0"));
907             vgl->VertexAttribPointer(vgl->GetAttribLocation(vgl->program[1], "MultiTexCoord0"), 2, GL_FLOAT, 0, 0, textureCoord);
908             vgl->EnableVertexAttribArray(vgl->GetAttribLocation(vgl->program[1], "VertexPosition"));
909             vgl->VertexAttribPointer(vgl->GetAttribLocation(vgl->program[1], "VertexPosition"), 2, GL_FLOAT, 0, 0, vertexCoord);
910         } else {
911             glEnableClientState(GL_VERTEX_ARRAY);
912             glEnableClientState(GL_TEXTURE_COORD_ARRAY);
913             glColor4f(1.0f, 1.0f, 1.0f, glr->alpha);
914             glTexCoordPointer(2, GL_FLOAT, 0, textureCoord);
915             glVertexPointer(2, GL_FLOAT, 0, vertexCoord);
916         }
917
918         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
919
920         if (!vgl->program[1]) {
921             glDisableClientState(GL_TEXTURE_COORD_ARRAY);
922             glDisableClientState(GL_VERTEX_ARRAY);
923         }
924     }
925     glDisable(GL_BLEND);
926     glDisable(GL_TEXTURE_2D);
927
928     /* Display */
929     vlc_gl_Swap(vgl->gl);
930
931     vlc_gl_Unlock(vgl->gl);
932     return VLC_SUCCESS;
933 }
934