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