lavd/opengl_enc: factorize create/release window functions
[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 texture_name[4];            ///< Textures' IDs
192     GLuint index_buffer;               ///< Index buffer
193     GLuint vertex_buffer;              ///< Vertex buffer
194     OpenGLVertexInfo vertex[4];        ///< VBO
195     GLint projection_matrix_location;  ///< Uniforms' locations
196     GLint model_view_matrix_location;
197     GLint color_map_location;
198     GLint chroma_div_w_location;
199     GLint chroma_div_h_location;
200     GLint texture_location[4];
201     GLint position_attrib;             ///< Attibutes' locations
202     GLint texture_coords_attrib;
203
204     GLfloat projection_matrix[16];     ///< Projection matrix
205     GLfloat model_view_matrix[16];     ///< Modev view matrix
206     GLfloat color_map[16];             ///< RGBA color map matrix
207     GLfloat chroma_div_w;              ///< Chroma subsampling w ratio
208     GLfloat chroma_div_h;              ///< Chroma subsampling h ratio
209
210     /* Stream information */
211     GLenum format;
212     GLenum type;
213     int width;                         ///< Stream width
214     int height;                        ///< Stream height
215     enum AVPixelFormat pix_fmt;        ///< Stream pixel format
216     int picture_width;                 ///< Rendered width
217     int picture_height;                ///< Rendered height
218     int window_width;
219     int window_height;
220 } OpenGLContext;
221
222 static const struct OpenGLFormatDesc {
223     enum AVPixelFormat fixel_format;
224     const char * const * fragment_shader;
225     GLenum format;
226     GLenum type;
227 } opengl_format_desc[] = {
228     { AV_PIX_FMT_YUV420P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
229     { AV_PIX_FMT_YUV444P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
230     { AV_PIX_FMT_YUV422P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
231     { AV_PIX_FMT_YUV410P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
232     { AV_PIX_FMT_YUV411P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
233     { AV_PIX_FMT_YUV440P,    &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
234     { AV_PIX_FMT_YUV420P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
235     { AV_PIX_FMT_YUV422P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
236     { AV_PIX_FMT_YUV444P16,  &FF_OPENGL_FRAGMENT_SHADER_YUV_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
237     { AV_PIX_FMT_YUVA420P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
238     { AV_PIX_FMT_YUVA444P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
239     { AV_PIX_FMT_YUVA422P,   &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
240     { AV_PIX_FMT_YUVA420P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
241     { AV_PIX_FMT_YUVA422P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
242     { AV_PIX_FMT_YUVA444P16, &FF_OPENGL_FRAGMENT_SHADER_YUVA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
243     { AV_PIX_FMT_RGB24,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_BYTE },
244     { AV_PIX_FMT_BGR24,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_BYTE },
245     { AV_PIX_FMT_0RGB,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
246     { AV_PIX_FMT_RGB0,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
247     { AV_PIX_FMT_0BGR,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
248     { AV_PIX_FMT_BGR0,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, GL_UNSIGNED_BYTE },
249     { AV_PIX_FMT_RGB565,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT_5_6_5 },
250     { AV_PIX_FMT_BGR565,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT_5_6_5 },
251     { AV_PIX_FMT_RGB555,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, FF_GL_UNSIGNED_SHORT_1_5_5_5_REV },
252     { AV_PIX_FMT_BGR555,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGBA, FF_GL_UNSIGNED_SHORT_1_5_5_5_REV },
253     { AV_PIX_FMT_RGB8,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, FF_GL_UNSIGNED_BYTE_3_3_2 },
254     { AV_PIX_FMT_BGR8,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, FF_GL_UNSIGNED_BYTE_2_3_3_REV },
255     { AV_PIX_FMT_RGB48,      &FF_OPENGL_FRAGMENT_SHADER_RGB_PACKET,  GL_RGB, GL_UNSIGNED_SHORT },
256     { AV_PIX_FMT_ARGB,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
257     { AV_PIX_FMT_RGBA,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
258     { AV_PIX_FMT_ABGR,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
259     { AV_PIX_FMT_BGRA,       &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_BYTE },
260     { AV_PIX_FMT_RGBA64,     &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_SHORT },
261     { AV_PIX_FMT_BGRA64,     &FF_OPENGL_FRAGMENT_SHADER_RGBA_PACKET, GL_RGBA, GL_UNSIGNED_SHORT },
262     { AV_PIX_FMT_GBRP,       &FF_OPENGL_FRAGMENT_SHADER_RGB_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
263     { AV_PIX_FMT_GBRP16,     &FF_OPENGL_FRAGMENT_SHADER_RGB_PLANAR,  FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
264     { AV_PIX_FMT_GBRAP,      &FF_OPENGL_FRAGMENT_SHADER_RGBA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_BYTE },
265     { AV_PIX_FMT_GBRAP16,    &FF_OPENGL_FRAGMENT_SHADER_RGBA_PLANAR, FF_GL_RED_COMPONENT, GL_UNSIGNED_SHORT },
266     { AV_PIX_FMT_NONE,       NULL }
267 };
268
269 static av_cold int opengl_prepare_vertex(AVFormatContext *s);
270 static int opengl_draw(AVFormatContext *h, AVPacket *pkt, int repaint);
271 static av_cold int opengl_init_context(OpenGLContext *opengl);
272
273 static int opengl_resize(AVFormatContext *h, int width, int height)
274 {
275     int ret = 0;
276     OpenGLContext *opengl = h->priv_data;
277     opengl->window_width = width;
278     opengl->window_height = height;
279     /* max_viewport_width == 0 means write_header was not called yet. */
280     if (opengl->max_viewport_width) {
281         if (opengl->no_window &&
282             (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
283             av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
284             goto end;
285         }
286         if ((ret = opengl_prepare_vertex(h)) < 0)
287             goto end;
288         ret = opengl_draw(h, NULL, 1);
289     }
290   end:
291     return ret;
292 }
293
294 static int opengl_control_message(AVFormatContext *h, int type, void *data, size_t data_size)
295 {
296     OpenGLContext *opengl = h->priv_data;
297     switch(type) {
298     case AV_APP_TO_DEV_WINDOW_SIZE:
299         if (data) {
300             AVDeviceRect *message = data;
301             return opengl_resize(h, message->width, message->height);
302         }
303         return AVERROR(EINVAL);
304     case AV_APP_TO_DEV_WINDOW_REPAINT:
305         return opengl_resize(h, opengl->window_width, opengl->window_height);
306     }
307     return AVERROR(ENOSYS);
308 }
309
310 #if HAVE_SDL
311 static int opengl_sdl_recreate_window(OpenGLContext *opengl, int width, int height)
312 {
313     opengl->surface = SDL_SetVideoMode(width, height,
314                                        32, SDL_OPENGL | SDL_RESIZABLE);
315     if (!opengl->surface) {
316         av_log(opengl, AV_LOG_ERROR, "Unable to set video mode: %s\n", SDL_GetError());
317         return AVERROR_EXTERNAL;
318     }
319     SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
320     SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
321     SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
322     SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
323     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
324     return 0;
325 }
326
327 static int opengl_sdl_process_events(AVFormatContext *h)
328 {
329     int ret;
330     OpenGLContext *opengl = h->priv_data;
331     SDL_Event event;
332     SDL_PumpEvents();
333     while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_ALLEVENTS) > 0) {
334         switch (event.type) {
335         case SDL_QUIT:
336             return AVERROR(EIO);
337         case SDL_KEYDOWN:
338             switch (event.key.keysym.sym) {
339             case SDLK_ESCAPE:
340             case SDLK_q:
341                 return AVERROR(EIO);
342             }
343             return 0;
344         case SDL_VIDEORESIZE: {
345             char buffer[100];
346             int reinit;
347             AVDeviceRect message;
348             /* clean up old context because SDL_SetVideoMode may lose its state. */
349             SDL_VideoDriverName(buffer, sizeof(buffer));
350             reinit = !av_strncasecmp(buffer, "quartz", sizeof(buffer));
351             if (reinit) {
352                 glDeleteTextures(4, opengl->texture_name);
353                 opengl->glprocs.glDeleteBuffers(2, &opengl->index_buffer);
354             }
355             if ((ret = opengl_sdl_recreate_window(opengl, event.resize.w, event.resize.h)) < 0)
356                 return ret;
357             if (reinit && (ret = opengl_init_context(opengl)) < 0)
358                 return ret;
359             message.width = opengl->surface->w;
360             message.height = opengl->surface->h;
361             return opengl_control_message(h, AV_APP_TO_DEV_WINDOW_SIZE, &message, sizeof(AVDeviceRect));
362             }
363         }
364     }
365     return 0;
366 }
367
368 static int av_cold opengl_sdl_create_window(AVFormatContext *h)
369 {
370     int ret;
371     char buffer[100];
372     OpenGLContext *opengl = h->priv_data;
373     AVDeviceRect message;
374     if (SDL_Init(SDL_INIT_VIDEO)) {
375         av_log(opengl, AV_LOG_ERROR, "Unable to initialize SDL: %s\n", SDL_GetError());
376         return AVERROR_EXTERNAL;
377     }
378     if ((ret = opengl_sdl_recreate_window(opengl, opengl->width, opengl->height)) < 0)
379         return ret;
380     av_log(opengl, AV_LOG_INFO, "SDL driver: '%s'.\n", SDL_VideoDriverName(buffer, sizeof(buffer)));
381     message.width = opengl->surface->w;
382     message.height = opengl->surface->h;
383     opengl_control_message(h, AV_APP_TO_DEV_WINDOW_SIZE, &message, sizeof(AVDeviceRect));
384     return 0;
385 }
386
387 static int av_cold opengl_sdl_load_procedures(OpenGLContext *opengl)
388 {
389     FFOpenGLFunctions *procs = &opengl->glprocs;
390
391 #define LOAD_OPENGL_FUN(name, type) \
392     procs->name = (type)SDL_GL_GetProcAddress(#name); \
393     if (!procs->name) { \
394         av_log(opengl, AV_LOG_ERROR, "Cannot load OpenGL function: '%s'\n", #name); \
395         return AVERROR(ENOSYS); \
396     }
397
398     LOAD_OPENGL_FUN(glActiveTexture, FF_PFNGLACTIVETEXTUREPROC)
399     LOAD_OPENGL_FUN(glGenBuffers, FF_PFNGLGENBUFFERSPROC)
400     LOAD_OPENGL_FUN(glDeleteBuffers, FF_PFNGLDELETEBUFFERSPROC)
401     LOAD_OPENGL_FUN(glBufferData, FF_PFNGLBUFFERDATAPROC)
402     LOAD_OPENGL_FUN(glBindBuffer, FF_PFNGLBINDBUFFERPROC)
403     LOAD_OPENGL_FUN(glGetAttribLocation, FF_PFNGLGETATTRIBLOCATIONPROC)
404     LOAD_OPENGL_FUN(glGetUniformLocation, FF_PFNGLGETUNIFORMLOCATIONPROC)
405     LOAD_OPENGL_FUN(glUniform1f, FF_PFNGLUNIFORM1FPROC)
406     LOAD_OPENGL_FUN(glUniform1i, FF_PFNGLUNIFORM1IPROC)
407     LOAD_OPENGL_FUN(glUniformMatrix4fv, FF_PFNGLUNIFORMMATRIX4FVPROC)
408     LOAD_OPENGL_FUN(glCreateProgram, FF_PFNGLCREATEPROGRAMPROC)
409     LOAD_OPENGL_FUN(glDeleteProgram, FF_PFNGLDELETEPROGRAMPROC)
410     LOAD_OPENGL_FUN(glUseProgram, FF_PFNGLUSEPROGRAMPROC)
411     LOAD_OPENGL_FUN(glLinkProgram, FF_PFNGLLINKPROGRAMPROC)
412     LOAD_OPENGL_FUN(glGetProgramiv, FF_PFNGLGETPROGRAMIVPROC)
413     LOAD_OPENGL_FUN(glGetProgramInfoLog, FF_PFNGLGETPROGRAMINFOLOGPROC)
414     LOAD_OPENGL_FUN(glAttachShader, FF_PFNGLATTACHSHADERPROC)
415     LOAD_OPENGL_FUN(glCreateShader, FF_PFNGLCREATESHADERPROC)
416     LOAD_OPENGL_FUN(glDeleteShader, FF_PFNGLDELETESHADERPROC)
417     LOAD_OPENGL_FUN(glCompileShader, FF_PFNGLCOMPILESHADERPROC)
418     LOAD_OPENGL_FUN(glShaderSource, FF_PFNGLSHADERSOURCEPROC)
419     LOAD_OPENGL_FUN(glGetShaderiv, FF_PFNGLGETSHADERIVPROC)
420     LOAD_OPENGL_FUN(glGetShaderInfoLog, FF_PFNGLGETSHADERINFOLOGPROC)
421     LOAD_OPENGL_FUN(glEnableVertexAttribArray, FF_PFNGLENABLEVERTEXATTRIBARRAYPROC)
422     LOAD_OPENGL_FUN(glVertexAttribPointer, FF_PFNGLVERTEXATTRIBPOINTERPROC)
423
424     return 0;
425
426 #undef LOAD_OPENGL_FUN
427 }
428 #endif /* HAVE_SDL */
429
430 #if defined(__APPLE__)
431 static int av_cold opengl_load_procedures(OpenGLContext *opengl)
432 {
433     FFOpenGLFunctions *procs = &opengl->glprocs;
434
435     procs->glActiveTexture = glActiveTexture;
436     procs->glGenBuffers = glGenBuffers;
437     procs->glDeleteBuffers = glDeleteBuffers;
438     procs->glBufferData = glBufferData;
439     procs->glBindBuffer = glBindBuffer;
440     procs->glGetAttribLocation = glGetAttribLocation;
441     procs->glGetUniformLocation = glGetUniformLocation;
442     procs->glUniform1f = glUniform1f;
443     procs->glUniform1i = glUniform1i;
444     procs->glUniformMatrix4fv = glUniformMatrix4fv;
445     procs->glCreateProgram = glCreateProgram;
446     procs->glDeleteProgram = glDeleteProgram;
447     procs->glUseProgram = glUseProgram;
448     procs->glLinkProgram = glLinkProgram;
449     procs->glGetProgramiv = glGetProgramiv;
450     procs->glGetProgramInfoLog = glGetProgramInfoLog;
451     procs->glAttachShader = glAttachShader;
452     procs->glCreateShader = glCreateShader;
453     procs->glDeleteShader = glDeleteShader;
454     procs->glCompileShader = glCompileShader;
455     procs->glShaderSource = glShaderSource;
456     procs->glGetShaderiv = glGetShaderiv;
457     procs->glGetShaderInfoLog = glGetShaderInfoLog;
458     procs->glEnableVertexAttribArray = glEnableVertexAttribArray;
459     procs->glVertexAttribPointer = (FF_PFNGLVERTEXATTRIBPOINTERPROC) glVertexAttribPointer;
460     return 0;
461 }
462 #else
463 static int av_cold opengl_load_procedures(OpenGLContext *opengl)
464 {
465     FFOpenGLFunctions *procs = &opengl->glprocs;
466
467 #if HAVE_GLXGETPROCADDRESS
468 #define SelectedGetProcAddress glXGetProcAddress
469 #elif HAVE_WGLGETPROCADDRESS
470 #define SelectedGetProcAddress wglGetProcAddress
471 #endif
472
473 #define LOAD_OPENGL_FUN(name, type) \
474     procs->name = (type)SelectedGetProcAddress(#name); \
475     if (!procs->name) { \
476         av_log(opengl, AV_LOG_ERROR, "Cannot load OpenGL function: '%s'\n", #name); \
477         return AVERROR(ENOSYS); \
478     }
479
480     LOAD_OPENGL_FUN(glActiveTexture, FF_PFNGLACTIVETEXTUREPROC)
481     LOAD_OPENGL_FUN(glGenBuffers, FF_PFNGLGENBUFFERSPROC)
482     LOAD_OPENGL_FUN(glDeleteBuffers, FF_PFNGLDELETEBUFFERSPROC)
483     LOAD_OPENGL_FUN(glBufferData, FF_PFNGLBUFFERDATAPROC)
484     LOAD_OPENGL_FUN(glBindBuffer, FF_PFNGLBINDBUFFERPROC)
485     LOAD_OPENGL_FUN(glGetAttribLocation, FF_PFNGLGETATTRIBLOCATIONPROC)
486     LOAD_OPENGL_FUN(glGetUniformLocation, FF_PFNGLGETUNIFORMLOCATIONPROC)
487     LOAD_OPENGL_FUN(glUniform1f, FF_PFNGLUNIFORM1FPROC)
488     LOAD_OPENGL_FUN(glUniform1i, FF_PFNGLUNIFORM1IPROC)
489     LOAD_OPENGL_FUN(glUniformMatrix4fv, FF_PFNGLUNIFORMMATRIX4FVPROC)
490     LOAD_OPENGL_FUN(glCreateProgram, FF_PFNGLCREATEPROGRAMPROC)
491     LOAD_OPENGL_FUN(glDeleteProgram, FF_PFNGLDELETEPROGRAMPROC)
492     LOAD_OPENGL_FUN(glUseProgram, FF_PFNGLUSEPROGRAMPROC)
493     LOAD_OPENGL_FUN(glLinkProgram, FF_PFNGLLINKPROGRAMPROC)
494     LOAD_OPENGL_FUN(glGetProgramiv, FF_PFNGLGETPROGRAMIVPROC)
495     LOAD_OPENGL_FUN(glGetProgramInfoLog, FF_PFNGLGETPROGRAMINFOLOGPROC)
496     LOAD_OPENGL_FUN(glAttachShader, FF_PFNGLATTACHSHADERPROC)
497     LOAD_OPENGL_FUN(glCreateShader, FF_PFNGLCREATESHADERPROC)
498     LOAD_OPENGL_FUN(glDeleteShader, FF_PFNGLDELETESHADERPROC)
499     LOAD_OPENGL_FUN(glCompileShader, FF_PFNGLCOMPILESHADERPROC)
500     LOAD_OPENGL_FUN(glShaderSource, FF_PFNGLSHADERSOURCEPROC)
501     LOAD_OPENGL_FUN(glGetShaderiv, FF_PFNGLGETSHADERIVPROC)
502     LOAD_OPENGL_FUN(glGetShaderInfoLog, FF_PFNGLGETSHADERINFOLOGPROC)
503     LOAD_OPENGL_FUN(glEnableVertexAttribArray, FF_PFNGLENABLEVERTEXATTRIBARRAYPROC)
504     LOAD_OPENGL_FUN(glVertexAttribPointer, FF_PFNGLVERTEXATTRIBPOINTERPROC)
505
506     return 0;
507
508 #undef SelectedGetProcAddress
509 #undef LOAD_OPENGL_FUN
510 }
511 #endif
512
513 static av_always_inline void opengl_make_identity(float matrix[16])
514 {
515     memset(matrix, 0, 16 * sizeof(float));
516     matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1.0f;
517 }
518
519 static av_always_inline void opengl_make_ortho(float matrix[16],
520                                                float left,   float right,
521                                                float bottom, float top,
522                                                float nearZ,  float farZ)
523 {
524     float ral = right + left;
525     float rsl = right - left;
526     float tab = top + bottom;
527     float tsb = top - bottom;
528     float fan = farZ + nearZ;
529     float fsn = farZ - nearZ;
530
531     memset(matrix, 0, 16 * sizeof(float));
532     matrix[0] = 2.0f / rsl;
533     matrix[5] = 2.0f / tsb;
534     matrix[10] = -2.0f / fsn;
535     matrix[12] = -ral / rsl;
536     matrix[13] = -tab / tsb;
537     matrix[14] = -fan / fsn;
538     matrix[15] = 1.0f;
539 }
540
541 static av_cold int opengl_read_limits(OpenGLContext *opengl)
542 {
543     static const struct{
544         const char *extention;
545         int major;
546         int minor;
547     } required_extensions[] = {
548         { "GL_ARB_multitexture",         1, 3 },
549         { "GL_ARB_vertex_buffer_object", 1, 5 }, //GLX_ARB_vertex_buffer_object
550         { "GL_ARB_vertex_shader",        2, 0 },
551         { "GL_ARB_fragment_shader",      2, 0 },
552         { "GL_ARB_shader_objects",       2, 0 },
553         { NULL,                          0, 0 }
554     };
555     int i, major, minor;
556     const char *extensions, *version;
557
558     version = glGetString(GL_VERSION);
559     extensions = glGetString(GL_EXTENSIONS);
560
561     av_log(opengl, AV_LOG_DEBUG, "OpenGL version: %s\n", version);
562     sscanf(version, "%d.%d", &major, &minor);
563
564     for (i = 0; required_extensions[i].extention; i++) {
565         if (major < required_extensions[i].major &&
566             (major == required_extensions[i].major && minor < required_extensions[i].minor) &&
567             !strstr(extensions, required_extensions[i].extention)) {
568             av_log(opengl, AV_LOG_ERROR, "Required extension %s is not supported.\n",
569                    required_extensions[i].extention);
570             av_log(opengl, AV_LOG_DEBUG, "Supported extensions are: %s\n", extensions);
571             return AVERROR(ENOSYS);
572         }
573     }
574     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &opengl->max_texture_size);
575     glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &opengl->max_viewport_width);
576     opengl->non_pow_2_textures = major >= 2 || strstr(extensions, "GL_ARB_texture_non_power_of_two");
577
578     av_log(opengl, AV_LOG_DEBUG, "Non Power of 2 textures support: %s\n", opengl->non_pow_2_textures ? "Yes" : "No");
579     av_log(opengl, AV_LOG_DEBUG, "Max texture size: %dx%d\n", opengl->max_texture_size, opengl->max_texture_size);
580     av_log(opengl, AV_LOG_DEBUG, "Max viewport size: %dx%d\n",
581            opengl->max_viewport_width, opengl->max_viewport_height);
582
583     OPENGL_ERROR_CHECK(opengl);
584     return 0;
585   fail:
586     return AVERROR_EXTERNAL;
587 }
588
589 static const char* opengl_get_fragment_shader_code(enum AVPixelFormat format)
590 {
591     int i;
592     for (i = 0; i < FF_ARRAY_ELEMS(opengl_format_desc); i++) {
593         if (opengl_format_desc[i].fixel_format == format)
594             return *opengl_format_desc[i].fragment_shader;
595     }
596     return NULL;
597 }
598
599 static av_always_inline int opengl_type_size(GLenum type)
600 {
601     switch(type) {
602     case GL_UNSIGNED_SHORT:
603     case FF_GL_UNSIGNED_SHORT_1_5_5_5_REV:
604     case GL_UNSIGNED_SHORT_5_6_5:
605         return 2;
606     case GL_UNSIGNED_BYTE:
607     case FF_GL_UNSIGNED_BYTE_3_3_2:
608     case FF_GL_UNSIGNED_BYTE_2_3_3_REV:
609     default:
610         break;
611     }
612     return 1;
613 }
614
615 static av_cold void opengl_get_texture_params(OpenGLContext *opengl)
616 {
617     int i;
618     for (i = 0; i < FF_ARRAY_ELEMS(opengl_format_desc); i++) {
619         if (opengl_format_desc[i].fixel_format == opengl->pix_fmt) {
620             opengl->format = opengl_format_desc[i].format;
621             opengl->type = opengl_format_desc[i].type;
622             break;
623         }
624     }
625 }
626
627 static void opengl_compute_display_area(AVFormatContext *s)
628 {
629     AVRational sar, dar; /* sample and display aspect ratios */
630     OpenGLContext *opengl = s->priv_data;
631     AVStream *st = s->streams[0];
632     AVCodecContext *encctx = st->codec;
633
634     /* compute overlay width and height from the codec context information */
635     sar = st->sample_aspect_ratio.num ? st->sample_aspect_ratio : (AVRational){ 1, 1 };
636     dar = av_mul_q(sar, (AVRational){ encctx->width, encctx->height });
637
638     /* we suppose the screen has a 1/1 sample aspect ratio */
639     /* fit in the window */
640     if (av_cmp_q(dar, (AVRational){ opengl->window_width, opengl->window_height }) > 0) {
641         /* fit in width */
642         opengl->picture_width = opengl->window_width;
643         opengl->picture_height = av_rescale(opengl->picture_width, dar.den, dar.num);
644     } else {
645         /* fit in height */
646         opengl->picture_height = opengl->window_height;
647         opengl->picture_width = av_rescale(opengl->picture_height, dar.num, dar.den);
648     }
649 }
650
651 static av_cold void opengl_get_texture_size(OpenGLContext *opengl, int in_width, int in_height,
652                                             int *out_width, int *out_height)
653 {
654     if (opengl->non_pow_2_textures) {
655         *out_width = in_width;
656         *out_height = in_height;
657     } else {
658         int max = FFMIN(FFMAX(in_width, in_height), opengl->max_texture_size);
659         unsigned power_of_2 = 1;
660         while (power_of_2 < max)
661             power_of_2 *= 2;
662         *out_height = power_of_2;
663         *out_width = power_of_2;
664         av_log(opengl, AV_LOG_DEBUG, "Texture size calculated from %dx%d into %dx%d\n",
665                in_width, in_height, *out_width, *out_height);
666     }
667 }
668
669 static av_cold void opengl_fill_color_map(OpenGLContext *opengl)
670 {
671     const AVPixFmtDescriptor *desc;
672     int shift;
673     enum AVPixelFormat pix_fmt = opengl->pix_fmt;
674
675     /* We need order of components, not exact position, some minor HACKs here */
676     if (pix_fmt == AV_PIX_FMT_RGB565 || pix_fmt == AV_PIX_FMT_BGR555 ||
677         pix_fmt == AV_PIX_FMT_BGR8   || pix_fmt == AV_PIX_FMT_RGB8)
678         pix_fmt = AV_PIX_FMT_RGB24;
679     else if (pix_fmt == AV_PIX_FMT_BGR565 || pix_fmt == AV_PIX_FMT_RGB555)
680         pix_fmt = AV_PIX_FMT_BGR24;
681
682     desc = av_pix_fmt_desc_get(pix_fmt);
683     if (!(desc->flags & AV_PIX_FMT_FLAG_RGB))
684         return;
685
686 #define FILL_COMPONENT(i) { \
687         shift = desc->comp[i].depth_minus1 >> 3; \
688         opengl->color_map[(i << 2) + ((desc->comp[i].offset_plus1 - 1) >> shift)] = 1.0; \
689     }
690
691     memset(opengl->color_map, 0, sizeof(opengl->color_map));
692     FILL_COMPONENT(0);
693     FILL_COMPONENT(1);
694     FILL_COMPONENT(2);
695     if (desc->flags & AV_PIX_FMT_FLAG_ALPHA)
696         FILL_COMPONENT(3);
697
698 #undef FILL_COMPONENT
699 }
700
701 static av_cold GLuint opengl_load_shader(OpenGLContext *opengl, GLenum type, const char *source)
702 {
703     GLuint shader = opengl->glprocs.glCreateShader(type);
704     GLint result;
705     if (!shader) {
706         av_log(opengl, AV_LOG_ERROR, "glCreateShader() failed\n");
707         return 0;
708     }
709     opengl->glprocs.glShaderSource(shader, 1, &source, NULL);
710     opengl->glprocs.glCompileShader(shader);
711
712     opengl->glprocs.glGetShaderiv(shader, FF_GL_COMPILE_STATUS, &result);
713     if (!result) {
714         char *log;
715         opengl->glprocs.glGetShaderiv(shader, FF_GL_INFO_LOG_LENGTH, &result);
716         if (result) {
717             if ((log = av_malloc(result))) {
718                 opengl->glprocs.glGetShaderInfoLog(shader, result, NULL, log);
719                 av_log(opengl, AV_LOG_ERROR, "Compile error: %s\n", log);
720                 av_free(log);
721             }
722         }
723         goto fail;
724     }
725     OPENGL_ERROR_CHECK(opengl);
726     return shader;
727   fail:
728     opengl->glprocs.glDeleteShader(shader);
729     return 0;
730 }
731
732 static av_cold int opengl_compile_shaders(OpenGLContext *opengl, enum AVPixelFormat pix_fmt)
733 {
734     GLuint vertex_shader = 0, fragment_shader = 0;
735     GLint result;
736     const char *fragment_shader_code = opengl_get_fragment_shader_code(pix_fmt);
737
738     if (!fragment_shader_code) {
739         av_log(opengl, AV_LOG_ERROR, "Provided pixel format '%s' is not supported\n",
740                av_get_pix_fmt_name(pix_fmt));
741         return AVERROR(EINVAL);
742     }
743
744     vertex_shader = opengl_load_shader(opengl, FF_GL_VERTEX_SHADER,
745                                        FF_OPENGL_VERTEX_SHADER);
746     if (!vertex_shader) {
747         av_log(opengl, AV_LOG_ERROR, "Vertex shader loading failed.\n");
748         goto fail;
749     }
750     fragment_shader = opengl_load_shader(opengl, FF_GL_FRAGMENT_SHADER,
751                                          fragment_shader_code);
752     if (!fragment_shader) {
753         av_log(opengl, AV_LOG_ERROR, "Fragment shader loading failed.\n");
754         goto fail;
755     }
756
757     opengl->program = opengl->glprocs.glCreateProgram();
758     if (!opengl->program)
759         goto fail;
760
761     opengl->glprocs.glAttachShader(opengl->program, vertex_shader);
762     opengl->glprocs.glAttachShader(opengl->program, fragment_shader);
763     opengl->glprocs.glLinkProgram(opengl->program);
764
765     opengl->glprocs.glGetProgramiv(opengl->program, FF_GL_LINK_STATUS, &result);
766     if (!result) {
767         char *log;
768         opengl->glprocs.glGetProgramiv(opengl->program, FF_GL_INFO_LOG_LENGTH, &result);
769         if (result) {
770             log = av_malloc(result);
771             if (!log)
772                 goto fail;
773             opengl->glprocs.glGetProgramInfoLog(opengl->program, result, NULL, log);
774             av_log(opengl, AV_LOG_ERROR, "Link error: %s\n", log);
775             av_free(log);
776         }
777         goto fail;
778     }
779
780     opengl->position_attrib = opengl->glprocs.glGetAttribLocation(opengl->program, "a_position");
781     opengl->texture_coords_attrib = opengl->glprocs.glGetAttribLocation(opengl->program, "a_textureCoords");
782     opengl->projection_matrix_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_projectionMatrix");
783     opengl->model_view_matrix_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_modelViewMatrix");
784     opengl->color_map_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_colorMap");
785     opengl->texture_location[0] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture0");
786     opengl->texture_location[1] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture1");
787     opengl->texture_location[2] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture2");
788     opengl->texture_location[3] = opengl->glprocs.glGetUniformLocation(opengl->program, "u_texture3");
789     opengl->chroma_div_w_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_chroma_div_w");
790     opengl->chroma_div_h_location = opengl->glprocs.glGetUniformLocation(opengl->program, "u_chroma_div_h");
791
792     OPENGL_ERROR_CHECK(opengl);
793     return 0;
794   fail:
795     opengl->glprocs.glDeleteShader(vertex_shader);
796     opengl->glprocs.glDeleteShader(fragment_shader);
797     opengl->glprocs.glDeleteProgram(opengl->program);
798     opengl->program = 0;
799     return AVERROR_EXTERNAL;
800 }
801
802 static av_cold int opengl_configure_texture(OpenGLContext *opengl, GLuint texture,
803                                             GLsizei width, GLsizei height)
804 {
805     if (texture) {
806         int new_width, new_height;
807         opengl_get_texture_size(opengl, width, height, &new_width, &new_height);
808         glBindTexture(GL_TEXTURE_2D, texture);
809         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
810         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
811         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
812         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
813         glTexImage2D(GL_TEXTURE_2D, 0, opengl->format, new_width, new_height, 0,
814                      opengl->format, opengl->type, NULL);
815         OPENGL_ERROR_CHECK(NULL);
816     }
817     return 0;
818   fail:
819     return AVERROR_EXTERNAL;
820 }
821
822 static av_cold int opengl_prepare_vertex(AVFormatContext *s)
823 {
824     OpenGLContext *opengl = s->priv_data;
825     int tex_w, tex_h;
826
827     if (opengl->window_width > opengl->max_viewport_width || opengl->window_height > opengl->max_viewport_height) {
828         opengl->window_width = FFMAX(opengl->window_width, opengl->max_viewport_width);
829         opengl->window_height = FFMAX(opengl->window_height, opengl->max_viewport_height);
830         av_log(opengl, AV_LOG_WARNING, "Too big viewport requested, limited to %dx%d", opengl->window_width, opengl->window_height);
831     }
832     glViewport(0, 0, opengl->window_width, opengl->window_height);
833     opengl_make_ortho(opengl->projection_matrix,
834                       - (float)opengl->window_width  / 2.0f, (float)opengl->window_width  / 2.0f,
835                       - (float)opengl->window_height / 2.0f, (float)opengl->window_height / 2.0f,
836                       1.0f, -1.0f);
837     opengl_make_identity(opengl->model_view_matrix);
838
839     opengl_compute_display_area(s);
840
841     opengl->vertex[0].z = opengl->vertex[1].z = opengl->vertex[2].z = opengl->vertex[3].z = 0.0f;
842     opengl->vertex[0].x = opengl->vertex[1].x = - (float)opengl->picture_width / 2.0f;
843     opengl->vertex[2].x = opengl->vertex[3].x =   (float)opengl->picture_width / 2.0f;
844     opengl->vertex[1].y = opengl->vertex[2].y = - (float)opengl->picture_height / 2.0f;
845     opengl->vertex[0].y = opengl->vertex[3].y =   (float)opengl->picture_height / 2.0f;
846
847     opengl_get_texture_size(opengl, opengl->width, opengl->height, &tex_w, &tex_h);
848
849     opengl->vertex[0].s0 = 0.0f;
850     opengl->vertex[0].t0 = 0.0f;
851     opengl->vertex[1].s0 = 0.0f;
852     opengl->vertex[1].t0 = (float)opengl->height / (float)tex_h;
853     opengl->vertex[2].s0 = (float)opengl->width  / (float)tex_w;
854     opengl->vertex[2].t0 = (float)opengl->height / (float)tex_h;
855     opengl->vertex[3].s0 = (float)opengl->width  / (float)tex_w;
856     opengl->vertex[3].t0 = 0.0f;
857
858     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, opengl->vertex_buffer);
859     opengl->glprocs.glBufferData(FF_GL_ARRAY_BUFFER, sizeof(opengl->vertex), opengl->vertex, FF_GL_STATIC_DRAW);
860     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, 0);
861     OPENGL_ERROR_CHECK(opengl);
862     return 0;
863   fail:
864     return AVERROR_EXTERNAL;
865 }
866
867 static int opengl_prepare(OpenGLContext *opengl)
868 {
869     int i;
870     opengl->glprocs.glUseProgram(opengl->program);
871     opengl->glprocs.glUniformMatrix4fv(opengl->projection_matrix_location, 1, GL_FALSE, opengl->projection_matrix);
872     opengl->glprocs.glUniformMatrix4fv(opengl->model_view_matrix_location, 1, GL_FALSE, opengl->model_view_matrix);
873     for (i = 0; i < 4; i++)
874         if (opengl->texture_location[i] != -1) {
875             opengl->glprocs.glActiveTexture(GL_TEXTURE0 + i);
876             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[i]);
877             opengl->glprocs.glUniform1i(opengl->texture_location[i], i);
878         }
879     if (opengl->color_map_location != -1)
880         opengl->glprocs.glUniformMatrix4fv(opengl->color_map_location, 1, GL_FALSE, opengl->color_map);
881     if (opengl->chroma_div_h_location != -1)
882         opengl->glprocs.glUniform1f(opengl->chroma_div_h_location, opengl->chroma_div_h);
883     if (opengl->chroma_div_w_location != -1)
884         opengl->glprocs.glUniform1f(opengl->chroma_div_w_location, opengl->chroma_div_w);
885
886     OPENGL_ERROR_CHECK(opengl);
887     return 0;
888   fail:
889     return AVERROR_EXTERNAL;
890 }
891
892 static int opengl_create_window(AVFormatContext *h)
893 {
894     OpenGLContext *opengl = h->priv_data;
895     int ret;
896
897     if (!opengl->no_window) {
898 #if HAVE_SDL
899         if ((ret = opengl_sdl_create_window(h)) < 0) {
900             av_log(opengl, AV_LOG_ERROR, "Cannot create default SDL window.\n");
901             return ret;
902         }
903 #else
904         av_log(opengl, AV_LOG_ERROR, "FFmpeg is compiled without SDL. Cannot create default window.\n");
905         return AVERROR(ENOSYS);
906 #endif
907     } else {
908         if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_CREATE_WINDOW_BUFFER, NULL , 0)) < 0) {
909             av_log(opengl, AV_LOG_ERROR, "Application failed to create window buffer.\n");
910             return ret;
911         }
912         if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
913             av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
914             return ret;
915         }
916     }
917     return 0;
918 }
919
920 static int opengl_release_window(AVFormatContext *h)
921 {
922     int ret;
923     OpenGLContext *opengl = h->priv_data;
924     if (!opengl->no_window) {
925 #if HAVE_SDL
926         SDL_Quit();
927 #endif
928     } else if ((ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DESTROY_WINDOW_BUFFER, NULL , 0) < 0)) {
929         av_log(opengl, AV_LOG_ERROR, "Application failed to release window buffer.\n");
930         return ret;
931     }
932     return 0;
933 }
934
935 static av_cold int opengl_write_trailer(AVFormatContext *h)
936 {
937     OpenGLContext *opengl = h->priv_data;
938
939     if (opengl->no_window &&
940         avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0) < 0)
941         av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
942
943     glDeleteTextures(4, opengl->texture_name);
944     if (opengl && opengl->glprocs.glDeleteBuffers)
945         opengl->glprocs.glDeleteBuffers(2, &opengl->index_buffer);
946
947     opengl_release_window(h);
948
949     return 0;
950 }
951
952 static av_cold int opengl_init_context(OpenGLContext *opengl)
953 {
954     int i, ret;
955     const AVPixFmtDescriptor *desc;
956
957     if ((ret = opengl_compile_shaders(opengl, opengl->pix_fmt)) < 0)
958         goto fail;
959
960     desc = av_pix_fmt_desc_get(opengl->pix_fmt);
961     av_assert0(desc->nb_components > 0 && desc->nb_components <= 4);
962     glGenTextures(desc->nb_components, opengl->texture_name);
963
964     opengl->glprocs.glGenBuffers(2, &opengl->index_buffer);
965     if (!opengl->index_buffer || !opengl->vertex_buffer) {
966         av_log(opengl, AV_LOG_ERROR, "Buffer generation failed.\n");
967         ret = AVERROR_EXTERNAL;
968         goto fail;
969     }
970
971     opengl_configure_texture(opengl, opengl->texture_name[0], opengl->width, opengl->height);
972     if (desc->nb_components > 1) {
973         int has_alpha = desc->flags & AV_PIX_FMT_FLAG_ALPHA;
974         int num_planes = desc->nb_components - (has_alpha ? 1 : 0);
975         if (opengl->non_pow_2_textures) {
976             opengl->chroma_div_w = 1.0f;
977             opengl->chroma_div_h = 1.0f;
978         } else {
979             opengl->chroma_div_w = 1 << desc->log2_chroma_w;
980             opengl->chroma_div_h = 1 << desc->log2_chroma_h;
981         }
982         for (i = 1; i < num_planes; i++)
983             if (opengl->non_pow_2_textures)
984                 opengl_configure_texture(opengl, opengl->texture_name[i],
985                         FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w),
986                         FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h));
987             else
988                 opengl_configure_texture(opengl, opengl->texture_name[i], opengl->width, opengl->height);
989         if (has_alpha)
990             opengl_configure_texture(opengl, opengl->texture_name[3], opengl->width, opengl->height);
991     }
992
993     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, opengl->index_buffer);
994     opengl->glprocs.glBufferData(FF_GL_ELEMENT_ARRAY_BUFFER, sizeof(g_index), g_index, FF_GL_STATIC_DRAW);
995     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, 0);
996
997     glEnable(GL_BLEND);
998     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
999
1000     glClearColor((float)opengl->background[0] / 255.0f, (float)opengl->background[1] / 255.0f,
1001                  (float)opengl->background[2] / 255.0f, 1.0f);
1002
1003     ret = AVERROR_EXTERNAL;
1004     OPENGL_ERROR_CHECK(opengl);
1005
1006     return 0;
1007   fail:
1008     return ret;
1009 }
1010
1011 static av_cold int opengl_write_header(AVFormatContext *h)
1012 {
1013     OpenGLContext *opengl = h->priv_data;
1014     AVStream *st;
1015     int ret;
1016
1017     if (h->nb_streams != 1 ||
1018         h->streams[0]->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
1019         h->streams[0]->codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
1020         av_log(opengl, AV_LOG_ERROR, "Only a single video stream is supported.\n");
1021         return AVERROR(EINVAL);
1022     }
1023     st = h->streams[0];
1024     opengl->width = st->codec->width;
1025     opengl->height = st->codec->height;
1026     opengl->pix_fmt = st->codec->pix_fmt;
1027
1028     if (!opengl->window_title && !opengl->no_window)
1029         opengl->window_title = av_strdup(h->filename);
1030
1031     if ((ret = opengl_create_window(h)))
1032         goto fail;
1033
1034     if ((ret = opengl_read_limits(opengl)) < 0)
1035         goto fail;
1036
1037     if (opengl->width > opengl->max_texture_size || opengl->height > opengl->max_texture_size) {
1038         av_log(opengl, AV_LOG_ERROR, "Too big picture %dx%d, max supported size is %dx%d\n",
1039                opengl->width, opengl->height, opengl->max_texture_size, opengl->max_texture_size);
1040         ret = AVERROR(EINVAL);
1041         goto fail;
1042     }
1043
1044     if (!opengl->no_window) {
1045 #if HAVE_SDL
1046         if ((ret = opengl_sdl_load_procedures(opengl)) < 0)
1047             goto fail;
1048 #endif
1049     } else if ((ret = opengl_load_procedures(opengl)) < 0)
1050         goto fail;
1051
1052     opengl_fill_color_map(opengl);
1053     opengl_get_texture_params(opengl);
1054
1055     if ((ret = opengl_init_context(opengl)) < 0)
1056         goto fail;
1057
1058     if ((ret = opengl_prepare_vertex(h)) < 0)
1059         goto fail;
1060
1061     glClear(GL_COLOR_BUFFER_BIT);
1062
1063 #if HAVE_SDL
1064     if (!opengl->no_window)
1065         SDL_GL_SwapBuffers();
1066 #endif
1067     if (opengl->no_window &&
1068         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER, NULL , 0)) < 0) {
1069         av_log(opengl, AV_LOG_ERROR, "Application failed to display window buffer.\n");
1070         goto fail;
1071     }
1072
1073     ret = AVERROR_EXTERNAL;
1074     OPENGL_ERROR_CHECK(opengl);
1075     return 0;
1076
1077   fail:
1078     opengl_write_trailer(h);
1079     return ret;
1080 }
1081
1082 static uint8_t* opengl_get_plane_pointer(OpenGLContext *opengl, AVPacket *pkt, int comp_index,
1083                                          const AVPixFmtDescriptor *desc)
1084 {
1085     uint8_t *data = pkt->data;
1086     int wordsize = opengl_type_size(opengl->type);
1087     int width_chroma = FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w);
1088     int height_chroma = FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h);
1089     int plane = desc->comp[comp_index].plane;
1090
1091     switch(plane) {
1092     case 0:
1093         break;
1094     case 1:
1095         data += opengl->width * opengl->height * wordsize;
1096         break;
1097     case 2:
1098         data += opengl->width * opengl->height * wordsize;
1099         data += width_chroma * height_chroma * wordsize;
1100         break;
1101     case 3:
1102         data += opengl->width * opengl->height * wordsize;
1103         data += 2 * width_chroma * height_chroma * wordsize;
1104         break;
1105     default:
1106         return NULL;
1107     }
1108     return data;
1109 }
1110
1111 static int opengl_draw(AVFormatContext *h, AVPacket *pkt, int repaint)
1112 {
1113     OpenGLContext *opengl = h->priv_data;
1114     enum AVPixelFormat pix_fmt = h->streams[0]->codec->pix_fmt;
1115     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1116     int ret;
1117
1118 #if HAVE_SDL
1119     if (!opengl->no_window && (ret = opengl_sdl_process_events(h)) < 0)
1120         goto fail;
1121 #endif
1122     if (opengl->no_window &&
1123         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER, NULL , 0)) < 0) {
1124         av_log(opengl, AV_LOG_ERROR, "Application failed to prepare window buffer.\n");
1125         goto fail;
1126     }
1127
1128     glClear(GL_COLOR_BUFFER_BIT);
1129
1130     if (!repaint) {
1131         glBindTexture(GL_TEXTURE_2D, opengl->texture_name[0]);
1132         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, opengl->width, opengl->height, opengl->format, opengl->type,
1133                         opengl_get_plane_pointer(opengl, pkt, 0, desc));
1134         if (desc->flags & AV_PIX_FMT_FLAG_PLANAR) {
1135             int width_chroma = FF_CEIL_RSHIFT(opengl->width, desc->log2_chroma_w);
1136             int height_chroma = FF_CEIL_RSHIFT(opengl->height, desc->log2_chroma_h);
1137             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[1]);
1138             glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width_chroma, height_chroma, opengl->format, opengl->type,
1139                             opengl_get_plane_pointer(opengl, pkt, 1, desc));
1140             glBindTexture(GL_TEXTURE_2D, opengl->texture_name[2]);
1141             glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width_chroma, height_chroma, opengl->format, opengl->type,
1142                             opengl_get_plane_pointer(opengl, pkt, 2, desc));
1143             if (desc->flags & AV_PIX_FMT_FLAG_ALPHA) {
1144                 glBindTexture(GL_TEXTURE_2D, opengl->texture_name[3]);
1145                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, opengl->width, opengl->height, opengl->format, opengl->type,
1146                                 opengl_get_plane_pointer(opengl, pkt, 3, desc));
1147             }
1148         }
1149     }
1150     ret = AVERROR_EXTERNAL;
1151     OPENGL_ERROR_CHECK(opengl);
1152
1153     if ((ret = opengl_prepare(opengl)) < 0)
1154         goto fail;
1155
1156     opengl->glprocs.glBindBuffer(FF_GL_ARRAY_BUFFER, opengl->vertex_buffer);
1157     opengl->glprocs.glBindBuffer(FF_GL_ELEMENT_ARRAY_BUFFER, opengl->index_buffer);
1158     opengl->glprocs.glVertexAttribPointer(opengl->position_attrib, 3, GL_FLOAT, GL_FALSE, sizeof(OpenGLVertexInfo), 0);
1159     opengl->glprocs.glEnableVertexAttribArray(opengl->position_attrib);
1160     opengl->glprocs.glVertexAttribPointer(opengl->texture_coords_attrib, 2, GL_FLOAT, GL_FALSE, sizeof(OpenGLVertexInfo), 12);
1161     opengl->glprocs.glEnableVertexAttribArray(opengl->texture_coords_attrib);
1162
1163     glDrawElements(GL_TRIANGLES, FF_ARRAY_ELEMS(g_index), GL_UNSIGNED_SHORT, 0);
1164
1165     ret = AVERROR_EXTERNAL;
1166     OPENGL_ERROR_CHECK(opengl);
1167
1168 #if HAVE_SDL
1169     if (!opengl->no_window)
1170         SDL_GL_SwapBuffers();
1171 #endif
1172     if (opengl->no_window &&
1173         (ret = avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER, NULL , 0)) < 0) {
1174         av_log(opengl, AV_LOG_ERROR, "Application failed to display window buffer.\n");
1175         goto fail;
1176     }
1177
1178     return 0;
1179   fail:
1180     return ret;
1181 }
1182
1183 static int opengl_write_packet(AVFormatContext *h, AVPacket *pkt)
1184 {
1185     return opengl_draw(h, pkt, 0);
1186 }
1187
1188 #define OFFSET(x) offsetof(OpenGLContext, x)
1189 #define ENC AV_OPT_FLAG_ENCODING_PARAM
1190 static const AVOption options[] = {
1191     { "background",   "set background color",   OFFSET(background),   AV_OPT_TYPE_COLOR,  {.str = "black"}, CHAR_MIN, CHAR_MAX, ENC },
1192     { "no_window",    "disable default window", OFFSET(no_window),    AV_OPT_TYPE_INT,    {.i64 = 0}, INT_MIN, INT_MAX, ENC },
1193     { "window_title", "set window title",       OFFSET(window_title), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, ENC },
1194     { NULL }
1195 };
1196
1197 static const AVClass opengl_class = {
1198     .class_name = "opengl outdev",
1199     .item_name  = av_default_item_name,
1200     .option     = options,
1201     .version    = LIBAVUTIL_VERSION_INT,
1202 };
1203
1204 AVOutputFormat ff_opengl_muxer = {
1205     .name           = "opengl",
1206     .long_name      = NULL_IF_CONFIG_SMALL("OpenGL output"),
1207     .priv_data_size = sizeof(OpenGLContext),
1208     .audio_codec    = AV_CODEC_ID_NONE,
1209     .video_codec    = AV_CODEC_ID_RAWVIDEO,
1210     .write_header   = opengl_write_header,
1211     .write_packet   = opengl_write_packet,
1212     .write_trailer  = opengl_write_trailer,
1213     .control_message = opengl_control_message,
1214     .flags          = AVFMT_NOFILE | AVFMT_VARIABLE_FPS | AVFMT_NOTIMESTAMPS,
1215     .priv_class     = &opengl_class,
1216 };