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