cleanup: Silence compilation warnings on MinGW-w64
[mplayer.git] / libvo / gl_common.c
blob7cca800d405275c07735976c1e0f7d39fb4f021f
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 <math.h>
41 #include "talloc.h"
42 #include "gl_common.h"
43 #include "old_vo_wrapper.h"
44 #include "csputils.h"
45 #include "aspect.h"
46 #include "pnm_loader.h"
47 #include "options.h"
49 //! \defgroup glgeneral OpenGL general helper functions
51 //! \defgroup glcontext OpenGL context management helper functions
53 //! \defgroup gltexture OpenGL texture handling helper functions
55 //! \defgroup glconversion OpenGL conversion helper functions
57 /**
58 * \brief adjusts the GL_UNPACK_ALIGNMENT to fit the stride.
59 * \param stride number of bytes per line for which alignment should fit.
60 * \ingroup glgeneral
62 void glAdjustAlignment(GL *gl, int stride)
64 GLint gl_alignment;
65 if (stride % 8 == 0)
66 gl_alignment = 8;
67 else if (stride % 4 == 0)
68 gl_alignment = 4;
69 else if (stride % 2 == 0)
70 gl_alignment = 2;
71 else
72 gl_alignment = 1;
73 gl->PixelStorei(GL_UNPACK_ALIGNMENT, gl_alignment);
74 gl->PixelStorei(GL_PACK_ALIGNMENT, gl_alignment);
77 struct gl_name_map_struct {
78 GLint value;
79 const char *name;
82 #undef MAP
83 #define MAP(a) {a, # a}
84 //! mapping table for the glValName function
85 static const struct gl_name_map_struct gl_name_map[] = {
86 // internal format
87 MAP(GL_R3_G3_B2), MAP(GL_RGB4), MAP(GL_RGB5), MAP(GL_RGB8),
88 MAP(GL_RGB10), MAP(GL_RGB12), MAP(GL_RGB16), MAP(GL_RGBA2),
89 MAP(GL_RGBA4), MAP(GL_RGB5_A1), MAP(GL_RGBA8), MAP(GL_RGB10_A2),
90 MAP(GL_RGBA12), MAP(GL_RGBA16), MAP(GL_LUMINANCE8), MAP(GL_LUMINANCE16),
91 MAP(GL_R16),
93 // format
94 MAP(GL_RGB), MAP(GL_RGBA), MAP(GL_RED), MAP(GL_GREEN), MAP(GL_BLUE),
95 MAP(GL_ALPHA), MAP(GL_LUMINANCE), MAP(GL_LUMINANCE_ALPHA),
96 MAP(GL_COLOR_INDEX),
97 // rest 1.2 only
98 MAP(GL_BGR), MAP(GL_BGRA),
100 //type
101 MAP(GL_BYTE), MAP(GL_UNSIGNED_BYTE), MAP(GL_SHORT), MAP(GL_UNSIGNED_SHORT),
102 MAP(GL_INT), MAP(GL_UNSIGNED_INT), MAP(GL_FLOAT), MAP(GL_DOUBLE),
103 MAP(GL_2_BYTES), MAP(GL_3_BYTES), MAP(GL_4_BYTES),
104 // rest 1.2 only
105 MAP(GL_UNSIGNED_BYTE_3_3_2), MAP(GL_UNSIGNED_BYTE_2_3_3_REV),
106 MAP(GL_UNSIGNED_SHORT_5_6_5), MAP(GL_UNSIGNED_SHORT_5_6_5_REV),
107 MAP(GL_UNSIGNED_SHORT_4_4_4_4), MAP(GL_UNSIGNED_SHORT_4_4_4_4_REV),
108 MAP(GL_UNSIGNED_SHORT_5_5_5_1), MAP(GL_UNSIGNED_SHORT_1_5_5_5_REV),
109 MAP(GL_UNSIGNED_INT_8_8_8_8), MAP(GL_UNSIGNED_INT_8_8_8_8_REV),
110 MAP(GL_UNSIGNED_INT_10_10_10_2), MAP(GL_UNSIGNED_INT_2_10_10_10_REV),
111 {0, 0}
113 #undef MAP
116 * \brief return the name of an OpenGL constant
117 * \param value the constant
118 * \return name of the constant or "Unknown format!"
119 * \ingroup glgeneral
121 const char *glValName(GLint value)
123 int i = 0;
125 while (gl_name_map[i].name) {
126 if (gl_name_map[i].value == value)
127 return gl_name_map[i].name;
128 i++;
130 return "Unknown format!";
133 //! always return this format as internal texture format in glFindFormat
134 #define TEXTUREFORMAT_ALWAYS GL_RGB8
135 #undef TEXTUREFORMAT_ALWAYS
138 * \brief find the OpenGL settings coresponding to format.
140 * All parameters may be NULL.
141 * \param fmt MPlayer format to analyze.
142 * \param bpp [OUT] bits per pixel of that format.
143 * \param gl_texfmt [OUT] internal texture format that fits the
144 * image format, not necessarily the best for performance.
145 * \param gl_format [OUT] OpenGL format for this image format.
146 * \param gl_type [OUT] OpenGL type for this image format.
147 * \return 1 if format is supported by OpenGL, 0 if not.
148 * \ingroup gltexture
150 int glFindFormat(uint32_t fmt, int have_texture_rg, int *bpp, GLint *gl_texfmt,
151 GLenum *gl_format, GLenum *gl_type)
153 int supported = 1;
154 int dummy1;
155 GLenum dummy2;
156 GLint dummy3;
157 if (!bpp)
158 bpp = &dummy1;
159 if (!gl_texfmt)
160 gl_texfmt = &dummy3;
161 if (!gl_format)
162 gl_format = &dummy2;
163 if (!gl_type)
164 gl_type = &dummy2;
166 if (mp_get_chroma_shift(fmt, NULL, NULL, NULL)) {
167 // reduce the possible cases a bit
168 if (IMGFMT_IS_YUVP16_LE(fmt))
169 fmt = IMGFMT_420P16_LE;
170 else if (IMGFMT_IS_YUVP16_BE(fmt))
171 fmt = IMGFMT_420P16_BE;
172 else
173 fmt = IMGFMT_YV12;
176 *bpp = IMGFMT_IS_BGR(fmt) ? IMGFMT_BGR_DEPTH(fmt) : IMGFMT_RGB_DEPTH(fmt);
177 *gl_texfmt = 3;
178 switch (fmt) {
179 case IMGFMT_RGB48NE:
180 *gl_format = GL_RGB;
181 *gl_type = GL_UNSIGNED_SHORT;
182 break;
183 case IMGFMT_RGB24:
184 *gl_format = GL_RGB;
185 *gl_type = GL_UNSIGNED_BYTE;
186 break;
187 case IMGFMT_RGBA:
188 *gl_texfmt = 4;
189 *gl_format = GL_RGBA;
190 *gl_type = GL_UNSIGNED_BYTE;
191 break;
192 case IMGFMT_420P16:
193 supported = 0; // no native YUV support
194 *gl_texfmt = have_texture_rg ? GL_R16 : GL_LUMINANCE16;
195 *bpp = 16;
196 *gl_format = have_texture_rg ? GL_RED : GL_LUMINANCE;
197 *gl_type = GL_UNSIGNED_SHORT;
198 break;
199 case IMGFMT_YV12:
200 supported = 0; // no native YV12 support
201 case IMGFMT_Y800:
202 case IMGFMT_Y8:
203 *gl_texfmt = 1;
204 *bpp = 8;
205 *gl_format = GL_LUMINANCE;
206 *gl_type = GL_UNSIGNED_BYTE;
207 break;
208 case IMGFMT_UYVY:
209 // IMGFMT_YUY2 would be more logical for the _REV format,
210 // but gives clearly swapped colors.
211 case IMGFMT_YVYU:
212 *gl_texfmt = GL_YCBCR_MESA;
213 *bpp = 16;
214 *gl_format = GL_YCBCR_MESA;
215 *gl_type = fmt == IMGFMT_UYVY ? GL_UNSIGNED_SHORT_8_8 : GL_UNSIGNED_SHORT_8_8_REV;
216 break;
217 #if 0
218 // we do not support palettized formats, although the format the
219 // swscale produces works
220 case IMGFMT_RGB8:
221 gl_format = GL_RGB;
222 gl_type = GL_UNSIGNED_BYTE_2_3_3_REV;
223 break;
224 #endif
225 case IMGFMT_RGB15:
226 *gl_format = GL_RGBA;
227 *gl_type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
228 break;
229 case IMGFMT_RGB16:
230 *gl_format = GL_RGB;
231 *gl_type = GL_UNSIGNED_SHORT_5_6_5_REV;
232 break;
233 #if 0
234 case IMGFMT_BGR8:
235 // special case as red and blue have a differen number of bits.
236 // GL_BGR and GL_UNSIGNED_BYTE_3_3_2 isn't supported at least
237 // by nVidia drivers, and in addition would give more bits to
238 // blue than to red, which isn't wanted
239 gl_format = GL_RGB;
240 gl_type = GL_UNSIGNED_BYTE_3_3_2;
241 break;
242 #endif
243 case IMGFMT_BGR15:
244 *gl_format = GL_BGRA;
245 *gl_type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
246 break;
247 case IMGFMT_BGR16:
248 *gl_format = GL_RGB;
249 *gl_type = GL_UNSIGNED_SHORT_5_6_5;
250 break;
251 case IMGFMT_BGR24:
252 *gl_format = GL_BGR;
253 *gl_type = GL_UNSIGNED_BYTE;
254 break;
255 case IMGFMT_BGRA:
256 *gl_texfmt = 4;
257 *gl_format = GL_BGRA;
258 *gl_type = GL_UNSIGNED_BYTE;
259 break;
260 default:
261 *gl_texfmt = 4;
262 *gl_format = GL_RGBA;
263 *gl_type = GL_UNSIGNED_BYTE;
264 supported = 0;
266 #ifdef TEXTUREFORMAT_ALWAYS
267 *gl_texfmt = TEXTUREFORMAT_ALWAYS;
268 #endif
269 return supported;
272 #ifdef HAVE_LIBDL
273 #include <dlfcn.h>
274 #endif
276 * \brief find address of a linked function
277 * \param s name of function to find
278 * \return address of function or NULL if not found
280 static void *getdladdr(const char *s)
282 void *ret = NULL;
283 #ifdef HAVE_LIBDL
284 void *handle = dlopen(NULL, RTLD_LAZY);
285 if (!handle)
286 return NULL;
287 ret = dlsym(handle, s);
288 dlclose(handle);
289 #endif
290 return ret;
293 typedef struct {
294 ptrdiff_t offset; // offset to the function pointer in struct GL
295 const char *extstr;
296 const char *funcnames[7];
297 void *fallback;
298 } extfunc_desc_t;
300 #define DEF_FUNC_DESC(name) \
301 {offsetof(GL, name), NULL, {"gl" # name, NULL}, gl ## name}
302 #define DEF_EXT_FUNCS(...) __VA_ARGS__
303 #define DEF_EXT_DESC(name, ext, funcnames) \
304 {offsetof(GL, name), ext, {DEF_EXT_FUNCS funcnames}}
306 static const extfunc_desc_t extfuncs[] = {
307 // these aren't extension functions but we query them anyway to allow
308 // different "backends" with one binary
309 DEF_FUNC_DESC(Begin),
310 DEF_FUNC_DESC(End),
311 DEF_FUNC_DESC(Viewport),
312 DEF_FUNC_DESC(MatrixMode),
313 DEF_FUNC_DESC(LoadIdentity),
314 DEF_FUNC_DESC(Translated),
315 DEF_FUNC_DESC(Scaled),
316 DEF_FUNC_DESC(Ortho),
317 DEF_FUNC_DESC(Frustum),
318 DEF_FUNC_DESC(PushMatrix),
319 DEF_FUNC_DESC(PopMatrix),
320 DEF_FUNC_DESC(Clear),
321 DEF_FUNC_DESC(GenLists),
322 DEF_FUNC_DESC(DeleteLists),
323 DEF_FUNC_DESC(NewList),
324 DEF_FUNC_DESC(EndList),
325 DEF_FUNC_DESC(CallList),
326 DEF_FUNC_DESC(CallLists),
327 DEF_FUNC_DESC(GenTextures),
328 DEF_FUNC_DESC(DeleteTextures),
329 DEF_FUNC_DESC(TexEnvf),
330 DEF_FUNC_DESC(TexEnvi),
331 DEF_FUNC_DESC(Color4ub),
332 DEF_FUNC_DESC(Color3f),
333 DEF_FUNC_DESC(Color4f),
334 DEF_FUNC_DESC(ClearColor),
335 DEF_FUNC_DESC(ClearDepth),
336 DEF_FUNC_DESC(DepthFunc),
337 DEF_FUNC_DESC(Enable),
338 DEF_FUNC_DESC(Disable),
339 DEF_FUNC_DESC(DrawBuffer),
340 DEF_FUNC_DESC(DepthMask),
341 DEF_FUNC_DESC(BlendFunc),
342 DEF_FUNC_DESC(Flush),
343 DEF_FUNC_DESC(Finish),
344 DEF_FUNC_DESC(PixelStorei),
345 DEF_FUNC_DESC(TexImage1D),
346 DEF_FUNC_DESC(TexImage2D),
347 DEF_FUNC_DESC(TexSubImage2D),
348 DEF_FUNC_DESC(GetTexImage),
349 DEF_FUNC_DESC(TexParameteri),
350 DEF_FUNC_DESC(TexParameterf),
351 DEF_FUNC_DESC(TexParameterfv),
352 DEF_FUNC_DESC(TexCoord2f),
353 DEF_FUNC_DESC(Vertex2f),
354 DEF_FUNC_DESC(Vertex3f),
355 DEF_FUNC_DESC(Normal3f),
356 DEF_FUNC_DESC(Lightfv),
357 DEF_FUNC_DESC(ColorMaterial),
358 DEF_FUNC_DESC(ShadeModel),
359 DEF_FUNC_DESC(GetIntegerv),
360 DEF_FUNC_DESC(ColorMask),
361 DEF_FUNC_DESC(ReadPixels),
362 DEF_FUNC_DESC(ReadBuffer),
364 DEF_EXT_DESC(GenBuffers, NULL,
365 ("glGenBuffers", "glGenBuffersARB")),
366 DEF_EXT_DESC(DeleteBuffers, NULL,
367 ("glDeleteBuffers", "glDeleteBuffersARB")),
368 DEF_EXT_DESC(BindBuffer, NULL,
369 ("glBindBuffer", "glBindBufferARB")),
370 DEF_EXT_DESC(MapBuffer, NULL,
371 ("glMapBuffer", "glMapBufferARB")),
372 DEF_EXT_DESC(UnmapBuffer, NULL,
373 ("glUnmapBuffer", "glUnmapBufferARB")),
374 DEF_EXT_DESC(BufferData, NULL,
375 ("glBufferData", "glBufferDataARB")),
376 DEF_EXT_DESC(BeginFragmentShader, "ATI_fragment_shader",
377 ("glBeginFragmentShaderATI")),
378 DEF_EXT_DESC(EndFragmentShader, "ATI_fragment_shader",
379 ("glEndFragmentShaderATI")),
380 DEF_EXT_DESC(SampleMap, "ATI_fragment_shader",
381 ("glSampleMapATI")),
382 DEF_EXT_DESC(ColorFragmentOp2, "ATI_fragment_shader",
383 ("glColorFragmentOp2ATI")),
384 DEF_EXT_DESC(ColorFragmentOp3, "ATI_fragment_shader",
385 ("glColorFragmentOp3ATI")),
386 DEF_EXT_DESC(SetFragmentShaderConstant, "ATI_fragment_shader",
387 ("glSetFragmentShaderConstantATI")),
388 DEF_EXT_DESC(ActiveTexture, NULL,
389 ("glActiveTexture", "glActiveTextureARB")),
390 DEF_EXT_DESC(BindTexture, NULL,
391 ("glBindTexture", "glBindTextureARB", "glBindTextureEXT")),
392 DEF_EXT_DESC(MultiTexCoord2f, NULL,
393 ("glMultiTexCoord2f", "glMultiTexCoord2fARB")),
394 DEF_EXT_DESC(GenPrograms, "_program",
395 ("glGenProgramsARB")),
396 DEF_EXT_DESC(DeletePrograms, "_program",
397 ("glDeleteProgramsARB")),
398 DEF_EXT_DESC(BindProgram, "_program",
399 ("glBindProgramARB")),
400 DEF_EXT_DESC(ProgramString, "_program",
401 ("glProgramStringARB")),
402 DEF_EXT_DESC(GetProgramiv, "_program",
403 ("glGetProgramivARB")),
404 DEF_EXT_DESC(ProgramEnvParameter4f, "_program",
405 ("glProgramEnvParameter4fARB")),
406 DEF_EXT_DESC(SwapInterval, "_swap_control",
407 ("glXSwapIntervalSGI", "glXSwapInterval", "wglSwapIntervalSGI",
408 "wglSwapInterval", "wglSwapIntervalEXT")),
409 DEF_EXT_DESC(TexImage3D, NULL,
410 ("glTexImage3D")),
411 {-1}
415 * \brief find the function pointers of some useful OpenGL extensions
416 * \param getProcAddress function to resolve function names, may be NULL
417 * \param ext2 an extra extension string
419 static void getFunctions(GL *gl, void *(*getProcAddress)(const GLubyte *),
420 const char *ext2)
422 const extfunc_desc_t *dsc;
423 const char *extensions;
424 char *allexts;
426 if (!getProcAddress)
427 getProcAddress = (void *)getdladdr;
429 // special case, we need glGetString before starting to find the other functions
430 gl->GetString = getProcAddress("glGetString");
431 if (!gl->GetString)
432 gl->GetString = glGetString;
434 extensions = (const char *)gl->GetString(GL_EXTENSIONS);
435 if (!extensions)
436 extensions = "";
437 if (!ext2)
438 ext2 = "";
439 allexts = malloc(strlen(extensions) + strlen(ext2) + 2);
440 strcpy(allexts, extensions);
441 strcat(allexts, " ");
442 strcat(allexts, ext2);
443 mp_msg(MSGT_VO, MSGL_DBG2, "OpenGL extensions string:\n%s\n", allexts);
444 for (dsc = extfuncs; dsc->offset >= 0; dsc++) {
445 void *ptr = NULL;
446 int i;
447 if (!dsc->extstr || strstr(allexts, dsc->extstr)) {
448 for (i = 0; !ptr && dsc->funcnames[i]; i++)
449 ptr = getProcAddress((const GLubyte *)dsc->funcnames[i]);
451 if (!ptr)
452 ptr = dsc->fallback;
453 void **funcptr = (void**)(((char*)gl) + dsc->offset);
454 *funcptr = ptr;
456 free(allexts);
460 * \brief create a texture and set some defaults
461 * \param target texture taget, usually GL_TEXTURE_2D
462 * \param fmt internal texture format
463 * \param format texture host data format
464 * \param type texture host data type
465 * \param filter filter used for scaling, e.g. GL_LINEAR
466 * \param w texture width
467 * \param h texture height
468 * \param val luminance value to fill texture with
469 * \ingroup gltexture
471 void glCreateClearTex(GL *gl, GLenum target, GLenum fmt, GLenum format,
472 GLenum type, GLint filter, int w, int h,
473 unsigned char val)
475 GLfloat fval = (GLfloat)val / 255.0;
476 GLfloat border[4] = {
477 fval, fval, fval, fval
479 int stride;
480 char *init;
481 if (w == 0)
482 w = 1;
483 if (h == 0)
484 h = 1;
485 stride = w * glFmt2bpp(format, type);
486 if (!stride)
487 return;
488 init = malloc(stride * h);
489 memset(init, val, stride * h);
490 glAdjustAlignment(gl, stride);
491 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, w);
492 gl->TexImage2D(target, 0, fmt, w, h, 0, format, type, init);
493 gl->TexParameterf(target, GL_TEXTURE_PRIORITY, 1.0);
494 gl->TexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
495 gl->TexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
496 gl->TexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
497 gl->TexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
498 // Border texels should not be used with CLAMP_TO_EDGE
499 // We set a sane default anyway.
500 gl->TexParameterfv(target, GL_TEXTURE_BORDER_COLOR, border);
501 free(init);
504 static GLint detect_hqtexfmt(GL *gl)
506 const char *extensions = (const char *)gl->GetString(GL_EXTENSIONS);
507 if (strstr(extensions, "_texture_float"))
508 return GL_RGB32F;
509 else if (strstr(extensions, "NV_float_buffer"))
510 return GL_FLOAT_RGB32_NV;
511 return GL_RGB16;
515 * \brief creates a texture from a PPM file
516 * \param target texture taget, usually GL_TEXTURE_2D
517 * \param fmt internal texture format, 0 for default
518 * \param filter filter used for scaling, e.g. GL_LINEAR
519 * \param f file to read PPM from
520 * \param width [out] width of texture
521 * \param height [out] height of texture
522 * \param maxval [out] maxval value from PPM file
523 * \return 0 on error, 1 otherwise
524 * \ingroup gltexture
526 int glCreatePPMTex(GL *gl, GLenum target, GLenum fmt, GLint filter,
527 FILE *f, int *width, int *height, int *maxval)
529 int w, h, m, bpp;
530 GLenum type;
531 uint8_t *data = read_pnm(f, &w, &h, &bpp, &m);
532 GLint hqtexfmt = detect_hqtexfmt(gl);
533 if (!data || (bpp != 3 && bpp != 6)) {
534 free(data);
535 return 0;
537 if (!fmt) {
538 fmt = bpp == 6 ? hqtexfmt : 3;
539 if (fmt == GL_FLOAT_RGB32_NV && target != GL_TEXTURE_RECTANGLE)
540 fmt = GL_RGB16;
542 type = bpp == 6 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
543 glCreateClearTex(gl, target, fmt, GL_RGB, type, filter, w, h, 0);
544 glUploadTex(gl, target, GL_RGB, type,
545 data, w * bpp, 0, 0, w, h, 0);
546 free(data);
547 if (width)
548 *width = w;
549 if (height)
550 *height = h;
551 if (maxval)
552 *maxval = m;
553 return 1;
557 * \brief return the number of bytes per pixel for the given format
558 * \param format OpenGL format
559 * \param type OpenGL type
560 * \return bytes per pixel
561 * \ingroup glgeneral
563 * Does not handle all possible variants, just those used by MPlayer
565 int glFmt2bpp(GLenum format, GLenum type)
567 int component_size = 0;
568 switch (type) {
569 case GL_UNSIGNED_BYTE_3_3_2:
570 case GL_UNSIGNED_BYTE_2_3_3_REV:
571 return 1;
572 case GL_UNSIGNED_SHORT_5_5_5_1:
573 case GL_UNSIGNED_SHORT_1_5_5_5_REV:
574 case GL_UNSIGNED_SHORT_5_6_5:
575 case GL_UNSIGNED_SHORT_5_6_5_REV:
576 return 2;
577 case GL_UNSIGNED_BYTE:
578 component_size = 1;
579 break;
580 case GL_UNSIGNED_SHORT:
581 component_size = 2;
582 break;
584 switch (format) {
585 case GL_LUMINANCE:
586 case GL_ALPHA:
587 return component_size;
588 case GL_YCBCR_MESA:
589 return 2;
590 case GL_RGB:
591 case GL_BGR:
592 return 3 * component_size;
593 case GL_RGBA:
594 case GL_BGRA:
595 return 4 * component_size;
596 case GL_RED:
597 return component_size;
599 return 0; // unknown
603 * \brief upload a texture, handling things like stride and slices
604 * \param target texture target, usually GL_TEXTURE_2D
605 * \param format OpenGL format of data
606 * \param type OpenGL type of data
607 * \param dataptr data to upload
608 * \param stride data stride
609 * \param x x offset in texture
610 * \param y y offset in texture
611 * \param w width of the texture part to upload
612 * \param h height of the texture part to upload
613 * \param slice height of an upload slice, 0 for all at once
614 * \ingroup gltexture
616 void glUploadTex(GL *gl, GLenum target, GLenum format, GLenum type,
617 const void *dataptr, int stride,
618 int x, int y, int w, int h, int slice)
620 const uint8_t *data = dataptr;
621 int y_max = y + h;
622 if (w <= 0 || h <= 0)
623 return;
624 if (slice <= 0)
625 slice = h;
626 if (stride < 0) {
627 data += (h - 1) * stride;
628 stride = -stride;
630 // this is not always correct, but should work for MPlayer
631 glAdjustAlignment(gl, stride);
632 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
633 for (; y + slice <= y_max; y += slice) {
634 gl->TexSubImage2D(target, 0, x, y, w, slice, format, type, data);
635 data += stride * slice;
637 if (y < y_max)
638 gl->TexSubImage2D(target, 0, x, y, w, y_max - y, format, type, data);
642 * \brief download a texture, handling things like stride and slices
643 * \param target texture target, usually GL_TEXTURE_2D
644 * \param format OpenGL format of data
645 * \param type OpenGL type of data
646 * \param dataptr destination memory for download
647 * \param stride data stride (must be positive)
648 * \ingroup gltexture
650 void glDownloadTex(GL *gl, GLenum target, GLenum format, GLenum type,
651 void *dataptr, int stride)
653 // this is not always correct, but should work for MPlayer
654 glAdjustAlignment(gl, stride);
655 gl->PixelStorei(GL_PACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
656 gl->GetTexImage(target, 0, format, type, dataptr);
660 * \brief Setup ATI version of register combiners for YUV to RGB conversion.
661 * \param csp_params parameters used for colorspace conversion
662 * \param text if set use the GL_ATI_text_fragment_shader API as
663 * used on OS X.
665 static void glSetupYUVFragmentATI(GL *gl, struct mp_csp_params *csp_params,
666 int text)
668 GLint i;
669 float yuv2rgb[3][4];
671 gl->GetIntegerv(GL_MAX_TEXTURE_UNITS, &i);
672 if (i < 3)
673 mp_msg(MSGT_VO, MSGL_ERR,
674 "[gl] 3 texture units needed for YUV combiner (ATI) support (found %i)\n", i);
676 mp_get_yuv2rgb_coeffs(csp_params, yuv2rgb);
677 for (i = 0; i < 3; i++) {
678 int j;
679 yuv2rgb[i][3] -= -0.5 * (yuv2rgb[i][1] + yuv2rgb[i][2]);
680 for (j = 0; j < 4; j++) {
681 yuv2rgb[i][j] *= 0.125;
682 yuv2rgb[i][j] += 0.5;
683 if (yuv2rgb[i][j] > 1)
684 yuv2rgb[i][j] = 1;
685 if (yuv2rgb[i][j] < 0)
686 yuv2rgb[i][j] = 0;
689 if (text == 0) {
690 GLfloat c0[4] = { yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0] };
691 GLfloat c1[4] = { yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1] };
692 GLfloat c2[4] = { yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2] };
693 GLfloat c3[4] = { yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3] };
694 if (!gl->BeginFragmentShader || !gl->EndFragmentShader ||
695 !gl->SetFragmentShaderConstant || !gl->SampleMap ||
696 !gl->ColorFragmentOp2 || !gl->ColorFragmentOp3) {
697 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Combiner (ATI) functions missing!\n");
698 return;
700 gl->GetIntegerv(GL_NUM_FRAGMENT_REGISTERS_ATI, &i);
701 if (i < 3)
702 mp_msg(MSGT_VO, MSGL_ERR,
703 "[gl] 3 registers needed for YUV combiner (ATI) support (found %i)\n", i);
704 gl->BeginFragmentShader();
705 gl->SetFragmentShaderConstant(GL_CON_0_ATI, c0);
706 gl->SetFragmentShaderConstant(GL_CON_1_ATI, c1);
707 gl->SetFragmentShaderConstant(GL_CON_2_ATI, c2);
708 gl->SetFragmentShaderConstant(GL_CON_3_ATI, c3);
709 gl->SampleMap(GL_REG_0_ATI, GL_TEXTURE0, GL_SWIZZLE_STR_ATI);
710 gl->SampleMap(GL_REG_1_ATI, GL_TEXTURE1, GL_SWIZZLE_STR_ATI);
711 gl->SampleMap(GL_REG_2_ATI, GL_TEXTURE2, GL_SWIZZLE_STR_ATI);
712 gl->ColorFragmentOp2(GL_MUL_ATI, GL_REG_1_ATI, GL_NONE, GL_NONE,
713 GL_REG_1_ATI, GL_NONE, GL_BIAS_BIT_ATI,
714 GL_CON_1_ATI, GL_NONE, GL_BIAS_BIT_ATI);
715 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_2_ATI, GL_NONE, GL_NONE,
716 GL_REG_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
717 GL_CON_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
718 GL_REG_1_ATI, GL_NONE, GL_NONE);
719 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_0_ATI, GL_NONE, GL_NONE,
720 GL_REG_0_ATI, GL_NONE, GL_NONE,
721 GL_CON_0_ATI, GL_NONE, GL_BIAS_BIT_ATI,
722 GL_REG_2_ATI, GL_NONE, GL_NONE);
723 gl->ColorFragmentOp2(GL_ADD_ATI, GL_REG_0_ATI, GL_NONE, GL_8X_BIT_ATI,
724 GL_REG_0_ATI, GL_NONE, GL_NONE,
725 GL_CON_3_ATI, GL_NONE, GL_BIAS_BIT_ATI);
726 gl->EndFragmentShader();
727 } else {
728 static const char template[] =
729 "!!ATIfs1.0\n"
730 "StartConstants;\n"
731 " CONSTANT c0 = {%e, %e, %e};\n"
732 " CONSTANT c1 = {%e, %e, %e};\n"
733 " CONSTANT c2 = {%e, %e, %e};\n"
734 " CONSTANT c3 = {%e, %e, %e};\n"
735 "EndConstants;\n"
736 "StartOutputPass;\n"
737 " SampleMap r0, t0.str;\n"
738 " SampleMap r1, t1.str;\n"
739 " SampleMap r2, t2.str;\n"
740 " MUL r1.rgb, r1.bias, c1.bias;\n"
741 " MAD r2.rgb, r2.bias, c2.bias, r1;\n"
742 " MAD r0.rgb, r0, c0.bias, r2;\n"
743 " ADD r0.rgb.8x, r0, c3.bias;\n"
744 "EndPass;\n";
745 char buffer[512];
746 snprintf(buffer, sizeof(buffer), template,
747 yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0],
748 yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1],
749 yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2],
750 yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3]);
751 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
752 buffer);
753 loadGPUProgram(gl, GL_TEXT_FRAGMENT_SHADER_ATI, buffer);
757 // Replace all occurances of variables named "$"+name (e.g. $foo) in *text with
758 // replace, and return the result. *text must have been allocated with talloc.
759 static void replace_var_str(char **text, const char *name, const char *replace)
761 size_t namelen = strlen(name);
762 char *nextvar = *text;
763 void *parent = talloc_parent(*text);
764 for (;;) {
765 nextvar = strchr(nextvar, '$');
766 if (!nextvar)
767 break;
768 char *until = nextvar;
769 nextvar++;
770 if (strncmp(nextvar, name, namelen) != 0)
771 continue;
772 nextvar += namelen;
773 // try not to replace prefixes of other vars (e.g. $foo vs. $foo_bar)
774 char term = nextvar[0];
775 if (isalnum(term) || term == '_')
776 continue;
777 int prelength = until - *text;
778 int postlength = nextvar - *text;
779 char *n = talloc_asprintf(parent, "%.*s%s%s", prelength, *text, replace,
780 nextvar);
781 talloc_free(*text);
782 *text = n;
783 nextvar = *text + postlength;
787 static void replace_var_float(char **text, const char *name, float replace)
789 char *s = talloc_asprintf(NULL, "%e", replace);
790 replace_var_str(text, name, s);
791 talloc_free(s);
794 static void replace_var_char(char **text, const char *name, char replace)
796 char s[2] = { replace, '\0' };
797 replace_var_str(text, name, s);
800 // Append template to *text. Possibly initialize *text if it's NULL.
801 static void append_template(char **text, const char* template)
803 if (!text)
804 *text = talloc_strdup(NULL, template);
805 else
806 *text = talloc_strdup_append(*text, template);
810 * \brief helper function for gen_spline_lookup_tex
811 * \param x subpixel-position ((0,1) range) to calculate weights for
812 * \param dst where to store transformed weights, must provide space for 4 GLfloats
814 * calculates the weights and stores them after appropriate transformation
815 * for the scaler fragment program.
817 static void store_weights(float x, GLfloat *dst)
819 float w0 = (((-1 * x + 3) * x - 3) * x + 1) / 6;
820 float w1 = (((3 * x - 6) * x + 0) * x + 4) / 6;
821 float w2 = (((-3 * x + 3) * x + 3) * x + 1) / 6;
822 float w3 = (((1 * x + 0) * x + 0) * x + 0) / 6;
823 *dst++ = 1 + x - w1 / (w0 + w1);
824 *dst++ = 1 - x + w3 / (w2 + w3);
825 *dst++ = w0 + w1;
826 *dst++ = 0;
829 //! to avoid artefacts this should be rather large
830 #define LOOKUP_BSPLINE_RES (2 * 1024)
832 * \brief creates the 1D lookup texture needed for fast higher-order filtering
833 * \param unit texture unit to attach texture to
835 static void gen_spline_lookup_tex(GL *gl, GLenum unit)
837 GLfloat *tex = calloc(4 * LOOKUP_BSPLINE_RES, sizeof(*tex));
838 GLfloat *tp = tex;
839 int i;
840 for (i = 0; i < LOOKUP_BSPLINE_RES; i++) {
841 float x = (float)(i + 0.5) / LOOKUP_BSPLINE_RES;
842 store_weights(x, tp);
843 tp += 4;
845 store_weights(0, tex);
846 store_weights(1, &tex[4 * (LOOKUP_BSPLINE_RES - 1)]);
847 gl->ActiveTexture(unit);
848 gl->TexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, LOOKUP_BSPLINE_RES, 0, GL_RGBA,
849 GL_FLOAT, tex);
850 gl->TexParameterf(GL_TEXTURE_1D, GL_TEXTURE_PRIORITY, 1.0);
851 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
852 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
853 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
854 gl->ActiveTexture(GL_TEXTURE0);
855 free(tex);
858 #define SAMPLE(dest, coord, texture) \
859 "TEX textemp, " coord ", " texture ", $tex_type;\n" \
860 "MOV " dest ", textemp.r;\n"
862 static const char *bilin_filt_template =
863 SAMPLE("yuv.$out_comp","fragment.texcoord[$in_tex]","texture[$in_tex]");
865 #define BICUB_FILT_MAIN \
866 /* first y-interpolation */ \
867 "ADD coord, fragment.texcoord[$in_tex].xyxy, cdelta.xyxw;\n" \
868 "ADD coord2, fragment.texcoord[$in_tex].xyxy, cdelta.zyzw;\n" \
869 SAMPLE("a.r","coord.xyxy","texture[$in_tex]") \
870 SAMPLE("a.g","coord.zwzw","texture[$in_tex]") \
871 /* second y-interpolation */ \
872 SAMPLE("b.r","coord2.xyxy","texture[$in_tex]") \
873 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]") \
874 "LRP a.b, parmy.b, a.rrrr, a.gggg;\n" \
875 "LRP a.a, parmy.b, b.rrrr, b.gggg;\n" \
876 /* x-interpolation */ \
877 "LRP yuv.$out_comp, parmx.b, a.bbbb, a.aaaa;\n"
879 static const char *bicub_filt_template_2D =
880 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
881 "TEX parmx, coord.x, texture[$texs], 1D;\n"
882 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
883 "TEX parmy, coord.y, texture[$texs], 1D;\n"
884 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
885 BICUB_FILT_MAIN;
887 static const char *bicub_filt_template_RECT =
888 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
889 "TEX parmx, coord.x, texture[$texs], 1D;\n"
890 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
891 "TEX parmy, coord.y, texture[$texs], 1D;\n"
892 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
893 BICUB_FILT_MAIN;
895 #define CALCWEIGHTS(t, s) \
896 "MAD "t ", {-0.5, 0.1666, 0.3333, -0.3333}, "s ", {1, 0, -0.5, 0.5};\n" \
897 "MAD "t ", "t ", "s ", {0, 0, -0.5, 0.5};\n" \
898 "MAD "t ", "t ", "s ", {-0.6666, 0, 0.8333, 0.1666};\n" \
899 "RCP a.x, "t ".z;\n" \
900 "RCP a.y, "t ".w;\n" \
901 "MAD "t ".xy, "t ".xyxy, a.xyxy, {1, 1, 0, 0};\n" \
902 "ADD "t ".x, "t ".xxxx, "s ";\n" \
903 "SUB "t ".y, "t ".yyyy, "s ";\n"
905 static const char *bicub_notex_filt_template_2D =
906 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
907 "FRC coord.xy, coord.xyxy;\n"
908 CALCWEIGHTS("parmx", "coord.xxxx")
909 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
910 CALCWEIGHTS("parmy", "coord.yyyy")
911 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
912 BICUB_FILT_MAIN;
914 static const char *bicub_notex_filt_template_RECT =
915 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
916 "FRC coord.xy, coord.xyxy;\n"
917 CALCWEIGHTS("parmx", "coord.xxxx")
918 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
919 CALCWEIGHTS("parmy", "coord.yyyy")
920 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
921 BICUB_FILT_MAIN;
923 #define BICUB_X_FILT_MAIN \
924 "ADD coord.xy, fragment.texcoord[$in_tex].xyxy, cdelta.xyxy;\n" \
925 "ADD coord2.xy, fragment.texcoord[$in_tex].xyxy, cdelta.zyzy;\n" \
926 SAMPLE("a.r","coord","texture[$in_tex]") \
927 SAMPLE("b.r","coord2","texture[$in_tex]") \
928 /* x-interpolation */ \
929 "LRP yuv.$out_comp, parmx.b, a.rrrr, b.rrrr;\n"
931 static const char *bicub_x_filt_template_2D =
932 "MAD coord.x, fragment.texcoord[$in_tex], {$texw}, {0.5};\n"
933 "TEX parmx, coord, texture[$texs], 1D;\n"
934 "MUL cdelta.xyz, parmx.rrgg, {-$ptw, 0, $ptw};\n"
935 BICUB_X_FILT_MAIN;
937 static const char *bicub_x_filt_template_RECT =
938 "ADD coord.x, fragment.texcoord[$in_tex], {0.5};\n"
939 "TEX parmx, coord, texture[$texs], 1D;\n"
940 "MUL cdelta.xyz, parmx.rrgg, {-1, 0, 1};\n"
941 BICUB_X_FILT_MAIN;
943 static const char *unsharp_filt_template =
944 "PARAM dcoord$out_comp = {$ptw_05, $pth_05, $ptw_05, -$pth_05};\n"
945 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
946 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
947 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
948 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
949 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
950 "ADD b.r, b.r, b.g;\n"
951 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
952 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
953 "DP3 b, b, {0.25, 0.25, 0.25};\n"
954 "SUB b.r, a.r, b.r;\n"
955 "MAD textemp.r, b.r, {$strength}, a.r;\n"
956 "MOV yuv.$out_comp, textemp.r;\n";
958 static const char *unsharp_filt_template2 =
959 "PARAM dcoord$out_comp = {$ptw_12, $pth_12, $ptw_12, -$pth_12};\n"
960 "PARAM dcoord2$out_comp = {$ptw_15, 0, 0, $pth_15};\n"
961 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
962 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
963 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
964 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
965 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
966 "ADD b.r, b.r, b.g;\n"
967 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
968 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
969 "ADD b.r, b.r, b.b;\n"
970 "ADD b.a, b.r, b.g;\n"
971 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
972 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
973 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
974 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
975 "ADD b.r, b.r, b.g;\n"
976 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
977 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
978 "DP4 b.r, b, {-0.1171875, -0.1171875, -0.1171875, -0.09765625};\n"
979 "MAD b.r, a.r, {0.859375}, b.r;\n"
980 "MAD textemp.r, b.r, {$strength}, a.r;\n"
981 "MOV yuv.$out_comp, textemp.r;\n";
983 static const char *yuv_prog_template =
984 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
985 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
986 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
987 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
988 "TEMP res;\n"
989 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
990 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
991 "MAD result.color.rgb, yuv.bbbb, vcoef, res;\n"
992 "END";
994 static const char *yuv_pow_prog_template =
995 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
996 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
997 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
998 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
999 "PARAM gamma = {$gamma_r, $gamma_g, $gamma_b};\n"
1000 "TEMP res;\n"
1001 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
1002 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1003 "MAD_SAT res.rgb, yuv.bbbb, vcoef, res;\n"
1004 "POW result.color.r, res.r, gamma.r;\n"
1005 "POW result.color.g, res.g, gamma.g;\n"
1006 "POW result.color.b, res.b, gamma.b;\n"
1007 "END";
1009 static const char *yuv_lookup_prog_template =
1010 "PARAM ycoef = {$cm11, $cm21, $cm31, 0};\n"
1011 "PARAM ucoef = {$cm12, $cm22, $cm32, 0};\n"
1012 "PARAM vcoef = {$cm13, $cm23, $cm33, 0};\n"
1013 "PARAM offsets = {$cm14, $cm24, $cm34, 0.125};\n"
1014 "TEMP res;\n"
1015 "MAD res, yuv.rrrr, ycoef, offsets;\n"
1016 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1017 "MAD res.rgb, yuv.bbbb, vcoef, res;\n"
1018 "TEX result.color.r, res.raaa, texture[$conv_tex0], 2D;\n"
1019 "ADD res.a, res.a, 0.25;\n"
1020 "TEX result.color.g, res.gaaa, texture[$conv_tex0], 2D;\n"
1021 "ADD res.a, res.a, 0.25;\n"
1022 "TEX result.color.b, res.baaa, texture[$conv_tex0], 2D;\n"
1023 "END";
1025 static const char *yuv_lookup3d_prog_template =
1026 "TEX result.color, yuv, texture[$conv_tex0], 3D;\n"
1027 "END";
1030 * \brief creates and initializes helper textures needed for scaling texture read
1031 * \param scaler scaler type to create texture for
1032 * \param texu contains next free texture unit number
1033 * \param texs texture unit ids for the scaler are stored in this array
1035 static void create_scaler_textures(GL *gl, int scaler, int *texu, char *texs)
1037 switch (scaler) {
1038 case YUV_SCALER_BILIN:
1039 case YUV_SCALER_BICUB_NOTEX:
1040 case YUV_SCALER_UNSHARP:
1041 case YUV_SCALER_UNSHARP2:
1042 break;
1043 case YUV_SCALER_BICUB:
1044 case YUV_SCALER_BICUB_X:
1045 texs[0] = (*texu)++;
1046 gen_spline_lookup_tex(gl, GL_TEXTURE0 + texs[0]);
1047 texs[0] += '0';
1048 break;
1049 default:
1050 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown scaler type %i\n", scaler);
1054 //! resolution of texture for gamma lookup table
1055 #define LOOKUP_RES 512
1056 //! resolution for 3D yuv->rgb conversion lookup table
1057 #define LOOKUP_3DRES 32
1059 * \brief creates and initializes helper textures needed for yuv conversion
1060 * \param params struct containing parameters like brightness, gamma, ...
1061 * \param texu contains next free texture unit number
1062 * \param texs texture unit ids for the conversion are stored in this array
1064 static void create_conv_textures(GL *gl, gl_conversion_params_t *params,
1065 int *texu, char *texs)
1067 unsigned char *lookup_data = NULL;
1068 int conv = YUV_CONVERSION(params->type);
1069 switch (conv) {
1070 case YUV_CONVERSION_FRAGMENT:
1071 case YUV_CONVERSION_FRAGMENT_POW:
1072 break;
1073 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1074 texs[0] = (*texu)++;
1075 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1076 lookup_data = malloc(4 * LOOKUP_RES);
1077 mp_gen_gamma_map(lookup_data, LOOKUP_RES, params->csp_params.rgamma);
1078 mp_gen_gamma_map(&lookup_data[LOOKUP_RES], LOOKUP_RES,
1079 params->csp_params.ggamma);
1080 mp_gen_gamma_map(&lookup_data[2 * LOOKUP_RES], LOOKUP_RES,
1081 params->csp_params.bgamma);
1082 glCreateClearTex(gl, GL_TEXTURE_2D, GL_LUMINANCE8, GL_LUMINANCE,
1083 GL_UNSIGNED_BYTE, GL_LINEAR, LOOKUP_RES, 4, 0);
1084 glUploadTex(gl, GL_TEXTURE_2D, GL_LUMINANCE, GL_UNSIGNED_BYTE,
1085 lookup_data, LOOKUP_RES, 0, 0, LOOKUP_RES, 4, 0);
1086 gl->ActiveTexture(GL_TEXTURE0);
1087 texs[0] += '0';
1088 break;
1089 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1091 int sz = LOOKUP_3DRES + 2; // texture size including borders
1092 if (!gl->TexImage3D) {
1093 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing 3D texture function!\n");
1094 break;
1096 texs[0] = (*texu)++;
1097 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1098 lookup_data = malloc(3 * sz * sz * sz);
1099 mp_gen_yuv2rgb_map(&params->csp_params, lookup_data, LOOKUP_3DRES);
1100 glAdjustAlignment(gl, sz);
1101 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1102 gl->TexImage3D(GL_TEXTURE_3D, 0, 3, sz, sz, sz, 1,
1103 GL_RGB, GL_UNSIGNED_BYTE, lookup_data);
1104 gl->TexParameterf(GL_TEXTURE_3D, GL_TEXTURE_PRIORITY, 1.0);
1105 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1106 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1107 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1108 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1109 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
1110 gl->ActiveTexture(GL_TEXTURE0);
1111 texs[0] += '0';
1113 break;
1114 default:
1115 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n", conv);
1117 free(lookup_data);
1121 * \brief adds a scaling texture read at the current fragment program position
1122 * \param scaler type of scaler to insert
1123 * \param prog pointer to fragment program so far
1124 * \param texs array containing the texture unit identifiers for this scaler
1125 * \param in_tex texture unit the scaler should read from
1126 * \param out_comp component of the yuv variable the scaler stores the result in
1127 * \param rect if rectangular (pixel) adressing should be used for in_tex
1128 * \param texw width of the in_tex texture
1129 * \param texh height of the in_tex texture
1130 * \param strength strength of filter effect if the scaler does some kind of filtering
1132 static void add_scaler(int scaler, char **prog, char *texs,
1133 char in_tex, char out_comp, int rect, int texw, int texh,
1134 double strength)
1136 const char *ttype = rect ? "RECT" : "2D";
1137 const float ptw = rect ? 1.0 : 1.0 / texw;
1138 const float pth = rect ? 1.0 : 1.0 / texh;
1139 switch (scaler) {
1140 case YUV_SCALER_BILIN:
1141 append_template(prog, bilin_filt_template);
1142 break;
1143 case YUV_SCALER_BICUB:
1144 if (rect)
1145 append_template(prog, bicub_filt_template_RECT);
1146 else
1147 append_template(prog, bicub_filt_template_2D);
1148 break;
1149 case YUV_SCALER_BICUB_X:
1150 if (rect)
1151 append_template(prog, bicub_x_filt_template_RECT);
1152 else
1153 append_template(prog, bicub_x_filt_template_2D);
1154 break;
1155 case YUV_SCALER_BICUB_NOTEX:
1156 if (rect)
1157 append_template(prog, bicub_notex_filt_template_RECT);
1158 else
1159 append_template(prog, bicub_notex_filt_template_2D);
1160 break;
1161 case YUV_SCALER_UNSHARP:
1162 append_template(prog, unsharp_filt_template);
1163 break;
1164 case YUV_SCALER_UNSHARP2:
1165 append_template(prog, unsharp_filt_template2);
1166 break;
1169 replace_var_char(prog, "texs", texs[0]);
1170 replace_var_char(prog, "in_tex", in_tex);
1171 replace_var_char(prog, "out_comp", out_comp);
1172 replace_var_str(prog, "tex_type", ttype);
1173 replace_var_float(prog, "texw", texw);
1174 replace_var_float(prog, "texh", texh);
1175 replace_var_float(prog, "ptw", ptw);
1176 replace_var_float(prog, "pth", pth);
1178 // this is silly, not sure if that couldn't be in the shader source instead
1179 replace_var_float(prog, "ptw_05", ptw * 0.5);
1180 replace_var_float(prog, "pth_05", pth * 0.5);
1181 replace_var_float(prog, "ptw_15", ptw * 1.5);
1182 replace_var_float(prog, "pth_15", pth * 1.5);
1183 replace_var_float(prog, "ptw_12", ptw * 1.2);
1184 replace_var_float(prog, "pth_12", pth * 1.2);
1186 replace_var_float(prog, "strength", strength);
1189 static const struct {
1190 const char *name;
1191 GLenum cur;
1192 GLenum max;
1193 } progstats[] = {
1194 {"instructions", 0x88A0, 0x88A1},
1195 {"native instructions", 0x88A2, 0x88A3},
1196 {"temporaries", 0x88A4, 0x88A5},
1197 {"native temporaries", 0x88A6, 0x88A7},
1198 {"parameters", 0x88A8, 0x88A9},
1199 {"native parameters", 0x88AA, 0x88AB},
1200 {"attribs", 0x88AC, 0x88AD},
1201 {"native attribs", 0x88AE, 0x88AF},
1202 {"ALU instructions", 0x8805, 0x880B},
1203 {"TEX instructions", 0x8806, 0x880C},
1204 {"TEX indirections", 0x8807, 0x880D},
1205 {"native ALU instructions", 0x8808, 0x880E},
1206 {"native TEX instructions", 0x8809, 0x880F},
1207 {"native TEX indirections", 0x880A, 0x8810},
1208 {NULL, 0, 0}
1212 * \brief load the specified GPU Program
1213 * \param target program target to load into, only GL_FRAGMENT_PROGRAM is tested
1214 * \param prog program string
1215 * \return 1 on success, 0 otherwise
1217 int loadGPUProgram(GL *gl, GLenum target, char *prog)
1219 int i;
1220 GLint cur = 0, max = 0, err = 0;
1221 if (!gl->ProgramString) {
1222 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing GPU program function\n");
1223 return 0;
1225 gl->ProgramString(target, GL_PROGRAM_FORMAT_ASCII, strlen(prog), prog);
1226 gl->GetIntegerv(GL_PROGRAM_ERROR_POSITION, &err);
1227 if (err != -1) {
1228 mp_msg(MSGT_VO, MSGL_ERR,
1229 "[gl] Error compiling fragment program, make sure your card supports\n"
1230 "[gl] GL_ARB_fragment_program (use glxinfo to check).\n"
1231 "[gl] Error message:\n %s at %.10s\n",
1232 gl->GetString(GL_PROGRAM_ERROR_STRING), &prog[err]);
1233 return 0;
1235 if (!gl->GetProgramiv || !mp_msg_test(MSGT_VO, MSGL_DBG2))
1236 return 1;
1237 mp_msg(MSGT_VO, MSGL_V, "[gl] Program statistics:\n");
1238 for (i = 0; progstats[i].name; i++) {
1239 gl->GetProgramiv(target, progstats[i].cur, &cur);
1240 gl->GetProgramiv(target, progstats[i].max, &max);
1241 mp_msg(MSGT_VO, MSGL_V, "[gl] %s: %i/%i\n", progstats[i].name, cur,
1242 max);
1244 return 1;
1247 #define MAX_PROGSZ (1024 * 1024)
1250 * \brief setup a fragment program that will do YUV->RGB conversion
1251 * \param parms struct containing parameters like conversion and scaler type,
1252 * brightness, ...
1254 static void glSetupYUVFragprog(GL *gl, gl_conversion_params_t *params)
1256 int type = params->type;
1257 int texw = params->texw;
1258 int texh = params->texh;
1259 int rect = params->target == GL_TEXTURE_RECTANGLE;
1260 static const char prog_hdr[] =
1261 "!!ARBfp1.0\n"
1262 "OPTION ARB_precision_hint_fastest;\n"
1263 // all scaler variables must go here so they aren't defined
1264 // multiple times when the same scaler is used more than once
1265 "TEMP coord, coord2, cdelta, parmx, parmy, a, b, yuv, textemp;\n";
1266 char *yuv_prog = NULL;
1267 char **prog = &yuv_prog;
1268 int cur_texu = 3;
1269 char lum_scale_texs[1];
1270 char chrom_scale_texs[1];
1271 char conv_texs[1];
1272 GLint i;
1273 // this is the conversion matrix, with y, u, v factors
1274 // for red, green, blue and the constant offsets
1275 float yuv2rgb[3][4];
1276 create_conv_textures(gl, params, &cur_texu, conv_texs);
1277 create_scaler_textures(gl, YUV_LUM_SCALER(type), &cur_texu, lum_scale_texs);
1278 if (YUV_CHROM_SCALER(type) == YUV_LUM_SCALER(type))
1279 memcpy(chrom_scale_texs, lum_scale_texs, sizeof(chrom_scale_texs));
1280 else
1281 create_scaler_textures(gl, YUV_CHROM_SCALER(type), &cur_texu,
1282 chrom_scale_texs);
1283 gl->GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &i);
1284 if (i < cur_texu)
1285 mp_msg(MSGT_VO, MSGL_ERR,
1286 "[gl] %i texture units needed for this type of YUV fragment support (found %i)\n",
1287 cur_texu, i);
1288 if (!gl->ProgramString) {
1289 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] ProgramString function missing!\n");
1290 return;
1292 append_template(prog, prog_hdr);
1293 add_scaler(YUV_LUM_SCALER(type), prog, lum_scale_texs,
1294 '0', 'r', rect, texw, texh, params->filter_strength);
1295 add_scaler(YUV_CHROM_SCALER(type), prog,
1296 chrom_scale_texs, '1', 'g', rect, params->chrom_texw,
1297 params->chrom_texh, params->filter_strength);
1298 add_scaler(YUV_CHROM_SCALER(type), prog,
1299 chrom_scale_texs, '2', 'b', rect, params->chrom_texw,
1300 params->chrom_texh, params->filter_strength);
1301 mp_get_yuv2rgb_coeffs(&params->csp_params, yuv2rgb);
1302 switch (YUV_CONVERSION(type)) {
1303 case YUV_CONVERSION_FRAGMENT:
1304 append_template(prog, yuv_prog_template);
1305 break;
1306 case YUV_CONVERSION_FRAGMENT_POW:
1307 append_template(prog, yuv_pow_prog_template);
1308 break;
1309 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1310 append_template(prog, yuv_lookup_prog_template);
1311 break;
1312 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1313 append_template(prog, yuv_lookup3d_prog_template);
1314 break;
1315 default:
1316 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1317 YUV_CONVERSION(type));
1318 break;
1320 for (int r = 0; r < 3; r++) {
1321 for (int c = 0; c < 4; c++) {
1322 // "cmRC"
1323 char var[] = { 'c', 'm', '1' + r, '1' + c, '\0' };
1324 replace_var_float(prog, var, yuv2rgb[r][c]);
1327 replace_var_float(prog, "gamma_r", (float)1.0 / params->csp_params.rgamma);
1328 replace_var_float(prog, "gamma_g", (float)1.0 / params->csp_params.ggamma);
1329 replace_var_float(prog, "gamma_b", (float)1.0 / params->csp_params.bgamma);
1330 replace_var_char(prog, "conv_tex0", conv_texs[0]);
1331 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
1332 yuv_prog);
1333 loadGPUProgram(gl, GL_FRAGMENT_PROGRAM, yuv_prog);
1334 talloc_free(yuv_prog);
1338 * \brief detect the best YUV->RGB conversion method available
1340 int glAutodetectYUVConversion(GL *gl)
1342 const char *extensions = gl->GetString(GL_EXTENSIONS);
1343 if (!extensions || !gl->MultiTexCoord2f)
1344 return YUV_CONVERSION_NONE;
1345 if (strstr(extensions, "GL_ARB_fragment_program"))
1346 return YUV_CONVERSION_FRAGMENT;
1347 if (strstr(extensions, "GL_ATI_text_fragment_shader"))
1348 return YUV_CONVERSION_TEXT_FRAGMENT;
1349 if (strstr(extensions, "GL_ATI_fragment_shader"))
1350 return YUV_CONVERSION_COMBINERS_ATI;
1351 return YUV_CONVERSION_NONE;
1355 * \brief setup YUV->RGB conversion
1356 * \param parms struct containing parameters like conversion and scaler type,
1357 * brightness, ...
1358 * \ingroup glconversion
1360 void glSetupYUVConversion(GL *gl, gl_conversion_params_t *params)
1362 if (params->chrom_texw == 0)
1363 params->chrom_texw = 1;
1364 if (params->chrom_texh == 0)
1365 params->chrom_texh = 1;
1366 switch (YUV_CONVERSION(params->type)) {
1367 case YUV_CONVERSION_COMBINERS_ATI:
1368 glSetupYUVFragmentATI(gl, &params->csp_params, 0);
1369 break;
1370 case YUV_CONVERSION_TEXT_FRAGMENT:
1371 glSetupYUVFragmentATI(gl, &params->csp_params, 1);
1372 break;
1373 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1374 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1375 case YUV_CONVERSION_FRAGMENT:
1376 case YUV_CONVERSION_FRAGMENT_POW:
1377 glSetupYUVFragprog(gl, params);
1378 break;
1379 case YUV_CONVERSION_NONE:
1380 break;
1381 default:
1382 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1383 YUV_CONVERSION(params->type));
1388 * \brief enable the specified YUV conversion
1389 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1390 * \param type type of YUV conversion
1391 * \ingroup glconversion
1393 void glEnableYUVConversion(GL *gl, GLenum target, int type)
1395 switch (YUV_CONVERSION(type)) {
1396 case YUV_CONVERSION_COMBINERS_ATI:
1397 gl->ActiveTexture(GL_TEXTURE1);
1398 gl->Enable(target);
1399 gl->ActiveTexture(GL_TEXTURE2);
1400 gl->Enable(target);
1401 gl->ActiveTexture(GL_TEXTURE0);
1402 gl->Enable(GL_FRAGMENT_SHADER_ATI);
1403 break;
1404 case YUV_CONVERSION_TEXT_FRAGMENT:
1405 gl->ActiveTexture(GL_TEXTURE1);
1406 gl->Enable(target);
1407 gl->ActiveTexture(GL_TEXTURE2);
1408 gl->Enable(target);
1409 gl->ActiveTexture(GL_TEXTURE0);
1410 gl->Enable(GL_TEXT_FRAGMENT_SHADER_ATI);
1411 break;
1412 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1413 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1414 case YUV_CONVERSION_FRAGMENT_POW:
1415 case YUV_CONVERSION_FRAGMENT:
1416 case YUV_CONVERSION_NONE:
1417 gl->Enable(GL_FRAGMENT_PROGRAM);
1418 break;
1423 * \brief disable the specified YUV conversion
1424 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1425 * \param type type of YUV conversion
1426 * \ingroup glconversion
1428 void glDisableYUVConversion(GL *gl, GLenum target, int type)
1430 switch (YUV_CONVERSION(type)) {
1431 case YUV_CONVERSION_COMBINERS_ATI:
1432 gl->ActiveTexture(GL_TEXTURE1);
1433 gl->Disable(target);
1434 gl->ActiveTexture(GL_TEXTURE2);
1435 gl->Disable(target);
1436 gl->ActiveTexture(GL_TEXTURE0);
1437 gl->Disable(GL_FRAGMENT_SHADER_ATI);
1438 break;
1439 case YUV_CONVERSION_TEXT_FRAGMENT:
1440 gl->Disable(GL_TEXT_FRAGMENT_SHADER_ATI);
1441 // HACK: at least the Mac OS X 10.5 PPC Radeon drivers are broken and
1442 // without this disable the texture units while the program is still
1443 // running (10.4 PPC seems to work without this though).
1444 gl->Flush();
1445 gl->ActiveTexture(GL_TEXTURE1);
1446 gl->Disable(target);
1447 gl->ActiveTexture(GL_TEXTURE2);
1448 gl->Disable(target);
1449 gl->ActiveTexture(GL_TEXTURE0);
1450 break;
1451 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1452 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1453 case YUV_CONVERSION_FRAGMENT_POW:
1454 case YUV_CONVERSION_FRAGMENT:
1455 case YUV_CONVERSION_NONE:
1456 gl->Disable(GL_FRAGMENT_PROGRAM);
1457 break;
1461 void glEnable3DLeft(GL *gl, int type)
1463 GLint buffer;
1464 switch (type) {
1465 case GL_3D_RED_CYAN:
1466 gl->ColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
1467 break;
1468 case GL_3D_GREEN_MAGENTA:
1469 gl->ColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
1470 break;
1471 case GL_3D_QUADBUFFER:
1472 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1473 switch (buffer) {
1474 case GL_FRONT:
1475 case GL_FRONT_LEFT:
1476 case GL_FRONT_RIGHT:
1477 buffer = GL_FRONT_LEFT;
1478 break;
1479 case GL_BACK:
1480 case GL_BACK_LEFT:
1481 case GL_BACK_RIGHT:
1482 buffer = GL_BACK_LEFT;
1483 break;
1485 gl->DrawBuffer(buffer);
1486 break;
1490 void glEnable3DRight(GL *gl, int type)
1492 GLint buffer;
1493 switch (type) {
1494 case GL_3D_RED_CYAN:
1495 gl->ColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
1496 break;
1497 case GL_3D_GREEN_MAGENTA:
1498 gl->ColorMask(GL_TRUE, GL_FALSE, GL_TRUE, GL_FALSE);
1499 break;
1500 case GL_3D_QUADBUFFER:
1501 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1502 switch (buffer) {
1503 case GL_FRONT:
1504 case GL_FRONT_LEFT:
1505 case GL_FRONT_RIGHT:
1506 buffer = GL_FRONT_RIGHT;
1507 break;
1508 case GL_BACK:
1509 case GL_BACK_LEFT:
1510 case GL_BACK_RIGHT:
1511 buffer = GL_BACK_RIGHT;
1512 break;
1514 gl->DrawBuffer(buffer);
1515 break;
1519 void glDisable3D(GL *gl, int type)
1521 GLint buffer;
1522 switch (type) {
1523 case GL_3D_RED_CYAN:
1524 case GL_3D_GREEN_MAGENTA:
1525 gl->ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1526 break;
1527 case GL_3D_QUADBUFFER:
1528 gl->DrawBuffer(vo_doublebuffering ? GL_BACK : GL_FRONT);
1529 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1530 switch (buffer) {
1531 case GL_FRONT:
1532 case GL_FRONT_LEFT:
1533 case GL_FRONT_RIGHT:
1534 buffer = GL_FRONT;
1535 break;
1536 case GL_BACK:
1537 case GL_BACK_LEFT:
1538 case GL_BACK_RIGHT:
1539 buffer = GL_BACK;
1540 break;
1542 gl->DrawBuffer(buffer);
1543 break;
1548 * \brief draw a texture part at given 2D coordinates
1549 * \param x screen top coordinate
1550 * \param y screen left coordinate
1551 * \param w screen width coordinate
1552 * \param h screen height coordinate
1553 * \param tx texture top coordinate in pixels
1554 * \param ty texture left coordinate in pixels
1555 * \param tw texture part width in pixels
1556 * \param th texture part height in pixels
1557 * \param sx width of texture in pixels
1558 * \param sy height of texture in pixels
1559 * \param rect_tex whether this texture uses texture_rectangle extension
1560 * \param is_yv12 if != 0, also draw the textures from units 1 and 2,
1561 * bits 8 - 15 and 16 - 23 specify the x and y scaling of those textures
1562 * \param flip flip the texture upside down
1563 * \ingroup gltexture
1565 void glDrawTex(GL *gl, GLfloat x, GLfloat y, GLfloat w, GLfloat h,
1566 GLfloat tx, GLfloat ty, GLfloat tw, GLfloat th,
1567 int sx, int sy, int rect_tex, int is_yv12, int flip)
1569 int chroma_x_shift = (is_yv12 >> 8) & 31;
1570 int chroma_y_shift = (is_yv12 >> 16) & 31;
1571 GLfloat xscale = 1 << chroma_x_shift;
1572 GLfloat yscale = 1 << chroma_y_shift;
1573 GLfloat tx2 = tx / xscale, ty2 = ty / yscale, tw2 = tw / xscale, th2 = th / yscale;
1574 if (!rect_tex) {
1575 tx /= sx;
1576 ty /= sy;
1577 tw /= sx;
1578 th /= sy;
1579 tx2 = tx, ty2 = ty, tw2 = tw, th2 = th;
1581 if (flip) {
1582 y += h;
1583 h = -h;
1585 gl->Begin(GL_QUADS);
1586 gl->TexCoord2f(tx, ty);
1587 if (is_yv12) {
1588 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2);
1589 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2);
1591 gl->Vertex2f(x, y);
1592 gl->TexCoord2f(tx, ty + th);
1593 if (is_yv12) {
1594 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2 + th2);
1595 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2 + th2);
1597 gl->Vertex2f(x, y + h);
1598 gl->TexCoord2f(tx + tw, ty + th);
1599 if (is_yv12) {
1600 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2 + th2);
1601 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2 + th2);
1603 gl->Vertex2f(x + w, y + h);
1604 gl->TexCoord2f(tx + tw, ty);
1605 if (is_yv12) {
1606 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2);
1607 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2);
1609 gl->Vertex2f(x + w, y);
1610 gl->End();
1613 #ifdef CONFIG_GL_COCOA
1614 #include "cocoa_common.h"
1615 static int create_window_cocoa(struct MPGLContext *ctx, uint32_t d_width,
1616 uint32_t d_height, uint32_t flags)
1618 if (vo_cocoa_create_window(ctx->vo, d_width, d_height, flags) == 0) {
1619 return SET_WINDOW_OK;
1620 } else {
1621 return SET_WINDOW_FAILED;
1624 static int setGlWindow_cocoa(MPGLContext *ctx)
1626 vo_cocoa_change_attributes(ctx->vo);
1627 getFunctions(ctx->gl, (void *)getdladdr, NULL);
1628 if (!ctx->gl->SwapInterval)
1629 ctx->gl->SwapInterval = vo_cocoa_swap_interval;
1630 return SET_WINDOW_OK;
1633 static void releaseGlContext_cocoa(MPGLContext *ctx)
1637 static void swapGlBuffers_cocoa(MPGLContext *ctx)
1639 vo_cocoa_swap_buffers();
1642 static int cocoa_check_events(struct vo *vo)
1644 return vo_cocoa_check_events(vo);
1647 static void cocoa_update_xinerama_info(struct vo *vo)
1649 vo_cocoa_update_xinerama_info(vo);
1652 static void cocoa_fullscreen(struct vo *vo)
1654 vo_cocoa_fullscreen(vo);
1656 #endif
1658 #ifdef CONFIG_GL_WIN32
1659 #include "w32_common.h"
1661 static int create_window_w32(struct MPGLContext *ctx, uint32_t d_width,
1662 uint32_t d_height, uint32_t flags)
1664 if (!vo_w32_config(d_width, d_height, flags))
1665 return -1;
1666 return 0;
1670 * \brief little helper since wglGetProcAddress definition does not fit our
1671 * getProcAddress
1672 * \param procName name of function to look up
1673 * \return function pointer returned by wglGetProcAddress
1675 static void *w32gpa(const GLubyte *procName)
1677 HMODULE oglmod;
1678 void *res = wglGetProcAddress(procName);
1679 if (res)
1680 return res;
1681 oglmod = GetModuleHandle("opengl32.dll");
1682 return GetProcAddress(oglmod, procName);
1685 static int setGlWindow_w32(MPGLContext *ctx)
1687 HWND win = vo_w32_window;
1688 int *vinfo = &ctx->vinfo.w32;
1689 HGLRC *context = &ctx->context.w32;
1690 int new_vinfo;
1691 HDC windc = vo_w32_get_dc(win);
1692 HGLRC new_context = 0;
1693 int keep_context = 0;
1694 int res = SET_WINDOW_FAILED;
1695 GL *gl = ctx->gl;
1697 // should only be needed when keeping context, but not doing glFinish
1698 // can cause flickering even when we do not keep it.
1699 if (*context)
1700 gl->Finish();
1701 new_vinfo = GetPixelFormat(windc);
1702 if (*context && *vinfo && new_vinfo && *vinfo == new_vinfo) {
1703 // we can keep the wglContext
1704 new_context = *context;
1705 keep_context = 1;
1706 } else {
1707 // create a context
1708 new_context = wglCreateContext(windc);
1709 if (!new_context) {
1710 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GL context!\n");
1711 goto out;
1715 // set context
1716 if (!wglMakeCurrent(windc, new_context)) {
1717 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GL context!\n");
1718 if (!keep_context)
1719 wglDeleteContext(new_context);
1720 goto out;
1723 // set new values
1724 vo_w32_window = win;
1726 RECT rect;
1727 GetClientRect(win, &rect);
1728 ctx->vo->dwidth = rect.right;
1729 ctx->vo->dheight = rect.bottom;
1731 if (!keep_context) {
1732 if (*context)
1733 wglDeleteContext(*context);
1734 *context = new_context;
1735 *vinfo = new_vinfo;
1736 getFunctions(gl, w32gpa, NULL);
1738 // and inform that reinit is neccessary
1739 res = SET_WINDOW_REINIT;
1740 } else
1741 res = SET_WINDOW_OK;
1743 out:
1744 vo_w32_release_dc(win, windc);
1745 return res;
1748 static void releaseGlContext_w32(MPGLContext *ctx)
1750 int *vinfo = &ctx->vinfo.w32;
1751 HGLRC *context = &ctx->context.w32;
1752 *vinfo = 0;
1753 if (*context) {
1754 wglMakeCurrent(0, 0);
1755 wglDeleteContext(*context);
1757 *context = 0;
1760 static void swapGlBuffers_w32(MPGLContext *ctx)
1762 HDC vo_hdc = vo_w32_get_dc(vo_w32_window);
1763 SwapBuffers(vo_hdc);
1764 vo_w32_release_dc(vo_w32_window, vo_hdc);
1767 //trivial wrappers (w32 code uses old vo API)
1768 static void new_vo_w32_ontop(struct vo *vo) { vo_w32_ontop(); }
1769 static void new_vo_w32_border(struct vo *vo) { vo_w32_border(); }
1770 static void new_vo_w32_fullscreen(struct vo *vo) { vo_w32_fullscreen(); }
1771 static int new_vo_w32_check_events(struct vo *vo) { return vo_w32_check_events(); }
1772 static void new_w32_update_xinerama_info(struct vo *vo) { w32_update_xinerama_info(); }
1773 #endif
1774 #ifdef CONFIG_GL_X11
1775 #include "x11_common.h"
1777 static int create_window_x11(struct MPGLContext *ctx, uint32_t d_width,
1778 uint32_t d_height, uint32_t flags)
1780 struct vo *vo = ctx->vo;
1782 static int default_glx_attribs[] = {
1783 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1784 GLX_DOUBLEBUFFER, None
1786 static int stereo_glx_attribs[] = {
1787 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1788 GLX_DOUBLEBUFFER, GLX_STEREO, None
1790 XVisualInfo *vinfo = NULL;
1791 if (flags & VOFLAG_STEREO) {
1792 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
1793 stereo_glx_attribs);
1794 if (!vinfo)
1795 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Could not find a stereo visual,"
1796 " 3D will probably not work!\n");
1798 if (!vinfo)
1799 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
1800 default_glx_attribs);
1801 if (!vinfo) {
1802 mp_msg(MSGT_VO, MSGL_ERR, "[gl] no GLX support present\n");
1803 return -1;
1805 mp_msg(MSGT_VO, MSGL_V, "[gl] GLX chose visual with ID 0x%x\n",
1806 (int)vinfo->visualid);
1808 Colormap colormap = XCreateColormap(vo->x11->display, vo->x11->rootwin,
1809 vinfo->visual, AllocNone);
1810 vo_x11_create_vo_window(vo, vinfo, vo->dx, vo->dy, d_width, d_height,
1811 flags, colormap, "gl");
1813 return 0;
1817 * \brief Returns the XVisualInfo associated with Window win.
1818 * \param win Window whose XVisualInfo is returne.
1819 * \return XVisualInfo of the window. Caller must use XFree to free it.
1821 static XVisualInfo *getWindowVisualInfo(MPGLContext *ctx, Window win)
1823 XWindowAttributes xw_attr;
1824 XVisualInfo vinfo_template;
1825 int tmp;
1826 XGetWindowAttributes(ctx->vo->x11->display, win, &xw_attr);
1827 vinfo_template.visualid = XVisualIDFromVisual(xw_attr.visual);
1828 return XGetVisualInfo(ctx->vo->x11->display, VisualIDMask, &vinfo_template, &tmp);
1831 static void appendstr(char **dst, const char *str)
1833 int newsize;
1834 char *newstr;
1835 if (!str)
1836 return;
1837 newsize = strlen(*dst) + 1 + strlen(str) + 1;
1838 newstr = realloc(*dst, newsize);
1839 if (!newstr)
1840 return;
1841 *dst = newstr;
1842 strcat(*dst, " ");
1843 strcat(*dst, str);
1847 * \brief Changes the window in which video is displayed.
1848 * If possible only transfers the context to the new window, otherwise
1849 * creates a new one, which must be initialized by the caller.
1850 * \param vinfo Currently used visual.
1851 * \param context Currently used context.
1852 * \param win window that should be used for drawing.
1853 * \return one of SET_WINDOW_FAILED, SET_WINDOW_OK or SET_WINDOW_REINIT.
1854 * In case of SET_WINDOW_REINIT the context could not be transfered
1855 * and the caller must initialize it correctly.
1856 * \ingroup glcontext
1858 static int setGlWindow_x11(MPGLContext *ctx)
1860 XVisualInfo **vinfo = &ctx->vinfo.x11;
1861 GLXContext *context = &ctx->context.x11;
1862 Display *display = ctx->vo->x11->display;
1863 Window win = ctx->vo->x11->window;
1864 XVisualInfo *new_vinfo;
1865 GLXContext new_context = NULL;
1866 int keep_context = 0;
1867 GL *gl = ctx->gl;
1869 // should only be needed when keeping context, but not doing glFinish
1870 // can cause flickering even when we do not keep it.
1871 if (*context)
1872 gl->Finish();
1873 new_vinfo = getWindowVisualInfo(ctx, win);
1874 if (*context && *vinfo && new_vinfo &&
1875 (*vinfo)->visualid == new_vinfo->visualid) {
1876 // we can keep the GLXContext
1877 new_context = *context;
1878 XFree(new_vinfo);
1879 new_vinfo = *vinfo;
1880 keep_context = 1;
1881 } else {
1882 // create a context
1883 new_context = glXCreateContext(display, new_vinfo, NULL, True);
1884 if (!new_context) {
1885 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GLX context!\n");
1886 XFree(new_vinfo);
1887 return SET_WINDOW_FAILED;
1891 // set context
1892 if (!glXMakeCurrent(display, ctx->vo->x11->window, new_context)) {
1893 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GLX context!\n");
1894 if (!keep_context) {
1895 glXDestroyContext(display, new_context);
1896 XFree(new_vinfo);
1898 return SET_WINDOW_FAILED;
1901 // set new values
1902 ctx->vo->x11->window = win;
1903 vo_x11_update_geometry(ctx->vo, 1);
1904 if (!keep_context) {
1905 void *(*getProcAddress)(const GLubyte *);
1906 const char *(*glXExtStr)(Display *, int);
1907 char *glxstr = strdup("");
1908 if (*context)
1909 glXDestroyContext(display, *context);
1910 *context = new_context;
1911 if (*vinfo)
1912 XFree(*vinfo);
1913 *vinfo = new_vinfo;
1914 getProcAddress = getdladdr("glXGetProcAddress");
1915 if (!getProcAddress)
1916 getProcAddress = getdladdr("glXGetProcAddressARB");
1917 glXExtStr = getdladdr("glXQueryExtensionsString");
1918 if (glXExtStr)
1919 appendstr(&glxstr, glXExtStr(display, DefaultScreen(display)));
1920 glXExtStr = getdladdr("glXGetClientString");
1921 if (glXExtStr)
1922 appendstr(&glxstr, glXExtStr(display, GLX_EXTENSIONS));
1923 glXExtStr = getdladdr("glXGetServerString");
1924 if (glXExtStr)
1925 appendstr(&glxstr, glXExtStr(display, GLX_EXTENSIONS));
1927 getFunctions(gl, getProcAddress, glxstr);
1928 if (!gl->GenPrograms && gl->GetString &&
1929 getProcAddress &&
1930 strstr(gl->GetString(GL_EXTENSIONS), "GL_ARB_vertex_program")) {
1931 mp_msg(MSGT_VO, MSGL_WARN,
1932 "Broken glXGetProcAddress detected, trying workaround\n");
1933 getFunctions(gl, NULL, glxstr);
1935 free(glxstr);
1937 // and inform that reinit is neccessary
1938 return SET_WINDOW_REINIT;
1940 return SET_WINDOW_OK;
1944 * \brief free the VisualInfo and GLXContext of an OpenGL context.
1945 * \ingroup glcontext
1947 static void releaseGlContext_x11(MPGLContext *ctx)
1949 XVisualInfo **vinfo = &ctx->vinfo.x11;
1950 GLXContext *context = &ctx->context.x11;
1951 Display *display = ctx->vo->x11->display;
1952 GL *gl = ctx->gl;
1953 if (*vinfo)
1954 XFree(*vinfo);
1955 *vinfo = NULL;
1956 if (*context) {
1957 gl->Finish();
1958 glXMakeCurrent(display, None, NULL);
1959 glXDestroyContext(display, *context);
1961 *context = 0;
1964 static void swapGlBuffers_x11(MPGLContext *ctx)
1966 glXSwapBuffers(ctx->vo->x11->display, ctx->vo->x11->window);
1968 #endif
1970 #ifdef CONFIG_GL_SDL
1971 #include "sdl_common.h"
1973 static int create_window_sdl(struct MPGLContext *ctx, uint32_t d_width,
1974 uint32_t d_height, uint32_t flags)
1976 SDL_WM_SetCaption(vo_get_window_title(ctx->vo), NULL);
1977 ctx->vo->dwidth = d_width;
1978 ctx->vo->dheight = d_height;
1979 return 0;
1982 static void swapGlBuffers_sdl(MPGLContext *ctx)
1984 SDL_GL_SwapBuffers();
1987 static void *sdlgpa(const GLubyte *name)
1989 return SDL_GL_GetProcAddress(name);
1992 static int setGlWindow_sdl(MPGLContext *ctx)
1994 if (sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE) < 0)
1995 return SET_WINDOW_FAILED;
1996 SDL_GL_LoadLibrary(NULL);
1997 getFunctions(ctx->gl, sdlgpa, NULL);
1998 return SET_WINDOW_OK;
2001 static void releaseGlContext_sdl(MPGLContext *ctx)
2005 static int sdl_check_events(struct vo *vo)
2007 int res = 0;
2008 SDL_Event event;
2009 while (SDL_PollEvent(&event))
2010 res |= sdl_default_handle_event(&event);
2011 // poll "events" from within MPlayer code
2012 res |= sdl_default_handle_event(NULL);
2013 if (res & VO_EVENT_RESIZE)
2014 sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE);
2015 return res;
2018 static void new_sdl_update_xinerama_info(struct vo *vo) { sdl_update_xinerama_info(); }
2019 static void new_vo_sdl_fullscreen(struct vo *vo) { vo_sdl_fullscreen(); }
2021 #endif
2023 MPGLContext *init_mpglcontext(enum MPGLType type, struct vo *vo)
2025 MPGLContext *ctx;
2026 if (type == GLTYPE_AUTO) {
2027 ctx = init_mpglcontext(GLTYPE_COCOA, vo);
2028 if (ctx)
2029 return ctx;
2030 ctx = init_mpglcontext(GLTYPE_W32, vo);
2031 if (ctx)
2032 return ctx;
2033 ctx = init_mpglcontext(GLTYPE_X11, vo);
2034 if (ctx)
2035 return ctx;
2036 return init_mpglcontext(GLTYPE_SDL, vo);
2038 ctx = talloc_zero(NULL, MPGLContext);
2039 ctx->gl = talloc_zero(ctx, GL);
2040 ctx->type = type;
2041 ctx->vo = vo;
2042 switch (ctx->type) {
2043 #ifdef CONFIG_GL_COCOA
2044 case GLTYPE_COCOA:
2045 ctx->create_window = create_window_cocoa;
2046 ctx->setGlWindow = setGlWindow_cocoa;
2047 ctx->releaseGlContext = releaseGlContext_cocoa;
2048 ctx->swapGlBuffers = swapGlBuffers_cocoa;
2049 ctx->check_events = cocoa_check_events;
2050 ctx->update_xinerama_info = cocoa_update_xinerama_info;
2051 ctx->fullscreen = cocoa_fullscreen;
2052 if (vo_cocoa_init(vo))
2053 return ctx;
2054 break;
2055 #endif
2056 #ifdef CONFIG_GL_WIN32
2057 case GLTYPE_W32:
2058 ctx->create_window = create_window_w32;
2059 ctx->setGlWindow = setGlWindow_w32;
2060 ctx->releaseGlContext = releaseGlContext_w32;
2061 ctx->swapGlBuffers = swapGlBuffers_w32;
2062 ctx->update_xinerama_info = new_w32_update_xinerama_info;
2063 ctx->border = new_vo_w32_border;
2064 ctx->check_events = new_vo_w32_check_events;
2065 ctx->fullscreen = new_vo_w32_fullscreen;
2066 ctx->ontop = new_vo_w32_ontop;
2067 //the win32 code is hardcoded to use the deprecated vo API
2068 global_vo = vo;
2069 if (vo_w32_init())
2070 return ctx;
2071 break;
2072 #endif
2073 #ifdef CONFIG_GL_X11
2074 case GLTYPE_X11:
2075 ctx->create_window = create_window_x11;
2076 ctx->setGlWindow = setGlWindow_x11;
2077 ctx->releaseGlContext = releaseGlContext_x11;
2078 ctx->swapGlBuffers = swapGlBuffers_x11;
2079 ctx->update_xinerama_info = update_xinerama_info;
2080 ctx->border = vo_x11_border;
2081 ctx->check_events = vo_x11_check_events;
2082 ctx->fullscreen = vo_x11_fullscreen;
2083 ctx->ontop = vo_x11_ontop;
2084 if (vo_init(vo))
2085 return ctx;
2086 break;
2087 #endif
2088 #ifdef CONFIG_GL_SDL
2089 case GLTYPE_SDL:
2090 ctx->create_window = create_window_sdl;
2091 ctx->setGlWindow = setGlWindow_sdl;
2092 ctx->releaseGlContext = releaseGlContext_sdl;
2093 ctx->swapGlBuffers = swapGlBuffers_sdl;
2094 ctx->update_xinerama_info = new_sdl_update_xinerama_info;
2095 ctx->check_events = sdl_check_events;
2096 ctx->fullscreen = new_vo_sdl_fullscreen;
2097 //the SDL code is hardcoded to use the deprecated vo API
2098 global_vo = vo;
2099 if (vo_sdl_init())
2100 return ctx;
2101 break;
2102 #endif
2104 talloc_free(ctx);
2105 return NULL;
2108 void uninit_mpglcontext(MPGLContext *ctx)
2110 if (!ctx)
2111 return;
2112 ctx->releaseGlContext(ctx);
2113 switch (ctx->type) {
2114 #ifdef CONFIG_GL_COCOA
2115 case GLTYPE_COCOA:
2116 vo_cocoa_uninit(ctx->vo);
2117 break;
2118 #endif
2119 #ifdef CONFIG_GL_WIN32
2120 case GLTYPE_W32:
2121 vo_w32_uninit();
2122 break;
2123 #endif
2124 #ifdef CONFIG_GL_X11
2125 case GLTYPE_X11:
2126 vo_x11_uninit(ctx->vo);
2127 break;
2128 #endif
2129 #ifdef CONFIG_GL_SDL
2130 case GLTYPE_SDL:
2131 vo_sdl_uninit();
2132 break;
2133 #endif
2135 talloc_free(ctx);