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