lavd/opengl_enc: add gray8/16 formats
[ffmpeg.git] / libavdevice / opengl_enc.c
1 /*
2  * Copyright (c) 2014 Lukasz Marek
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 //TODO: support for more formats
22 //TODO: support for more systems.
23 //TODO: implement X11, Windows, Mac OS native default window. SDL 1.2 doesn't allow to render to custom thread.
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <stddef.h>
30
31 #include "config.h"
32
33 #if HAVE_OPENGL_GL3_H
34 #include <OpenGL/gl3.h>
35 #elif HAVE_ES2_GL_H
36 #include <ES2/gl.h>
37 #else
38 #include <GL/gl.h>
39 #include <GL/glext.h>
40 #endif
41 #if HAVE_GLXGETPROCADDRESS
42 #include <GL/glx.h>
43 #endif
44 #if HAVE_WINDOWS_H
45 #include <windows.h>
46 #endif
47
48 #if HAVE_SDL
49 #include <SDL.h>
50 #endif
51
52 #include "libavutil/common.h"
53 #include "libavutil/pixdesc.h"
54 #include "libavutil/log.h"
55 #include "libavutil/opt.h"
56 #include "libavutil/avassert.h"
57 #include "libavutil/avstring.h"
58 #include "libavformat/avformat.h"
59 #include "libavdevice/avdevice.h"
60 #include "opengl_enc_shaders.h"
61
62 #ifndef APIENTRY
63 #define APIENTRY
64 #endif
65
66 /* FF_GL_RED_COMPONENT is used for plannar pixel types.
67  * Only red component is sampled in shaders.
68  * On some platforms GL_RED is not availabe and GL_LUMINANCE have to be used,
69  * but since OpenGL 3.0 GL_LUMINANCE is deprecated.
70  * GL_RED produces RGBA = value, 0, 0, 1.
71  * GL_LUMINANCE produces RGBA = value, value, value, 1.
72  * Note: GL_INTENSITY may also be used which produce RGBA = value, value, value, value. */
73 #if defined(GL_RED)
74 #define FF_GL_RED_COMPONENT GL_RED
75 #elif defined(GL_LUMINANCE)
76 #define FF_GL_RED_COMPONENT GL_LUMINANCE
77 #else
78 #define FF_GL_RED_COMPONENT 0x1903; //GL_RED
79 #endif
80
81 /* Constants not defined for iOS */
82 #define FF_GL_UNSIGNED_BYTE_3_3_2 0x8032
83 #define FF_GL_UNSIGNED_BYTE_2_3_3_REV 0x8362
84 #define FF_GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366
85
86 /* MinGW exposes only OpenGL 1.1 API */
87 #define FF_GL_ARRAY_BUFFER                0x8892
88 #define FF_GL_ELEMENT_ARRAY_BUFFER        0x8893
89 #define FF_GL_STATIC_DRAW                 0x88E4
90 #define FF_GL_FRAGMENT_SHADER             0x8B30
91 #define FF_GL_VERTEX_SHADER               0x8B31
92 #define FF_GL_COMPILE_STATUS              0x8B81
93 #define FF_GL_LINK_STATUS                 0x8B82
94 #define FF_GL_INFO_LOG_LENGTH             0x8B84
95 typedef void   (APIENTRY *FF_PFNGLACTIVETEXTUREPROC) (GLenum texture);
96 typedef void   (APIENTRY *FF_PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
97 typedef void   (APIENTRY *FF_PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
98 typedef void   (APIENTRY *FF_PFNGLBUFFERDATAPROC) (GLenum target, ptrdiff_t size, const GLvoid *data, GLenum usage);
99 typedef void   (APIENTRY *FF_PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
100 typedef GLint  (APIENTRY *FF_PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const char *name);
101 typedef void   (APIENTRY *FF_PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
102 typedef void   (APIENTRY *FF_PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, uintptr_t pointer);
103 typedef GLint  (APIENTRY *FF_PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const char *name);
104 typedef void   (APIENTRY *FF_PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
105 typedef void   (APIENTRY *FF_PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
106 typedef void   (APIENTRY *FF_PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
107 typedef GLuint (APIENTRY *FF_PFNGLCREATEPROGRAMPROC) (void);
108 typedef void   (APIENTRY *FF_PFNGLDELETEPROGRAMPROC) (GLuint program);
109 typedef void   (APIENTRY *FF_PFNGLUSEPROGRAMPROC) (GLuint program);
110 typedef void   (APIENTRY *FF_PFNGLLINKPROGRAMPROC) (GLuint program);
111 typedef void   (APIENTRY *FF_PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
112 typedef void   (APIENTRY *FF_PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, char *infoLog);
113 typedef void   (APIENTRY *FF_PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
114 typedef GLuint (APIENTRY *FF_PFNGLCREATESHADERPROC) (GLenum type);
115 typedef void   (APIENTRY *FF_PFNGLDELETESHADERPROC) (GLuint shader);
116 typedef void   (APIENTRY *FF_PFNGLCOMPILESHADERPROC) (GLuint shader);
117 typedef void   (APIENTRY *FF_PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const char* *string, const GLint *length);
118 typedef void   (APIENTRY *FF_PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
119 typedef void   (APIENTRY *FF_PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, char *infoLog);
120
121 typedef struct FFOpenGLFunctions {
122     FF_PFNGLACTIVETEXTUREPROC glActiveTexture;                     //Require GL ARB multitexture
123     FF_PFNGLGENBUFFERSPROC glGenBuffers;                           //Require GL_ARB_vertex_buffer_object
124     FF_PFNGLDELETEBUFFERSPROC glDeleteBuffers;                     //Require GL_ARB_vertex_buffer_object
125     FF_PFNGLBUFFERDATAPROC glBufferData;                           //Require GL_ARB_vertex_buffer_object
126     FF_PFNGLBINDBUFFERPROC glBindBuffer;                           //Require GL_ARB_vertex_buffer_object
127     FF_PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation;             //Require GL_ARB_vertex_shader
128     FF_PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; //Require GL_ARB_vertex_shader
129     FF_PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;         //Require GL_ARB_vertex_shader
130     FF_PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;           //Require GL_ARB_shader_objects
131     FF_PFNGLUNIFORM1FPROC glUniform1f;                             //Require GL_ARB_shader_objects
132     FF_PFNGLUNIFORM1IPROC glUniform1i;                             //Require GL_ARB_shader_objects
133     FF_PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv;               //Require GL_ARB_shader_objects
134     FF_PFNGLCREATEPROGRAMPROC glCreateProgram;                     //Require GL_ARB_shader_objects
135     FF_PFNGLDELETEPROGRAMPROC glDeleteProgram;                     //Require GL_ARB_shader_objects
136     FF_PFNGLUSEPROGRAMPROC glUseProgram;                           //Require GL_ARB_shader_objects
137     FF_PFNGLLINKPROGRAMPROC glLinkProgram;                         //Require GL_ARB_shader_objects
138     FF_PFNGLGETPROGRAMIVPROC glGetProgramiv;                       //Require GL_ARB_shader_objects
139     FF_PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;             //Require GL_ARB_shader_objects
140     FF_PFNGLATTACHSHADERPROC glAttachShader;                       //Require GL_ARB_shader_objects
141     FF_PFNGLCREATESHADERPROC glCreateShader;                       //Require GL_ARB_shader_objects
142     FF_PFNGLDELETESHADERPROC glDeleteShader;                       //Require GL_ARB_shader_objects
143     FF_PFNGLCOMPILESHADERPROC glCompileShader;                     //Require GL_ARB_shader_objects
144     FF_PFNGLSHADERSOURCEPROC glShaderSource;                       //Require GL_ARB_shader_objects
145     FF_PFNGLGETSHADERIVPROC glGetShaderiv;                         //Require GL_ARB_shader_objects
146     FF_PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;               //Require GL_ARB_shader_objects
147 } FFOpenGLFunctions;
148
149 #define OPENGL_ERROR_CHECK(ctx) \
150 {\
151     GLenum err_code; \
152     if ((err_code = glGetError()) != GL_NO_ERROR) { \
153         av_log(ctx, AV_LOG_ERROR, "OpenGL error occurred in '%s', line %d: %d\n", __FUNCTION__, __LINE__, err_code); \
154         goto fail; \
155     } \
156 }\
157
158 typedef struct OpenGLVertexInfo
159 {
160     float x, y, z;    ///<Position
161     float s0, t0;     ///<Texture coords
162 } OpenGLVertexInfo;
163
164 /* defines 2 triangles to display */
165 static GLushort g_index[6] =
166 {
167     0, 1, 2,
168     0, 3, 2,
169 };
170
171 typedef struct OpenGLContext {
172     AVClass *class;                    ///< class for private options
173
174 #if HAVE_SDL
175     SDL_Surface *surface;
176 #endif
177     FFOpenGLFunctions glprocs;
178
179     uint8_t background[4];             ///< Background color
180     int no_window;                     ///< 0 for create default window
181     char *window_title;                ///< Title of the window
182
183     /* OpenGL implementation limits */
184     GLint max_texture_size;            ///< Maximum texture size
185     GLint max_viewport_width;          ///< Maximum viewport size
186     GLint max_viewport_height;         ///< Maximum viewport size
187     int non_pow_2_textures;            ///< 1 when non power of 2 textures are supported
188
189     /* Current OpenGL configuration */
190     GLuint program;                    ///< Shader program
191     GLuint vertex_shader;              ///< Vertex shader
192     GLuint fragment_shader;            ///< Fragment shader for current pix_pmt
193     GLuint texture_name[4];            ///< Textures' IDs
194     GLuint index_buffer;               ///< Index buffer
195     GLuint vertex_buffer;              ///< Vertex buffer
196     OpenGLVertexInfo vertex[4];        ///< VBO
197     GLint projection_matrix_location;  ///< Uniforms' locations
198     GLint model_view_matrix_location;
199     GLint color_map_location;
200     GLint chroma_div_w_location;
201     GLint chroma_div_h_location;
202     GLint texture_location[4];
203     GLint position_attrib;             ///< Attibutes' locations
204     GLint texture_coords_attrib;
205
206     GLfloat projection_matrix[16];     ///< Projection matrix
207     GLfloat model_view_matrix[16];     ///< Modev view matrix
208     GLfloat color_map[16];             ///< RGBA color map matrix
209     GLfloat chroma_div_w;              ///< Chroma subsampling w ratio
210     GLfloat chroma_div_h;              ///< Chroma subsampling h ratio
211
212     /* Stream information */
213     GLenum format;
214     GLenum type;
215     int width;                         ///< Stream width
216     int height;                        ///< Stream height
217     enum AVPixelFormat pix_fmt;        ///< Stream pixel format
218     int picture_width;                 ///< Rendered width
219     int picture_height;                ///< Rendered height
220     int window_width;
221     int window_height;
222 } OpenGLContext;
223
224 static const struct OpenGLFormatDesc {
225     enum AVPixelFormat fixel_format;
226     const char * const * fragment_shader;
227     GLenum format;
228     GLenum type;
229 } opengl_format_desc[] = {
230     { AV_PIX_FMT_YUV420P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
231     { AV_PIX_FMT_YUV444P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
232     { AV_PIX_FMT_YUV422P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
233     { AV_PIX_FMT_YUV410P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
234     { AV_PIX_FMT_YUV411P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
235     { AV_PIX_FMT_YUV440P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
236     { AV_PIX_FMT_YUV420P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
237     { AV_PIX_FMT_YUV422P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
238     { AV_PIX_FMT_YUV444P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
239     { AV_PIX_FMT_YUVA420P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
240     { AV_PIX_FMT_YUVA444P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
241     { AV_PIX_FMT_YUVA422P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
242     { AV_PIX_FMT_YUVA420P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
243     { AV_PIX_FMT_YUVA422P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
244     { AV_PIX_FMT_YUVA444P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
245     { AV_PIX_FMT_RGB24,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_BYTE },
246     { AV_PIX_FMT_BGR24,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_BYTE },
247     { AV_PIX_FMT_0RGB,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
248     { AV_PIX_FMT_RGB0,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
249     { AV_PIX_FMT_0BGR,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
250     { AV_PIX_FMT_BGR0,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
251     { AV_PIX_FMT_RGB565,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT_5_6_5 },
252     { AV_PIX_FMT_BGR565,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT_5_6_5 },
253     { AV_PIX_FMT_RGB555,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, FF_GL_UNSIGNED_SHORT_1_5_5_5_REV },
254     { AV_PIX_FMT_BGR555,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, FF_GL_UNSIGNED_SHORT_1_5_5_5_REV },
255     { AV_PIX_FMT_RGB8,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, FF_GL_UNSIGNED_BYTE_3_3_2 },
256     { AV_PIX_FMT_BGR8,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, FF_GL_UNSIGNED_BYTE_2_3_3_REV },
257     { AV_PIX_FMT_RGB48,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT },
258     { AV_PIX_FMT_ARGB,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
259     { AV_PIX_FMT_RGBA,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
260     { AV_PIX_FMT_ABGR,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
261     { AV_PIX_FMT_BGRA,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
262     { AV_PIX_FMT_RGBA64,     &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_SHORT },
263     { AV_PIX_FMT_BGRA64,     &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_SHORT },
264     { AV_PIX_FMT_GBRP,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
265     { AV_PIX_FMT_GBRP16,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
266     { AV_PIX_FMT_GBRAP,      &FF_OPENGL_FRAGMENT_SHADER_RGBA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
267     { AV_PIX_FMT_GBRAP16,    &FF_OPENGL_FRAGMENT_SHADER_RGBA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
268     { AV_PIX_FMT_GRAY8,      &FF_OPENGL_FRAGMENT_SHADER_GRAY,        FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
269     { AV_PIX_FMT_GRAY16,     &FF_OPENGL_FRAGMENT_SHADER_GRAY,        FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
270     { AV_PIX_FMT_NONE,       NULL }
271 };
272
273 static av_cold int opengl_prepare_vertex(AVFormatContext *s);
274 static int opengl_draw(AVFormatContext *h, AVPacket *pkt, int repaint);
275 static av_cold int opengl_init_context(OpenGLContext *opengl);
276
277 static av_cold void opengl_deinit_context(OpenGLContext *opengl)
278 {
279     glDeleteTextures(4, opengl->texture_name);
280     opengl->texture_name[0] = opengl->texture_name[1] =
281     opengl->texture_name[2] = opengl->texture_name[3] = 0;
282     if (opengl->glprocs.glUseProgram)
283         opengl->glprocs.glUseProgram(0);
284     if (opengl->glprocs.glDeleteProgram) {
285         opengl->glprocs.glDeleteProgram(opengl->program);
286         opengl->program = 0;
287     }
288     if (opengl->glprocs.glDeleteShader) {
289         opengl->glprocs.glDeleteShader(opengl->vertex_shader);
290         opengl->glprocs.glDeleteShader(opengl->fragment_shader);
291         opengl->vertex_shader = opengl->fragment_shader = 0;
292     }
293     if (opengl->glprocs.glBindBuffer) {
294         opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, 0);
295         opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, 0);
296     }
297     if (opengl->glprocs.glDeleteBuffers) {
298         opengl->glprocs.glDeleteBuffers(2, &opengl->index_buffer);
299         opengl->vertex_buffer = opengl->index_buffer = 0;
300     }
301 }
302
303 static int opengl_resize(AVFormatContext *h, int width, int height)
304 {
305     int ret = 0;
306     OpenGLContext *opengl = h->priv_data;
307     opengl->window_width = width;
308     opengl->window_height = height;
309     /* max_viewport_width == 0 means write_header was not called yet. */
310     if (opengl->max_viewport_width) {
311         if (opengl->no_window &&
312             (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
313             av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
314             goto end;
315         }
316         if ((ret = opengl_prepare_vertex(h)) < 0)
317             goto end;
318         ret = opengl_draw(h, NULL, 1);
319     }
320   end:
321     return ret;
322 }
323
324 static int opengl_control_message(AVFormatContext *h, int type, void *data, size_t data_size)
325 {
326     OpenGLContext *opengl = h->priv_data;
327     switch(type) {
328     case AV_APP_TO_DEV_WINDOW_SIZE:
329         if (data) {
330             AVDeviceRect *message = data;
331             return opengl_resize(h, message->width, message->height);
332         }
333         return AVERROR(EINVAL);
334     case AV_APP_TO_DEV_WINDOW_REPAINT:
335         return opengl_resize(h, opengl->window_width, opengl->window_height);
336     }
337     return AVERROR(ENOSYS);
338 }
339
340 #if HAVE_SDL
341 static int opengl_sdl_recreate_window(OpenGLContext *opengl, int width, int height)
342 {
343     opengl->surface = SDL_SetVideoMode(width, height,
344                                        32, SDL_OPENGL | SDL_RESIZABLE);
345     if (!opengl->surface) {
346         av_log(opengl, AV_LOG_ERROR, "Unable to set video mode: %s\n", SDL_GetError());
347         return AVERROR_EXTERNAL;
348     }
349     SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
350     SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
351     SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
352     SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
353     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
354     return 0;
355 }
356
357 static int opengl_sdl_process_events(AVFormatContext *h)
358 {
359     int ret;
360     OpenGLContext *opengl = h->priv_data;
361     SDL_Event event;
362     SDL_PumpEvents();
363     while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_ALLEVENTS) > 0) {
364         switch (event.type) {
365         case SDL_QUIT:
366             return AVERROR(EIO);
367         case SDL_KEYDOWN:
368             switch (event.key.keysym.sym) {
369             case SDLK_ESCAPE:
370             case SDLK_q:
371                 return AVERROR(EIO);
372             }
373             return 0;
374         case SDL_VIDEORESIZE: {
375             char buffer[100];
376             int reinit;
377             AVDeviceRect message;
378             /* clean up old context because SDL_SetVideoMode may lose its state. */
379             SDL_VideoDriverName(buffer, sizeof(buffer));
380             reinit = !av_strncasecmp(buffer, "quartz", sizeof(buffer));
381             if (reinit) {
382                 opengl_deinit_context(opengl);
383             }
384             if ((ret = opengl_sdl_recreate_window(opengl, event.resize.w, event.resize.h)) < 0)
385                 return ret;
386             if (reinit && (ret = opengl_init_context(opengl)) < 0)
387                 return ret;
388             message.width = opengl->surface->w;
389             message.height = opengl->surface->h;
390             return opengl_control_message(h, AV_APP_TO_DEV_WINDOW_SIZE, &message, sizeof(AVDeviceRect));
391             }
392         }
393     }
394     return 0;
395 }
396
397 static int av_cold opengl_sdl_create_window(AVFormatContext *h)
398 {
399     int ret;
400     char buffer[100];
401     OpenGLContext *opengl = h->priv_data;
402     AVDeviceRect message;
403     if (SDL_Init(SDL_INIT_VIDEO)) {
404         av_log(opengl, AV_LOG_ERROR, "Unable to initialize SDL: %s\n", SDL_GetError());
405         return AVERROR_EXTERNAL;
406     }
407     if ((ret = opengl_sdl_recreate_window(opengl, opengl->width, opengl->height)) < 0)
408         return ret;
409     av_log(opengl, AV_LOG_INFO, "SDL driver: '%s'.\n", SDL_VideoDriverName(buffer, sizeof(buffer)));
410     message.width = opengl->surface->w;
411     message.height = opengl->surface->h;
412     SDL_WM_SetCaption(opengl->window_title, NULL);
413     opengl_control_message(h, AV_APP_TO_DEV_WINDOW_SIZE, &message, sizeof(AVDeviceRect));
414     return 0;
415 }
416
417 static int av_cold opengl_sdl_load_procedures(OpenGLContext *opengl)
418 {
419     FFOpenGLFunctions *procs = &opengl->glprocs;
420
421 #define LOAD_OPENGL_FUN(name, type) \
422     procs->name = (type)SDL_GL_GetProcAddress(#name); \
423     if (!procs->name) { \
424         av_log(opengl, AV_LOG_ERROR, "Cannot load OpenGL function: '%s'\n", #name); \
425         return AVERROR(ENOSYS); \
426     }
427
428     LOAD_OPENGL_FUN(glActiveTexture, FF_PFNGLACTIVETEXTUREPROC)
429     LOAD_OPENGL_FUN(glGenBuffers, FF_PFNGLGENBUFFERSPROC)
430     LOAD_OPENGL_FUN(glDeleteBuffers, FF_PFNGLDELETEBUFFERSPROC)
431     LOAD_OPENGL_FUN(glBufferData, FF_PFNGLBUFFERDATAPROC)
432     LOAD_OPENGL_FUN(glBindBuffer, FF_PFNGLBINDBUFFERPROC)
433     LOAD_OPENGL_FUN(glGetAttribLocation, FF_PFNGLGETATTRIBLOCATIONPROC)
434     LOAD_OPENGL_FUN(glGetUniformLocation, FF_PFNGLGETUNIFORMLOCATIONPROC)
435     LOAD_OPENGL_FUN(glUniform1f, FF_PFNGLUNIFORM1FPROC)
436     LOAD_OPENGL_FUN(glUniform1i, FF_PFNGLUNIFORM1IPROC)
437     LOAD_OPENGL_FUN(glUniformMatrix4fv, FF_PFNGLUNIFORMMATRIX4FVPROC)
438     LOAD_OPENGL_FUN(glCreateProgram, FF_PFNGLCREATEPROGRAMPROC)
439     LOAD_OPENGL_FUN(glDeleteProgram, FF_PFNGLDELETEPROGRAMPROC)
440     LOAD_OPENGL_FUN(glUseProgram, FF_PFNGLUSEPROGRAMPROC)
441     LOAD_OPENGL_FUN(glLinkProgram, FF_PFNGLLINKPROGRAMPROC)
442     LOAD_OPENGL_FUN(glGetProgramiv, FF_PFNGLGETPROGRAMIVPROC)
443     LOAD_OPENGL_FUN(glGetProgramInfoLog, FF_PFNGLGETPROGRAMINFOLOGPROC)
444     LOAD_OPENGL_FUN(glAttachShader, FF_PFNGLATTACHSHADERPROC)
445     LOAD_OPENGL_FUN(glCreateShader, FF_PFNGLCREATESHADERPROC)
446     LOAD_OPENGL_FUN(glDeleteShader, FF_PFNGLDELETESHADERPROC)
447     LOAD_OPENGL_FUN(glCompileShader, FF_PFNGLCOMPILESHADERPROC)
448     LOAD_OPENGL_FUN(glShaderSource, FF_PFNGLSHADERSOURCEPROC)
449     LOAD_OPENGL_FUN(glGetShaderiv, FF_PFNGLGETSHADERIVPROC)
450     LOAD_OPENGL_FUN(glGetShaderInfoLog, FF_PFNGLGETSHADERINFOLOGPROC)
451     LOAD_OPENGL_FUN(glEnableVertexAttribArray, FF_PFNGLENABLEVERTEXATTRIBARRAYPROC)
452     LOAD_OPENGL_FUN(glVertexAttribPointer, FF_PFNGLVERTEXATTRIBPOINTERPROC)
453
454     return 0;
455
456 #undef LOAD_OPENGL_FUN
457 }
458 #endif /* HAVE_SDL */
459
460 #if defined(__APPLE__)
461 static int av_cold opengl_load_procedures(OpenGLContext *opengl)
462 {
463     FFOpenGLFunctions *procs = &opengl->glprocs;
464
465 #if HAVE_SDL
466     if (!opengl->no_window)
467         return opengl_sdl_load_procedures(opengl);
468 #endif
469
470     procs->glActiveTexture = glActiveTexture;
471     procs->glGenBuffers = glGenBuffers;
472     procs->glDeleteBuffers = glDeleteBuffers;
473     procs->glBufferData = glBufferData;
474     procs->glBindBuffer = glBindBuffer;
475     procs->glGetAttribLocation = glGetAttribLocation;
476     procs->glGetUniformLocation = glGetUniformLocation;
477     procs->glUniform1f = glUniform1f;
478     procs->glUniform1i = glUniform1i;
479     procs->glUniformMatrix4fv = glUniformMatrix4fv;
480     procs->glCreateProgram = glCreateProgram;
481     procs->glDeleteProgram = glDeleteProgram;
482     procs->glUseProgram = glUseProgram;
483     procs->glLinkProgram = glLinkProgram;
484     procs->glGetProgramiv = glGetProgramiv;
485     procs->glGetProgramInfoLog = glGetProgramInfoLog;
486     procs->glAttachShader = glAttachShader;
487     procs->glCreateShader = glCreateShader;
488     procs->glDeleteShader = glDeleteShader;
489     procs->glCompileShader = glCompileShader;
490     procs->glShaderSource = glShaderSource;
491     procs->glGetShaderiv = glGetShaderiv;
492     procs->glGetShaderInfoLog = glGetShaderInfoLog;
493     procs->glEnableVertexAttribArray = glEnableVertexAttribArray;
494     procs->glVertexAttribPointer = (FF_PFNGLVERTEXATTRIBPOINTERPROC) glVertexAttribPointer;
495     return 0;
496 }
497 #else
498 static int av_cold opengl_load_procedures(OpenGLContext *opengl)
499 {
500     FFOpenGLFunctions *procs = &opengl->glprocs;
501
502 #if HAVE_GLXGETPROCADDRESS
503 #define SelectedGetProcAddress glXGetProcAddress
504 #elif HAVE_WGLGETPROCADDRESS
505 #define SelectedGetProcAddress wglGetProcAddress
506 #endif
507
508 #define LOAD_OPENGL_FUN(name, type) \
509     procs->name = (type)SelectedGetProcAddress(#name); \
510     if (!procs->name) { \
511         av_log(opengl, AV_LOG_ERROR, "Cannot load OpenGL function: '%s'\n", #name); \
512         return AVERROR(ENOSYS); \
513     }
514
515 #if HAVE_SDL
516     if (!opengl->no_window)
517         return opengl_sdl_load_procedures(opengl);
518 #endif
519
520     LOAD_OPENGL_FUN(glActiveTexture, FF_PFNGLACTIVETEXTUREPROC)
521     LOAD_OPENGL_FUN(glGenBuffers, FF_PFNGLGENBUFFERSPROC)
522     LOAD_OPENGL_FUN(glDeleteBuffers, FF_PFNGLDELETEBUFFERSPROC)
523     LOAD_OPENGL_FUN(glBufferData, FF_PFNGLBUFFERDATAPROC)
524     LOAD_OPENGL_FUN(glBindBuffer, FF_PFNGLBINDBUFFERPROC)
525     LOAD_OPENGL_FUN(glGetAttribLocation, FF_PFNGLGETATTRIBLOCATIONPROC)
526     LOAD_OPENGL_FUN(glGetUniformLocation, FF_PFNGLGETUNIFORMLOCATIONPROC)
527     LOAD_OPENGL_FUN(glUniform1f, FF_PFNGLUNIFORM1FPROC)
528     LOAD_OPENGL_FUN(glUniform1i, FF_PFNGLUNIFORM1IPROC)
529     LOAD_OPENGL_FUN(glUniformMatrix4fv, FF_PFNGLUNIFORMMATRIX4FVPROC)
530     LOAD_OPENGL_FUN(glCreateProgram, FF_PFNGLCREATEPROGRAMPROC)
531     LOAD_OPENGL_FUN(glDeleteProgram, FF_PFNGLDELETEPROGRAMPROC)
532     LOAD_OPENGL_FUN(glUseProgram, FF_PFNGLUSEPROGRAMPROC)
533     LOAD_OPENGL_FUN(glLinkProgram, FF_PFNGLLINKPROGRAMPROC)
534     LOAD_OPENGL_FUN(glGetProgramiv, FF_PFNGLGETPROGRAMIVPROC)
535     LOAD_OPENGL_FUN(glGetProgramInfoLog, FF_PFNGLGETPROGRAMINFOLOGPROC)
536     LOAD_OPENGL_FUN(glAttachShader, FF_PFNGLATTACHSHADERPROC)
537     LOAD_OPENGL_FUN(glCreateShader, FF_PFNGLCREATESHADERPROC)
538     LOAD_OPENGL_FUN(glDeleteShader, FF_PFNGLDELETESHADERPROC)
539     LOAD_OPENGL_FUN(glCompileShader, FF_PFNGLCOMPILESHADERPROC)
540     LOAD_OPENGL_FUN(glShaderSource, FF_PFNGLSHADERSOURCEPROC)
541     LOAD_OPENGL_FUN(glGetShaderiv, FF_PFNGLGETSHADERIVPROC)
542     LOAD_OPENGL_FUN(glGetShaderInfoLog, FF_PFNGLGETSHADERINFOLOGPROC)
543     LOAD_OPENGL_FUN(glEnableVertexAttribArray, FF_PFNGLENABLEVERTEXATTRIBARRAYPROC)
544     LOAD_OPENGL_FUN(glVertexAttribPointer, FF_PFNGLVERTEXATTRIBPOINTERPROC)
545
546     return 0;
547
548 #undef SelectedGetProcAddress
549 #undef LOAD_OPENGL_FUN
550 }
551 #endif
552
553 static void opengl_make_identity(float matrix[16])
554 {
555     memset(matrix, 0, 16 * sizeof(float));
556     matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1.0f;
557 }
558
559 static void opengl_make_ortho(float matrix[16], float left, float right,
560                               float bottom, float top, float nearZ, float farZ)
561 {
562     float ral = right + left;
563     float rsl = right - left;
564     float tab = top + bottom;
565     float tsb = top - bottom;
566     float fan = farZ + nearZ;
567     float fsn = farZ - nearZ;
568
569     memset(matrix, 0, 16 * sizeof(float));
570     matrix[0] = 2.0f / rsl;
571     matrix[5] = 2.0f / tsb;
572     matrix[10] = -2.0f / fsn;
573     matrix[12] = -ral / rsl;
574     matrix[13] = -tab / tsb;
575     matrix[14] = -fan / fsn;
576     matrix[15] = 1.0f;
577 }
578
579 static av_cold int opengl_read_limits(OpenGLContext *opengl)
580 {
581     static const struct{
582         const char *extention;
583         int major;
584         int minor;
585     } required_extensions[] = {
586         { "GL_ARB_multitexture",         1, 3 },
587         { "GL_ARB_vertex_buffer_object", 1, 5 }, //GLX_ARB_vertex_buffer_object
588         { "GL_ARB_vertex_shader",        2, 0 },
589         { "GL_ARB_fragment_shader",      2, 0 },
590         { "GL_ARB_shader_objects",       2, 0 },
591         { NULL,                          0, 0 }
592     };
593     int i, major, minor;
594     const char *extensions, *version;
595
596     version = glGetString(GL_VERSION);
597     extensions = glGetString(GL_EXTENSIONS);
598
599     av_log(opengl, AV_LOG_DEBUG, "OpenGL version: %s\n", version);
600     sscanf(version, "%d.%d", &major, &minor);
601
602     for (i = 0; required_extensions[i].extention; i++) {
603         if (major < required_extensions[i].major &&
604             (major == required_extensions[i].major && minor < required_extensions[i].minor) &&
605             !strstr(extensions, required_extensions[i].extention)) {
606             av_log(opengl, AV_LOG_ERROR, "Required extension %s is not supported.\n",
607                    required_extensions[i].extention);
608             av_log(opengl, AV_LOG_DEBUG, "Supported extensions are: %s\n", extensions);
609             return AVERROR(ENOSYS);
610         }
611     }
612     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &opengl->max_texture_size);
613     glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &opengl->max_viewport_width);
614     opengl->non_pow_2_textures = major >= 2 || strstr(extensions, "GL_ARB_texture_non_power_of_two");
615
616     av_log(opengl, AV_LOG_DEBUG, "Non Power of 2 textures support: %s\n", opengl->non_pow_2_textures ? "Yes" : "No");
617     av_log(opengl, AV_LOG_DEBUG, "Max texture size: %dx%d\n", opengl->max_texture_size, opengl->max_texture_size);
618     av_log(opengl, AV_LOG_DEBUG, "Max viewport size: %dx%d\n",
619            opengl->max_viewport_width, opengl->max_viewport_height);
620
621     OPENGL_ERROR_CHECK(opengl);
622     return 0;
623   fail:
624     return AVERROR_EXTERNAL;
625 }
626
627 static const char* opengl_get_fragment_shader_code(enum AVPixelFormat format)
628 {
629     int i;
630     for (i = 0; i < FF_ARRAY_ELEMS(opengl_format_desc); i++) {
631         if (opengl_format_desc[i].fixel_format == format)
632             return *opengl_format_desc[i].fragment_shader;
633     }
634     return NULL;
635 }
636
637 static int opengl_type_size(GLenum type)
638 {
639     switch(type) {
640     case GL_UNSIGNED_SHORT:
641     case FF_GL_UNSIGNED_SHORT_1_5_5_5_REV:
642     case GL_UNSIGNED_SHORT_5_6_5:
643         return 2;
644     case GL_UNSIGNED_BYTE:
645     case FF_GL_UNSIGNED_BYTE_3_3_2:
646     case FF_GL_UNSIGNED_BYTE_2_3_3_REV:
647     default:
648         break;
649     }
650     return 1;
651 }
652
653 static av_cold void opengl_get_texture_params(OpenGLContext *opengl)
654 {
655     int i;
656     for (i = 0; i < FF_ARRAY_ELEMS(opengl_format_desc); i++) {
657         if (opengl_format_desc[i].fixel_format == opengl->pix_fmt) {
658             opengl->format = opengl_format_desc[i].format;
659             opengl->type = opengl_format_desc[i].type;
660             break;
661         }
662     }
663 }
664
665 static void opengl_compute_display_area(AVFormatContext *s)
666 {
667     AVRational sar, dar; /* sample and display aspect ratios */
668     OpenGLContext *opengl = s->priv_data;
669     AVStream *st = s->streams[0];
670     AVCodecContext *encctx = st->codec;
671
672     /* compute overlay width and height from the codec context information */
673     sar = st->sample_aspect_ratio.num ? st->sample_aspect_ratio : (AVRational){ 1, 1 };
674     dar = av_mul_q(sar, (AVRational){ encctx->width, encctx->height });
675
676     /* we suppose the screen has a 1/1 sample aspect ratio */
677     /* fit in the window */
678     if (av_cmp_q(dar, (AVRational){ opengl->window_width, opengl->window_height }) > 0) {
679         /* fit in width */
680         opengl->picture_width = opengl->window_width;
681         opengl->picture_height = av_rescale(opengl->picture_width, dar.den, dar.num);
682     } else {
683         /* fit in height */
684         opengl->picture_height = opengl->window_height;
685         opengl->picture_width = av_rescale(opengl->picture_height, dar.num, dar.den);
686     }
687 }
688
689 static av_cold void opengl_get_texture_size(OpenGLContext *opengl, int in_width, int in_height,
690                                             int *out_width, int *out_height)
691 {
692     if (opengl->non_pow_2_textures) {
693         *out_width = in_width;
694         *out_height = in_height;
695     } else {
696         int max = FFMIN(FFMAX(in_width, in_height), opengl->max_texture_size);
697         unsigned power_of_2 = 1;
698         while (power_of_2 < max)
699             power_of_2 *= 2;
700         *out_height = power_of_2;
701         *out_width = power_of_2;
702         av_log(opengl, AV_LOG_DEBUG, "Texture size calculated from %dx%d into %dx%d\n",
703                in_width, in_height, *out_width, *out_height);
704     }
705 }
706
707 static av_cold void opengl_fill_color_map(OpenGLContext *opengl)
708 {
709     const AVPixFmtDescriptor *desc;
710     int shift;
711     enum AVPixelFormat pix_fmt = opengl->pix_fmt;
712
713     /* We need order of components, not exact position, some minor HACKs here */
714     if (pix_fmt == AV_PIX_FMT_RGB565 || pix_fmt == AV_PIX_FMT_BGR555 ||
715         pix_fmt == AV_PIX_FMT_BGR8   || pix_fmt == AV_PIX_FMT_RGB8)
716         pix_fmt = AV_PIX_FMT_RGB24;
717     else if (pix_fmt == AV_PIX_FMT_BGR565 || pix_fmt == AV_PIX_FMT_RGB555)
718         pix_fmt = AV_PIX_FMT_BGR24;
719
720     desc = av_pix_fmt_desc_get(pix_fmt);
721     if (!(desc->flags & AV_PIX_FMT_FLAG_RGB))
722         return;
723
724 #define FILL_COMPONENT(i) { \
725         shift = desc->comp[i].depth_minus1 >> 3; \
726         opengl->color_map[(i << 2) + ((desc->comp[i].offset_plus1 - 1) >> shift)] = 1.0; \
727     }
728
729     memset(opengl->color_map, 0, sizeof(opengl->color_map));
730     FILL_COMPONENT(0);
731     FILL_COMPONENT(1);
732     FILL_COMPONENT(2);
733     if (desc->flags & AV_PIX_FMT_FLAG_ALPHA)
734         FILL_COMPONENT(3);
735
736 #undef FILL_COMPONENT
737 }
738
739 static av_cold GLuint opengl_load_shader(OpenGLContext *opengl, GLenum type, const char *source)
740 {
741     GLuint shader = opengl->glprocs.glCreateShader(type);
742     GLint result;
743     if (!shader) {
744         av_log(opengl, AV_LOG_ERROR, "glCreateShader() failed\n");
745         return 0;
746     }
747     opengl->glprocs.glShaderSource(shader, 1, &source, NULL);
748     opengl->glprocs.glCompileShader(shader);
749
750     opengl->glprocs.glGetShaderiv(shader, FF_GL_COMPILE_STATUS, &result);
751     if (!result) {
752         char *log;
753         opengl->glprocs.glGetShaderiv(shader, FF_GL_INFO_LOG_LENGTH, &result);
754         if (result) {
755             if ((log = av_malloc(result))) {
756                 opengl->glprocs.glGetShaderInfoLog(shader, result, NULL, log);
757                 av_log(opengl, AV_LOG_ERROR, "Compile error: %s\n", log);
758                 av_free(log);
759             }
760         }
761         goto fail;
762     }
763     OPENGL_ERROR_CHECK(opengl);
764     return shader;
765   fail:
766     opengl->glprocs.glDeleteShader(shader);
767     return 0;
768 }
769
770 static av_cold int opengl_compile_shaders(OpenGLContext *opengl, enum AVPixelFormat pix_fmt)
771 {
772     GLint result;
773     const char *fragment_shader_code = opengl_get_fragment_shader_code(pix_fmt);
774
775     if (!fragment_shader_code) {
776         av_log(opengl, AV_LOG_ERROR, "Provided pixel format '%s' is not supported\n",
777                av_get_pix_fmt_name(pix_fmt));
778         return AVERROR(EINVAL);
779     }
780
781     opengl->vertex_shader = opengl_load_shader(opengl, FF_GL_VERTEX_SHADER,
782                                                FF_OPENGL_VERTEX_SHADER);
783     if (!opengl->vertex_shader) {
784         av_log(opengl, AV_LOG_ERROR, "Vertex shader loading failed.\n");
785         goto fail;
786     }
787     opengl->fragment_shader = opengl_load_shader(opengl, FF_GL_FRAGMENT_SHADER,
788                                                  fragment_shader_code);
789     if (!opengl->fragment_shader) {
790         av_log(opengl, AV_LOG_ERROR, "Fragment shader loading failed.\n");
791         goto fail;
792     }
793
794     opengl->program = opengl->glprocs.glCreateProgram();
795     if (!opengl->program)
796         goto fail;
797
798     opengl->glprocs.glAttachShader(opengl->program, opengl->vertex_shader);
799     opengl->glprocs.glAttachShader(opengl->program, opengl->fragment_shader);
800     opengl->glprocs.glLinkProgram(opengl->program);
801
802     opengl->glprocs.glGetProgramiv(opengl->program, FF_GL_LINK_STATUS, &result);
803     if (!result) {
804         char *log;
805         opengl->glprocs.glGetProgramiv(opengl->program, FF_GL_INFO_LOG_LENGTH, &result);
806         if (result) {
807             log = av_malloc(result);
808             if (!log)
809                 goto fail;
810             opengl->glprocs.glGetProgramInfoLog(opengl->program, result, NULL, log);
811             av_log(opengl, AV_LOG_ERROR, "Link error: %s\n", log);
812             av_free(log);
813         }
814         goto fail;
815     }
816
817     opengl->position_attrib = opengl->glprocs.glGetAttribLocation(opengl->program, "a_position");
818     opengl->texture_coords_attrib = opengl->glprocs.glGetAttribLocation(opengl->program, "a_textureCoords");
819     opengl->projection_matrix_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_projectionMatrix");
820     opengl->model_view_matrix_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_modelViewMatrix");
821     opengl->color_map_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_colorMap");
822     opengl->texture_location[0] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture0");
823     opengl->texture_location[1] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture1");
824     opengl->texture_location[2] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture2");
825     opengl->texture_location[3] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture3");
826     opengl->chroma_div_w_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_chroma_div_w");
827     opengl->chroma_div_h_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_chroma_div_h");
828
829     OPENGL_ERROR_CHECK(opengl);
830     return 0;
831   fail:
832     opengl->glprocs.glDeleteShader(opengl->vertex_shader);
833     opengl->glprocs.glDeleteShader(opengl->fragment_shader);
834     opengl->glprocs.glDeleteProgram(opengl->program);
835     opengl->fragment_shader = opengl->vertex_shader = opengl->program = 0;
836     return AVERROR_EXTERNAL;
837 }
838
839 static av_cold int opengl_configure_texture(OpenGLContext *opengl, GLuint texture,
840                                             GLsizei width, GLsizei height)
841 {
842     if (texture) {
843         int new_width, new_height;
844         opengl_get_texture_size(opengl, width, height, &new_width, &new_height);
845         glBindTexture(GL_TEXTURE_2D, texture);
846         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
847         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
848         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
849         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
850         glTexImage2D(GL_TEXTURE_2D, 0, opengl->format, new_width, new_height, 0,
851                      opengl->format, opengl->type, NULL);
852         OPENGL_ERROR_CHECK(NULL);
853     }
854     return 0;
855   fail:
856     return AVERROR_EXTERNAL;
857 }
858
859 static av_cold int opengl_prepare_vertex(AVFormatContext *s)
860 {
861     OpenGLContext *opengl = s->priv_data;
862     int tex_w, tex_h;
863
864     if (opengl->window_width > opengl->max_viewport_width || opengl->window_height > opengl->max_viewport_height) {
865         opengl->window_width = FFMAX(opengl->window_width, opengl->max_viewport_width);
866         opengl->window_height = FFMAX(opengl->window_height, opengl->max_viewport_height);
867         av_log(opengl, AV_LOG_WARNING, "Too big viewport requested, limited to %dx%d", opengl->window_width, opengl->window_height);
868     }
869     glViewport(0, 0, opengl->window_width, opengl->window_height);
870     opengl_make_ortho(opengl->projection_matrix,
871                       - (float)opengl->window_width  / 2.0f, (float)opengl->window_width  / 2.0f,
872                       - (float)opengl->window_height / 2.0f, (float)opengl->window_height / 2.0f,
873                       1.0f, -1.0f);
874     opengl_make_identity(opengl->model_view_matrix);
875
876     opengl_compute_display_area(s);
877
878     opengl->vertex[0].z = opengl->vertex[1].z = opengl->vertex[2].z = opengl->vertex[3].z = 0.0f;
879     opengl->vertex[0].x = opengl->vertex[1].x = - (float)opengl->picture_width / 2.0f;
880     opengl->vertex[2].x = opengl->vertex[3].x =   (float)opengl->picture_width / 2.0f;
881     opengl->vertex[1].y = opengl->vertex[2].y = - (float)opengl->picture_height / 2.0f;
882     opengl->vertex[0].y = opengl->vertex[3].y =   (float)opengl->picture_height / 2.0f;
883
884     opengl_get_texture_size(opengl, opengl->width, opengl->height, &tex_w, &tex_h);
885
886     opengl->vertex[0].s0 = 0.0f;
887     opengl->vertex[0].t0 = 0.0f;
888     opengl->vertex[1].s0 = 0.0f;
889     opengl->vertex[1].t0 = (float)opengl->height / (float)tex_h;
890     opengl->vertex[2].s0 = (float)opengl->width  / (float)tex_w;
891     opengl->vertex[2].t0 = (float)opengl->height / (float)tex_h;
892     opengl->vertex[3].s0 = (float)opengl->width  / (float)tex_w;
893     opengl->vertex[3].t0 = 0.0f;
894
895     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, opengl->vertex_buffer);
896     opengl->glprocs.glBufferData(FF_GL_ARRAY_BUFFER, sizeof(opengl->vertex), opengl->vertex, FF_GL_STATIC_DRAW);
897     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, 0);
898     OPENGL_ERROR_CHECK(opengl);
899     return 0;
900   fail:
901     return AVERROR_EXTERNAL;
902 }
903
904 static int opengl_prepare(OpenGLContext *opengl)
905 {
906     int i;
907     opengl->glprocs.glUseProgram(opengl->program);
908     opengl->glprocs.glUniformMatrix4fv(opengl->projection_matrix_location, 1, GL_FALSE, opengl->projection_matrix);
909     opengl->glprocs.glUniformMatrix4fv(opengl->model_view_matrix_location, 1, GL_FALSE, opengl->model_view_matrix);
910     for (i = 0; i < 4; i++)
911         if (opengl->texture_location[i] != -1) {
912             opengl->glprocs.glActiveTexture(GL_TEXTURE0 + i);
913             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[i]);
914             opengl->glprocs.glUniform1i(opengl->texture_location[i], i);
915         }
916     if (opengl->color_map_location != -1)
917         opengl->glprocs.glUniformMatrix4fv(opengl->color_map_location, 1, GL_FALSE, opengl->color_map);
918     if (opengl->chroma_div_h_location != -1)
919         opengl->glprocs.glUniform1f(opengl->chroma_div_h_location, opengl->chroma_div_h);
920     if (opengl->chroma_div_w_location != -1)
921         opengl->glprocs.glUniform1f(opengl->chroma_div_w_location, opengl->chroma_div_w);
922
923     OPENGL_ERROR_CHECK(opengl);
924     return 0;
925   fail:
926     return AVERROR_EXTERNAL;
927 }
928
929 static int opengl_create_window(AVFormatContext *h)
930 {
931     OpenGLContext *opengl = h->priv_data;
932     int ret;
933
934     if (!opengl->no_window) {
935 #if HAVE_SDL
936         if ((ret = opengl_sdl_create_window(h)) < 0) {
937             av_log(opengl, AV_LOG_ERROR, "Cannot create default SDL window.\n");
938             return ret;
939         }
940 #else
941         av_log(opengl, AV_LOG_ERROR, "FFmpeg is compiled without SDL. Cannot create default window.\n");
942         return AVERROR(ENOSYS);
943 #endif
944     } else {
945         if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_CREATE_WINDOW_BUFFER, NULL , 0)) < 0) {
946             av_log(opengl, AV_LOG_ERROR, "Application failed to create window buffer.\n");
947             return ret;
948         }
949         if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
950             av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
951             return ret;
952         }
953     }
954     return 0;
955 }
956
957 static int opengl_release_window(AVFormatContext *h)
958 {
959     int ret;
960     OpenGLContext *opengl = h->priv_data;
961     if (!opengl->no_window) {
962 #if HAVE_SDL
963         SDL_Quit();
964 #endif
965     } else if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DESTROY_WINDOW_BUFFER, NULL , 0)) < 0) {
966         av_log(opengl, AV_LOG_ERROR, "Application failed to release window buffer.\n");
967         return ret;
968     }
969     return 0;
970 }
971
972 static av_cold int opengl_write_trailer(AVFormatContext *h)
973 {
974     OpenGLContext *opengl = h->priv_data;
975
976     if (opengl->no_window &&
977         avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0) < 0)
978         av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
979
980     opengl_deinit_context(opengl);
981     opengl_release_window(h);
982
983     return 0;
984 }
985
986 static av_cold int opengl_init_context(OpenGLContext *opengl)
987 {
988     int i, ret;
989     const AVPixFmtDescriptor *desc;
990
991     if ((ret = opengl_compile_shaders(opengl, opengl->pix_fmt)) < 0)
992         goto fail;
993
994     desc = av_pix_fmt_desc_get(opengl->pix_fmt);
995     av_assert0(desc->nb_components > 0 && desc->nb_components <= 4);
996     glGenTextures(desc->nb_components, opengl->texture_name);
997
998     opengl->glprocs.glGenBuffers(2, &opengl->index_buffer);
999     if (!opengl->index_buffer || !opengl->vertex_buffer) {
1000         av_log(opengl, AV_LOG_ERROR, "Buffer generation failed.\n");
1001         ret = AVERROR_EXTERNAL;
1002         goto fail;
1003     }
1004
1005     opengl_configure_texture(opengl, opengl->texture_name[0], opengl->width, opengl->height);
1006     if (desc->nb_components > 1) {
1007         int has_alpha = desc->flags & AV_PIX_FMT_FLAG_ALPHA;
1008         int num_planes = desc->nb_components - (has_alpha ? 1 : 0);
1009         if (opengl->non_pow_2_textures) {
1010             opengl->chroma_div_w = 1.0f;
1011             opengl->chroma_div_h = 1.0f;
1012         } else {
1013             opengl->chroma_div_w = 1 << desc->log2_chroma_w;
1014             opengl->chroma_div_h = 1 << desc->log2_chroma_h;
1015         }
1016         for (i = 1; i < num_planes; i++)
1017             if (opengl->non_pow_2_textures)
1018                 opengl_configure_texture(opengl, opengl->texture_name[i],
1019                         FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w),
1020                         FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h));
1021             else
1022                 opengl_configure_texture(opengl, opengl->texture_name[i], opengl->width, opengl->height);
1023         if (has_alpha)
1024             opengl_configure_texture(opengl, opengl->texture_name[3], opengl->width, opengl->height);
1025     }
1026
1027     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, opengl->index_buffer);
1028     opengl->glprocs.glBufferData(FF_GL_ELEMENT_ARRAY_BUFFER, sizeof(g_index), g_index, FF_GL_STATIC_DRAW);
1029     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, 0);
1030
1031     glEnable(GL_BLEND);
1032     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1033
1034     glClearColor((float)opengl->background[0] / 255.0f, (float)opengl->background[1] / 255.0f,
1035                  (float)opengl->background[2] / 255.0f, 1.0f);
1036
1037     ret = AVERROR_EXTERNAL;
1038     OPENGL_ERROR_CHECK(opengl);
1039
1040     return 0;
1041   fail:
1042     return ret;
1043 }
1044
1045 static av_cold int opengl_write_header(AVFormatContext *h)
1046 {
1047     OpenGLContext *opengl = h->priv_data;
1048     AVStream *st;
1049     int ret;
1050
1051     if (h->nb_streams != 1 ||
1052         h->streams[0]->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
1053         h->streams[0]->codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
1054         av_log(opengl, AV_LOG_ERROR, "Only a single video stream is supported.\n");
1055         return AVERROR(EINVAL);
1056     }
1057     st = h->streams[0];
1058     opengl->width = st->codec->width;
1059     opengl->height = st->codec->height;
1060     opengl->pix_fmt = st->codec->pix_fmt;
1061
1062     if (!opengl->window_title && !opengl->no_window)
1063         opengl->window_title = av_strdup(h->filename);
1064
1065     if ((ret = opengl_create_window(h)))
1066         goto fail;
1067
1068     if ((ret = opengl_read_limits(opengl)) < 0)
1069         goto fail;
1070
1071     if (opengl->width > opengl->max_texture_size || opengl->height > opengl->max_texture_size) {
1072         av_log(opengl, AV_LOG_ERROR, "Too big picture %dx%d, max supported size is %dx%d\n",
1073                opengl->width, opengl->height, opengl->max_texture_size, opengl->max_texture_size);
1074         ret = AVERROR(EINVAL);
1075         goto fail;
1076     }
1077
1078     if ((ret = opengl_load_procedures(opengl)) < 0)
1079         goto fail;
1080
1081     opengl_fill_color_map(opengl);
1082     opengl_get_texture_params(opengl);
1083
1084     if ((ret = opengl_init_context(opengl)) < 0)
1085         goto fail;
1086
1087     if ((ret = opengl_prepare_vertex(h)) < 0)
1088         goto fail;
1089
1090     glClear(GL_COLOR_BUFFER_BIT);
1091
1092 #if HAVE_SDL
1093     if (!opengl->no_window)
1094         SDL_GL_SwapBuffers();
1095 #endif
1096     if (opengl->no_window &&
1097         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER, NULL , 0)) < 0) {
1098         av_log(opengl, AV_LOG_ERROR, "Application failed to display window buffer.\n");
1099         goto fail;
1100     }
1101
1102     ret = AVERROR_EXTERNAL;
1103     OPENGL_ERROR_CHECK(opengl);
1104     return 0;
1105
1106   fail:
1107     opengl_write_trailer(h);
1108     return ret;
1109 }
1110
1111 static uint8_t* opengl_get_plane_pointer(OpenGLContext *opengl, AVPacket *pkt, int comp_index,
1112                                          const AVPixFmtDescriptor *desc)
1113 {
1114     uint8_t *data = pkt->data;
1115     int wordsize = opengl_type_size(opengl->type);
1116     int width_chroma = FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w);
1117     int height_chroma = FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h);
1118     int plane = desc->comp[comp_index].plane;
1119
1120     switch(plane) {
1121     case 0:
1122         break;
1123     case 1:
1124         data += opengl->width * opengl->height * wordsize;
1125         break;
1126     case 2:
1127         data += opengl->width * opengl->height * wordsize;
1128         data += width_chroma * height_chroma * wordsize;
1129         break;
1130     case 3:
1131         data += opengl->width * opengl->height * wordsize;
1132         data += 2 * width_chroma * height_chroma * wordsize;
1133         break;
1134     default:
1135         return NULL;
1136     }
1137     return data;
1138 }
1139
1140 static int opengl_draw(AVFormatContext *h, AVPacket *pkt, int repaint)
1141 {
1142     OpenGLContext *opengl = h->priv_data;
1143     enum AVPixelFormat pix_fmt = h->streams[0]->codec->pix_fmt;
1144     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1145     int ret;
1146
1147 #if HAVE_SDL
1148     if (!opengl->no_window && (ret = opengl_sdl_process_events(h)) < 0)
1149         goto fail;
1150 #endif
1151     if (opengl->no_window &&
1152         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
1153         av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
1154         goto fail;
1155     }
1156
1157     glClear(GL_COLOR_BUFFER_BIT);
1158
1159     if (!repaint) {
1160         glBindTexture(GL_TEXTURE_2D, opengl->texture_name[0]);
1161         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, opengl->width, opengl->height, opengl->format, opengl->type,
1162                         opengl_get_plane_pointer(opengl, pkt, 0, desc));
1163         if (desc->flags & AV_PIX_FMT_FLAG_PLANAR) {
1164             int width_chroma = FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w);
1165             int height_chroma = FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h);
1166             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[1]);
1167             glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width_chroma, height_chroma, opengl->format, opengl->type,
1168                             opengl_get_plane_pointer(opengl, pkt, 1, desc));
1169             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[2]);
1170             glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width_chroma, height_chroma, opengl->format, opengl->type,
1171                             opengl_get_plane_pointer(opengl, pkt, 2, desc));
1172             if (desc->flags & AV_PIX_FMT_FLAG_ALPHA) {
1173                 glBindTexture(GL_TEXTURE_2D, opengl->texture_name[3]);
1174                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, opengl->width, opengl->height, opengl->format, opengl->type,
1175                                 opengl_get_plane_pointer(opengl, pkt, 3, desc));
1176             }
1177         }
1178     }
1179     ret = AVERROR_EXTERNAL;
1180     OPENGL_ERROR_CHECK(opengl);
1181
1182     if ((ret = opengl_prepare(opengl)) < 0)
1183         goto fail;
1184
1185     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, opengl->vertex_buffer);
1186     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, opengl->index_buffer);
1187     opengl->glprocs.glVertexAttribPointer(opengl->position_attrib, 3, GL_FLOAT, GL_FALSE, sizeof(OpenGLVertexInfo), 0);
1188     opengl->glprocs.glEnableVertexAttribArray(opengl->position_attrib);
1189     opengl->glprocs.glVertexAttribPointer(opengl->texture_coords_attrib, 2, GL_FLOAT, GL_FALSE, sizeof(OpenGLVertexInfo), 12);
1190     opengl->glprocs.glEnableVertexAttribArray(opengl->texture_coords_attrib);
1191
1192     glDrawElements(GL_TRIANGLES, FF_ARRAY_ELEMS(g_index), GL_UNSIGNED_SHORT, 0);
1193
1194     ret = AVERROR_EXTERNAL;
1195     OPENGL_ERROR_CHECK(opengl);
1196
1197 #if HAVE_SDL
1198     if (!opengl->no_window)
1199         SDL_GL_SwapBuffers();
1200 #endif
1201     if (opengl->no_window &&
1202         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER, NULL , 0)) < 0) {
1203         av_log(opengl, AV_LOG_ERROR, "Application failed to display window buffer.\n");
1204         goto fail;
1205     }
1206
1207     return 0;
1208   fail:
1209     return ret;
1210 }
1211
1212 static int opengl_write_packet(AVFormatContext *h, AVPacket *pkt)
1213 {
1214     return opengl_draw(h, pkt, 0);
1215 }
1216
1217 #define OFFSET(x) offsetof(OpenGLContext, x)
1218 #define ENC AV_OPT_FLAG_ENCODING_PARAM
1219 static const AVOption options[] = {
1220     { "background",   "set background color",   OFFSET(background),   AV_OPT_TYPE_COLOR,  {.str = "black"}, CHAR_MIN, CHAR_MAX, ENC },
1221     { "no_window",    "disable default window", OFFSET(no_window),    AV_OPT_TYPE_INT,    {.i64 = 0}, INT_MIN, INT_MAX, ENC },
1222     { "window_title", "set window title",       OFFSET(window_title), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, ENC },
1223     { NULL }
1224 };
1225
1226 static const AVClass opengl_class = {
1227     .class_name = "opengl outdev",
1228     .item_name  = av_default_item_name,
1229     .option     = options,
1230     .version    = LIBAVUTIL_VERSION_INT,
1231 };
1232
1233 AVOutputFormat ff_opengl_muxer = {
1234     .name           = "opengl",
1235     .long_name      = NULL_IF_CONFIG_SMALL("OpenGL output"),
1236     .priv_data_size = sizeof(OpenGLContext),
1237     .audio_codec    = AV_CODEC_ID_NONE,
1238     .video_codec    = AV_CODEC_ID_RAWVIDEO,
1239     .write_header   = opengl_write_header,
1240     .write_packet   = opengl_write_packet,
1241     .write_trailer  = opengl_write_trailer,
1242     .control_message = opengl_control_message,
1243     .flags          = AVFMT_NOFILE | AVFMT_VARIABLE_FPS | AVFMT_NOTIMESTAMPS,
1244     .priv_class     = &opengl_class,
1245 };