]> git.sesse.net Git - movit/blob - init.cpp
Fix a buffer overflow in ycbcr_conversion_effect_test.
[movit] / init.cpp
1 #include <epoxy/gl.h>
2 #include <assert.h>
3 #include <stddef.h>
4 #include <algorithm>
5 #include <string>
6
7 #include "init.h"
8 #include "resource_pool.h"
9 #include "util.h"
10
11 using namespace std;
12
13 namespace movit {
14
15 bool movit_initialized = false;
16 MovitDebugLevel movit_debug_level = MOVIT_DEBUG_ON;
17 float movit_texel_subpixel_precision;
18 bool movit_srgb_textures_supported;
19 bool movit_timer_queries_supported;
20 int movit_num_wrongly_rounded;
21 bool movit_shader_rounding_supported;
22 MovitShaderModel movit_shader_model;
23
24 // The rules for objects with nontrivial constructors in static scope
25 // are somewhat convoluted, and easy to mess up. We simply have a
26 // pointer instead (and never care to clean it up).
27 string *movit_data_directory = NULL;
28
29 namespace {
30
31 void measure_texel_subpixel_precision()
32 {
33         ResourcePool resource_pool;
34         static const unsigned width = 4096;
35
36         // Generate a destination texture to render to, and an FBO.
37         GLuint dst_texnum, fbo;
38
39         glGenTextures(1, &dst_texnum);
40         check_error();
41         glBindTexture(GL_TEXTURE_2D, dst_texnum);
42         check_error();
43         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, 1, 0, GL_RGBA, GL_FLOAT, NULL);
44         check_error();
45
46         glGenFramebuffers(1, &fbo);
47         check_error();
48         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
49         check_error();
50         glFramebufferTexture2D(
51                 GL_FRAMEBUFFER,
52                 GL_COLOR_ATTACHMENT0,
53                 GL_TEXTURE_2D,
54                 dst_texnum,
55                 0);
56         check_error();
57
58         // Now generate a simple texture that's just [0,1].
59         GLuint src_texnum;
60         float texdata[] = { 0, 1 };
61         glGenTextures(1, &src_texnum);
62         check_error();
63         glBindTexture(GL_TEXTURE_2D, src_texnum);
64         check_error();
65         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
66         check_error();
67         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
68         check_error();
69         glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F, 2, 1, 0, GL_RED, GL_FLOAT, texdata);
70         check_error();
71
72         // Basic state.
73         glDisable(GL_BLEND);
74         check_error();
75         glDisable(GL_DEPTH_TEST);
76         check_error();
77         glDepthMask(GL_FALSE);
78         check_error();
79
80         glViewport(0, 0, width, 1);
81
82         GLuint glsl_program_num = resource_pool.compile_glsl_program(
83                 read_version_dependent_file("vs", "vert"),
84                 read_version_dependent_file("texture1d", "frag"));
85         glUseProgram(glsl_program_num);
86         check_error();
87         glUniform1i(glGetUniformLocation(glsl_program_num, "tex"), 0);  // Bind the 2D sampler.
88         check_error();
89
90         // Draw the texture stretched over a long quad, interpolating it out.
91         // Note that since the texel center is in (0.5), we need to adjust the
92         // texture coordinates in order not to get long stretches of (1,1,1,...)
93         // at the start and (...,0,0,0) at the end.
94         float vertices[] = {
95                 0.0f, 1.0f,
96                 0.0f, 0.0f,
97                 1.0f, 1.0f,
98                 1.0f, 0.0f
99         };
100         float texcoords[] = {
101                 0.25f, 0.0f,
102                 0.25f, 0.0f,
103                 0.75f, 0.0f,
104                 0.75f, 0.0f
105         };
106
107         GLuint vao;
108         glGenVertexArrays(1, &vao);
109         check_error();
110         glBindVertexArray(vao);
111         check_error();
112
113         GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
114         GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(texcoords), texcoords);
115
116         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
117         check_error();
118
119         cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
120         cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
121
122         glUseProgram(0);
123         check_error();
124
125         // Now read the data back and see what the card did.
126         // (We only look at the red channel; the others will surely be the same.)
127         // We assume a linear ramp; anything else will give sort of odd results here.
128         float out_data[width * 4];
129         glReadPixels(0, 0, width, 1, GL_RGBA, GL_FLOAT, out_data);
130         check_error();
131
132         float biggest_jump = 0.0f;
133         for (unsigned i = 1; i < width; ++i) {
134                 assert(out_data[i * 4] >= out_data[(i - 1) * 4]);
135                 biggest_jump = max(biggest_jump, out_data[i * 4] - out_data[(i - 1) * 4]);
136         }
137
138         assert(biggest_jump > 0.0);
139         movit_texel_subpixel_precision = biggest_jump;
140
141         // Clean up.
142         glBindTexture(GL_TEXTURE_2D, 0);
143         check_error();
144         glBindFramebuffer(GL_FRAMEBUFFER, 0);
145         check_error();
146         glDeleteFramebuffers(1, &fbo);
147         check_error();
148         glDeleteTextures(1, &dst_texnum);
149         check_error();
150         glDeleteTextures(1, &src_texnum);
151         check_error();
152
153         resource_pool.release_glsl_program(glsl_program_num);
154         glDeleteVertexArrays(1, &vao);
155         check_error();
156 }
157
158 void measure_roundoff_problems()
159 {
160         ResourcePool resource_pool;
161
162         // Generate a destination texture to render to, and an FBO.
163         GLuint dst_texnum, fbo;
164
165         glGenTextures(1, &dst_texnum);
166         check_error();
167         glBindTexture(GL_TEXTURE_2D, dst_texnum);
168         check_error();
169         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
170         check_error();
171
172         glGenFramebuffers(1, &fbo);
173         check_error();
174         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
175         check_error();
176         glFramebufferTexture2D(
177                 GL_FRAMEBUFFER,
178                 GL_COLOR_ATTACHMENT0,
179                 GL_TEXTURE_2D,
180                 dst_texnum,
181                 0);
182         check_error();
183
184         // Now generate a texture where every value except the last should be
185         // rounded up to the next one. However, there are cards (in highly
186         // common use) that can't do this right, for unknown reasons.
187         GLuint src_texnum;
188         float texdata[512];
189         for (int i = 0; i < 256; ++i) {
190                 texdata[i * 2 + 0] = (i + 0.48) / 255.0;
191                 texdata[i * 2 + 1] = (i + 0.52) / 255.0;
192         }
193         glGenTextures(1, &src_texnum);
194         check_error();
195         glBindTexture(GL_TEXTURE_2D, src_texnum);
196         check_error();
197         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
198         check_error();
199         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
200         check_error();
201         glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 512, 1, 0, GL_RED, GL_FLOAT, texdata);
202         check_error();
203
204         // Basic state.
205         glDisable(GL_BLEND);
206         check_error();
207         glDisable(GL_DEPTH_TEST);
208         check_error();
209         glDepthMask(GL_FALSE);
210         check_error();
211
212         glViewport(0, 0, 512, 1);
213
214         GLuint glsl_program_num = resource_pool.compile_glsl_program(
215                 read_version_dependent_file("vs", "vert"),
216                 read_version_dependent_file("texture1d", "frag"));
217         glUseProgram(glsl_program_num);
218         check_error();
219         glUniform1i(glGetUniformLocation(glsl_program_num, "tex"), 0);  // Bind the 2D sampler.
220
221         // Draw the texture stretched over a long quad, interpolating it out.
222         float vertices[] = {
223                 0.0f, 1.0f,
224                 0.0f, 0.0f,
225                 1.0f, 1.0f,
226                 1.0f, 0.0f
227         };
228
229         GLuint vao;
230         glGenVertexArrays(1, &vao);
231         check_error();
232         glBindVertexArray(vao);
233         check_error();
234
235         GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
236         GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same data.
237
238         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
239         check_error();
240
241         cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
242         cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
243
244         glUseProgram(0);
245         check_error();
246
247         // Now read the data back and see what the card did. (Ignore the last value.)
248         // (We only look at the red channel; the others will surely be the same.)
249         unsigned char out_data[512 * 4];
250         glReadPixels(0, 0, 512, 1, GL_RGBA, GL_UNSIGNED_BYTE, out_data);
251         check_error();
252
253         int wrongly_rounded = 0;
254         for (unsigned i = 0; i < 255; ++i) {
255                 if (out_data[(i * 2 + 0) * 4] != i) {
256                         ++wrongly_rounded;
257                 }
258                 if (out_data[(i * 2 + 1) * 4] != i + 1) {
259                         ++wrongly_rounded;
260                 }
261         }
262
263         movit_num_wrongly_rounded = wrongly_rounded;
264
265         // Clean up.
266         glBindTexture(GL_TEXTURE_2D, 0);
267         check_error();
268         glBindFramebuffer(GL_FRAMEBUFFER, 0);
269         check_error();
270         glDeleteFramebuffers(1, &fbo);
271         check_error();
272         glDeleteTextures(1, &dst_texnum);
273         check_error();
274         glDeleteTextures(1, &src_texnum);
275         check_error();
276
277         resource_pool.release_glsl_program(glsl_program_num);
278         glDeleteVertexArrays(1, &vao);
279         check_error();
280 }
281
282 struct RequiredExtension {
283         int min_equivalent_gl_version;
284         const char extension_name[64];
285 };
286 const RequiredExtension required_extensions[] = {
287         // We fundamentally need FBOs and floating-point textures.
288         // FBOs are covered by OpenGL 1.5, and are not an extension there.
289         // Floating-point textures are part of OpenGL 3.0 and newer.
290         { 15, "GL_ARB_framebuffer_object" },
291         { 30, "GL_ARB_texture_float" },
292
293         // We assume that we can use non-power-of-two textures without restrictions.
294         { 20, "GL_ARB_texture_non_power_of_two" },
295
296         // We also need GLSL fragment shaders.
297         { 20, "GL_ARB_fragment_shader" },
298         { 20, "GL_ARB_shading_language_100" },
299
300         // FlatInput and YCbCrInput uses PBOs. (They could in theory do without,
301         // but no modern card would really not provide it.)
302         { 21, "GL_ARB_pixel_buffer_object" },
303
304         // ResampleEffect uses RG textures to encode a two-component LUT.
305         // We also need GL_R several places, for single-channel input.
306         { 30, "GL_ARB_texture_rg" },
307 };
308
309 bool check_extensions()
310 {
311         // GLES generally doesn't use extensions as actively as desktop OpenGL.
312         // For now, we say that for GLES, we require GLES 3, which has everything
313         // we need.
314         if (!epoxy_is_desktop_gl()) {
315                 if (epoxy_gl_version() >= 30) {
316                         movit_srgb_textures_supported = true;
317                         movit_shader_rounding_supported = true;
318                         return true;
319                 } else {
320                         fprintf(stderr, "Movit system requirements: GLES version %.1f is too old (GLES 3.0 needed).\n",
321                                 0.1f * epoxy_gl_version());
322                         fprintf(stderr, "Movit initialization failed.\n");
323                         return false;
324                 }
325         }
326
327         // Check all extensions, and output errors for the ones that we are missing.
328         bool all_ok = true;
329         int gl_version = epoxy_gl_version();
330
331         for (unsigned i = 0; i < sizeof(required_extensions) / sizeof(required_extensions[0]); ++i) {
332                 if (gl_version < required_extensions[i].min_equivalent_gl_version &&
333                     !epoxy_has_gl_extension(required_extensions[i].extension_name)) {
334                         fprintf(stderr, "Movit system requirements: Needs extension '%s' or at least OpenGL version %.1f (has version %.1f)\n",
335                                 required_extensions[i].extension_name,
336                                 0.1f * required_extensions[i].min_equivalent_gl_version,
337                                 0.1f * gl_version);
338                         all_ok = false;
339                 }
340         }
341
342         if (!all_ok) {
343                 fprintf(stderr, "Movit initialization failed.\n");
344                 return false;
345         }
346
347         // sRGB texture decode would be nice, but are not mandatory
348         // (GammaExpansionEffect can do the same thing if needed).
349         movit_srgb_textures_supported =
350                 (epoxy_gl_version() >= 21 || epoxy_has_gl_extension("GL_EXT_texture_sRGB"));
351
352         // We may want to use round() at the end of the final shader,
353         // if supported. We need either GLSL 1.30 or this extension to do that,
354         // and 1.30 brings with it other things that we don't want to demand
355         // for now.
356         movit_shader_rounding_supported =
357                 (epoxy_gl_version() >= 30 || epoxy_has_gl_extension("GL_EXT_gpu_shader4"));
358
359         // The user can specify that they want a timing report for each
360         // phase in an effect chain. However, that depends on this extension;
361         // without it, we do cannot even create the query objects.
362         movit_timer_queries_supported =
363                 (epoxy_gl_version() >= 33 || epoxy_has_gl_extension("GL_ARB_timer_query"));
364
365         return true;
366 }
367
368 double get_glsl_version()
369 {
370         char *glsl_version_str = strdup((const char *)glGetString(GL_SHADING_LANGUAGE_VERSION));
371
372         // Skip past the first period.
373         char *ptr = strchr(glsl_version_str, '.');
374         assert(ptr != NULL);
375         ++ptr;
376
377         // Now cut the string off at the next period or space, whatever comes first
378         // (unless the string ends first).
379         while (*ptr && *ptr != '.' && *ptr != ' ') {
380                 ++ptr;
381         }
382         *ptr = '\0';
383
384         // Now we have something on the form X.YY. We convert it to a float, and hope
385         // that if it's inexact (e.g. 1.30), atof() will round the same way the
386         // compiler will.
387         float glsl_version = atof(glsl_version_str);
388         free(glsl_version_str);
389
390         return glsl_version;
391 }
392
393 void APIENTRY debug_callback(GLenum source,
394                              GLenum type,
395                              GLuint id,
396                              GLenum severity,
397                              GLsizei length,
398                              const char *message,
399                              const void *userParam)
400 {
401         printf("Debug: %s\n", message);
402 }
403
404 }  // namespace
405
406 bool init_movit(const string& data_directory, MovitDebugLevel debug_level)
407 {
408         if (movit_initialized) {
409                 return true;
410         }
411
412         movit_data_directory = new string(data_directory);
413         movit_debug_level = debug_level;
414
415         // geez 
416         glPixelStorei(GL_PACK_ALIGNMENT, 1);
417         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
418         glDisable(GL_DITHER);
419
420         // You can turn this on if you want detailed debug messages from the driver.
421         // You should probably also ask for a debug context (see gtest_sdl_main.cpp),
422         // or you might not get much data back.
423         // glDebugMessageCallbackARB(callback, NULL);
424         // glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
425
426         if (!check_extensions()) {
427                 return false;
428         }
429
430         // Find out what shader model we should compile for.
431         if (epoxy_is_desktop_gl()) {
432                 if (get_glsl_version() >= 1.30) {
433                         movit_shader_model = MOVIT_GLSL_130;
434                 } else {
435                         movit_shader_model = MOVIT_GLSL_110;
436                 }
437         } else {
438                 movit_shader_model = MOVIT_ESSL_300;
439         }
440
441         measure_texel_subpixel_precision();
442         measure_roundoff_problems();
443
444         movit_initialized = true;
445         return true;
446 }
447
448 }  // namespace movit