audio: add af_lavrresample, remove old resampling filters
[mplayer.git] / libvo / gl_common.c
blobf6ea2ebd415140d065bdbd63b7a3267a1dfd886f
1 /*
2 * common OpenGL routines
4 * copyleft (C) 2005-2010 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
5 * Special thanks go to the xine team and Matthias Hopf, whose video_out_opengl.c
6 * gave me lots of good ideas.
8 * This file is part of MPlayer.
10 * MPlayer is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * MPlayer is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * You can alternatively redistribute this file and/or
25 * modify it under the terms of the GNU Lesser General Public
26 * License as published by the Free Software Foundation; either
27 * version 2.1 of the License, or (at your option) any later version.
30 /**
31 * \file gl_common.c
32 * \brief OpenGL helper functions used by vo_gl.c and vo_gl2.c
35 #include <stddef.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <stdbool.h>
41 #include <math.h>
42 #include "talloc.h"
43 #include "gl_common.h"
44 #include "old_vo_wrapper.h"
45 #include "csputils.h"
46 #include "aspect.h"
47 #include "pnm_loader.h"
48 #include "options.h"
50 //! \defgroup glgeneral OpenGL general helper functions
52 // GLU has this as gluErrorString (we don't use GLU, as it is legacy-OpenGL)
53 static const char *gl_error_to_string(GLenum error)
55 switch (error) {
56 case GL_INVALID_ENUM: return "INVALID_ENUM";
57 case GL_INVALID_VALUE: return "INVALID_VALUE";
58 case GL_INVALID_OPERATION: return "INVALID_OPERATION";
59 case GL_INVALID_FRAMEBUFFER_OPERATION:
60 return "INVALID_FRAMEBUFFER_OPERATION";
61 case GL_OUT_OF_MEMORY: return "OUT_OF_MEMORY";
62 default: return "unknown";
66 void glCheckError(GL *gl, const char *info)
68 for (;;) {
69 GLenum error = gl->GetError();
70 if (error == GL_NO_ERROR)
71 break;
72 mp_msg(MSGT_VO, MSGL_ERR, "[gl] %s: OpenGL error %s.\n", info,
73 gl_error_to_string(error));
77 //! \defgroup glcontext OpenGL context management helper functions
79 //! \defgroup gltexture OpenGL texture handling helper functions
81 //! \defgroup glconversion OpenGL conversion helper functions
83 /**
84 * \brief adjusts the GL_UNPACK_ALIGNMENT to fit the stride.
85 * \param stride number of bytes per line for which alignment should fit.
86 * \ingroup glgeneral
88 void glAdjustAlignment(GL *gl, int stride)
90 GLint gl_alignment;
91 if (stride % 8 == 0)
92 gl_alignment = 8;
93 else if (stride % 4 == 0)
94 gl_alignment = 4;
95 else if (stride % 2 == 0)
96 gl_alignment = 2;
97 else
98 gl_alignment = 1;
99 gl->PixelStorei(GL_UNPACK_ALIGNMENT, gl_alignment);
100 gl->PixelStorei(GL_PACK_ALIGNMENT, gl_alignment);
103 //! always return this format as internal texture format in glFindFormat
104 #define TEXTUREFORMAT_ALWAYS GL_RGB8
105 #undef TEXTUREFORMAT_ALWAYS
108 * \brief find the OpenGL settings coresponding to format.
110 * All parameters may be NULL.
111 * \param fmt MPlayer format to analyze.
112 * \param bpp [OUT] bits per pixel of that format.
113 * \param gl_texfmt [OUT] internal texture format that fits the
114 * image format, not necessarily the best for performance.
115 * \param gl_format [OUT] OpenGL format for this image format.
116 * \param gl_type [OUT] OpenGL type for this image format.
117 * \return 1 if format is supported by OpenGL, 0 if not.
118 * \ingroup gltexture
120 int glFindFormat(uint32_t fmt, int have_texture_rg, int *bpp, GLint *gl_texfmt,
121 GLenum *gl_format, GLenum *gl_type)
123 int supported = 1;
124 int dummy1;
125 GLenum dummy2;
126 GLint dummy3;
127 if (!bpp)
128 bpp = &dummy1;
129 if (!gl_texfmt)
130 gl_texfmt = &dummy3;
131 if (!gl_format)
132 gl_format = &dummy2;
133 if (!gl_type)
134 gl_type = &dummy2;
136 if (mp_get_chroma_shift(fmt, NULL, NULL, NULL)) {
137 // reduce the possible cases a bit
138 if (IMGFMT_IS_YUVP16_LE(fmt))
139 fmt = IMGFMT_420P16_LE;
140 else if (IMGFMT_IS_YUVP16_BE(fmt))
141 fmt = IMGFMT_420P16_BE;
142 else
143 fmt = IMGFMT_YV12;
146 *bpp = IMGFMT_IS_BGR(fmt) ? IMGFMT_BGR_DEPTH(fmt) : IMGFMT_RGB_DEPTH(fmt);
147 *gl_texfmt = 3;
148 switch (fmt) {
149 case IMGFMT_RGB48NE:
150 *gl_format = GL_RGB;
151 *gl_type = GL_UNSIGNED_SHORT;
152 break;
153 case IMGFMT_RGB24:
154 *gl_format = GL_RGB;
155 *gl_type = GL_UNSIGNED_BYTE;
156 break;
157 case IMGFMT_RGBA:
158 *gl_texfmt = 4;
159 *gl_format = GL_RGBA;
160 *gl_type = GL_UNSIGNED_BYTE;
161 break;
162 case IMGFMT_420P16:
163 supported = 0; // no native YUV support
164 *gl_texfmt = have_texture_rg ? GL_R16 : GL_LUMINANCE16;
165 *bpp = 16;
166 *gl_format = have_texture_rg ? GL_RED : GL_LUMINANCE;
167 *gl_type = GL_UNSIGNED_SHORT;
168 break;
169 case IMGFMT_YV12:
170 supported = 0; // no native YV12 support
171 case IMGFMT_Y800:
172 case IMGFMT_Y8:
173 *gl_texfmt = 1;
174 *bpp = 8;
175 *gl_format = GL_LUMINANCE;
176 *gl_type = GL_UNSIGNED_BYTE;
177 break;
178 case IMGFMT_UYVY:
179 // IMGFMT_YUY2 would be more logical for the _REV format,
180 // but gives clearly swapped colors.
181 case IMGFMT_YVYU:
182 *gl_texfmt = GL_YCBCR_MESA;
183 *bpp = 16;
184 *gl_format = GL_YCBCR_MESA;
185 *gl_type = fmt == IMGFMT_UYVY ? GL_UNSIGNED_SHORT_8_8 : GL_UNSIGNED_SHORT_8_8_REV;
186 break;
187 #if 0
188 // we do not support palettized formats, although the format the
189 // swscale produces works
190 case IMGFMT_RGB8:
191 *gl_format = GL_RGB;
192 *gl_type = GL_UNSIGNED_BYTE_2_3_3_REV;
193 break;
194 #endif
195 case IMGFMT_RGB15:
196 *gl_format = GL_RGBA;
197 *gl_type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
198 break;
199 case IMGFMT_RGB16:
200 *gl_format = GL_RGB;
201 *gl_type = GL_UNSIGNED_SHORT_5_6_5_REV;
202 break;
203 #if 0
204 case IMGFMT_BGR8:
205 // special case as red and blue have a different number of bits.
206 // GL_BGR and GL_UNSIGNED_BYTE_3_3_2 isn't supported at least
207 // by nVidia drivers, and in addition would give more bits to
208 // blue than to red, which isn't wanted
209 *gl_format = GL_RGB;
210 *gl_type = GL_UNSIGNED_BYTE_3_3_2;
211 break;
212 #endif
213 case IMGFMT_BGR15:
214 *gl_format = GL_BGRA;
215 *gl_type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
216 break;
217 case IMGFMT_BGR16:
218 *gl_format = GL_RGB;
219 *gl_type = GL_UNSIGNED_SHORT_5_6_5;
220 break;
221 case IMGFMT_BGR24:
222 *gl_format = GL_BGR;
223 *gl_type = GL_UNSIGNED_BYTE;
224 break;
225 case IMGFMT_BGRA:
226 *gl_texfmt = 4;
227 *gl_format = GL_BGRA;
228 *gl_type = GL_UNSIGNED_BYTE;
229 break;
230 default:
231 *gl_texfmt = 4;
232 *gl_format = GL_RGBA;
233 *gl_type = GL_UNSIGNED_BYTE;
234 supported = 0;
236 #ifdef TEXTUREFORMAT_ALWAYS
237 *gl_texfmt = TEXTUREFORMAT_ALWAYS;
238 #endif
239 return supported;
242 #ifdef HAVE_LIBDL
243 #include <dlfcn.h>
244 #endif
246 * \brief find address of a linked function
247 * \param s name of function to find
248 * \return address of function or NULL if not found
250 static void *getdladdr(const char *s)
252 void *ret = NULL;
253 #ifdef HAVE_LIBDL
254 void *handle = dlopen(NULL, RTLD_LAZY);
255 if (!handle)
256 return NULL;
257 ret = dlsym(handle, s);
258 dlclose(handle);
259 #endif
260 return ret;
263 typedef struct {
264 ptrdiff_t offset; // offset to the function pointer in struct GL
265 const char *extstr;
266 const char *funcnames[7];
267 void *fallback;
268 bool is_gl3;
269 } extfunc_desc_t;
271 #define DEF_FUNC_DESC(name) \
272 {offsetof(GL, name), NULL, {"gl" # name}, gl ## name}
273 #define DEF_EXT_FUNCS(...) __VA_ARGS__
274 #define DEF_EXT_DESC(name, ext, funcnames) \
275 {offsetof(GL, name), ext, {DEF_EXT_FUNCS funcnames}}
276 // These are mostly handled the same, but needed because at least the MESA
277 // headers don't define any function prototypes for these.
278 #define DEF_GL3_DESC(name) \
279 {offsetof(GL, name), NULL, {"gl" # name}, NULL, .is_gl3 = true}
281 static const extfunc_desc_t extfuncs[] = {
282 // these aren't extension functions but we query them anyway to allow
283 // different "backends" with one binary
284 DEF_FUNC_DESC(Viewport),
285 DEF_FUNC_DESC(Clear),
286 DEF_FUNC_DESC(GenTextures),
287 DEF_FUNC_DESC(DeleteTextures),
288 DEF_FUNC_DESC(TexEnvi),
289 DEF_FUNC_DESC(ClearColor),
290 DEF_FUNC_DESC(Enable),
291 DEF_FUNC_DESC(Disable),
292 DEF_FUNC_DESC(DrawBuffer),
293 DEF_FUNC_DESC(DepthMask),
294 DEF_FUNC_DESC(BlendFunc),
295 DEF_FUNC_DESC(Flush),
296 DEF_FUNC_DESC(Finish),
297 DEF_FUNC_DESC(PixelStorei),
298 DEF_FUNC_DESC(TexImage1D),
299 DEF_FUNC_DESC(TexImage2D),
300 DEF_FUNC_DESC(TexSubImage2D),
301 DEF_FUNC_DESC(GetTexImage),
302 DEF_FUNC_DESC(TexParameteri),
303 DEF_FUNC_DESC(TexParameterf),
304 DEF_FUNC_DESC(TexParameterfv),
305 DEF_FUNC_DESC(GetIntegerv),
306 DEF_FUNC_DESC(GetBooleanv),
307 DEF_FUNC_DESC(ColorMask),
308 DEF_FUNC_DESC(ReadPixels),
309 DEF_FUNC_DESC(ReadBuffer),
310 DEF_FUNC_DESC(DrawArrays),
311 DEF_FUNC_DESC(GetString),
312 DEF_FUNC_DESC(GetError),
314 // legacy GL functions (1.x - 2.x)
315 DEF_FUNC_DESC(Begin),
316 DEF_FUNC_DESC(End),
317 DEF_FUNC_DESC(MatrixMode),
318 DEF_FUNC_DESC(LoadIdentity),
319 DEF_FUNC_DESC(Translated),
320 DEF_FUNC_DESC(Scaled),
321 DEF_FUNC_DESC(Ortho),
322 DEF_FUNC_DESC(PushMatrix),
323 DEF_FUNC_DESC(PopMatrix),
324 DEF_FUNC_DESC(GenLists),
325 DEF_FUNC_DESC(DeleteLists),
326 DEF_FUNC_DESC(NewList),
327 DEF_FUNC_DESC(EndList),
328 DEF_FUNC_DESC(CallList),
329 DEF_FUNC_DESC(CallLists),
330 DEF_FUNC_DESC(Color4ub),
331 DEF_FUNC_DESC(Color4f),
332 DEF_FUNC_DESC(TexCoord2f),
333 DEF_FUNC_DESC(TexCoord2fv),
334 DEF_FUNC_DESC(Vertex2f),
335 DEF_FUNC_DESC(VertexPointer),
336 DEF_FUNC_DESC(ColorPointer),
337 DEF_FUNC_DESC(TexCoordPointer),
338 DEF_FUNC_DESC(EnableClientState),
339 DEF_FUNC_DESC(DisableClientState),
341 // OpenGL extension functions
342 DEF_EXT_DESC(GenBuffers, NULL,
343 ("glGenBuffers", "glGenBuffersARB")),
344 DEF_EXT_DESC(DeleteBuffers, NULL,
345 ("glDeleteBuffers", "glDeleteBuffersARB")),
346 DEF_EXT_DESC(BindBuffer, NULL,
347 ("glBindBuffer", "glBindBufferARB")),
348 DEF_EXT_DESC(MapBuffer, NULL,
349 ("glMapBuffer", "glMapBufferARB")),
350 DEF_EXT_DESC(UnmapBuffer, NULL,
351 ("glUnmapBuffer", "glUnmapBufferARB")),
352 DEF_EXT_DESC(BufferData, NULL,
353 ("glBufferData", "glBufferDataARB")),
354 DEF_EXT_DESC(ActiveTexture, NULL,
355 ("glActiveTexture", "glActiveTextureARB")),
356 DEF_EXT_DESC(BindTexture, NULL,
357 ("glBindTexture", "glBindTextureARB", "glBindTextureEXT")),
358 DEF_EXT_DESC(MultiTexCoord2f, NULL,
359 ("glMultiTexCoord2f", "glMultiTexCoord2fARB")),
360 DEF_EXT_DESC(GenPrograms, "_program",
361 ("glGenProgramsARB")),
362 DEF_EXT_DESC(DeletePrograms, "_program",
363 ("glDeleteProgramsARB")),
364 DEF_EXT_DESC(BindProgram, "_program",
365 ("glBindProgramARB")),
366 DEF_EXT_DESC(ProgramString, "_program",
367 ("glProgramStringARB")),
368 DEF_EXT_DESC(GetProgramivARB, "_program",
369 ("glGetProgramivARB")),
370 DEF_EXT_DESC(ProgramEnvParameter4f, "_program",
371 ("glProgramEnvParameter4fARB")),
372 DEF_EXT_DESC(SwapInterval, "_swap_control",
373 ("glXSwapIntervalSGI", "glXSwapInterval", "wglSwapIntervalSGI",
374 "wglSwapInterval", "wglSwapIntervalEXT")),
375 DEF_EXT_DESC(TexImage3D, NULL,
376 ("glTexImage3D")),
378 // ancient ATI extensions
379 DEF_EXT_DESC(BeginFragmentShader, "ATI_fragment_shader",
380 ("glBeginFragmentShaderATI")),
381 DEF_EXT_DESC(EndFragmentShader, "ATI_fragment_shader",
382 ("glEndFragmentShaderATI")),
383 DEF_EXT_DESC(SampleMap, "ATI_fragment_shader",
384 ("glSampleMapATI")),
385 DEF_EXT_DESC(ColorFragmentOp2, "ATI_fragment_shader",
386 ("glColorFragmentOp2ATI")),
387 DEF_EXT_DESC(ColorFragmentOp3, "ATI_fragment_shader",
388 ("glColorFragmentOp3ATI")),
389 DEF_EXT_DESC(SetFragmentShaderConstant, "ATI_fragment_shader",
390 ("glSetFragmentShaderConstantATI")),
392 // GL 3, possibly in GL 2.x as well in form of extensions
393 DEF_GL3_DESC(GenBuffers),
394 DEF_GL3_DESC(DeleteBuffers),
395 DEF_GL3_DESC(BindBuffer),
396 DEF_GL3_DESC(MapBuffer),
397 DEF_GL3_DESC(UnmapBuffer),
398 DEF_GL3_DESC(BufferData),
399 DEF_GL3_DESC(ActiveTexture),
400 DEF_GL3_DESC(BindTexture),
401 DEF_GL3_DESC(GenVertexArrays),
402 DEF_GL3_DESC(BindVertexArray),
403 DEF_GL3_DESC(GetAttribLocation),
404 DEF_GL3_DESC(EnableVertexAttribArray),
405 DEF_GL3_DESC(DisableVertexAttribArray),
406 DEF_GL3_DESC(VertexAttribPointer),
407 DEF_GL3_DESC(DeleteVertexArrays),
408 DEF_GL3_DESC(UseProgram),
409 DEF_GL3_DESC(GetUniformLocation),
410 DEF_GL3_DESC(CompileShader),
411 DEF_GL3_DESC(CreateProgram),
412 DEF_GL3_DESC(CreateShader),
413 DEF_GL3_DESC(ShaderSource),
414 DEF_GL3_DESC(LinkProgram),
415 DEF_GL3_DESC(AttachShader),
416 DEF_GL3_DESC(DeleteShader),
417 DEF_GL3_DESC(DeleteProgram),
418 DEF_GL3_DESC(GetShaderInfoLog),
419 DEF_GL3_DESC(GetShaderiv),
420 DEF_GL3_DESC(GetProgramInfoLog),
421 DEF_GL3_DESC(GetProgramiv),
422 DEF_GL3_DESC(GetStringi),
423 DEF_GL3_DESC(BindAttribLocation),
424 DEF_GL3_DESC(BindFramebuffer),
425 DEF_GL3_DESC(GenFramebuffers),
426 DEF_GL3_DESC(DeleteFramebuffers),
427 DEF_GL3_DESC(CheckFramebufferStatus),
428 DEF_GL3_DESC(FramebufferTexture2D),
429 DEF_GL3_DESC(Uniform1f),
430 DEF_GL3_DESC(Uniform3f),
431 DEF_GL3_DESC(Uniform1i),
432 DEF_GL3_DESC(UniformMatrix3fv),
433 DEF_GL3_DESC(UniformMatrix4x3fv),
435 {-1}
439 * \brief find the function pointers of some useful OpenGL extensions
440 * \param getProcAddress function to resolve function names, may be NULL
441 * \param ext2 an extra extension string
443 static void getFunctions(GL *gl, void *(*getProcAddress)(const GLubyte *),
444 const char *ext2, bool is_gl3)
446 const extfunc_desc_t *dsc;
447 char *allexts = talloc_strdup(NULL, ext2 ? ext2 : "");
449 *gl = (GL) {0};
451 if (!getProcAddress)
452 getProcAddress = (void *)getdladdr;
454 if (is_gl3) {
455 gl->GetStringi = getProcAddress("glGetStringi");
456 gl->GetIntegerv = getProcAddress("glGetIntegerv");
458 if (!(gl->GetStringi && gl->GetIntegerv))
459 return;
461 GLint exts;
462 gl->GetIntegerv(GL_NUM_EXTENSIONS, &exts);
463 for (int n = 0; n < exts; n++) {
464 allexts = talloc_asprintf_append(allexts, " %s",
465 gl->GetStringi(GL_EXTENSIONS, n));
467 } else {
468 gl->GetString = getProcAddress("glGetString");
469 if (!gl->GetString)
470 gl->GetString = glGetString;
471 const char *ext = (char*)gl->GetString(GL_EXTENSIONS);
472 allexts = talloc_asprintf_append(allexts, " %s", ext);
475 mp_msg(MSGT_VO, MSGL_DBG2, "OpenGL extensions string:\n%s\n", allexts);
476 for (dsc = extfuncs; dsc->offset >= 0; dsc++) {
477 void *ptr = NULL;
478 if (!dsc->extstr || strstr(allexts, dsc->extstr)) {
479 for (int i = 0; !ptr && dsc->funcnames[i]; i++)
480 ptr = getProcAddress((const GLubyte *)dsc->funcnames[i]);
482 if (!ptr)
483 ptr = dsc->fallback;
484 if (!ptr && !dsc->extstr && (!dsc->is_gl3 || is_gl3))
485 mp_msg(MSGT_VO, MSGL_WARN, "[gl] OpenGL function not found: %s\n",
486 dsc->funcnames[0]);
487 void **funcptr = (void**)(((char*)gl) + dsc->offset);
488 *funcptr = ptr;
490 talloc_free(allexts);
494 * \brief create a texture and set some defaults
495 * \param target texture taget, usually GL_TEXTURE_2D
496 * \param fmt internal texture format
497 * \param format texture host data format
498 * \param type texture host data type
499 * \param filter filter used for scaling, e.g. GL_LINEAR
500 * \param w texture width
501 * \param h texture height
502 * \param val luminance value to fill texture with
503 * \ingroup gltexture
505 void glCreateClearTex(GL *gl, GLenum target, GLenum fmt, GLenum format,
506 GLenum type, GLint filter, int w, int h,
507 unsigned char val)
509 GLfloat fval = (GLfloat)val / 255.0;
510 GLfloat border[4] = {
511 fval, fval, fval, fval
513 int stride;
514 char *init;
515 if (w == 0)
516 w = 1;
517 if (h == 0)
518 h = 1;
519 stride = w * glFmt2bpp(format, type);
520 if (!stride)
521 return;
522 init = malloc(stride * h);
523 memset(init, val, stride * h);
524 glAdjustAlignment(gl, stride);
525 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, w);
526 gl->TexImage2D(target, 0, fmt, w, h, 0, format, type, init);
527 gl->TexParameterf(target, GL_TEXTURE_PRIORITY, 1.0);
528 gl->TexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
529 gl->TexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
530 gl->TexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
531 gl->TexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
532 // Border texels should not be used with CLAMP_TO_EDGE
533 // We set a sane default anyway.
534 gl->TexParameterfv(target, GL_TEXTURE_BORDER_COLOR, border);
535 free(init);
538 static GLint detect_hqtexfmt(GL *gl)
540 const char *extensions = (const char *)gl->GetString(GL_EXTENSIONS);
541 if (strstr(extensions, "_texture_float"))
542 return GL_RGB32F;
543 else if (strstr(extensions, "NV_float_buffer"))
544 return GL_FLOAT_RGB32_NV;
545 return GL_RGB16;
549 * \brief creates a texture from a PPM file
550 * \param target texture taget, usually GL_TEXTURE_2D
551 * \param fmt internal texture format, 0 for default
552 * \param filter filter used for scaling, e.g. GL_LINEAR
553 * \param f file to read PPM from
554 * \param width [out] width of texture
555 * \param height [out] height of texture
556 * \param maxval [out] maxval value from PPM file
557 * \return 0 on error, 1 otherwise
558 * \ingroup gltexture
560 int glCreatePPMTex(GL *gl, GLenum target, GLenum fmt, GLint filter,
561 FILE *f, int *width, int *height, int *maxval)
563 int w, h, m, bpp;
564 GLenum type;
565 uint8_t *data = read_pnm(f, &w, &h, &bpp, &m);
566 GLint hqtexfmt = detect_hqtexfmt(gl);
567 if (!data || (bpp != 3 && bpp != 6)) {
568 free(data);
569 return 0;
571 if (!fmt) {
572 fmt = bpp == 6 ? hqtexfmt : 3;
573 if (fmt == GL_FLOAT_RGB32_NV && target != GL_TEXTURE_RECTANGLE)
574 fmt = GL_RGB16;
576 type = bpp == 6 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
577 glCreateClearTex(gl, target, fmt, GL_RGB, type, filter, w, h, 0);
578 glUploadTex(gl, target, GL_RGB, type,
579 data, w * bpp, 0, 0, w, h, 0);
580 free(data);
581 if (width)
582 *width = w;
583 if (height)
584 *height = h;
585 if (maxval)
586 *maxval = m;
587 return 1;
591 * \brief return the number of bytes per pixel for the given format
592 * \param format OpenGL format
593 * \param type OpenGL type
594 * \return bytes per pixel
595 * \ingroup glgeneral
597 * Does not handle all possible variants, just those used by MPlayer
599 int glFmt2bpp(GLenum format, GLenum type)
601 int component_size = 0;
602 switch (type) {
603 case GL_UNSIGNED_BYTE_3_3_2:
604 case GL_UNSIGNED_BYTE_2_3_3_REV:
605 return 1;
606 case GL_UNSIGNED_SHORT_5_5_5_1:
607 case GL_UNSIGNED_SHORT_1_5_5_5_REV:
608 case GL_UNSIGNED_SHORT_5_6_5:
609 case GL_UNSIGNED_SHORT_5_6_5_REV:
610 return 2;
611 case GL_UNSIGNED_BYTE:
612 component_size = 1;
613 break;
614 case GL_UNSIGNED_SHORT:
615 component_size = 2;
616 break;
618 switch (format) {
619 case GL_LUMINANCE:
620 case GL_ALPHA:
621 return component_size;
622 case GL_YCBCR_MESA:
623 return 2;
624 case GL_RGB:
625 case GL_BGR:
626 return 3 * component_size;
627 case GL_RGBA:
628 case GL_BGRA:
629 return 4 * component_size;
630 case GL_RED:
631 return component_size;
632 case GL_RG:
633 case GL_LUMINANCE_ALPHA:
634 return 2 * component_size;
636 return 0; // unknown
640 * \brief upload a texture, handling things like stride and slices
641 * \param target texture target, usually GL_TEXTURE_2D
642 * \param format OpenGL format of data
643 * \param type OpenGL type of data
644 * \param dataptr data to upload
645 * \param stride data stride
646 * \param x x offset in texture
647 * \param y y offset in texture
648 * \param w width of the texture part to upload
649 * \param h height of the texture part to upload
650 * \param slice height of an upload slice, 0 for all at once
651 * \ingroup gltexture
653 void glUploadTex(GL *gl, GLenum target, GLenum format, GLenum type,
654 const void *dataptr, int stride,
655 int x, int y, int w, int h, int slice)
657 const uint8_t *data = dataptr;
658 int y_max = y + h;
659 if (w <= 0 || h <= 0)
660 return;
661 if (slice <= 0)
662 slice = h;
663 if (stride < 0) {
664 data += (h - 1) * stride;
665 stride = -stride;
667 // this is not always correct, but should work for MPlayer
668 glAdjustAlignment(gl, stride);
669 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
670 for (; y + slice <= y_max; y += slice) {
671 gl->TexSubImage2D(target, 0, x, y, w, slice, format, type, data);
672 data += stride * slice;
674 if (y < y_max)
675 gl->TexSubImage2D(target, 0, x, y, w, y_max - y, format, type, data);
679 * \brief download a texture, handling things like stride and slices
680 * \param target texture target, usually GL_TEXTURE_2D
681 * \param format OpenGL format of data
682 * \param type OpenGL type of data
683 * \param dataptr destination memory for download
684 * \param stride data stride (must be positive)
685 * \ingroup gltexture
687 void glDownloadTex(GL *gl, GLenum target, GLenum format, GLenum type,
688 void *dataptr, int stride)
690 // this is not always correct, but should work for MPlayer
691 glAdjustAlignment(gl, stride);
692 gl->PixelStorei(GL_PACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
693 gl->GetTexImage(target, 0, format, type, dataptr);
697 * \brief Setup ATI version of register combiners for YUV to RGB conversion.
698 * \param csp_params parameters used for colorspace conversion
699 * \param text if set use the GL_ATI_text_fragment_shader API as
700 * used on OS X.
702 static void glSetupYUVFragmentATI(GL *gl, struct mp_csp_params *csp_params,
703 int text)
705 GLint i;
706 float yuv2rgb[3][4];
708 gl->GetIntegerv(GL_MAX_TEXTURE_UNITS, &i);
709 if (i < 3)
710 mp_msg(MSGT_VO, MSGL_ERR,
711 "[gl] 3 texture units needed for YUV combiner (ATI) support (found %i)\n", i);
713 mp_get_yuv2rgb_coeffs(csp_params, yuv2rgb);
714 for (i = 0; i < 3; i++) {
715 int j;
716 yuv2rgb[i][3] -= -0.5 * (yuv2rgb[i][1] + yuv2rgb[i][2]);
717 for (j = 0; j < 4; j++) {
718 yuv2rgb[i][j] *= 0.125;
719 yuv2rgb[i][j] += 0.5;
720 if (yuv2rgb[i][j] > 1)
721 yuv2rgb[i][j] = 1;
722 if (yuv2rgb[i][j] < 0)
723 yuv2rgb[i][j] = 0;
726 if (text == 0) {
727 GLfloat c0[4] = { yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0] };
728 GLfloat c1[4] = { yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1] };
729 GLfloat c2[4] = { yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2] };
730 GLfloat c3[4] = { yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3] };
731 if (!gl->BeginFragmentShader || !gl->EndFragmentShader ||
732 !gl->SetFragmentShaderConstant || !gl->SampleMap ||
733 !gl->ColorFragmentOp2 || !gl->ColorFragmentOp3) {
734 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Combiner (ATI) functions missing!\n");
735 return;
737 gl->GetIntegerv(GL_NUM_FRAGMENT_REGISTERS_ATI, &i);
738 if (i < 3)
739 mp_msg(MSGT_VO, MSGL_ERR,
740 "[gl] 3 registers needed for YUV combiner (ATI) support (found %i)\n", i);
741 gl->BeginFragmentShader();
742 gl->SetFragmentShaderConstant(GL_CON_0_ATI, c0);
743 gl->SetFragmentShaderConstant(GL_CON_1_ATI, c1);
744 gl->SetFragmentShaderConstant(GL_CON_2_ATI, c2);
745 gl->SetFragmentShaderConstant(GL_CON_3_ATI, c3);
746 gl->SampleMap(GL_REG_0_ATI, GL_TEXTURE0, GL_SWIZZLE_STR_ATI);
747 gl->SampleMap(GL_REG_1_ATI, GL_TEXTURE1, GL_SWIZZLE_STR_ATI);
748 gl->SampleMap(GL_REG_2_ATI, GL_TEXTURE2, GL_SWIZZLE_STR_ATI);
749 gl->ColorFragmentOp2(GL_MUL_ATI, GL_REG_1_ATI, GL_NONE, GL_NONE,
750 GL_REG_1_ATI, GL_NONE, GL_BIAS_BIT_ATI,
751 GL_CON_1_ATI, GL_NONE, GL_BIAS_BIT_ATI);
752 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_2_ATI, GL_NONE, GL_NONE,
753 GL_REG_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
754 GL_CON_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
755 GL_REG_1_ATI, GL_NONE, GL_NONE);
756 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_0_ATI, GL_NONE, GL_NONE,
757 GL_REG_0_ATI, GL_NONE, GL_NONE,
758 GL_CON_0_ATI, GL_NONE, GL_BIAS_BIT_ATI,
759 GL_REG_2_ATI, GL_NONE, GL_NONE);
760 gl->ColorFragmentOp2(GL_ADD_ATI, GL_REG_0_ATI, GL_NONE, GL_8X_BIT_ATI,
761 GL_REG_0_ATI, GL_NONE, GL_NONE,
762 GL_CON_3_ATI, GL_NONE, GL_BIAS_BIT_ATI);
763 gl->EndFragmentShader();
764 } else {
765 static const char template[] =
766 "!!ATIfs1.0\n"
767 "StartConstants;\n"
768 " CONSTANT c0 = {%e, %e, %e};\n"
769 " CONSTANT c1 = {%e, %e, %e};\n"
770 " CONSTANT c2 = {%e, %e, %e};\n"
771 " CONSTANT c3 = {%e, %e, %e};\n"
772 "EndConstants;\n"
773 "StartOutputPass;\n"
774 " SampleMap r0, t0.str;\n"
775 " SampleMap r1, t1.str;\n"
776 " SampleMap r2, t2.str;\n"
777 " MUL r1.rgb, r1.bias, c1.bias;\n"
778 " MAD r2.rgb, r2.bias, c2.bias, r1;\n"
779 " MAD r0.rgb, r0, c0.bias, r2;\n"
780 " ADD r0.rgb.8x, r0, c3.bias;\n"
781 "EndPass;\n";
782 char buffer[512];
783 snprintf(buffer, sizeof(buffer), template,
784 yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0],
785 yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1],
786 yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2],
787 yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3]);
788 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
789 buffer);
790 loadGPUProgram(gl, GL_TEXT_FRAGMENT_SHADER_ATI, buffer);
794 // Replace all occurances of variables named "$"+name (e.g. $foo) in *text with
795 // replace, and return the result. *text must have been allocated with talloc.
796 static void replace_var_str(char **text, const char *name, const char *replace)
798 size_t namelen = strlen(name);
799 char *nextvar = *text;
800 void *parent = talloc_parent(*text);
801 for (;;) {
802 nextvar = strchr(nextvar, '$');
803 if (!nextvar)
804 break;
805 char *until = nextvar;
806 nextvar++;
807 if (strncmp(nextvar, name, namelen) != 0)
808 continue;
809 nextvar += namelen;
810 // try not to replace prefixes of other vars (e.g. $foo vs. $foo_bar)
811 char term = nextvar[0];
812 if (isalnum(term) || term == '_')
813 continue;
814 int prelength = until - *text;
815 int postlength = nextvar - *text;
816 char *n = talloc_asprintf(parent, "%.*s%s%s", prelength, *text, replace,
817 nextvar);
818 talloc_free(*text);
819 *text = n;
820 nextvar = *text + postlength;
824 static void replace_var_float(char **text, const char *name, float replace)
826 char *s = talloc_asprintf(NULL, "%e", replace);
827 replace_var_str(text, name, s);
828 talloc_free(s);
831 static void replace_var_char(char **text, const char *name, char replace)
833 char s[2] = { replace, '\0' };
834 replace_var_str(text, name, s);
837 // Append template to *text. Possibly initialize *text if it's NULL.
838 static void append_template(char **text, const char* template)
840 if (!text)
841 *text = talloc_strdup(NULL, template);
842 else
843 *text = talloc_strdup_append(*text, template);
847 * \brief helper function for gen_spline_lookup_tex
848 * \param x subpixel-position ((0,1) range) to calculate weights for
849 * \param dst where to store transformed weights, must provide space for 4 GLfloats
851 * calculates the weights and stores them after appropriate transformation
852 * for the scaler fragment program.
854 static void store_weights(float x, GLfloat *dst)
856 float w0 = (((-1 * x + 3) * x - 3) * x + 1) / 6;
857 float w1 = (((3 * x - 6) * x + 0) * x + 4) / 6;
858 float w2 = (((-3 * x + 3) * x + 3) * x + 1) / 6;
859 float w3 = (((1 * x + 0) * x + 0) * x + 0) / 6;
860 *dst++ = 1 + x - w1 / (w0 + w1);
861 *dst++ = 1 - x + w3 / (w2 + w3);
862 *dst++ = w0 + w1;
863 *dst++ = 0;
866 //! to avoid artefacts this should be rather large
867 #define LOOKUP_BSPLINE_RES (2 * 1024)
869 * \brief creates the 1D lookup texture needed for fast higher-order filtering
870 * \param unit texture unit to attach texture to
872 static void gen_spline_lookup_tex(GL *gl, GLenum unit)
874 GLfloat *tex = calloc(4 * LOOKUP_BSPLINE_RES, sizeof(*tex));
875 GLfloat *tp = tex;
876 int i;
877 for (i = 0; i < LOOKUP_BSPLINE_RES; i++) {
878 float x = (float)(i + 0.5) / LOOKUP_BSPLINE_RES;
879 store_weights(x, tp);
880 tp += 4;
882 store_weights(0, tex);
883 store_weights(1, &tex[4 * (LOOKUP_BSPLINE_RES - 1)]);
884 gl->ActiveTexture(unit);
885 gl->TexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, LOOKUP_BSPLINE_RES, 0, GL_RGBA,
886 GL_FLOAT, tex);
887 gl->TexParameterf(GL_TEXTURE_1D, GL_TEXTURE_PRIORITY, 1.0);
888 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
889 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
890 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
891 gl->ActiveTexture(GL_TEXTURE0);
892 free(tex);
895 #define NOISE_RES 2048
898 * \brief creates the 1D lookup texture needed to generate pseudo-random numbers.
899 * \param unit texture unit to attach texture to
901 static void gen_noise_lookup_tex(GL *gl, GLenum unit) {
902 GLfloat *tex = calloc(NOISE_RES, sizeof(*tex));
903 uint32_t lcg = 0x79381c11;
904 int i;
905 for (i = 0; i < NOISE_RES; i++)
906 tex[i] = (double)i / (NOISE_RES - 1);
907 for (i = 0; i < NOISE_RES - 1; i++) {
908 int remain = NOISE_RES - i;
909 int idx = i + (lcg >> 16) % remain;
910 GLfloat tmp = tex[i];
911 tex[i] = tex[idx];
912 tex[idx] = tmp;
913 lcg = lcg * 1664525 + 1013904223;
915 gl->ActiveTexture(unit);
916 gl->TexImage1D(GL_TEXTURE_1D, 0, 1, NOISE_RES, 0, GL_RED, GL_FLOAT, tex);
917 gl->TexParameterf(GL_TEXTURE_1D, GL_TEXTURE_PRIORITY, 1.0);
918 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
919 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
920 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
921 gl->ActiveTexture(GL_TEXTURE0);
922 free(tex);
925 #define SAMPLE(dest, coord, texture) \
926 "TEX textemp, " coord ", " texture ", $tex_type;\n" \
927 "MOV " dest ", textemp.r;\n"
929 static const char bilin_filt_template[] =
930 SAMPLE("yuv.$out_comp","fragment.texcoord[$in_tex]","texture[$in_tex]");
932 #define BICUB_FILT_MAIN \
933 /* first y-interpolation */ \
934 "ADD coord, fragment.texcoord[$in_tex].xyxy, cdelta.xyxw;\n" \
935 "ADD coord2, fragment.texcoord[$in_tex].xyxy, cdelta.zyzw;\n" \
936 SAMPLE("a.r","coord.xyxy","texture[$in_tex]") \
937 SAMPLE("a.g","coord.zwzw","texture[$in_tex]") \
938 /* second y-interpolation */ \
939 SAMPLE("b.r","coord2.xyxy","texture[$in_tex]") \
940 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]") \
941 "LRP a.b, parmy.b, a.rrrr, a.gggg;\n" \
942 "LRP a.a, parmy.b, b.rrrr, b.gggg;\n" \
943 /* x-interpolation */ \
944 "LRP yuv.$out_comp, parmx.b, a.bbbb, a.aaaa;\n"
946 static const char bicub_filt_template_2D[] =
947 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
948 "TEX parmx, coord.x, texture[$texs], 1D;\n"
949 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
950 "TEX parmy, coord.y, texture[$texs], 1D;\n"
951 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
952 BICUB_FILT_MAIN;
954 static const char bicub_filt_template_RECT[] =
955 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
956 "TEX parmx, coord.x, texture[$texs], 1D;\n"
957 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
958 "TEX parmy, coord.y, texture[$texs], 1D;\n"
959 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
960 BICUB_FILT_MAIN;
962 #define CALCWEIGHTS(t, s) \
963 "MAD "t ", {-0.5, 0.1666, 0.3333, -0.3333}, "s ", {1, 0, -0.5, 0.5};\n" \
964 "MAD "t ", "t ", "s ", {0, 0, -0.5, 0.5};\n" \
965 "MAD "t ", "t ", "s ", {-0.6666, 0, 0.8333, 0.1666};\n" \
966 "RCP a.x, "t ".z;\n" \
967 "RCP a.y, "t ".w;\n" \
968 "MAD "t ".xy, "t ".xyxy, a.xyxy, {1, 1, 0, 0};\n" \
969 "ADD "t ".x, "t ".xxxx, "s ";\n" \
970 "SUB "t ".y, "t ".yyyy, "s ";\n"
972 static const char bicub_notex_filt_template_2D[] =
973 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
974 "FRC coord.xy, coord.xyxy;\n"
975 CALCWEIGHTS("parmx", "coord.xxxx")
976 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
977 CALCWEIGHTS("parmy", "coord.yyyy")
978 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
979 BICUB_FILT_MAIN;
981 static const char bicub_notex_filt_template_RECT[] =
982 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
983 "FRC coord.xy, coord.xyxy;\n"
984 CALCWEIGHTS("parmx", "coord.xxxx")
985 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
986 CALCWEIGHTS("parmy", "coord.yyyy")
987 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
988 BICUB_FILT_MAIN;
990 #define BICUB_X_FILT_MAIN \
991 "ADD coord.xy, fragment.texcoord[$in_tex].xyxy, cdelta.xyxy;\n" \
992 "ADD coord2.xy, fragment.texcoord[$in_tex].xyxy, cdelta.zyzy;\n" \
993 SAMPLE("a.r","coord","texture[$in_tex]") \
994 SAMPLE("b.r","coord2","texture[$in_tex]") \
995 /* x-interpolation */ \
996 "LRP yuv.$out_comp, parmx.b, a.rrrr, b.rrrr;\n"
998 static const char bicub_x_filt_template_2D[] =
999 "MAD coord.x, fragment.texcoord[$in_tex], {$texw}, {0.5};\n"
1000 "TEX parmx, coord, texture[$texs], 1D;\n"
1001 "MUL cdelta.xyz, parmx.rrgg, {-$ptw, 0, $ptw};\n"
1002 BICUB_X_FILT_MAIN;
1004 static const char bicub_x_filt_template_RECT[] =
1005 "ADD coord.x, fragment.texcoord[$in_tex], {0.5};\n"
1006 "TEX parmx, coord, texture[$texs], 1D;\n"
1007 "MUL cdelta.xyz, parmx.rrgg, {-1, 0, 1};\n"
1008 BICUB_X_FILT_MAIN;
1010 static const char unsharp_filt_template[] =
1011 "PARAM dcoord$out_comp = {$ptw_05, $pth_05, $ptw_05, -$pth_05};\n"
1012 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
1013 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
1014 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
1015 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
1016 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
1017 "ADD b.r, b.r, b.g;\n"
1018 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
1019 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
1020 "DP3 b, b, {0.25, 0.25, 0.25};\n"
1021 "SUB b.r, a.r, b.r;\n"
1022 "MAD textemp.r, b.r, {$strength}, a.r;\n"
1023 "MOV yuv.$out_comp, textemp.r;\n";
1025 static const char unsharp_filt_template2[] =
1026 "PARAM dcoord$out_comp = {$ptw_12, $pth_12, $ptw_12, -$pth_12};\n"
1027 "PARAM dcoord2$out_comp = {$ptw_15, 0, 0, $pth_15};\n"
1028 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
1029 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
1030 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
1031 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
1032 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
1033 "ADD b.r, b.r, b.g;\n"
1034 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
1035 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
1036 "ADD b.r, b.r, b.b;\n"
1037 "ADD b.a, b.r, b.g;\n"
1038 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
1039 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
1040 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
1041 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
1042 "ADD b.r, b.r, b.g;\n"
1043 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
1044 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
1045 "DP4 b.r, b, {-0.1171875, -0.1171875, -0.1171875, -0.09765625};\n"
1046 "MAD b.r, a.r, {0.859375}, b.r;\n"
1047 "MAD textemp.r, b.r, {$strength}, a.r;\n"
1048 "MOV yuv.$out_comp, textemp.r;\n";
1050 static const char yuv_prog_template[] =
1051 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
1052 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
1053 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
1054 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
1055 "TEMP res;\n"
1056 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
1057 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1058 "MAD res.rgb, yuv.bbbb, vcoef, res;\n";
1060 static const char yuv_pow_prog_template[] =
1061 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
1062 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
1063 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
1064 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
1065 "PARAM gamma = {$gamma_r, $gamma_g, $gamma_b};\n"
1066 "TEMP res;\n"
1067 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
1068 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1069 "MAD_SAT res.rgb, yuv.bbbb, vcoef, res;\n"
1070 "POW res.r, res.r, gamma.r;\n"
1071 "POW res.g, res.g, gamma.g;\n"
1072 "POW res.b, res.b, gamma.b;\n";
1074 static const char yuv_lookup_prog_template[] =
1075 "PARAM ycoef = {$cm11, $cm21, $cm31, 0};\n"
1076 "PARAM ucoef = {$cm12, $cm22, $cm32, 0};\n"
1077 "PARAM vcoef = {$cm13, $cm23, $cm33, 0};\n"
1078 "PARAM offsets = {$cm14, $cm24, $cm34, 0.125};\n"
1079 "TEMP res;\n"
1080 "MAD res, yuv.rrrr, ycoef, offsets;\n"
1081 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1082 "MAD res.rgb, yuv.bbbb, vcoef, res;\n"
1083 "TEX res.r, res.raaa, texture[$conv_tex0], 2D;\n"
1084 "ADD res.a, res.a, 0.25;\n"
1085 "TEX res.g, res.gaaa, texture[$conv_tex0], 2D;\n"
1086 "ADD res.a, res.a, 0.25;\n"
1087 "TEX res.b, res.baaa, texture[$conv_tex0], 2D;\n";
1089 static const char yuv_lookup3d_prog_template[] =
1090 "TEMP res;\n"
1091 "TEX res, yuv, texture[$conv_tex0], 3D;\n";
1093 static const char noise_filt_template[] =
1094 "MUL coord.xy, fragment.texcoord[0], {$noise_sx, $noise_sy};\n"
1095 "TEMP rand;\n"
1096 "TEX rand.r, coord.x, texture[$noise_filt_tex], 1D;\n"
1097 "ADD rand.r, rand.r, coord.y;\n"
1098 "TEX rand.r, rand.r, texture[$noise_filt_tex], 1D;\n"
1099 "MAD res.rgb, rand.rrrr, {$noise_str, $noise_str, $noise_str}, res;\n";
1102 * \brief creates and initializes helper textures needed for scaling texture read
1103 * \param scaler scaler type to create texture for
1104 * \param texu contains next free texture unit number
1105 * \param texs texture unit ids for the scaler are stored in this array
1107 static void create_scaler_textures(GL *gl, int scaler, int *texu, char *texs)
1109 switch (scaler) {
1110 case YUV_SCALER_BILIN:
1111 case YUV_SCALER_BICUB_NOTEX:
1112 case YUV_SCALER_UNSHARP:
1113 case YUV_SCALER_UNSHARP2:
1114 break;
1115 case YUV_SCALER_BICUB:
1116 case YUV_SCALER_BICUB_X:
1117 texs[0] = (*texu)++;
1118 gen_spline_lookup_tex(gl, GL_TEXTURE0 + texs[0]);
1119 texs[0] += '0';
1120 break;
1121 default:
1122 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown scaler type %i\n", scaler);
1126 //! resolution of texture for gamma lookup table
1127 #define LOOKUP_RES 512
1128 //! resolution for 3D yuv->rgb conversion lookup table
1129 #define LOOKUP_3DRES 32
1131 * \brief creates and initializes helper textures needed for yuv conversion
1132 * \param params struct containing parameters like brightness, gamma, ...
1133 * \param texu contains next free texture unit number
1134 * \param texs texture unit ids for the conversion are stored in this array
1136 static void create_conv_textures(GL *gl, gl_conversion_params_t *params,
1137 int *texu, char *texs)
1139 unsigned char *lookup_data = NULL;
1140 int conv = YUV_CONVERSION(params->type);
1141 switch (conv) {
1142 case YUV_CONVERSION_FRAGMENT:
1143 case YUV_CONVERSION_FRAGMENT_POW:
1144 break;
1145 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1146 texs[0] = (*texu)++;
1147 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1148 lookup_data = malloc(4 * LOOKUP_RES);
1149 mp_gen_gamma_map(lookup_data, LOOKUP_RES, params->csp_params.rgamma);
1150 mp_gen_gamma_map(&lookup_data[LOOKUP_RES], LOOKUP_RES,
1151 params->csp_params.ggamma);
1152 mp_gen_gamma_map(&lookup_data[2 * LOOKUP_RES], LOOKUP_RES,
1153 params->csp_params.bgamma);
1154 glCreateClearTex(gl, GL_TEXTURE_2D, GL_LUMINANCE8, GL_LUMINANCE,
1155 GL_UNSIGNED_BYTE, GL_LINEAR, LOOKUP_RES, 4, 0);
1156 glUploadTex(gl, GL_TEXTURE_2D, GL_LUMINANCE, GL_UNSIGNED_BYTE,
1157 lookup_data, LOOKUP_RES, 0, 0, LOOKUP_RES, 4, 0);
1158 gl->ActiveTexture(GL_TEXTURE0);
1159 texs[0] += '0';
1160 break;
1161 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1163 int sz = LOOKUP_3DRES + 2; // texture size including borders
1164 if (!gl->TexImage3D) {
1165 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing 3D texture function!\n");
1166 break;
1168 texs[0] = (*texu)++;
1169 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1170 lookup_data = malloc(3 * sz * sz * sz);
1171 mp_gen_yuv2rgb_map(&params->csp_params, lookup_data, LOOKUP_3DRES);
1172 glAdjustAlignment(gl, sz);
1173 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1174 gl->TexImage3D(GL_TEXTURE_3D, 0, 3, sz, sz, sz, 1,
1175 GL_RGB, GL_UNSIGNED_BYTE, lookup_data);
1176 gl->TexParameterf(GL_TEXTURE_3D, GL_TEXTURE_PRIORITY, 1.0);
1177 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1178 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1179 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1180 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1181 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
1182 gl->ActiveTexture(GL_TEXTURE0);
1183 texs[0] += '0';
1185 break;
1186 default:
1187 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n", conv);
1189 free(lookup_data);
1193 * \brief adds a scaling texture read at the current fragment program position
1194 * \param scaler type of scaler to insert
1195 * \param prog pointer to fragment program so far
1196 * \param texs array containing the texture unit identifiers for this scaler
1197 * \param in_tex texture unit the scaler should read from
1198 * \param out_comp component of the yuv variable the scaler stores the result in
1199 * \param rect if rectangular (pixel) adressing should be used for in_tex
1200 * \param texw width of the in_tex texture
1201 * \param texh height of the in_tex texture
1202 * \param strength strength of filter effect if the scaler does some kind of filtering
1204 static void add_scaler(int scaler, char **prog, char *texs,
1205 char in_tex, char out_comp, int rect, int texw, int texh,
1206 double strength)
1208 const char *ttype = rect ? "RECT" : "2D";
1209 const float ptw = rect ? 1.0 : 1.0 / texw;
1210 const float pth = rect ? 1.0 : 1.0 / texh;
1211 switch (scaler) {
1212 case YUV_SCALER_BILIN:
1213 append_template(prog, bilin_filt_template);
1214 break;
1215 case YUV_SCALER_BICUB:
1216 if (rect)
1217 append_template(prog, bicub_filt_template_RECT);
1218 else
1219 append_template(prog, bicub_filt_template_2D);
1220 break;
1221 case YUV_SCALER_BICUB_X:
1222 if (rect)
1223 append_template(prog, bicub_x_filt_template_RECT);
1224 else
1225 append_template(prog, bicub_x_filt_template_2D);
1226 break;
1227 case YUV_SCALER_BICUB_NOTEX:
1228 if (rect)
1229 append_template(prog, bicub_notex_filt_template_RECT);
1230 else
1231 append_template(prog, bicub_notex_filt_template_2D);
1232 break;
1233 case YUV_SCALER_UNSHARP:
1234 append_template(prog, unsharp_filt_template);
1235 break;
1236 case YUV_SCALER_UNSHARP2:
1237 append_template(prog, unsharp_filt_template2);
1238 break;
1241 replace_var_char(prog, "texs", texs[0]);
1242 replace_var_char(prog, "in_tex", in_tex);
1243 replace_var_char(prog, "out_comp", out_comp);
1244 replace_var_str(prog, "tex_type", ttype);
1245 replace_var_float(prog, "texw", texw);
1246 replace_var_float(prog, "texh", texh);
1247 replace_var_float(prog, "ptw", ptw);
1248 replace_var_float(prog, "pth", pth);
1250 // this is silly, not sure if that couldn't be in the shader source instead
1251 replace_var_float(prog, "ptw_05", ptw * 0.5);
1252 replace_var_float(prog, "pth_05", pth * 0.5);
1253 replace_var_float(prog, "ptw_15", ptw * 1.5);
1254 replace_var_float(prog, "pth_15", pth * 1.5);
1255 replace_var_float(prog, "ptw_12", ptw * 1.2);
1256 replace_var_float(prog, "pth_12", pth * 1.2);
1258 replace_var_float(prog, "strength", strength);
1261 static const struct {
1262 const char *name;
1263 GLenum cur;
1264 GLenum max;
1265 } progstats[] = {
1266 {"instructions", 0x88A0, 0x88A1},
1267 {"native instructions", 0x88A2, 0x88A3},
1268 {"temporaries", 0x88A4, 0x88A5},
1269 {"native temporaries", 0x88A6, 0x88A7},
1270 {"parameters", 0x88A8, 0x88A9},
1271 {"native parameters", 0x88AA, 0x88AB},
1272 {"attribs", 0x88AC, 0x88AD},
1273 {"native attribs", 0x88AE, 0x88AF},
1274 {"ALU instructions", 0x8805, 0x880B},
1275 {"TEX instructions", 0x8806, 0x880C},
1276 {"TEX indirections", 0x8807, 0x880D},
1277 {"native ALU instructions", 0x8808, 0x880E},
1278 {"native TEX instructions", 0x8809, 0x880F},
1279 {"native TEX indirections", 0x880A, 0x8810},
1280 {NULL, 0, 0}
1284 * \brief load the specified GPU Program
1285 * \param target program target to load into, only GL_FRAGMENT_PROGRAM is tested
1286 * \param prog program string
1287 * \return 1 on success, 0 otherwise
1289 int loadGPUProgram(GL *gl, GLenum target, char *prog)
1291 int i;
1292 GLint cur = 0, max = 0, err = 0;
1293 if (!gl->ProgramString) {
1294 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing GPU program function\n");
1295 return 0;
1297 gl->ProgramString(target, GL_PROGRAM_FORMAT_ASCII, strlen(prog), prog);
1298 gl->GetIntegerv(GL_PROGRAM_ERROR_POSITION, &err);
1299 if (err != -1) {
1300 mp_msg(MSGT_VO, MSGL_ERR,
1301 "[gl] Error compiling fragment program, make sure your card supports\n"
1302 "[gl] GL_ARB_fragment_program (use glxinfo to check).\n"
1303 "[gl] Error message:\n %s at %.10s\n",
1304 gl->GetString(GL_PROGRAM_ERROR_STRING), &prog[err]);
1305 return 0;
1307 if (!gl->GetProgramivARB || !mp_msg_test(MSGT_VO, MSGL_DBG2))
1308 return 1;
1309 mp_msg(MSGT_VO, MSGL_V, "[gl] Program statistics:\n");
1310 for (i = 0; progstats[i].name; i++) {
1311 gl->GetProgramivARB(target, progstats[i].cur, &cur);
1312 gl->GetProgramivARB(target, progstats[i].max, &max);
1313 mp_msg(MSGT_VO, MSGL_V, "[gl] %s: %i/%i\n", progstats[i].name, cur,
1314 max);
1316 return 1;
1319 #define MAX_PROGSZ (1024 * 1024)
1322 * \brief setup a fragment program that will do YUV->RGB conversion
1323 * \param parms struct containing parameters like conversion and scaler type,
1324 * brightness, ...
1326 static void glSetupYUVFragprog(GL *gl, gl_conversion_params_t *params)
1328 int type = params->type;
1329 int texw = params->texw;
1330 int texh = params->texh;
1331 int rect = params->target == GL_TEXTURE_RECTANGLE;
1332 static const char prog_hdr[] =
1333 "!!ARBfp1.0\n"
1334 "OPTION ARB_precision_hint_fastest;\n"
1335 // all scaler variables must go here so they aren't defined
1336 // multiple times when the same scaler is used more than once
1337 "TEMP coord, coord2, cdelta, parmx, parmy, a, b, yuv, textemp;\n";
1338 char *yuv_prog = NULL;
1339 char **prog = &yuv_prog;
1340 int cur_texu = 3;
1341 char lum_scale_texs[1];
1342 char chrom_scale_texs[1];
1343 char conv_texs[1];
1344 char filt_texs[1] = {0};
1345 GLint i;
1346 // this is the conversion matrix, with y, u, v factors
1347 // for red, green, blue and the constant offsets
1348 float yuv2rgb[3][4];
1349 int noise = params->noise_strength != 0;
1350 create_conv_textures(gl, params, &cur_texu, conv_texs);
1351 create_scaler_textures(gl, YUV_LUM_SCALER(type), &cur_texu, lum_scale_texs);
1352 if (YUV_CHROM_SCALER(type) == YUV_LUM_SCALER(type))
1353 memcpy(chrom_scale_texs, lum_scale_texs, sizeof(chrom_scale_texs));
1354 else
1355 create_scaler_textures(gl, YUV_CHROM_SCALER(type), &cur_texu,
1356 chrom_scale_texs);
1358 if (noise) {
1359 gen_noise_lookup_tex(gl, cur_texu);
1360 filt_texs[0] = '0' + cur_texu++;
1363 gl->GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &i);
1364 if (i < cur_texu)
1365 mp_msg(MSGT_VO, MSGL_ERR,
1366 "[gl] %i texture units needed for this type of YUV fragment support (found %i)\n",
1367 cur_texu, i);
1368 if (!gl->ProgramString) {
1369 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] ProgramString function missing!\n");
1370 return;
1372 append_template(prog, prog_hdr);
1373 add_scaler(YUV_LUM_SCALER(type), prog, lum_scale_texs,
1374 '0', 'r', rect, texw, texh, params->filter_strength);
1375 add_scaler(YUV_CHROM_SCALER(type), prog,
1376 chrom_scale_texs, '1', 'g', rect, params->chrom_texw,
1377 params->chrom_texh, params->filter_strength);
1378 add_scaler(YUV_CHROM_SCALER(type), prog,
1379 chrom_scale_texs, '2', 'b', rect, params->chrom_texw,
1380 params->chrom_texh, params->filter_strength);
1381 mp_get_yuv2rgb_coeffs(&params->csp_params, yuv2rgb);
1382 switch (YUV_CONVERSION(type)) {
1383 case YUV_CONVERSION_FRAGMENT:
1384 append_template(prog, yuv_prog_template);
1385 break;
1386 case YUV_CONVERSION_FRAGMENT_POW:
1387 append_template(prog, yuv_pow_prog_template);
1388 break;
1389 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1390 append_template(prog, yuv_lookup_prog_template);
1391 break;
1392 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1393 append_template(prog, yuv_lookup3d_prog_template);
1394 break;
1395 default:
1396 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1397 YUV_CONVERSION(type));
1398 break;
1400 for (int r = 0; r < 3; r++) {
1401 for (int c = 0; c < 4; c++) {
1402 // "cmRC"
1403 char var[] = { 'c', 'm', '1' + r, '1' + c, '\0' };
1404 replace_var_float(prog, var, yuv2rgb[r][c]);
1407 replace_var_float(prog, "gamma_r", (float)1.0 / params->csp_params.rgamma);
1408 replace_var_float(prog, "gamma_g", (float)1.0 / params->csp_params.ggamma);
1409 replace_var_float(prog, "gamma_b", (float)1.0 / params->csp_params.bgamma);
1410 replace_var_char(prog, "conv_tex0", conv_texs[0]);
1412 if (noise) {
1413 // 1.0 strength is suitable for dithering 8 to 6 bit
1414 double str = params->noise_strength * (1.0 / 64);
1415 double scale_x = (double)NOISE_RES / texw;
1416 double scale_y = (double)NOISE_RES / texh;
1417 if (rect) {
1418 scale_x /= texw;
1419 scale_y /= texh;
1421 append_template(prog, noise_filt_template);
1422 replace_var_float(prog, "noise_sx", scale_x);
1423 replace_var_float(prog, "noise_sy", scale_y);
1424 replace_var_char(prog, "noise_filt_tex", filt_texs[0]);
1425 replace_var_float(prog, "noise_str", str);
1428 append_template(prog, "MOV result.color.rgb, res;\nEND");
1430 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
1431 yuv_prog);
1432 loadGPUProgram(gl, GL_FRAGMENT_PROGRAM, yuv_prog);
1433 talloc_free(yuv_prog);
1437 * \brief detect the best YUV->RGB conversion method available
1439 int glAutodetectYUVConversion(GL *gl)
1441 const char *extensions = gl->GetString(GL_EXTENSIONS);
1442 if (!extensions || !gl->MultiTexCoord2f)
1443 return YUV_CONVERSION_NONE;
1444 if (strstr(extensions, "GL_ARB_fragment_program"))
1445 return YUV_CONVERSION_FRAGMENT;
1446 if (strstr(extensions, "GL_ATI_text_fragment_shader"))
1447 return YUV_CONVERSION_TEXT_FRAGMENT;
1448 if (strstr(extensions, "GL_ATI_fragment_shader"))
1449 return YUV_CONVERSION_COMBINERS_ATI;
1450 return YUV_CONVERSION_NONE;
1454 * \brief setup YUV->RGB conversion
1455 * \param parms struct containing parameters like conversion and scaler type,
1456 * brightness, ...
1457 * \ingroup glconversion
1459 void glSetupYUVConversion(GL *gl, gl_conversion_params_t *params)
1461 if (params->chrom_texw == 0)
1462 params->chrom_texw = 1;
1463 if (params->chrom_texh == 0)
1464 params->chrom_texh = 1;
1465 switch (YUV_CONVERSION(params->type)) {
1466 case YUV_CONVERSION_COMBINERS_ATI:
1467 glSetupYUVFragmentATI(gl, &params->csp_params, 0);
1468 break;
1469 case YUV_CONVERSION_TEXT_FRAGMENT:
1470 glSetupYUVFragmentATI(gl, &params->csp_params, 1);
1471 break;
1472 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1473 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1474 case YUV_CONVERSION_FRAGMENT:
1475 case YUV_CONVERSION_FRAGMENT_POW:
1476 glSetupYUVFragprog(gl, params);
1477 break;
1478 case YUV_CONVERSION_NONE:
1479 break;
1480 default:
1481 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1482 YUV_CONVERSION(params->type));
1487 * \brief enable the specified YUV conversion
1488 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1489 * \param type type of YUV conversion
1490 * \ingroup glconversion
1492 void glEnableYUVConversion(GL *gl, GLenum target, int type)
1494 switch (YUV_CONVERSION(type)) {
1495 case YUV_CONVERSION_COMBINERS_ATI:
1496 gl->ActiveTexture(GL_TEXTURE1);
1497 gl->Enable(target);
1498 gl->ActiveTexture(GL_TEXTURE2);
1499 gl->Enable(target);
1500 gl->ActiveTexture(GL_TEXTURE0);
1501 gl->Enable(GL_FRAGMENT_SHADER_ATI);
1502 break;
1503 case YUV_CONVERSION_TEXT_FRAGMENT:
1504 gl->ActiveTexture(GL_TEXTURE1);
1505 gl->Enable(target);
1506 gl->ActiveTexture(GL_TEXTURE2);
1507 gl->Enable(target);
1508 gl->ActiveTexture(GL_TEXTURE0);
1509 gl->Enable(GL_TEXT_FRAGMENT_SHADER_ATI);
1510 break;
1511 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1512 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1513 case YUV_CONVERSION_FRAGMENT_POW:
1514 case YUV_CONVERSION_FRAGMENT:
1515 case YUV_CONVERSION_NONE:
1516 gl->Enable(GL_FRAGMENT_PROGRAM);
1517 break;
1522 * \brief disable the specified YUV conversion
1523 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1524 * \param type type of YUV conversion
1525 * \ingroup glconversion
1527 void glDisableYUVConversion(GL *gl, GLenum target, int type)
1529 switch (YUV_CONVERSION(type)) {
1530 case YUV_CONVERSION_COMBINERS_ATI:
1531 gl->ActiveTexture(GL_TEXTURE1);
1532 gl->Disable(target);
1533 gl->ActiveTexture(GL_TEXTURE2);
1534 gl->Disable(target);
1535 gl->ActiveTexture(GL_TEXTURE0);
1536 gl->Disable(GL_FRAGMENT_SHADER_ATI);
1537 break;
1538 case YUV_CONVERSION_TEXT_FRAGMENT:
1539 gl->Disable(GL_TEXT_FRAGMENT_SHADER_ATI);
1540 // HACK: at least the Mac OS X 10.5 PPC Radeon drivers are broken and
1541 // without this disable the texture units while the program is still
1542 // running (10.4 PPC seems to work without this though).
1543 gl->Flush();
1544 gl->ActiveTexture(GL_TEXTURE1);
1545 gl->Disable(target);
1546 gl->ActiveTexture(GL_TEXTURE2);
1547 gl->Disable(target);
1548 gl->ActiveTexture(GL_TEXTURE0);
1549 break;
1550 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1551 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1552 case YUV_CONVERSION_FRAGMENT_POW:
1553 case YUV_CONVERSION_FRAGMENT:
1554 case YUV_CONVERSION_NONE:
1555 gl->Disable(GL_FRAGMENT_PROGRAM);
1556 break;
1560 void glEnable3DLeft(GL *gl, int type)
1562 GLint buffer;
1563 switch (type) {
1564 case GL_3D_RED_CYAN:
1565 gl->ColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
1566 break;
1567 case GL_3D_GREEN_MAGENTA:
1568 gl->ColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
1569 break;
1570 case GL_3D_QUADBUFFER:
1571 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1572 switch (buffer) {
1573 case GL_FRONT:
1574 case GL_FRONT_LEFT:
1575 case GL_FRONT_RIGHT:
1576 buffer = GL_FRONT_LEFT;
1577 break;
1578 case GL_BACK:
1579 case GL_BACK_LEFT:
1580 case GL_BACK_RIGHT:
1581 buffer = GL_BACK_LEFT;
1582 break;
1584 gl->DrawBuffer(buffer);
1585 break;
1589 void glEnable3DRight(GL *gl, int type)
1591 GLint buffer;
1592 switch (type) {
1593 case GL_3D_RED_CYAN:
1594 gl->ColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
1595 break;
1596 case GL_3D_GREEN_MAGENTA:
1597 gl->ColorMask(GL_TRUE, GL_FALSE, GL_TRUE, GL_FALSE);
1598 break;
1599 case GL_3D_QUADBUFFER:
1600 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1601 switch (buffer) {
1602 case GL_FRONT:
1603 case GL_FRONT_LEFT:
1604 case GL_FRONT_RIGHT:
1605 buffer = GL_FRONT_RIGHT;
1606 break;
1607 case GL_BACK:
1608 case GL_BACK_LEFT:
1609 case GL_BACK_RIGHT:
1610 buffer = GL_BACK_RIGHT;
1611 break;
1613 gl->DrawBuffer(buffer);
1614 break;
1618 void glDisable3D(GL *gl, int type)
1620 GLint buffer;
1621 switch (type) {
1622 case GL_3D_RED_CYAN:
1623 case GL_3D_GREEN_MAGENTA:
1624 gl->ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1625 break;
1626 case GL_3D_QUADBUFFER:
1627 gl->DrawBuffer(vo_doublebuffering ? GL_BACK : GL_FRONT);
1628 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1629 switch (buffer) {
1630 case GL_FRONT:
1631 case GL_FRONT_LEFT:
1632 case GL_FRONT_RIGHT:
1633 buffer = GL_FRONT;
1634 break;
1635 case GL_BACK:
1636 case GL_BACK_LEFT:
1637 case GL_BACK_RIGHT:
1638 buffer = GL_BACK;
1639 break;
1641 gl->DrawBuffer(buffer);
1642 break;
1647 * \brief draw a texture part at given 2D coordinates
1648 * \param x screen top coordinate
1649 * \param y screen left coordinate
1650 * \param w screen width coordinate
1651 * \param h screen height coordinate
1652 * \param tx texture top coordinate in pixels
1653 * \param ty texture left coordinate in pixels
1654 * \param tw texture part width in pixels
1655 * \param th texture part height in pixels
1656 * \param sx width of texture in pixels
1657 * \param sy height of texture in pixels
1658 * \param rect_tex whether this texture uses texture_rectangle extension
1659 * \param is_yv12 if != 0, also draw the textures from units 1 and 2,
1660 * bits 8 - 15 and 16 - 23 specify the x and y scaling of those textures
1661 * \param flip flip the texture upside down
1662 * \ingroup gltexture
1664 void glDrawTex(GL *gl, GLfloat x, GLfloat y, GLfloat w, GLfloat h,
1665 GLfloat tx, GLfloat ty, GLfloat tw, GLfloat th,
1666 int sx, int sy, int rect_tex, int is_yv12, int flip)
1668 int chroma_x_shift = (is_yv12 >> 8) & 31;
1669 int chroma_y_shift = (is_yv12 >> 16) & 31;
1670 GLfloat xscale = 1 << chroma_x_shift;
1671 GLfloat yscale = 1 << chroma_y_shift;
1672 GLfloat tx2 = tx / xscale, ty2 = ty / yscale, tw2 = tw / xscale, th2 = th / yscale;
1673 if (!rect_tex) {
1674 tx /= sx;
1675 ty /= sy;
1676 tw /= sx;
1677 th /= sy;
1678 tx2 = tx, ty2 = ty, tw2 = tw, th2 = th;
1680 if (flip) {
1681 y += h;
1682 h = -h;
1684 gl->Begin(GL_QUADS);
1685 gl->TexCoord2f(tx, ty);
1686 if (is_yv12) {
1687 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2);
1688 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2);
1690 gl->Vertex2f(x, y);
1691 gl->TexCoord2f(tx, ty + th);
1692 if (is_yv12) {
1693 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2 + th2);
1694 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2 + th2);
1696 gl->Vertex2f(x, y + h);
1697 gl->TexCoord2f(tx + tw, ty + th);
1698 if (is_yv12) {
1699 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2 + th2);
1700 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2 + th2);
1702 gl->Vertex2f(x + w, y + h);
1703 gl->TexCoord2f(tx + tw, ty);
1704 if (is_yv12) {
1705 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2);
1706 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2);
1708 gl->Vertex2f(x + w, y);
1709 gl->End();
1712 #ifdef CONFIG_GL_COCOA
1713 #include "cocoa_common.h"
1714 static int create_window_cocoa(struct MPGLContext *ctx, uint32_t d_width,
1715 uint32_t d_height, uint32_t flags)
1717 if (vo_cocoa_create_window(ctx->vo, d_width, d_height, flags, 0) == 0) {
1718 return SET_WINDOW_OK;
1719 } else {
1720 return SET_WINDOW_FAILED;
1724 static int create_window_cocoa_gl3(struct MPGLContext *ctx, int gl_flags,
1725 int gl_version, uint32_t d_width,
1726 uint32_t d_height, uint32_t flags)
1728 int rv = vo_cocoa_create_window(ctx->vo, d_width, d_height, flags, 1);
1729 getFunctions(ctx->gl, (void *)vo_cocoa_glgetaddr, NULL, true);
1730 ctx->depth_r = vo_cocoa_cgl_color_size(ctx->vo);
1731 ctx->depth_g = vo_cocoa_cgl_color_size(ctx->vo);
1732 ctx->depth_b = vo_cocoa_cgl_color_size(ctx->vo);
1733 return rv;
1736 static int setGlWindow_cocoa(MPGLContext *ctx)
1738 vo_cocoa_change_attributes(ctx->vo);
1739 getFunctions(ctx->gl, (void *)vo_cocoa_glgetaddr, NULL, false);
1740 if (!ctx->gl->SwapInterval)
1741 ctx->gl->SwapInterval = vo_cocoa_swap_interval;
1742 return SET_WINDOW_OK;
1745 static void releaseGlContext_cocoa(MPGLContext *ctx)
1749 static void swapGlBuffers_cocoa(MPGLContext *ctx)
1751 vo_cocoa_swap_buffers(ctx->vo);
1753 #endif
1755 #ifdef CONFIG_GL_WIN32
1756 #include <windows.h>
1757 #include "w32_common.h"
1759 struct w32_context {
1760 int vinfo;
1761 HGLRC context;
1764 static int create_window_w32(struct MPGLContext *ctx, uint32_t d_width,
1765 uint32_t d_height, uint32_t flags)
1767 if (!vo_w32_config(d_width, d_height, flags))
1768 return -1;
1769 return 0;
1773 * \brief little helper since wglGetProcAddress definition does not fit our
1774 * getProcAddress
1775 * \param procName name of function to look up
1776 * \return function pointer returned by wglGetProcAddress
1778 static void *w32gpa(const GLubyte *procName)
1780 HMODULE oglmod;
1781 void *res = wglGetProcAddress(procName);
1782 if (res)
1783 return res;
1784 oglmod = GetModuleHandle("opengl32.dll");
1785 return GetProcAddress(oglmod, procName);
1788 static int create_window_w32_gl3(struct MPGLContext *ctx, int gl_flags,
1789 int gl_version, uint32_t d_width,
1790 uint32_t d_height, uint32_t flags) {
1791 if (!vo_w32_config(d_width, d_height, flags))
1792 return -1;
1794 struct w32_context *w32_ctx = ctx->priv;
1795 HGLRC *context = &w32_ctx->context;
1797 if (*context) // reuse existing context
1798 return 0; // not reusing it breaks gl3!
1800 HWND win = vo_w32_window;
1801 HDC windc = vo_w32_get_dc(win);
1802 HGLRC new_context = 0;
1804 new_context = wglCreateContext(windc);
1805 if (!new_context) {
1806 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GL context!\n");
1807 return -1;
1810 // set context
1811 if (!wglMakeCurrent(windc, new_context)) {
1812 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GL context!\n");
1813 goto out;
1816 const char *(GLAPIENTRY *wglGetExtensionsStringARB)(HDC hdc)
1817 = w32gpa((const GLubyte*)"wglGetExtensionsStringARB");
1819 if (!wglGetExtensionsStringARB)
1820 goto unsupported;
1822 const char *wgl_exts = wglGetExtensionsStringARB(windc);
1823 if (!strstr(wgl_exts, "WGL_ARB_create_context"))
1824 goto unsupported;
1826 HGLRC (GLAPIENTRY *wglCreateContextAttribsARB)(HDC hDC, HGLRC hShareContext,
1827 const int *attribList)
1828 = w32gpa((const GLubyte*)"wglCreateContextAttribsARB");
1830 if (!wglCreateContextAttribsARB)
1831 goto unsupported;
1833 int attribs[] = {
1834 WGL_CONTEXT_MAJOR_VERSION_ARB, MPGL_VER_GET_MAJOR(gl_version),
1835 WGL_CONTEXT_MINOR_VERSION_ARB, MPGL_VER_GET_MINOR(gl_version),
1836 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
1837 WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
1841 *context = wglCreateContextAttribsARB(windc, 0, attribs);
1842 if (! *context) {
1843 // NVidia, instead of ignoring WGL_CONTEXT_FLAGS_ARB, will error out if
1844 // it's present on pre-3.2 contexts.
1845 // Remove it from attribs and retry the context creation.
1846 attribs[6] = attribs[7] = 0;
1847 *context = wglCreateContextAttribsARB(windc, 0, attribs);
1849 if (! *context) {
1850 int err = GetLastError();
1851 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create an OpenGL 3.x"
1852 " context: error 0x%x\n", err);
1853 goto out;
1856 wglMakeCurrent(NULL, NULL);
1857 wglDeleteContext(new_context);
1859 if (!wglMakeCurrent(windc, *context)) {
1860 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GL3 context!\n");
1861 wglDeleteContext(*context);
1862 return -1;
1865 /* update function pointers */
1866 getFunctions(ctx->gl, w32gpa, NULL, true);
1868 int pfmt = GetPixelFormat(windc);
1869 PIXELFORMATDESCRIPTOR pfd;
1870 if (DescribePixelFormat(windc, pfmt, sizeof(PIXELFORMATDESCRIPTOR), &pfd)) {
1871 ctx->depth_r = pfd.cRedBits;
1872 ctx->depth_g = pfd.cGreenBits;
1873 ctx->depth_b = pfd.cBlueBits;
1876 return 0;
1878 unsupported:
1879 mp_msg(MSGT_VO, MSGL_ERR, "[gl] The current OpenGL implementation does"
1880 " not support OpenGL 3.x \n");
1881 out:
1882 wglDeleteContext(new_context);
1883 return -1;
1886 static int setGlWindow_w32(MPGLContext *ctx)
1888 HWND win = vo_w32_window;
1889 struct w32_context *w32_ctx = ctx->priv;
1890 int *vinfo = &w32_ctx->vinfo;
1891 HGLRC *context = &w32_ctx->context;
1892 int new_vinfo;
1893 HDC windc = vo_w32_get_dc(win);
1894 HGLRC new_context = 0;
1895 int keep_context = 0;
1896 int res = SET_WINDOW_FAILED;
1897 GL *gl = ctx->gl;
1899 // should only be needed when keeping context, but not doing glFinish
1900 // can cause flickering even when we do not keep it.
1901 if (*context)
1902 gl->Finish();
1903 new_vinfo = GetPixelFormat(windc);
1904 if (*context && *vinfo && new_vinfo && *vinfo == new_vinfo) {
1905 // we can keep the wglContext
1906 new_context = *context;
1907 keep_context = 1;
1908 } else {
1909 // create a context
1910 new_context = wglCreateContext(windc);
1911 if (!new_context) {
1912 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GL context!\n");
1913 goto out;
1917 // set context
1918 if (!wglMakeCurrent(windc, new_context)) {
1919 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GL context!\n");
1920 if (!keep_context)
1921 wglDeleteContext(new_context);
1922 goto out;
1925 // set new values
1926 vo_w32_window = win;
1928 RECT rect;
1929 GetClientRect(win, &rect);
1930 ctx->vo->dwidth = rect.right;
1931 ctx->vo->dheight = rect.bottom;
1933 if (!keep_context) {
1934 if (*context)
1935 wglDeleteContext(*context);
1936 *context = new_context;
1937 *vinfo = new_vinfo;
1939 getFunctions(ctx->gl, w32gpa, NULL, false);
1941 // and inform that reinit is neccessary
1942 res = SET_WINDOW_REINIT;
1943 } else
1944 res = SET_WINDOW_OK;
1946 out:
1947 vo_w32_release_dc(win, windc);
1948 return res;
1951 static void releaseGlContext_w32(MPGLContext *ctx)
1953 struct w32_context *w32_ctx = ctx->priv;
1954 int *vinfo = &w32_ctx->vinfo;
1955 HGLRC *context = &w32_ctx->context;
1956 *vinfo = 0;
1957 if (*context) {
1958 wglMakeCurrent(0, 0);
1959 wglDeleteContext(*context);
1961 *context = 0;
1964 static void swapGlBuffers_w32(MPGLContext *ctx)
1966 HDC vo_hdc = vo_w32_get_dc(vo_w32_window);
1967 SwapBuffers(vo_hdc);
1968 vo_w32_release_dc(vo_w32_window, vo_hdc);
1971 //trivial wrappers (w32 code uses old vo API)
1972 static void new_vo_w32_ontop(struct vo *vo) { vo_w32_ontop(); }
1973 static void new_vo_w32_border(struct vo *vo) { vo_w32_border(); }
1974 static void new_vo_w32_fullscreen(struct vo *vo) { vo_w32_fullscreen(); }
1975 static int new_vo_w32_check_events(struct vo *vo) { return vo_w32_check_events(); }
1976 static void new_w32_update_xinerama_info(struct vo *vo) { w32_update_xinerama_info(); }
1977 static void new_vo_w32_uninit(struct vo *vo) { vo_w32_uninit(); }
1978 #endif
1980 #ifdef CONFIG_GL_X11
1981 #include <X11/Xlib.h>
1982 #include <GL/glx.h>
1983 #include "x11_common.h"
1985 struct glx_context {
1986 XVisualInfo *vinfo;
1987 GLXContext context;
1990 static int create_window_x11(struct MPGLContext *ctx, uint32_t d_width,
1991 uint32_t d_height, uint32_t flags)
1993 struct vo *vo = ctx->vo;
1995 static int default_glx_attribs[] = {
1996 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1997 GLX_DOUBLEBUFFER, None
1999 static int stereo_glx_attribs[] = {
2000 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
2001 GLX_DOUBLEBUFFER, GLX_STEREO, None
2003 XVisualInfo *vinfo = NULL;
2004 if (flags & VOFLAG_STEREO) {
2005 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
2006 stereo_glx_attribs);
2007 if (!vinfo)
2008 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Could not find a stereo visual,"
2009 " 3D will probably not work!\n");
2011 if (!vinfo)
2012 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
2013 default_glx_attribs);
2014 if (!vinfo) {
2015 mp_msg(MSGT_VO, MSGL_ERR, "[gl] no GLX support present\n");
2016 return -1;
2018 mp_msg(MSGT_VO, MSGL_V, "[gl] GLX chose visual with ID 0x%x\n",
2019 (int)vinfo->visualid);
2021 Colormap colormap = XCreateColormap(vo->x11->display, vo->x11->rootwin,
2022 vinfo->visual, AllocNone);
2023 vo_x11_create_vo_window(vo, vinfo, vo->dx, vo->dy, d_width, d_height,
2024 flags, colormap, "gl");
2026 return 0;
2030 * \brief Returns the XVisualInfo associated with Window win.
2031 * \param win Window whose XVisualInfo is returne.
2032 * \return XVisualInfo of the window. Caller must use XFree to free it.
2034 static XVisualInfo *getWindowVisualInfo(MPGLContext *ctx, Window win)
2036 XWindowAttributes xw_attr;
2037 XVisualInfo vinfo_template;
2038 int tmp;
2039 XGetWindowAttributes(ctx->vo->x11->display, win, &xw_attr);
2040 vinfo_template.visualid = XVisualIDFromVisual(xw_attr.visual);
2041 return XGetVisualInfo(ctx->vo->x11->display, VisualIDMask, &vinfo_template, &tmp);
2045 * \brief Changes the window in which video is displayed.
2046 * If possible only transfers the context to the new window, otherwise
2047 * creates a new one, which must be initialized by the caller.
2048 * \param vinfo Currently used visual.
2049 * \param context Currently used context.
2050 * \param win window that should be used for drawing.
2051 * \return one of SET_WINDOW_FAILED, SET_WINDOW_OK or SET_WINDOW_REINIT.
2052 * In case of SET_WINDOW_REINIT the context could not be transfered
2053 * and the caller must initialize it correctly.
2054 * \ingroup glcontext
2056 static int setGlWindow_x11(MPGLContext *ctx)
2058 struct glx_context *glx_context = ctx->priv;
2059 XVisualInfo **vinfo = &glx_context->vinfo;
2060 GLXContext *context = &glx_context->context;
2061 Display *display = ctx->vo->x11->display;
2062 Window win = ctx->vo->x11->window;
2063 XVisualInfo *new_vinfo;
2064 GLXContext new_context = NULL;
2065 int keep_context = 0;
2066 GL *gl = ctx->gl;
2068 // should only be needed when keeping context, but not doing glFinish
2069 // can cause flickering even when we do not keep it.
2070 if (*context)
2071 gl->Finish();
2072 new_vinfo = getWindowVisualInfo(ctx, win);
2073 if (*context && *vinfo && new_vinfo &&
2074 (*vinfo)->visualid == new_vinfo->visualid) {
2075 // we can keep the GLXContext
2076 new_context = *context;
2077 XFree(new_vinfo);
2078 new_vinfo = *vinfo;
2079 keep_context = 1;
2080 } else {
2081 // create a context
2082 new_context = glXCreateContext(display, new_vinfo, NULL, True);
2083 if (!new_context) {
2084 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GLX context!\n");
2085 XFree(new_vinfo);
2086 return SET_WINDOW_FAILED;
2090 // set context
2091 if (!glXMakeCurrent(display, ctx->vo->x11->window, new_context)) {
2092 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GLX context!\n");
2093 if (!keep_context) {
2094 glXDestroyContext(display, new_context);
2095 XFree(new_vinfo);
2097 return SET_WINDOW_FAILED;
2100 // set new values
2101 ctx->vo->x11->window = win;
2102 vo_x11_update_geometry(ctx->vo, 1);
2103 if (!keep_context) {
2104 void *(*getProcAddress)(const GLubyte *);
2105 if (*context)
2106 glXDestroyContext(display, *context);
2107 *context = new_context;
2108 if (*vinfo)
2109 XFree(*vinfo);
2110 *vinfo = new_vinfo;
2111 getProcAddress = getdladdr("glXGetProcAddress");
2112 if (!getProcAddress)
2113 getProcAddress = getdladdr("glXGetProcAddressARB");
2115 const char *glxstr = "";
2116 const char *(*glXExtStr)(Display *, int)
2117 = getdladdr("glXQueryExtensionsString");
2118 if (glXExtStr)
2119 glxstr = glXExtStr(display, ctx->vo->x11->screen);
2121 getFunctions(gl, getProcAddress, glxstr, false);
2122 if (!gl->GenPrograms && gl->GetString &&
2123 getProcAddress &&
2124 strstr(gl->GetString(GL_EXTENSIONS), "GL_ARB_vertex_program")) {
2125 mp_msg(MSGT_VO, MSGL_WARN,
2126 "Broken glXGetProcAddress detected, trying workaround\n");
2127 getFunctions(gl, NULL, glxstr, false);
2130 // and inform that reinit is neccessary
2131 return SET_WINDOW_REINIT;
2133 return SET_WINDOW_OK;
2136 // The GL3 initialization code roughly follows/copies from:
2137 // http://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX)
2138 // but also uses some of the old code.
2140 static GLXFBConfig select_fb_config(struct vo *vo, const int *attribs)
2142 int fbcount;
2143 GLXFBConfig *fbc = glXChooseFBConfig(vo->x11->display, vo->x11->screen,
2144 attribs, &fbcount);
2145 if (!fbc)
2146 return NULL;
2148 // The list in fbc is sorted (so that the first element is the best).
2149 GLXFBConfig fbconfig = fbc[0];
2151 XFree(fbc);
2153 return fbconfig;
2156 typedef GLXContext (*glXCreateContextAttribsARBProc)
2157 (Display*, GLXFBConfig, GLXContext, Bool, const int*);
2159 static int create_window_x11_gl3(struct MPGLContext *ctx, int gl_flags,
2160 int gl_version, uint32_t d_width,
2161 uint32_t d_height, uint32_t flags)
2163 struct vo *vo = ctx->vo;
2164 struct glx_context *glx_ctx = ctx->priv;
2166 if (glx_ctx->context) {
2167 // GL context and window already exist.
2168 // Only update window geometry etc.
2169 Colormap colormap = XCreateColormap(vo->x11->display, vo->x11->rootwin,
2170 glx_ctx->vinfo->visual, AllocNone);
2171 vo_x11_create_vo_window(vo, glx_ctx->vinfo, vo->dx, vo->dy, d_width,
2172 d_height, flags, colormap, "gl");
2173 XFreeColormap(vo->x11->display, colormap);
2174 return SET_WINDOW_OK;
2177 int glx_major, glx_minor;
2179 // FBConfigs were added in GLX version 1.3.
2180 if (!glXQueryVersion(vo->x11->display, &glx_major, &glx_minor) ||
2181 (MPGL_VER(glx_major, glx_minor) < MPGL_VER(1, 3)))
2183 mp_msg(MSGT_VO, MSGL_ERR, "[gl] GLX version older than 1.3.\n");
2184 return SET_WINDOW_FAILED;
2187 const int glx_attribs_stereo_value_idx = 1; // index of GLX_STEREO + 1
2188 int glx_attribs[] = {
2189 GLX_STEREO, False,
2190 GLX_X_RENDERABLE, True,
2191 GLX_RED_SIZE, 1,
2192 GLX_GREEN_SIZE, 1,
2193 GLX_BLUE_SIZE, 1,
2194 GLX_DOUBLEBUFFER, True,
2195 None
2197 GLXFBConfig fbc = NULL;
2198 if (flags & VOFLAG_STEREO) {
2199 glx_attribs[glx_attribs_stereo_value_idx] = True;
2200 fbc = select_fb_config(vo, glx_attribs);
2201 if (!fbc) {
2202 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Could not find a stereo visual,"
2203 " 3D will probably not work!\n");
2204 glx_attribs[glx_attribs_stereo_value_idx] = False;
2207 if (!fbc)
2208 fbc = select_fb_config(vo, glx_attribs);
2209 if (!fbc) {
2210 mp_msg(MSGT_VO, MSGL_ERR, "[gl] no GLX support present\n");
2211 return SET_WINDOW_FAILED;
2214 glXGetFBConfigAttrib(vo->x11->display, fbc, GLX_RED_SIZE, &ctx->depth_r);
2215 glXGetFBConfigAttrib(vo->x11->display, fbc, GLX_GREEN_SIZE, &ctx->depth_g);
2216 glXGetFBConfigAttrib(vo->x11->display, fbc, GLX_BLUE_SIZE, &ctx->depth_b);
2218 XVisualInfo *vinfo = glXGetVisualFromFBConfig(vo->x11->display, fbc);
2219 mp_msg(MSGT_VO, MSGL_V, "[gl] GLX chose visual with ID 0x%x\n",
2220 (int)vinfo->visualid);
2221 Colormap colormap = XCreateColormap(vo->x11->display, vo->x11->rootwin,
2222 vinfo->visual, AllocNone);
2223 vo_x11_create_vo_window(vo, vinfo, vo->dx, vo->dy, d_width, d_height,
2224 flags, colormap, "gl");
2225 XFreeColormap(vo->x11->display, colormap);
2227 glXCreateContextAttribsARBProc glXCreateContextAttribsARB =
2228 (glXCreateContextAttribsARBProc)
2229 glXGetProcAddressARB((const GLubyte *)"glXCreateContextAttribsARB");
2231 const char *glxstr = "";
2232 const char *(*glXExtStr)(Display *, int)
2233 = getdladdr("glXQueryExtensionsString");
2234 if (glXExtStr)
2235 glxstr = glXExtStr(vo->x11->display, vo->x11->screen);
2236 bool have_ctx_ext = glxstr && !!strstr(glxstr, "GLX_ARB_create_context");
2238 if (!(have_ctx_ext && glXCreateContextAttribsARB)) {
2239 XFree(vinfo);
2240 return SET_WINDOW_FAILED;
2243 int context_attribs[] = {
2244 GLX_CONTEXT_MAJOR_VERSION_ARB, MPGL_VER_GET_MAJOR(gl_version),
2245 GLX_CONTEXT_MINOR_VERSION_ARB, MPGL_VER_GET_MINOR(gl_version),
2246 GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
2247 GLX_CONTEXT_FLAGS_ARB,
2248 (gl_flags & MPGLFLAG_DEBUG ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
2249 None
2251 GLXContext context = glXCreateContextAttribsARB(vo->x11->display, fbc, 0,
2252 True, context_attribs);
2253 if (!context) {
2254 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GLX context!\n");
2255 XFree(vinfo);
2256 return SET_WINDOW_FAILED;
2259 // set context
2260 if (!glXMakeCurrent(vo->x11->display, vo->x11->window, context)) {
2261 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GLX context!\n");
2262 glXDestroyContext(vo->x11->display, context);
2263 XFree(vinfo);
2264 return SET_WINDOW_FAILED;
2267 glx_ctx->vinfo = vinfo;
2268 glx_ctx->context = context;
2270 getFunctions(ctx->gl, (void *)glXGetProcAddress, glxstr, true);
2272 return SET_WINDOW_REINIT;
2276 * \brief free the VisualInfo and GLXContext of an OpenGL context.
2277 * \ingroup glcontext
2279 static void releaseGlContext_x11(MPGLContext *ctx)
2281 struct glx_context *glx_ctx = ctx->priv;
2282 XVisualInfo **vinfo = &glx_ctx->vinfo;
2283 GLXContext *context = &glx_ctx->context;
2284 Display *display = ctx->vo->x11->display;
2285 GL *gl = ctx->gl;
2286 if (*vinfo)
2287 XFree(*vinfo);
2288 *vinfo = NULL;
2289 if (*context) {
2290 gl->Finish();
2291 glXMakeCurrent(display, None, NULL);
2292 glXDestroyContext(display, *context);
2294 *context = 0;
2297 static void swapGlBuffers_x11(MPGLContext *ctx)
2299 glXSwapBuffers(ctx->vo->x11->display, ctx->vo->x11->window);
2301 #endif
2303 #ifdef CONFIG_GL_SDL
2304 #include "sdl_common.h"
2306 static int create_window_sdl(struct MPGLContext *ctx, uint32_t d_width,
2307 uint32_t d_height, uint32_t flags)
2309 SDL_WM_SetCaption(vo_get_window_title(ctx->vo), NULL);
2310 ctx->vo->dwidth = d_width;
2311 ctx->vo->dheight = d_height;
2312 return 0;
2315 static void swapGlBuffers_sdl(MPGLContext *ctx)
2317 SDL_GL_SwapBuffers();
2320 static void *sdlgpa(const GLubyte *name)
2322 return SDL_GL_GetProcAddress(name);
2325 static int setGlWindow_sdl(MPGLContext *ctx)
2327 if (sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE) < 0)
2328 return SET_WINDOW_FAILED;
2329 SDL_GL_LoadLibrary(NULL);
2330 getFunctions(ctx->gl, sdlgpa, NULL, false);
2331 return SET_WINDOW_OK;
2334 static void releaseGlContext_sdl(MPGLContext *ctx)
2338 static int sdl_check_events(struct vo *vo)
2340 int res = 0;
2341 SDL_Event event;
2342 while (SDL_PollEvent(&event))
2343 res |= sdl_default_handle_event(&event);
2344 // poll "events" from within MPlayer code
2345 res |= sdl_default_handle_event(NULL);
2346 if (res & VO_EVENT_RESIZE)
2347 sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE);
2348 return res;
2351 static void new_sdl_update_xinerama_info(struct vo *vo) { sdl_update_xinerama_info(); }
2352 static void new_vo_sdl_fullscreen(struct vo *vo) { vo_sdl_fullscreen(); }
2353 static void new_vo_sdl_uninit(struct vo *vo) { vo_sdl_uninit(); }
2355 #endif
2357 struct backend {
2358 const char *name;
2359 enum MPGLType type;
2362 static struct backend backends[] = {
2363 {"auto", GLTYPE_AUTO},
2364 {"cocoa", GLTYPE_COCOA},
2365 {"win", GLTYPE_W32},
2366 {"x11", GLTYPE_X11},
2367 {"sdl", GLTYPE_SDL},
2368 // mplayer-svn aliases (note that mplayer-svn couples these with the numeric
2369 // values of the internal GLTYPE_* constants)
2370 {"-1", GLTYPE_AUTO},
2371 { "0", GLTYPE_W32},
2372 { "1", GLTYPE_X11},
2373 { "2", GLTYPE_SDL},
2378 int mpgl_find_backend(const char *name)
2380 for (const struct backend *entry = backends; entry->name; entry++) {
2381 if (strcmp(entry->name, name) == 0)
2382 return entry->type;
2384 return -1;
2387 MPGLContext *init_mpglcontext(enum MPGLType type, struct vo *vo)
2389 MPGLContext *ctx;
2390 if (type == GLTYPE_AUTO) {
2391 ctx = init_mpglcontext(GLTYPE_COCOA, vo);
2392 if (ctx)
2393 return ctx;
2394 ctx = init_mpglcontext(GLTYPE_W32, vo);
2395 if (ctx)
2396 return ctx;
2397 ctx = init_mpglcontext(GLTYPE_X11, vo);
2398 if (ctx)
2399 return ctx;
2400 return init_mpglcontext(GLTYPE_SDL, vo);
2402 ctx = talloc_zero(NULL, MPGLContext);
2403 ctx->gl = talloc_zero(ctx, GL);
2404 ctx->type = type;
2405 ctx->vo = vo;
2406 switch (ctx->type) {
2407 #ifdef CONFIG_GL_COCOA
2408 case GLTYPE_COCOA:
2409 ctx->create_window = create_window_cocoa;
2410 ctx->create_window_gl3 = create_window_cocoa_gl3;
2411 ctx->setGlWindow = setGlWindow_cocoa;
2412 ctx->releaseGlContext = releaseGlContext_cocoa;
2413 ctx->swapGlBuffers = swapGlBuffers_cocoa;
2414 ctx->check_events = vo_cocoa_check_events;
2415 ctx->update_xinerama_info = vo_cocoa_update_xinerama_info;
2416 ctx->fullscreen = vo_cocoa_fullscreen;
2417 ctx->ontop = vo_cocoa_ontop;
2418 ctx->pause = vo_cocoa_pause;
2419 ctx->resume = vo_cocoa_resume;
2420 ctx->vo_uninit = vo_cocoa_uninit;
2421 if (vo_cocoa_init(vo))
2422 return ctx;
2423 break;
2424 #endif
2425 #ifdef CONFIG_GL_WIN32
2426 case GLTYPE_W32:
2427 ctx->priv = talloc_zero(ctx, struct w32_context);
2428 ctx->create_window = create_window_w32;
2429 ctx->create_window_gl3 = create_window_w32_gl3;
2430 ctx->setGlWindow = setGlWindow_w32;
2431 ctx->releaseGlContext = releaseGlContext_w32;
2432 ctx->swapGlBuffers = swapGlBuffers_w32;
2433 ctx->update_xinerama_info = new_w32_update_xinerama_info;
2434 ctx->border = new_vo_w32_border;
2435 ctx->check_events = new_vo_w32_check_events;
2436 ctx->fullscreen = new_vo_w32_fullscreen;
2437 ctx->ontop = new_vo_w32_ontop;
2438 ctx->vo_uninit = new_vo_w32_uninit;
2439 //the win32 code is hardcoded to use the deprecated vo API
2440 global_vo = vo;
2441 if (vo_w32_init())
2442 return ctx;
2443 break;
2444 #endif
2445 #ifdef CONFIG_GL_X11
2446 case GLTYPE_X11:
2447 ctx->priv = talloc_zero(ctx, struct glx_context);
2448 ctx->create_window = create_window_x11;
2449 ctx->setGlWindow = setGlWindow_x11;
2450 ctx->create_window_gl3 = create_window_x11_gl3;
2451 ctx->releaseGlContext = releaseGlContext_x11;
2452 ctx->swapGlBuffers = swapGlBuffers_x11;
2453 ctx->update_xinerama_info = update_xinerama_info;
2454 ctx->border = vo_x11_border;
2455 ctx->check_events = vo_x11_check_events;
2456 ctx->fullscreen = vo_x11_fullscreen;
2457 ctx->ontop = vo_x11_ontop;
2458 ctx->vo_uninit = vo_x11_uninit;
2459 if (vo_init(vo))
2460 return ctx;
2461 break;
2462 #endif
2463 #ifdef CONFIG_GL_SDL
2464 case GLTYPE_SDL:
2465 ctx->create_window = create_window_sdl;
2466 ctx->setGlWindow = setGlWindow_sdl;
2467 ctx->releaseGlContext = releaseGlContext_sdl;
2468 ctx->swapGlBuffers = swapGlBuffers_sdl;
2469 ctx->update_xinerama_info = new_sdl_update_xinerama_info;
2470 ctx->check_events = sdl_check_events;
2471 ctx->fullscreen = new_vo_sdl_fullscreen;
2472 ctx->vo_uninit = new_vo_sdl_uninit;
2473 //the SDL code is hardcoded to use the deprecated vo API
2474 global_vo = vo;
2475 if (vo_sdl_init())
2476 return ctx;
2477 break;
2478 #endif
2480 talloc_free(ctx);
2481 return NULL;
2484 int create_mpglcontext(struct MPGLContext *ctx, int gl_flags, int gl_version,
2485 uint32_t d_width, uint32_t d_height, uint32_t flags)
2487 if (gl_version < MPGL_VER(3, 0)) {
2488 if (ctx->create_window(ctx, d_width, d_height, flags) < 0)
2489 return SET_WINDOW_FAILED;
2490 return ctx->setGlWindow(ctx);
2491 } else {
2492 if (!ctx->create_window_gl3) {
2493 mp_msg(MSGT_VO, MSGL_ERR, "[gl] OpenGL 3.x context creation not "
2494 "implemented.\n");
2495 return SET_WINDOW_FAILED;
2497 return ctx->create_window_gl3(ctx, gl_flags, gl_version, d_width,
2498 d_height, flags);
2502 void uninit_mpglcontext(MPGLContext *ctx)
2504 if (!ctx)
2505 return;
2506 ctx->releaseGlContext(ctx);
2507 ctx->vo_uninit(ctx->vo);
2508 talloc_free(ctx);
2511 void mp_log_source(int mod, int lev, const char *src)
2513 int line = 1;
2514 if (!src)
2515 return;
2516 while (*src) {
2517 const char *end = strchr(src, '\n');
2518 const char *next = end + 1;
2519 if (!end)
2520 next = end = src + strlen(src);
2521 mp_msg(mod, lev, "[%3d] %.*s\n", line, (int)(end - src), src);
2522 line++;
2523 src = next;