vo_gl: use a single texture for libass-rendered bitmaps
[mplayer.git] / libvo / gl_common.c
blob7f0c5f35878c4bb98e8fc7427b279576258c1da3
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(TexCoord2fv),
354 DEF_FUNC_DESC(Vertex2f),
355 DEF_FUNC_DESC(Vertex3f),
356 DEF_FUNC_DESC(Normal3f),
357 DEF_FUNC_DESC(Lightfv),
358 DEF_FUNC_DESC(ColorMaterial),
359 DEF_FUNC_DESC(ShadeModel),
360 DEF_FUNC_DESC(GetIntegerv),
361 DEF_FUNC_DESC(ColorMask),
362 DEF_FUNC_DESC(ReadPixels),
363 DEF_FUNC_DESC(ReadBuffer),
364 DEF_FUNC_DESC(VertexPointer),
365 DEF_FUNC_DESC(ColorPointer),
366 DEF_FUNC_DESC(TexCoordPointer),
367 DEF_FUNC_DESC(DrawArrays),
368 DEF_FUNC_DESC(EnableClientState),
369 DEF_FUNC_DESC(DisableClientState),
371 DEF_EXT_DESC(GenBuffers, NULL,
372 ("glGenBuffers", "glGenBuffersARB")),
373 DEF_EXT_DESC(DeleteBuffers, NULL,
374 ("glDeleteBuffers", "glDeleteBuffersARB")),
375 DEF_EXT_DESC(BindBuffer, NULL,
376 ("glBindBuffer", "glBindBufferARB")),
377 DEF_EXT_DESC(MapBuffer, NULL,
378 ("glMapBuffer", "glMapBufferARB")),
379 DEF_EXT_DESC(UnmapBuffer, NULL,
380 ("glUnmapBuffer", "glUnmapBufferARB")),
381 DEF_EXT_DESC(BufferData, NULL,
382 ("glBufferData", "glBufferDataARB")),
383 DEF_EXT_DESC(BeginFragmentShader, "ATI_fragment_shader",
384 ("glBeginFragmentShaderATI")),
385 DEF_EXT_DESC(EndFragmentShader, "ATI_fragment_shader",
386 ("glEndFragmentShaderATI")),
387 DEF_EXT_DESC(SampleMap, "ATI_fragment_shader",
388 ("glSampleMapATI")),
389 DEF_EXT_DESC(ColorFragmentOp2, "ATI_fragment_shader",
390 ("glColorFragmentOp2ATI")),
391 DEF_EXT_DESC(ColorFragmentOp3, "ATI_fragment_shader",
392 ("glColorFragmentOp3ATI")),
393 DEF_EXT_DESC(SetFragmentShaderConstant, "ATI_fragment_shader",
394 ("glSetFragmentShaderConstantATI")),
395 DEF_EXT_DESC(ActiveTexture, NULL,
396 ("glActiveTexture", "glActiveTextureARB")),
397 DEF_EXT_DESC(BindTexture, NULL,
398 ("glBindTexture", "glBindTextureARB", "glBindTextureEXT")),
399 DEF_EXT_DESC(MultiTexCoord2f, NULL,
400 ("glMultiTexCoord2f", "glMultiTexCoord2fARB")),
401 DEF_EXT_DESC(GenPrograms, "_program",
402 ("glGenProgramsARB")),
403 DEF_EXT_DESC(DeletePrograms, "_program",
404 ("glDeleteProgramsARB")),
405 DEF_EXT_DESC(BindProgram, "_program",
406 ("glBindProgramARB")),
407 DEF_EXT_DESC(ProgramString, "_program",
408 ("glProgramStringARB")),
409 DEF_EXT_DESC(GetProgramiv, "_program",
410 ("glGetProgramivARB")),
411 DEF_EXT_DESC(ProgramEnvParameter4f, "_program",
412 ("glProgramEnvParameter4fARB")),
413 DEF_EXT_DESC(SwapInterval, "_swap_control",
414 ("glXSwapIntervalSGI", "glXSwapInterval", "wglSwapIntervalSGI",
415 "wglSwapInterval", "wglSwapIntervalEXT")),
416 DEF_EXT_DESC(TexImage3D, NULL,
417 ("glTexImage3D")),
418 {-1}
422 * \brief find the function pointers of some useful OpenGL extensions
423 * \param getProcAddress function to resolve function names, may be NULL
424 * \param ext2 an extra extension string
426 static void getFunctions(GL *gl, void *(*getProcAddress)(const GLubyte *),
427 const char *ext2)
429 const extfunc_desc_t *dsc;
430 const char *extensions;
431 char *allexts;
433 if (!getProcAddress)
434 getProcAddress = (void *)getdladdr;
436 // special case, we need glGetString before starting to find the other functions
437 gl->GetString = getProcAddress("glGetString");
438 if (!gl->GetString)
439 gl->GetString = glGetString;
441 extensions = (const char *)gl->GetString(GL_EXTENSIONS);
442 if (!extensions)
443 extensions = "";
444 if (!ext2)
445 ext2 = "";
446 allexts = malloc(strlen(extensions) + strlen(ext2) + 2);
447 strcpy(allexts, extensions);
448 strcat(allexts, " ");
449 strcat(allexts, ext2);
450 mp_msg(MSGT_VO, MSGL_DBG2, "OpenGL extensions string:\n%s\n", allexts);
451 for (dsc = extfuncs; dsc->offset >= 0; dsc++) {
452 void *ptr = NULL;
453 int i;
454 if (!dsc->extstr || strstr(allexts, dsc->extstr)) {
455 for (i = 0; !ptr && dsc->funcnames[i]; i++)
456 ptr = getProcAddress((const GLubyte *)dsc->funcnames[i]);
458 if (!ptr)
459 ptr = dsc->fallback;
460 void **funcptr = (void**)(((char*)gl) + dsc->offset);
461 *funcptr = ptr;
463 free(allexts);
467 * \brief create a texture and set some defaults
468 * \param target texture taget, usually GL_TEXTURE_2D
469 * \param fmt internal texture format
470 * \param format texture host data format
471 * \param type texture host data type
472 * \param filter filter used for scaling, e.g. GL_LINEAR
473 * \param w texture width
474 * \param h texture height
475 * \param val luminance value to fill texture with
476 * \ingroup gltexture
478 void glCreateClearTex(GL *gl, GLenum target, GLenum fmt, GLenum format,
479 GLenum type, GLint filter, int w, int h,
480 unsigned char val)
482 GLfloat fval = (GLfloat)val / 255.0;
483 GLfloat border[4] = {
484 fval, fval, fval, fval
486 int stride;
487 char *init;
488 if (w == 0)
489 w = 1;
490 if (h == 0)
491 h = 1;
492 stride = w * glFmt2bpp(format, type);
493 if (!stride)
494 return;
495 init = malloc(stride * h);
496 memset(init, val, stride * h);
497 glAdjustAlignment(gl, stride);
498 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, w);
499 gl->TexImage2D(target, 0, fmt, w, h, 0, format, type, init);
500 gl->TexParameterf(target, GL_TEXTURE_PRIORITY, 1.0);
501 gl->TexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
502 gl->TexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
503 gl->TexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
504 gl->TexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
505 // Border texels should not be used with CLAMP_TO_EDGE
506 // We set a sane default anyway.
507 gl->TexParameterfv(target, GL_TEXTURE_BORDER_COLOR, border);
508 free(init);
511 static GLint detect_hqtexfmt(GL *gl)
513 const char *extensions = (const char *)gl->GetString(GL_EXTENSIONS);
514 if (strstr(extensions, "_texture_float"))
515 return GL_RGB32F;
516 else if (strstr(extensions, "NV_float_buffer"))
517 return GL_FLOAT_RGB32_NV;
518 return GL_RGB16;
522 * \brief creates a texture from a PPM file
523 * \param target texture taget, usually GL_TEXTURE_2D
524 * \param fmt internal texture format, 0 for default
525 * \param filter filter used for scaling, e.g. GL_LINEAR
526 * \param f file to read PPM from
527 * \param width [out] width of texture
528 * \param height [out] height of texture
529 * \param maxval [out] maxval value from PPM file
530 * \return 0 on error, 1 otherwise
531 * \ingroup gltexture
533 int glCreatePPMTex(GL *gl, GLenum target, GLenum fmt, GLint filter,
534 FILE *f, int *width, int *height, int *maxval)
536 int w, h, m, bpp;
537 GLenum type;
538 uint8_t *data = read_pnm(f, &w, &h, &bpp, &m);
539 GLint hqtexfmt = detect_hqtexfmt(gl);
540 if (!data || (bpp != 3 && bpp != 6)) {
541 free(data);
542 return 0;
544 if (!fmt) {
545 fmt = bpp == 6 ? hqtexfmt : 3;
546 if (fmt == GL_FLOAT_RGB32_NV && target != GL_TEXTURE_RECTANGLE)
547 fmt = GL_RGB16;
549 type = bpp == 6 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
550 glCreateClearTex(gl, target, fmt, GL_RGB, type, filter, w, h, 0);
551 glUploadTex(gl, target, GL_RGB, type,
552 data, w * bpp, 0, 0, w, h, 0);
553 free(data);
554 if (width)
555 *width = w;
556 if (height)
557 *height = h;
558 if (maxval)
559 *maxval = m;
560 return 1;
564 * \brief return the number of bytes per pixel for the given format
565 * \param format OpenGL format
566 * \param type OpenGL type
567 * \return bytes per pixel
568 * \ingroup glgeneral
570 * Does not handle all possible variants, just those used by MPlayer
572 int glFmt2bpp(GLenum format, GLenum type)
574 int component_size = 0;
575 switch (type) {
576 case GL_UNSIGNED_BYTE_3_3_2:
577 case GL_UNSIGNED_BYTE_2_3_3_REV:
578 return 1;
579 case GL_UNSIGNED_SHORT_5_5_5_1:
580 case GL_UNSIGNED_SHORT_1_5_5_5_REV:
581 case GL_UNSIGNED_SHORT_5_6_5:
582 case GL_UNSIGNED_SHORT_5_6_5_REV:
583 return 2;
584 case GL_UNSIGNED_BYTE:
585 component_size = 1;
586 break;
587 case GL_UNSIGNED_SHORT:
588 component_size = 2;
589 break;
591 switch (format) {
592 case GL_LUMINANCE:
593 case GL_ALPHA:
594 return component_size;
595 case GL_YCBCR_MESA:
596 return 2;
597 case GL_RGB:
598 case GL_BGR:
599 return 3 * component_size;
600 case GL_RGBA:
601 case GL_BGRA:
602 return 4 * component_size;
603 case GL_RED:
604 return component_size;
605 case GL_RG:
606 case GL_LUMINANCE_ALPHA:
607 return 2 * component_size;
609 return 0; // unknown
613 * \brief upload a texture, handling things like stride and slices
614 * \param target texture target, usually GL_TEXTURE_2D
615 * \param format OpenGL format of data
616 * \param type OpenGL type of data
617 * \param dataptr data to upload
618 * \param stride data stride
619 * \param x x offset in texture
620 * \param y y offset in texture
621 * \param w width of the texture part to upload
622 * \param h height of the texture part to upload
623 * \param slice height of an upload slice, 0 for all at once
624 * \ingroup gltexture
626 void glUploadTex(GL *gl, GLenum target, GLenum format, GLenum type,
627 const void *dataptr, int stride,
628 int x, int y, int w, int h, int slice)
630 const uint8_t *data = dataptr;
631 int y_max = y + h;
632 if (w <= 0 || h <= 0)
633 return;
634 if (slice <= 0)
635 slice = h;
636 if (stride < 0) {
637 data += (h - 1) * stride;
638 stride = -stride;
640 // this is not always correct, but should work for MPlayer
641 glAdjustAlignment(gl, stride);
642 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
643 for (; y + slice <= y_max; y += slice) {
644 gl->TexSubImage2D(target, 0, x, y, w, slice, format, type, data);
645 data += stride * slice;
647 if (y < y_max)
648 gl->TexSubImage2D(target, 0, x, y, w, y_max - y, format, type, data);
652 * \brief download a texture, handling things like stride and slices
653 * \param target texture target, usually GL_TEXTURE_2D
654 * \param format OpenGL format of data
655 * \param type OpenGL type of data
656 * \param dataptr destination memory for download
657 * \param stride data stride (must be positive)
658 * \ingroup gltexture
660 void glDownloadTex(GL *gl, GLenum target, GLenum format, GLenum type,
661 void *dataptr, int stride)
663 // this is not always correct, but should work for MPlayer
664 glAdjustAlignment(gl, stride);
665 gl->PixelStorei(GL_PACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
666 gl->GetTexImage(target, 0, format, type, dataptr);
670 * \brief Setup ATI version of register combiners for YUV to RGB conversion.
671 * \param csp_params parameters used for colorspace conversion
672 * \param text if set use the GL_ATI_text_fragment_shader API as
673 * used on OS X.
675 static void glSetupYUVFragmentATI(GL *gl, struct mp_csp_params *csp_params,
676 int text)
678 GLint i;
679 float yuv2rgb[3][4];
681 gl->GetIntegerv(GL_MAX_TEXTURE_UNITS, &i);
682 if (i < 3)
683 mp_msg(MSGT_VO, MSGL_ERR,
684 "[gl] 3 texture units needed for YUV combiner (ATI) support (found %i)\n", i);
686 mp_get_yuv2rgb_coeffs(csp_params, yuv2rgb);
687 for (i = 0; i < 3; i++) {
688 int j;
689 yuv2rgb[i][3] -= -0.5 * (yuv2rgb[i][1] + yuv2rgb[i][2]);
690 for (j = 0; j < 4; j++) {
691 yuv2rgb[i][j] *= 0.125;
692 yuv2rgb[i][j] += 0.5;
693 if (yuv2rgb[i][j] > 1)
694 yuv2rgb[i][j] = 1;
695 if (yuv2rgb[i][j] < 0)
696 yuv2rgb[i][j] = 0;
699 if (text == 0) {
700 GLfloat c0[4] = { yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0] };
701 GLfloat c1[4] = { yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1] };
702 GLfloat c2[4] = { yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2] };
703 GLfloat c3[4] = { yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3] };
704 if (!gl->BeginFragmentShader || !gl->EndFragmentShader ||
705 !gl->SetFragmentShaderConstant || !gl->SampleMap ||
706 !gl->ColorFragmentOp2 || !gl->ColorFragmentOp3) {
707 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Combiner (ATI) functions missing!\n");
708 return;
710 gl->GetIntegerv(GL_NUM_FRAGMENT_REGISTERS_ATI, &i);
711 if (i < 3)
712 mp_msg(MSGT_VO, MSGL_ERR,
713 "[gl] 3 registers needed for YUV combiner (ATI) support (found %i)\n", i);
714 gl->BeginFragmentShader();
715 gl->SetFragmentShaderConstant(GL_CON_0_ATI, c0);
716 gl->SetFragmentShaderConstant(GL_CON_1_ATI, c1);
717 gl->SetFragmentShaderConstant(GL_CON_2_ATI, c2);
718 gl->SetFragmentShaderConstant(GL_CON_3_ATI, c3);
719 gl->SampleMap(GL_REG_0_ATI, GL_TEXTURE0, GL_SWIZZLE_STR_ATI);
720 gl->SampleMap(GL_REG_1_ATI, GL_TEXTURE1, GL_SWIZZLE_STR_ATI);
721 gl->SampleMap(GL_REG_2_ATI, GL_TEXTURE2, GL_SWIZZLE_STR_ATI);
722 gl->ColorFragmentOp2(GL_MUL_ATI, GL_REG_1_ATI, GL_NONE, GL_NONE,
723 GL_REG_1_ATI, GL_NONE, GL_BIAS_BIT_ATI,
724 GL_CON_1_ATI, GL_NONE, GL_BIAS_BIT_ATI);
725 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_2_ATI, GL_NONE, GL_NONE,
726 GL_REG_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
727 GL_CON_2_ATI, GL_NONE, GL_BIAS_BIT_ATI,
728 GL_REG_1_ATI, GL_NONE, GL_NONE);
729 gl->ColorFragmentOp3(GL_MAD_ATI, GL_REG_0_ATI, GL_NONE, GL_NONE,
730 GL_REG_0_ATI, GL_NONE, GL_NONE,
731 GL_CON_0_ATI, GL_NONE, GL_BIAS_BIT_ATI,
732 GL_REG_2_ATI, GL_NONE, GL_NONE);
733 gl->ColorFragmentOp2(GL_ADD_ATI, GL_REG_0_ATI, GL_NONE, GL_8X_BIT_ATI,
734 GL_REG_0_ATI, GL_NONE, GL_NONE,
735 GL_CON_3_ATI, GL_NONE, GL_BIAS_BIT_ATI);
736 gl->EndFragmentShader();
737 } else {
738 static const char template[] =
739 "!!ATIfs1.0\n"
740 "StartConstants;\n"
741 " CONSTANT c0 = {%e, %e, %e};\n"
742 " CONSTANT c1 = {%e, %e, %e};\n"
743 " CONSTANT c2 = {%e, %e, %e};\n"
744 " CONSTANT c3 = {%e, %e, %e};\n"
745 "EndConstants;\n"
746 "StartOutputPass;\n"
747 " SampleMap r0, t0.str;\n"
748 " SampleMap r1, t1.str;\n"
749 " SampleMap r2, t2.str;\n"
750 " MUL r1.rgb, r1.bias, c1.bias;\n"
751 " MAD r2.rgb, r2.bias, c2.bias, r1;\n"
752 " MAD r0.rgb, r0, c0.bias, r2;\n"
753 " ADD r0.rgb.8x, r0, c3.bias;\n"
754 "EndPass;\n";
755 char buffer[512];
756 snprintf(buffer, sizeof(buffer), template,
757 yuv2rgb[0][0], yuv2rgb[1][0], yuv2rgb[2][0],
758 yuv2rgb[0][1], yuv2rgb[1][1], yuv2rgb[2][1],
759 yuv2rgb[0][2], yuv2rgb[1][2], yuv2rgb[2][2],
760 yuv2rgb[0][3], yuv2rgb[1][3], yuv2rgb[2][3]);
761 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
762 buffer);
763 loadGPUProgram(gl, GL_TEXT_FRAGMENT_SHADER_ATI, buffer);
767 // Replace all occurances of variables named "$"+name (e.g. $foo) in *text with
768 // replace, and return the result. *text must have been allocated with talloc.
769 static void replace_var_str(char **text, const char *name, const char *replace)
771 size_t namelen = strlen(name);
772 char *nextvar = *text;
773 void *parent = talloc_parent(*text);
774 for (;;) {
775 nextvar = strchr(nextvar, '$');
776 if (!nextvar)
777 break;
778 char *until = nextvar;
779 nextvar++;
780 if (strncmp(nextvar, name, namelen) != 0)
781 continue;
782 nextvar += namelen;
783 // try not to replace prefixes of other vars (e.g. $foo vs. $foo_bar)
784 char term = nextvar[0];
785 if (isalnum(term) || term == '_')
786 continue;
787 int prelength = until - *text;
788 int postlength = nextvar - *text;
789 char *n = talloc_asprintf(parent, "%.*s%s%s", prelength, *text, replace,
790 nextvar);
791 talloc_free(*text);
792 *text = n;
793 nextvar = *text + postlength;
797 static void replace_var_float(char **text, const char *name, float replace)
799 char *s = talloc_asprintf(NULL, "%e", replace);
800 replace_var_str(text, name, s);
801 talloc_free(s);
804 static void replace_var_char(char **text, const char *name, char replace)
806 char s[2] = { replace, '\0' };
807 replace_var_str(text, name, s);
810 // Append template to *text. Possibly initialize *text if it's NULL.
811 static void append_template(char **text, const char* template)
813 if (!text)
814 *text = talloc_strdup(NULL, template);
815 else
816 *text = talloc_strdup_append(*text, template);
820 * \brief helper function for gen_spline_lookup_tex
821 * \param x subpixel-position ((0,1) range) to calculate weights for
822 * \param dst where to store transformed weights, must provide space for 4 GLfloats
824 * calculates the weights and stores them after appropriate transformation
825 * for the scaler fragment program.
827 static void store_weights(float x, GLfloat *dst)
829 float w0 = (((-1 * x + 3) * x - 3) * x + 1) / 6;
830 float w1 = (((3 * x - 6) * x + 0) * x + 4) / 6;
831 float w2 = (((-3 * x + 3) * x + 3) * x + 1) / 6;
832 float w3 = (((1 * x + 0) * x + 0) * x + 0) / 6;
833 *dst++ = 1 + x - w1 / (w0 + w1);
834 *dst++ = 1 - x + w3 / (w2 + w3);
835 *dst++ = w0 + w1;
836 *dst++ = 0;
839 //! to avoid artefacts this should be rather large
840 #define LOOKUP_BSPLINE_RES (2 * 1024)
842 * \brief creates the 1D lookup texture needed for fast higher-order filtering
843 * \param unit texture unit to attach texture to
845 static void gen_spline_lookup_tex(GL *gl, GLenum unit)
847 GLfloat *tex = calloc(4 * LOOKUP_BSPLINE_RES, sizeof(*tex));
848 GLfloat *tp = tex;
849 int i;
850 for (i = 0; i < LOOKUP_BSPLINE_RES; i++) {
851 float x = (float)(i + 0.5) / LOOKUP_BSPLINE_RES;
852 store_weights(x, tp);
853 tp += 4;
855 store_weights(0, tex);
856 store_weights(1, &tex[4 * (LOOKUP_BSPLINE_RES - 1)]);
857 gl->ActiveTexture(unit);
858 gl->TexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, LOOKUP_BSPLINE_RES, 0, GL_RGBA,
859 GL_FLOAT, tex);
860 gl->TexParameterf(GL_TEXTURE_1D, GL_TEXTURE_PRIORITY, 1.0);
861 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
862 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
863 gl->TexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
864 gl->ActiveTexture(GL_TEXTURE0);
865 free(tex);
868 #define SAMPLE(dest, coord, texture) \
869 "TEX textemp, " coord ", " texture ", $tex_type;\n" \
870 "MOV " dest ", textemp.r;\n"
872 static const char *bilin_filt_template =
873 SAMPLE("yuv.$out_comp","fragment.texcoord[$in_tex]","texture[$in_tex]");
875 #define BICUB_FILT_MAIN \
876 /* first y-interpolation */ \
877 "ADD coord, fragment.texcoord[$in_tex].xyxy, cdelta.xyxw;\n" \
878 "ADD coord2, fragment.texcoord[$in_tex].xyxy, cdelta.zyzw;\n" \
879 SAMPLE("a.r","coord.xyxy","texture[$in_tex]") \
880 SAMPLE("a.g","coord.zwzw","texture[$in_tex]") \
881 /* second y-interpolation */ \
882 SAMPLE("b.r","coord2.xyxy","texture[$in_tex]") \
883 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]") \
884 "LRP a.b, parmy.b, a.rrrr, a.gggg;\n" \
885 "LRP a.a, parmy.b, b.rrrr, b.gggg;\n" \
886 /* x-interpolation */ \
887 "LRP yuv.$out_comp, parmx.b, a.bbbb, a.aaaa;\n"
889 static const char *bicub_filt_template_2D =
890 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
891 "TEX parmx, coord.x, texture[$texs], 1D;\n"
892 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
893 "TEX parmy, coord.y, texture[$texs], 1D;\n"
894 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
895 BICUB_FILT_MAIN;
897 static const char *bicub_filt_template_RECT =
898 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
899 "TEX parmx, coord.x, texture[$texs], 1D;\n"
900 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
901 "TEX parmy, coord.y, texture[$texs], 1D;\n"
902 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
903 BICUB_FILT_MAIN;
905 #define CALCWEIGHTS(t, s) \
906 "MAD "t ", {-0.5, 0.1666, 0.3333, -0.3333}, "s ", {1, 0, -0.5, 0.5};\n" \
907 "MAD "t ", "t ", "s ", {0, 0, -0.5, 0.5};\n" \
908 "MAD "t ", "t ", "s ", {-0.6666, 0, 0.8333, 0.1666};\n" \
909 "RCP a.x, "t ".z;\n" \
910 "RCP a.y, "t ".w;\n" \
911 "MAD "t ".xy, "t ".xyxy, a.xyxy, {1, 1, 0, 0};\n" \
912 "ADD "t ".x, "t ".xxxx, "s ";\n" \
913 "SUB "t ".y, "t ".yyyy, "s ";\n"
915 static const char *bicub_notex_filt_template_2D =
916 "MAD coord.xy, fragment.texcoord[$in_tex], {$texw, $texh}, {0.5, 0.5};\n"
917 "FRC coord.xy, coord.xyxy;\n"
918 CALCWEIGHTS("parmx", "coord.xxxx")
919 "MUL cdelta.xz, parmx.rrgg, {-$ptw, 0, $ptw, 0};\n"
920 CALCWEIGHTS("parmy", "coord.yyyy")
921 "MUL cdelta.yw, parmy.rrgg, {0, -$pth, 0, $pth};\n"
922 BICUB_FILT_MAIN;
924 static const char *bicub_notex_filt_template_RECT =
925 "ADD coord, fragment.texcoord[$in_tex], {0.5, 0.5};\n"
926 "FRC coord.xy, coord.xyxy;\n"
927 CALCWEIGHTS("parmx", "coord.xxxx")
928 "MUL cdelta.xz, parmx.rrgg, {-1, 0, 1, 0};\n"
929 CALCWEIGHTS("parmy", "coord.yyyy")
930 "MUL cdelta.yw, parmy.rrgg, {0, -1, 0, 1};\n"
931 BICUB_FILT_MAIN;
933 #define BICUB_X_FILT_MAIN \
934 "ADD coord.xy, fragment.texcoord[$in_tex].xyxy, cdelta.xyxy;\n" \
935 "ADD coord2.xy, fragment.texcoord[$in_tex].xyxy, cdelta.zyzy;\n" \
936 SAMPLE("a.r","coord","texture[$in_tex]") \
937 SAMPLE("b.r","coord2","texture[$in_tex]") \
938 /* x-interpolation */ \
939 "LRP yuv.$out_comp, parmx.b, a.rrrr, b.rrrr;\n"
941 static const char *bicub_x_filt_template_2D =
942 "MAD coord.x, fragment.texcoord[$in_tex], {$texw}, {0.5};\n"
943 "TEX parmx, coord, texture[$texs], 1D;\n"
944 "MUL cdelta.xyz, parmx.rrgg, {-$ptw, 0, $ptw};\n"
945 BICUB_X_FILT_MAIN;
947 static const char *bicub_x_filt_template_RECT =
948 "ADD coord.x, fragment.texcoord[$in_tex], {0.5};\n"
949 "TEX parmx, coord, texture[$texs], 1D;\n"
950 "MUL cdelta.xyz, parmx.rrgg, {-1, 0, 1};\n"
951 BICUB_X_FILT_MAIN;
953 static const char *unsharp_filt_template =
954 "PARAM dcoord$out_comp = {$ptw_05, $pth_05, $ptw_05, -$pth_05};\n"
955 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
956 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
957 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
958 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
959 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
960 "ADD b.r, b.r, b.g;\n"
961 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
962 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
963 "DP3 b, b, {0.25, 0.25, 0.25};\n"
964 "SUB b.r, a.r, b.r;\n"
965 "MAD textemp.r, b.r, {$strength}, a.r;\n"
966 "MOV yuv.$out_comp, textemp.r;\n";
968 static const char *unsharp_filt_template2 =
969 "PARAM dcoord$out_comp = {$ptw_12, $pth_12, $ptw_12, -$pth_12};\n"
970 "PARAM dcoord2$out_comp = {$ptw_15, 0, 0, $pth_15};\n"
971 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
972 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord$out_comp;\n"
973 SAMPLE("a.r","fragment.texcoord[$in_tex]","texture[$in_tex]")
974 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
975 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
976 "ADD b.r, b.r, b.g;\n"
977 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
978 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
979 "ADD b.r, b.r, b.b;\n"
980 "ADD b.a, b.r, b.g;\n"
981 "ADD coord, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
982 "SUB coord2, fragment.texcoord[$in_tex].xyxy, dcoord2$out_comp;\n"
983 SAMPLE("b.r","coord.xyxy","texture[$in_tex]")
984 SAMPLE("b.g","coord.zwzw","texture[$in_tex]")
985 "ADD b.r, b.r, b.g;\n"
986 SAMPLE("b.b","coord2.xyxy","texture[$in_tex]")
987 SAMPLE("b.g","coord2.zwzw","texture[$in_tex]")
988 "DP4 b.r, b, {-0.1171875, -0.1171875, -0.1171875, -0.09765625};\n"
989 "MAD b.r, a.r, {0.859375}, b.r;\n"
990 "MAD textemp.r, b.r, {$strength}, a.r;\n"
991 "MOV yuv.$out_comp, textemp.r;\n";
993 static const char *yuv_prog_template =
994 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
995 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
996 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
997 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
998 "TEMP res;\n"
999 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
1000 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1001 "MAD result.color.rgb, yuv.bbbb, vcoef, res;\n"
1002 "END";
1004 static const char *yuv_pow_prog_template =
1005 "PARAM ycoef = {$cm11, $cm21, $cm31};\n"
1006 "PARAM ucoef = {$cm12, $cm22, $cm32};\n"
1007 "PARAM vcoef = {$cm13, $cm23, $cm33};\n"
1008 "PARAM offsets = {$cm14, $cm24, $cm34};\n"
1009 "PARAM gamma = {$gamma_r, $gamma_g, $gamma_b};\n"
1010 "TEMP res;\n"
1011 "MAD res.rgb, yuv.rrrr, ycoef, offsets;\n"
1012 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1013 "MAD_SAT res.rgb, yuv.bbbb, vcoef, res;\n"
1014 "POW result.color.r, res.r, gamma.r;\n"
1015 "POW result.color.g, res.g, gamma.g;\n"
1016 "POW result.color.b, res.b, gamma.b;\n"
1017 "END";
1019 static const char *yuv_lookup_prog_template =
1020 "PARAM ycoef = {$cm11, $cm21, $cm31, 0};\n"
1021 "PARAM ucoef = {$cm12, $cm22, $cm32, 0};\n"
1022 "PARAM vcoef = {$cm13, $cm23, $cm33, 0};\n"
1023 "PARAM offsets = {$cm14, $cm24, $cm34, 0.125};\n"
1024 "TEMP res;\n"
1025 "MAD res, yuv.rrrr, ycoef, offsets;\n"
1026 "MAD res.rgb, yuv.gggg, ucoef, res;\n"
1027 "MAD res.rgb, yuv.bbbb, vcoef, res;\n"
1028 "TEX result.color.r, res.raaa, texture[$conv_tex0], 2D;\n"
1029 "ADD res.a, res.a, 0.25;\n"
1030 "TEX result.color.g, res.gaaa, texture[$conv_tex0], 2D;\n"
1031 "ADD res.a, res.a, 0.25;\n"
1032 "TEX result.color.b, res.baaa, texture[$conv_tex0], 2D;\n"
1033 "END";
1035 static const char *yuv_lookup3d_prog_template =
1036 "TEX result.color, yuv, texture[$conv_tex0], 3D;\n"
1037 "END";
1040 * \brief creates and initializes helper textures needed for scaling texture read
1041 * \param scaler scaler type to create texture for
1042 * \param texu contains next free texture unit number
1043 * \param texs texture unit ids for the scaler are stored in this array
1045 static void create_scaler_textures(GL *gl, int scaler, int *texu, char *texs)
1047 switch (scaler) {
1048 case YUV_SCALER_BILIN:
1049 case YUV_SCALER_BICUB_NOTEX:
1050 case YUV_SCALER_UNSHARP:
1051 case YUV_SCALER_UNSHARP2:
1052 break;
1053 case YUV_SCALER_BICUB:
1054 case YUV_SCALER_BICUB_X:
1055 texs[0] = (*texu)++;
1056 gen_spline_lookup_tex(gl, GL_TEXTURE0 + texs[0]);
1057 texs[0] += '0';
1058 break;
1059 default:
1060 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown scaler type %i\n", scaler);
1064 //! resolution of texture for gamma lookup table
1065 #define LOOKUP_RES 512
1066 //! resolution for 3D yuv->rgb conversion lookup table
1067 #define LOOKUP_3DRES 32
1069 * \brief creates and initializes helper textures needed for yuv conversion
1070 * \param params struct containing parameters like brightness, gamma, ...
1071 * \param texu contains next free texture unit number
1072 * \param texs texture unit ids for the conversion are stored in this array
1074 static void create_conv_textures(GL *gl, gl_conversion_params_t *params,
1075 int *texu, char *texs)
1077 unsigned char *lookup_data = NULL;
1078 int conv = YUV_CONVERSION(params->type);
1079 switch (conv) {
1080 case YUV_CONVERSION_FRAGMENT:
1081 case YUV_CONVERSION_FRAGMENT_POW:
1082 break;
1083 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1084 texs[0] = (*texu)++;
1085 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1086 lookup_data = malloc(4 * LOOKUP_RES);
1087 mp_gen_gamma_map(lookup_data, LOOKUP_RES, params->csp_params.rgamma);
1088 mp_gen_gamma_map(&lookup_data[LOOKUP_RES], LOOKUP_RES,
1089 params->csp_params.ggamma);
1090 mp_gen_gamma_map(&lookup_data[2 * LOOKUP_RES], LOOKUP_RES,
1091 params->csp_params.bgamma);
1092 glCreateClearTex(gl, GL_TEXTURE_2D, GL_LUMINANCE8, GL_LUMINANCE,
1093 GL_UNSIGNED_BYTE, GL_LINEAR, LOOKUP_RES, 4, 0);
1094 glUploadTex(gl, GL_TEXTURE_2D, GL_LUMINANCE, GL_UNSIGNED_BYTE,
1095 lookup_data, LOOKUP_RES, 0, 0, LOOKUP_RES, 4, 0);
1096 gl->ActiveTexture(GL_TEXTURE0);
1097 texs[0] += '0';
1098 break;
1099 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1101 int sz = LOOKUP_3DRES + 2; // texture size including borders
1102 if (!gl->TexImage3D) {
1103 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing 3D texture function!\n");
1104 break;
1106 texs[0] = (*texu)++;
1107 gl->ActiveTexture(GL_TEXTURE0 + texs[0]);
1108 lookup_data = malloc(3 * sz * sz * sz);
1109 mp_gen_yuv2rgb_map(&params->csp_params, lookup_data, LOOKUP_3DRES);
1110 glAdjustAlignment(gl, sz);
1111 gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1112 gl->TexImage3D(GL_TEXTURE_3D, 0, 3, sz, sz, sz, 1,
1113 GL_RGB, GL_UNSIGNED_BYTE, lookup_data);
1114 gl->TexParameterf(GL_TEXTURE_3D, GL_TEXTURE_PRIORITY, 1.0);
1115 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1116 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1117 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1118 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1119 gl->TexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
1120 gl->ActiveTexture(GL_TEXTURE0);
1121 texs[0] += '0';
1123 break;
1124 default:
1125 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n", conv);
1127 free(lookup_data);
1131 * \brief adds a scaling texture read at the current fragment program position
1132 * \param scaler type of scaler to insert
1133 * \param prog pointer to fragment program so far
1134 * \param texs array containing the texture unit identifiers for this scaler
1135 * \param in_tex texture unit the scaler should read from
1136 * \param out_comp component of the yuv variable the scaler stores the result in
1137 * \param rect if rectangular (pixel) adressing should be used for in_tex
1138 * \param texw width of the in_tex texture
1139 * \param texh height of the in_tex texture
1140 * \param strength strength of filter effect if the scaler does some kind of filtering
1142 static void add_scaler(int scaler, char **prog, char *texs,
1143 char in_tex, char out_comp, int rect, int texw, int texh,
1144 double strength)
1146 const char *ttype = rect ? "RECT" : "2D";
1147 const float ptw = rect ? 1.0 : 1.0 / texw;
1148 const float pth = rect ? 1.0 : 1.0 / texh;
1149 switch (scaler) {
1150 case YUV_SCALER_BILIN:
1151 append_template(prog, bilin_filt_template);
1152 break;
1153 case YUV_SCALER_BICUB:
1154 if (rect)
1155 append_template(prog, bicub_filt_template_RECT);
1156 else
1157 append_template(prog, bicub_filt_template_2D);
1158 break;
1159 case YUV_SCALER_BICUB_X:
1160 if (rect)
1161 append_template(prog, bicub_x_filt_template_RECT);
1162 else
1163 append_template(prog, bicub_x_filt_template_2D);
1164 break;
1165 case YUV_SCALER_BICUB_NOTEX:
1166 if (rect)
1167 append_template(prog, bicub_notex_filt_template_RECT);
1168 else
1169 append_template(prog, bicub_notex_filt_template_2D);
1170 break;
1171 case YUV_SCALER_UNSHARP:
1172 append_template(prog, unsharp_filt_template);
1173 break;
1174 case YUV_SCALER_UNSHARP2:
1175 append_template(prog, unsharp_filt_template2);
1176 break;
1179 replace_var_char(prog, "texs", texs[0]);
1180 replace_var_char(prog, "in_tex", in_tex);
1181 replace_var_char(prog, "out_comp", out_comp);
1182 replace_var_str(prog, "tex_type", ttype);
1183 replace_var_float(prog, "texw", texw);
1184 replace_var_float(prog, "texh", texh);
1185 replace_var_float(prog, "ptw", ptw);
1186 replace_var_float(prog, "pth", pth);
1188 // this is silly, not sure if that couldn't be in the shader source instead
1189 replace_var_float(prog, "ptw_05", ptw * 0.5);
1190 replace_var_float(prog, "pth_05", pth * 0.5);
1191 replace_var_float(prog, "ptw_15", ptw * 1.5);
1192 replace_var_float(prog, "pth_15", pth * 1.5);
1193 replace_var_float(prog, "ptw_12", ptw * 1.2);
1194 replace_var_float(prog, "pth_12", pth * 1.2);
1196 replace_var_float(prog, "strength", strength);
1199 static const struct {
1200 const char *name;
1201 GLenum cur;
1202 GLenum max;
1203 } progstats[] = {
1204 {"instructions", 0x88A0, 0x88A1},
1205 {"native instructions", 0x88A2, 0x88A3},
1206 {"temporaries", 0x88A4, 0x88A5},
1207 {"native temporaries", 0x88A6, 0x88A7},
1208 {"parameters", 0x88A8, 0x88A9},
1209 {"native parameters", 0x88AA, 0x88AB},
1210 {"attribs", 0x88AC, 0x88AD},
1211 {"native attribs", 0x88AE, 0x88AF},
1212 {"ALU instructions", 0x8805, 0x880B},
1213 {"TEX instructions", 0x8806, 0x880C},
1214 {"TEX indirections", 0x8807, 0x880D},
1215 {"native ALU instructions", 0x8808, 0x880E},
1216 {"native TEX instructions", 0x8809, 0x880F},
1217 {"native TEX indirections", 0x880A, 0x8810},
1218 {NULL, 0, 0}
1222 * \brief load the specified GPU Program
1223 * \param target program target to load into, only GL_FRAGMENT_PROGRAM is tested
1224 * \param prog program string
1225 * \return 1 on success, 0 otherwise
1227 int loadGPUProgram(GL *gl, GLenum target, char *prog)
1229 int i;
1230 GLint cur = 0, max = 0, err = 0;
1231 if (!gl->ProgramString) {
1232 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Missing GPU program function\n");
1233 return 0;
1235 gl->ProgramString(target, GL_PROGRAM_FORMAT_ASCII, strlen(prog), prog);
1236 gl->GetIntegerv(GL_PROGRAM_ERROR_POSITION, &err);
1237 if (err != -1) {
1238 mp_msg(MSGT_VO, MSGL_ERR,
1239 "[gl] Error compiling fragment program, make sure your card supports\n"
1240 "[gl] GL_ARB_fragment_program (use glxinfo to check).\n"
1241 "[gl] Error message:\n %s at %.10s\n",
1242 gl->GetString(GL_PROGRAM_ERROR_STRING), &prog[err]);
1243 return 0;
1245 if (!gl->GetProgramiv || !mp_msg_test(MSGT_VO, MSGL_DBG2))
1246 return 1;
1247 mp_msg(MSGT_VO, MSGL_V, "[gl] Program statistics:\n");
1248 for (i = 0; progstats[i].name; i++) {
1249 gl->GetProgramiv(target, progstats[i].cur, &cur);
1250 gl->GetProgramiv(target, progstats[i].max, &max);
1251 mp_msg(MSGT_VO, MSGL_V, "[gl] %s: %i/%i\n", progstats[i].name, cur,
1252 max);
1254 return 1;
1257 #define MAX_PROGSZ (1024 * 1024)
1260 * \brief setup a fragment program that will do YUV->RGB conversion
1261 * \param parms struct containing parameters like conversion and scaler type,
1262 * brightness, ...
1264 static void glSetupYUVFragprog(GL *gl, gl_conversion_params_t *params)
1266 int type = params->type;
1267 int texw = params->texw;
1268 int texh = params->texh;
1269 int rect = params->target == GL_TEXTURE_RECTANGLE;
1270 static const char prog_hdr[] =
1271 "!!ARBfp1.0\n"
1272 "OPTION ARB_precision_hint_fastest;\n"
1273 // all scaler variables must go here so they aren't defined
1274 // multiple times when the same scaler is used more than once
1275 "TEMP coord, coord2, cdelta, parmx, parmy, a, b, yuv, textemp;\n";
1276 char *yuv_prog = NULL;
1277 char **prog = &yuv_prog;
1278 int cur_texu = 3;
1279 char lum_scale_texs[1];
1280 char chrom_scale_texs[1];
1281 char conv_texs[1];
1282 GLint i;
1283 // this is the conversion matrix, with y, u, v factors
1284 // for red, green, blue and the constant offsets
1285 float yuv2rgb[3][4];
1286 create_conv_textures(gl, params, &cur_texu, conv_texs);
1287 create_scaler_textures(gl, YUV_LUM_SCALER(type), &cur_texu, lum_scale_texs);
1288 if (YUV_CHROM_SCALER(type) == YUV_LUM_SCALER(type))
1289 memcpy(chrom_scale_texs, lum_scale_texs, sizeof(chrom_scale_texs));
1290 else
1291 create_scaler_textures(gl, YUV_CHROM_SCALER(type), &cur_texu,
1292 chrom_scale_texs);
1293 gl->GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &i);
1294 if (i < cur_texu)
1295 mp_msg(MSGT_VO, MSGL_ERR,
1296 "[gl] %i texture units needed for this type of YUV fragment support (found %i)\n",
1297 cur_texu, i);
1298 if (!gl->ProgramString) {
1299 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] ProgramString function missing!\n");
1300 return;
1302 append_template(prog, prog_hdr);
1303 add_scaler(YUV_LUM_SCALER(type), prog, lum_scale_texs,
1304 '0', 'r', rect, texw, texh, params->filter_strength);
1305 add_scaler(YUV_CHROM_SCALER(type), prog,
1306 chrom_scale_texs, '1', 'g', rect, params->chrom_texw,
1307 params->chrom_texh, params->filter_strength);
1308 add_scaler(YUV_CHROM_SCALER(type), prog,
1309 chrom_scale_texs, '2', 'b', rect, params->chrom_texw,
1310 params->chrom_texh, params->filter_strength);
1311 mp_get_yuv2rgb_coeffs(&params->csp_params, yuv2rgb);
1312 switch (YUV_CONVERSION(type)) {
1313 case YUV_CONVERSION_FRAGMENT:
1314 append_template(prog, yuv_prog_template);
1315 break;
1316 case YUV_CONVERSION_FRAGMENT_POW:
1317 append_template(prog, yuv_pow_prog_template);
1318 break;
1319 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1320 append_template(prog, yuv_lookup_prog_template);
1321 break;
1322 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1323 append_template(prog, yuv_lookup3d_prog_template);
1324 break;
1325 default:
1326 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1327 YUV_CONVERSION(type));
1328 break;
1330 for (int r = 0; r < 3; r++) {
1331 for (int c = 0; c < 4; c++) {
1332 // "cmRC"
1333 char var[] = { 'c', 'm', '1' + r, '1' + c, '\0' };
1334 replace_var_float(prog, var, yuv2rgb[r][c]);
1337 replace_var_float(prog, "gamma_r", (float)1.0 / params->csp_params.rgamma);
1338 replace_var_float(prog, "gamma_g", (float)1.0 / params->csp_params.ggamma);
1339 replace_var_float(prog, "gamma_b", (float)1.0 / params->csp_params.bgamma);
1340 replace_var_char(prog, "conv_tex0", conv_texs[0]);
1341 mp_msg(MSGT_VO, MSGL_DBG2, "[gl] generated fragment program:\n%s\n",
1342 yuv_prog);
1343 loadGPUProgram(gl, GL_FRAGMENT_PROGRAM, yuv_prog);
1344 talloc_free(yuv_prog);
1348 * \brief detect the best YUV->RGB conversion method available
1350 int glAutodetectYUVConversion(GL *gl)
1352 const char *extensions = gl->GetString(GL_EXTENSIONS);
1353 if (!extensions || !gl->MultiTexCoord2f)
1354 return YUV_CONVERSION_NONE;
1355 if (strstr(extensions, "GL_ARB_fragment_program"))
1356 return YUV_CONVERSION_FRAGMENT;
1357 if (strstr(extensions, "GL_ATI_text_fragment_shader"))
1358 return YUV_CONVERSION_TEXT_FRAGMENT;
1359 if (strstr(extensions, "GL_ATI_fragment_shader"))
1360 return YUV_CONVERSION_COMBINERS_ATI;
1361 return YUV_CONVERSION_NONE;
1365 * \brief setup YUV->RGB conversion
1366 * \param parms struct containing parameters like conversion and scaler type,
1367 * brightness, ...
1368 * \ingroup glconversion
1370 void glSetupYUVConversion(GL *gl, gl_conversion_params_t *params)
1372 if (params->chrom_texw == 0)
1373 params->chrom_texw = 1;
1374 if (params->chrom_texh == 0)
1375 params->chrom_texh = 1;
1376 switch (YUV_CONVERSION(params->type)) {
1377 case YUV_CONVERSION_COMBINERS_ATI:
1378 glSetupYUVFragmentATI(gl, &params->csp_params, 0);
1379 break;
1380 case YUV_CONVERSION_TEXT_FRAGMENT:
1381 glSetupYUVFragmentATI(gl, &params->csp_params, 1);
1382 break;
1383 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1384 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1385 case YUV_CONVERSION_FRAGMENT:
1386 case YUV_CONVERSION_FRAGMENT_POW:
1387 glSetupYUVFragprog(gl, params);
1388 break;
1389 case YUV_CONVERSION_NONE:
1390 break;
1391 default:
1392 mp_msg(MSGT_VO, MSGL_ERR, "[gl] unknown conversion type %i\n",
1393 YUV_CONVERSION(params->type));
1398 * \brief enable the specified YUV conversion
1399 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1400 * \param type type of YUV conversion
1401 * \ingroup glconversion
1403 void glEnableYUVConversion(GL *gl, GLenum target, int type)
1405 switch (YUV_CONVERSION(type)) {
1406 case YUV_CONVERSION_COMBINERS_ATI:
1407 gl->ActiveTexture(GL_TEXTURE1);
1408 gl->Enable(target);
1409 gl->ActiveTexture(GL_TEXTURE2);
1410 gl->Enable(target);
1411 gl->ActiveTexture(GL_TEXTURE0);
1412 gl->Enable(GL_FRAGMENT_SHADER_ATI);
1413 break;
1414 case YUV_CONVERSION_TEXT_FRAGMENT:
1415 gl->ActiveTexture(GL_TEXTURE1);
1416 gl->Enable(target);
1417 gl->ActiveTexture(GL_TEXTURE2);
1418 gl->Enable(target);
1419 gl->ActiveTexture(GL_TEXTURE0);
1420 gl->Enable(GL_TEXT_FRAGMENT_SHADER_ATI);
1421 break;
1422 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1423 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1424 case YUV_CONVERSION_FRAGMENT_POW:
1425 case YUV_CONVERSION_FRAGMENT:
1426 case YUV_CONVERSION_NONE:
1427 gl->Enable(GL_FRAGMENT_PROGRAM);
1428 break;
1433 * \brief disable the specified YUV conversion
1434 * \param target texture target for Y, U and V textures (e.g. GL_TEXTURE_2D)
1435 * \param type type of YUV conversion
1436 * \ingroup glconversion
1438 void glDisableYUVConversion(GL *gl, GLenum target, int type)
1440 switch (YUV_CONVERSION(type)) {
1441 case YUV_CONVERSION_COMBINERS_ATI:
1442 gl->ActiveTexture(GL_TEXTURE1);
1443 gl->Disable(target);
1444 gl->ActiveTexture(GL_TEXTURE2);
1445 gl->Disable(target);
1446 gl->ActiveTexture(GL_TEXTURE0);
1447 gl->Disable(GL_FRAGMENT_SHADER_ATI);
1448 break;
1449 case YUV_CONVERSION_TEXT_FRAGMENT:
1450 gl->Disable(GL_TEXT_FRAGMENT_SHADER_ATI);
1451 // HACK: at least the Mac OS X 10.5 PPC Radeon drivers are broken and
1452 // without this disable the texture units while the program is still
1453 // running (10.4 PPC seems to work without this though).
1454 gl->Flush();
1455 gl->ActiveTexture(GL_TEXTURE1);
1456 gl->Disable(target);
1457 gl->ActiveTexture(GL_TEXTURE2);
1458 gl->Disable(target);
1459 gl->ActiveTexture(GL_TEXTURE0);
1460 break;
1461 case YUV_CONVERSION_FRAGMENT_LOOKUP3D:
1462 case YUV_CONVERSION_FRAGMENT_LOOKUP:
1463 case YUV_CONVERSION_FRAGMENT_POW:
1464 case YUV_CONVERSION_FRAGMENT:
1465 case YUV_CONVERSION_NONE:
1466 gl->Disable(GL_FRAGMENT_PROGRAM);
1467 break;
1471 void glEnable3DLeft(GL *gl, int type)
1473 GLint buffer;
1474 switch (type) {
1475 case GL_3D_RED_CYAN:
1476 gl->ColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
1477 break;
1478 case GL_3D_GREEN_MAGENTA:
1479 gl->ColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
1480 break;
1481 case GL_3D_QUADBUFFER:
1482 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1483 switch (buffer) {
1484 case GL_FRONT:
1485 case GL_FRONT_LEFT:
1486 case GL_FRONT_RIGHT:
1487 buffer = GL_FRONT_LEFT;
1488 break;
1489 case GL_BACK:
1490 case GL_BACK_LEFT:
1491 case GL_BACK_RIGHT:
1492 buffer = GL_BACK_LEFT;
1493 break;
1495 gl->DrawBuffer(buffer);
1496 break;
1500 void glEnable3DRight(GL *gl, int type)
1502 GLint buffer;
1503 switch (type) {
1504 case GL_3D_RED_CYAN:
1505 gl->ColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
1506 break;
1507 case GL_3D_GREEN_MAGENTA:
1508 gl->ColorMask(GL_TRUE, GL_FALSE, GL_TRUE, GL_FALSE);
1509 break;
1510 case GL_3D_QUADBUFFER:
1511 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1512 switch (buffer) {
1513 case GL_FRONT:
1514 case GL_FRONT_LEFT:
1515 case GL_FRONT_RIGHT:
1516 buffer = GL_FRONT_RIGHT;
1517 break;
1518 case GL_BACK:
1519 case GL_BACK_LEFT:
1520 case GL_BACK_RIGHT:
1521 buffer = GL_BACK_RIGHT;
1522 break;
1524 gl->DrawBuffer(buffer);
1525 break;
1529 void glDisable3D(GL *gl, int type)
1531 GLint buffer;
1532 switch (type) {
1533 case GL_3D_RED_CYAN:
1534 case GL_3D_GREEN_MAGENTA:
1535 gl->ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1536 break;
1537 case GL_3D_QUADBUFFER:
1538 gl->DrawBuffer(vo_doublebuffering ? GL_BACK : GL_FRONT);
1539 gl->GetIntegerv(GL_DRAW_BUFFER, &buffer);
1540 switch (buffer) {
1541 case GL_FRONT:
1542 case GL_FRONT_LEFT:
1543 case GL_FRONT_RIGHT:
1544 buffer = GL_FRONT;
1545 break;
1546 case GL_BACK:
1547 case GL_BACK_LEFT:
1548 case GL_BACK_RIGHT:
1549 buffer = GL_BACK;
1550 break;
1552 gl->DrawBuffer(buffer);
1553 break;
1558 * \brief draw a texture part at given 2D coordinates
1559 * \param x screen top coordinate
1560 * \param y screen left coordinate
1561 * \param w screen width coordinate
1562 * \param h screen height coordinate
1563 * \param tx texture top coordinate in pixels
1564 * \param ty texture left coordinate in pixels
1565 * \param tw texture part width in pixels
1566 * \param th texture part height in pixels
1567 * \param sx width of texture in pixels
1568 * \param sy height of texture in pixels
1569 * \param rect_tex whether this texture uses texture_rectangle extension
1570 * \param is_yv12 if != 0, also draw the textures from units 1 and 2,
1571 * bits 8 - 15 and 16 - 23 specify the x and y scaling of those textures
1572 * \param flip flip the texture upside down
1573 * \ingroup gltexture
1575 void glDrawTex(GL *gl, GLfloat x, GLfloat y, GLfloat w, GLfloat h,
1576 GLfloat tx, GLfloat ty, GLfloat tw, GLfloat th,
1577 int sx, int sy, int rect_tex, int is_yv12, int flip)
1579 int chroma_x_shift = (is_yv12 >> 8) & 31;
1580 int chroma_y_shift = (is_yv12 >> 16) & 31;
1581 GLfloat xscale = 1 << chroma_x_shift;
1582 GLfloat yscale = 1 << chroma_y_shift;
1583 GLfloat tx2 = tx / xscale, ty2 = ty / yscale, tw2 = tw / xscale, th2 = th / yscale;
1584 if (!rect_tex) {
1585 tx /= sx;
1586 ty /= sy;
1587 tw /= sx;
1588 th /= sy;
1589 tx2 = tx, ty2 = ty, tw2 = tw, th2 = th;
1591 if (flip) {
1592 y += h;
1593 h = -h;
1595 gl->Begin(GL_QUADS);
1596 gl->TexCoord2f(tx, ty);
1597 if (is_yv12) {
1598 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2);
1599 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2);
1601 gl->Vertex2f(x, y);
1602 gl->TexCoord2f(tx, ty + th);
1603 if (is_yv12) {
1604 gl->MultiTexCoord2f(GL_TEXTURE1, tx2, ty2 + th2);
1605 gl->MultiTexCoord2f(GL_TEXTURE2, tx2, ty2 + th2);
1607 gl->Vertex2f(x, y + h);
1608 gl->TexCoord2f(tx + tw, ty + th);
1609 if (is_yv12) {
1610 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2 + th2);
1611 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2 + th2);
1613 gl->Vertex2f(x + w, y + h);
1614 gl->TexCoord2f(tx + tw, ty);
1615 if (is_yv12) {
1616 gl->MultiTexCoord2f(GL_TEXTURE1, tx2 + tw2, ty2);
1617 gl->MultiTexCoord2f(GL_TEXTURE2, tx2 + tw2, ty2);
1619 gl->Vertex2f(x + w, y);
1620 gl->End();
1623 #ifdef CONFIG_GL_COCOA
1624 #include "cocoa_common.h"
1625 static int create_window_cocoa(struct MPGLContext *ctx, uint32_t d_width,
1626 uint32_t d_height, uint32_t flags)
1628 if (vo_cocoa_create_window(ctx->vo, d_width, d_height, flags) == 0) {
1629 return SET_WINDOW_OK;
1630 } else {
1631 return SET_WINDOW_FAILED;
1634 static int setGlWindow_cocoa(MPGLContext *ctx)
1636 vo_cocoa_change_attributes(ctx->vo);
1637 getFunctions(ctx->gl, (void *)vo_cocoa_glgetaddr, NULL);
1638 if (!ctx->gl->SwapInterval)
1639 ctx->gl->SwapInterval = vo_cocoa_swap_interval;
1640 return SET_WINDOW_OK;
1643 static void releaseGlContext_cocoa(MPGLContext *ctx)
1647 static void swapGlBuffers_cocoa(MPGLContext *ctx)
1649 vo_cocoa_swap_buffers();
1652 static int cocoa_check_events(struct vo *vo)
1654 return vo_cocoa_check_events(vo);
1657 static void cocoa_update_xinerama_info(struct vo *vo)
1659 vo_cocoa_update_xinerama_info(vo);
1662 static void cocoa_fullscreen(struct vo *vo)
1664 vo_cocoa_fullscreen(vo);
1666 #endif
1668 #ifdef CONFIG_GL_WIN32
1669 #include "w32_common.h"
1671 static int create_window_w32(struct MPGLContext *ctx, uint32_t d_width,
1672 uint32_t d_height, uint32_t flags)
1674 if (!vo_w32_config(d_width, d_height, flags))
1675 return -1;
1676 return 0;
1680 * \brief little helper since wglGetProcAddress definition does not fit our
1681 * getProcAddress
1682 * \param procName name of function to look up
1683 * \return function pointer returned by wglGetProcAddress
1685 static void *w32gpa(const GLubyte *procName)
1687 HMODULE oglmod;
1688 void *res = wglGetProcAddress(procName);
1689 if (res)
1690 return res;
1691 oglmod = GetModuleHandle("opengl32.dll");
1692 return GetProcAddress(oglmod, procName);
1695 static int setGlWindow_w32(MPGLContext *ctx)
1697 HWND win = vo_w32_window;
1698 int *vinfo = &ctx->vinfo.w32;
1699 HGLRC *context = &ctx->context.w32;
1700 int new_vinfo;
1701 HDC windc = vo_w32_get_dc(win);
1702 HGLRC new_context = 0;
1703 int keep_context = 0;
1704 int res = SET_WINDOW_FAILED;
1705 GL *gl = ctx->gl;
1707 // should only be needed when keeping context, but not doing glFinish
1708 // can cause flickering even when we do not keep it.
1709 if (*context)
1710 gl->Finish();
1711 new_vinfo = GetPixelFormat(windc);
1712 if (*context && *vinfo && new_vinfo && *vinfo == new_vinfo) {
1713 // we can keep the wglContext
1714 new_context = *context;
1715 keep_context = 1;
1716 } else {
1717 // create a context
1718 new_context = wglCreateContext(windc);
1719 if (!new_context) {
1720 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GL context!\n");
1721 goto out;
1725 // set context
1726 if (!wglMakeCurrent(windc, new_context)) {
1727 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GL context!\n");
1728 if (!keep_context)
1729 wglDeleteContext(new_context);
1730 goto out;
1733 // set new values
1734 vo_w32_window = win;
1736 RECT rect;
1737 GetClientRect(win, &rect);
1738 ctx->vo->dwidth = rect.right;
1739 ctx->vo->dheight = rect.bottom;
1741 if (!keep_context) {
1742 if (*context)
1743 wglDeleteContext(*context);
1744 *context = new_context;
1745 *vinfo = new_vinfo;
1746 getFunctions(gl, w32gpa, NULL);
1748 // and inform that reinit is neccessary
1749 res = SET_WINDOW_REINIT;
1750 } else
1751 res = SET_WINDOW_OK;
1753 out:
1754 vo_w32_release_dc(win, windc);
1755 return res;
1758 static void releaseGlContext_w32(MPGLContext *ctx)
1760 int *vinfo = &ctx->vinfo.w32;
1761 HGLRC *context = &ctx->context.w32;
1762 *vinfo = 0;
1763 if (*context) {
1764 wglMakeCurrent(0, 0);
1765 wglDeleteContext(*context);
1767 *context = 0;
1770 static void swapGlBuffers_w32(MPGLContext *ctx)
1772 HDC vo_hdc = vo_w32_get_dc(vo_w32_window);
1773 SwapBuffers(vo_hdc);
1774 vo_w32_release_dc(vo_w32_window, vo_hdc);
1777 //trivial wrappers (w32 code uses old vo API)
1778 static void new_vo_w32_ontop(struct vo *vo) { vo_w32_ontop(); }
1779 static void new_vo_w32_border(struct vo *vo) { vo_w32_border(); }
1780 static void new_vo_w32_fullscreen(struct vo *vo) { vo_w32_fullscreen(); }
1781 static int new_vo_w32_check_events(struct vo *vo) { return vo_w32_check_events(); }
1782 static void new_w32_update_xinerama_info(struct vo *vo) { w32_update_xinerama_info(); }
1783 #endif
1784 #ifdef CONFIG_GL_X11
1785 #include "x11_common.h"
1787 static int create_window_x11(struct MPGLContext *ctx, uint32_t d_width,
1788 uint32_t d_height, uint32_t flags)
1790 struct vo *vo = ctx->vo;
1792 static int default_glx_attribs[] = {
1793 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1794 GLX_DOUBLEBUFFER, None
1796 static int stereo_glx_attribs[] = {
1797 GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1798 GLX_DOUBLEBUFFER, GLX_STEREO, None
1800 XVisualInfo *vinfo = NULL;
1801 if (flags & VOFLAG_STEREO) {
1802 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
1803 stereo_glx_attribs);
1804 if (!vinfo)
1805 mp_msg(MSGT_VO, MSGL_ERR, "[gl] Could not find a stereo visual,"
1806 " 3D will probably not work!\n");
1808 if (!vinfo)
1809 vinfo = glXChooseVisual(vo->x11->display, vo->x11->screen,
1810 default_glx_attribs);
1811 if (!vinfo) {
1812 mp_msg(MSGT_VO, MSGL_ERR, "[gl] no GLX support present\n");
1813 return -1;
1815 mp_msg(MSGT_VO, MSGL_V, "[gl] GLX chose visual with ID 0x%x\n",
1816 (int)vinfo->visualid);
1818 Colormap colormap = XCreateColormap(vo->x11->display, vo->x11->rootwin,
1819 vinfo->visual, AllocNone);
1820 vo_x11_create_vo_window(vo, vinfo, vo->dx, vo->dy, d_width, d_height,
1821 flags, colormap, "gl");
1823 return 0;
1827 * \brief Returns the XVisualInfo associated with Window win.
1828 * \param win Window whose XVisualInfo is returne.
1829 * \return XVisualInfo of the window. Caller must use XFree to free it.
1831 static XVisualInfo *getWindowVisualInfo(MPGLContext *ctx, Window win)
1833 XWindowAttributes xw_attr;
1834 XVisualInfo vinfo_template;
1835 int tmp;
1836 XGetWindowAttributes(ctx->vo->x11->display, win, &xw_attr);
1837 vinfo_template.visualid = XVisualIDFromVisual(xw_attr.visual);
1838 return XGetVisualInfo(ctx->vo->x11->display, VisualIDMask, &vinfo_template, &tmp);
1841 static void appendstr(char **dst, const char *str)
1843 int newsize;
1844 char *newstr;
1845 if (!str)
1846 return;
1847 newsize = strlen(*dst) + 1 + strlen(str) + 1;
1848 newstr = realloc(*dst, newsize);
1849 if (!newstr)
1850 return;
1851 *dst = newstr;
1852 strcat(*dst, " ");
1853 strcat(*dst, str);
1857 * \brief Changes the window in which video is displayed.
1858 * If possible only transfers the context to the new window, otherwise
1859 * creates a new one, which must be initialized by the caller.
1860 * \param vinfo Currently used visual.
1861 * \param context Currently used context.
1862 * \param win window that should be used for drawing.
1863 * \return one of SET_WINDOW_FAILED, SET_WINDOW_OK or SET_WINDOW_REINIT.
1864 * In case of SET_WINDOW_REINIT the context could not be transfered
1865 * and the caller must initialize it correctly.
1866 * \ingroup glcontext
1868 static int setGlWindow_x11(MPGLContext *ctx)
1870 XVisualInfo **vinfo = &ctx->vinfo.x11;
1871 GLXContext *context = &ctx->context.x11;
1872 Display *display = ctx->vo->x11->display;
1873 Window win = ctx->vo->x11->window;
1874 XVisualInfo *new_vinfo;
1875 GLXContext new_context = NULL;
1876 int keep_context = 0;
1877 GL *gl = ctx->gl;
1879 // should only be needed when keeping context, but not doing glFinish
1880 // can cause flickering even when we do not keep it.
1881 if (*context)
1882 gl->Finish();
1883 new_vinfo = getWindowVisualInfo(ctx, win);
1884 if (*context && *vinfo && new_vinfo &&
1885 (*vinfo)->visualid == new_vinfo->visualid) {
1886 // we can keep the GLXContext
1887 new_context = *context;
1888 XFree(new_vinfo);
1889 new_vinfo = *vinfo;
1890 keep_context = 1;
1891 } else {
1892 // create a context
1893 new_context = glXCreateContext(display, new_vinfo, NULL, True);
1894 if (!new_context) {
1895 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not create GLX context!\n");
1896 XFree(new_vinfo);
1897 return SET_WINDOW_FAILED;
1901 // set context
1902 if (!glXMakeCurrent(display, ctx->vo->x11->window, new_context)) {
1903 mp_msg(MSGT_VO, MSGL_FATAL, "[gl] Could not set GLX context!\n");
1904 if (!keep_context) {
1905 glXDestroyContext(display, new_context);
1906 XFree(new_vinfo);
1908 return SET_WINDOW_FAILED;
1911 // set new values
1912 ctx->vo->x11->window = win;
1913 vo_x11_update_geometry(ctx->vo, 1);
1914 if (!keep_context) {
1915 void *(*getProcAddress)(const GLubyte *);
1916 const char *(*glXExtStr)(Display *, int);
1917 char *glxstr = strdup("");
1918 if (*context)
1919 glXDestroyContext(display, *context);
1920 *context = new_context;
1921 if (*vinfo)
1922 XFree(*vinfo);
1923 *vinfo = new_vinfo;
1924 getProcAddress = getdladdr("glXGetProcAddress");
1925 if (!getProcAddress)
1926 getProcAddress = getdladdr("glXGetProcAddressARB");
1927 glXExtStr = getdladdr("glXQueryExtensionsString");
1928 if (glXExtStr)
1929 appendstr(&glxstr, glXExtStr(display, DefaultScreen(display)));
1930 glXExtStr = getdladdr("glXGetClientString");
1931 if (glXExtStr)
1932 appendstr(&glxstr, glXExtStr(display, GLX_EXTENSIONS));
1933 glXExtStr = getdladdr("glXGetServerString");
1934 if (glXExtStr)
1935 appendstr(&glxstr, glXExtStr(display, GLX_EXTENSIONS));
1937 getFunctions(gl, getProcAddress, glxstr);
1938 if (!gl->GenPrograms && gl->GetString &&
1939 getProcAddress &&
1940 strstr(gl->GetString(GL_EXTENSIONS), "GL_ARB_vertex_program")) {
1941 mp_msg(MSGT_VO, MSGL_WARN,
1942 "Broken glXGetProcAddress detected, trying workaround\n");
1943 getFunctions(gl, NULL, glxstr);
1945 free(glxstr);
1947 // and inform that reinit is neccessary
1948 return SET_WINDOW_REINIT;
1950 return SET_WINDOW_OK;
1954 * \brief free the VisualInfo and GLXContext of an OpenGL context.
1955 * \ingroup glcontext
1957 static void releaseGlContext_x11(MPGLContext *ctx)
1959 XVisualInfo **vinfo = &ctx->vinfo.x11;
1960 GLXContext *context = &ctx->context.x11;
1961 Display *display = ctx->vo->x11->display;
1962 GL *gl = ctx->gl;
1963 if (*vinfo)
1964 XFree(*vinfo);
1965 *vinfo = NULL;
1966 if (*context) {
1967 gl->Finish();
1968 glXMakeCurrent(display, None, NULL);
1969 glXDestroyContext(display, *context);
1971 *context = 0;
1974 static void swapGlBuffers_x11(MPGLContext *ctx)
1976 glXSwapBuffers(ctx->vo->x11->display, ctx->vo->x11->window);
1978 #endif
1980 #ifdef CONFIG_GL_SDL
1981 #include "sdl_common.h"
1983 static int create_window_sdl(struct MPGLContext *ctx, uint32_t d_width,
1984 uint32_t d_height, uint32_t flags)
1986 SDL_WM_SetCaption(vo_get_window_title(ctx->vo), NULL);
1987 ctx->vo->dwidth = d_width;
1988 ctx->vo->dheight = d_height;
1989 return 0;
1992 static void swapGlBuffers_sdl(MPGLContext *ctx)
1994 SDL_GL_SwapBuffers();
1997 static void *sdlgpa(const GLubyte *name)
1999 return SDL_GL_GetProcAddress(name);
2002 static int setGlWindow_sdl(MPGLContext *ctx)
2004 if (sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE) < 0)
2005 return SET_WINDOW_FAILED;
2006 SDL_GL_LoadLibrary(NULL);
2007 getFunctions(ctx->gl, sdlgpa, NULL);
2008 return SET_WINDOW_OK;
2011 static void releaseGlContext_sdl(MPGLContext *ctx)
2015 static int sdl_check_events(struct vo *vo)
2017 int res = 0;
2018 SDL_Event event;
2019 while (SDL_PollEvent(&event))
2020 res |= sdl_default_handle_event(&event);
2021 // poll "events" from within MPlayer code
2022 res |= sdl_default_handle_event(NULL);
2023 if (res & VO_EVENT_RESIZE)
2024 sdl_set_mode(0, SDL_OPENGL | SDL_RESIZABLE);
2025 return res;
2028 static void new_sdl_update_xinerama_info(struct vo *vo) { sdl_update_xinerama_info(); }
2029 static void new_vo_sdl_fullscreen(struct vo *vo) { vo_sdl_fullscreen(); }
2031 #endif
2033 MPGLContext *init_mpglcontext(enum MPGLType type, struct vo *vo)
2035 MPGLContext *ctx;
2036 if (type == GLTYPE_AUTO) {
2037 ctx = init_mpglcontext(GLTYPE_COCOA, vo);
2038 if (ctx)
2039 return ctx;
2040 ctx = init_mpglcontext(GLTYPE_W32, vo);
2041 if (ctx)
2042 return ctx;
2043 ctx = init_mpglcontext(GLTYPE_X11, vo);
2044 if (ctx)
2045 return ctx;
2046 return init_mpglcontext(GLTYPE_SDL, vo);
2048 ctx = talloc_zero(NULL, MPGLContext);
2049 ctx->gl = talloc_zero(ctx, GL);
2050 ctx->type = type;
2051 ctx->vo = vo;
2052 switch (ctx->type) {
2053 #ifdef CONFIG_GL_COCOA
2054 case GLTYPE_COCOA:
2055 ctx->create_window = create_window_cocoa;
2056 ctx->setGlWindow = setGlWindow_cocoa;
2057 ctx->releaseGlContext = releaseGlContext_cocoa;
2058 ctx->swapGlBuffers = swapGlBuffers_cocoa;
2059 ctx->check_events = cocoa_check_events;
2060 ctx->update_xinerama_info = cocoa_update_xinerama_info;
2061 ctx->fullscreen = cocoa_fullscreen;
2062 ctx->ontop = vo_cocoa_ontop;
2063 if (vo_cocoa_init(vo))
2064 return ctx;
2065 break;
2066 #endif
2067 #ifdef CONFIG_GL_WIN32
2068 case GLTYPE_W32:
2069 ctx->create_window = create_window_w32;
2070 ctx->setGlWindow = setGlWindow_w32;
2071 ctx->releaseGlContext = releaseGlContext_w32;
2072 ctx->swapGlBuffers = swapGlBuffers_w32;
2073 ctx->update_xinerama_info = new_w32_update_xinerama_info;
2074 ctx->border = new_vo_w32_border;
2075 ctx->check_events = new_vo_w32_check_events;
2076 ctx->fullscreen = new_vo_w32_fullscreen;
2077 ctx->ontop = new_vo_w32_ontop;
2078 //the win32 code is hardcoded to use the deprecated vo API
2079 global_vo = vo;
2080 if (vo_w32_init())
2081 return ctx;
2082 break;
2083 #endif
2084 #ifdef CONFIG_GL_X11
2085 case GLTYPE_X11:
2086 ctx->create_window = create_window_x11;
2087 ctx->setGlWindow = setGlWindow_x11;
2088 ctx->releaseGlContext = releaseGlContext_x11;
2089 ctx->swapGlBuffers = swapGlBuffers_x11;
2090 ctx->update_xinerama_info = update_xinerama_info;
2091 ctx->border = vo_x11_border;
2092 ctx->check_events = vo_x11_check_events;
2093 ctx->fullscreen = vo_x11_fullscreen;
2094 ctx->ontop = vo_x11_ontop;
2095 if (vo_init(vo))
2096 return ctx;
2097 break;
2098 #endif
2099 #ifdef CONFIG_GL_SDL
2100 case GLTYPE_SDL:
2101 ctx->create_window = create_window_sdl;
2102 ctx->setGlWindow = setGlWindow_sdl;
2103 ctx->releaseGlContext = releaseGlContext_sdl;
2104 ctx->swapGlBuffers = swapGlBuffers_sdl;
2105 ctx->update_xinerama_info = new_sdl_update_xinerama_info;
2106 ctx->check_events = sdl_check_events;
2107 ctx->fullscreen = new_vo_sdl_fullscreen;
2108 //the SDL code is hardcoded to use the deprecated vo API
2109 global_vo = vo;
2110 if (vo_sdl_init())
2111 return ctx;
2112 break;
2113 #endif
2115 talloc_free(ctx);
2116 return NULL;
2119 void uninit_mpglcontext(MPGLContext *ctx)
2121 if (!ctx)
2122 return;
2123 ctx->releaseGlContext(ctx);
2124 switch (ctx->type) {
2125 #ifdef CONFIG_GL_COCOA
2126 case GLTYPE_COCOA:
2127 vo_cocoa_uninit(ctx->vo);
2128 break;
2129 #endif
2130 #ifdef CONFIG_GL_WIN32
2131 case GLTYPE_W32:
2132 vo_w32_uninit();
2133 break;
2134 #endif
2135 #ifdef CONFIG_GL_X11
2136 case GLTYPE_X11:
2137 vo_x11_uninit(ctx->vo);
2138 break;
2139 #endif
2140 #ifdef CONFIG_GL_SDL
2141 case GLTYPE_SDL:
2142 vo_sdl_uninit();
2143 break;
2144 #endif
2146 talloc_free(ctx);