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