6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
27 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
33 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
34 constexpr float patch_overlap_ratio = 0.75f;
35 constexpr unsigned coarsest_level = 5;
36 constexpr unsigned finest_level = 1;
37 constexpr unsigned patch_size_pixels = 12;
39 // Weighting constants for the different parts of the variational refinement.
40 // These don't correspond 1:1 to the values given in the DIS paper,
41 // since we have different normalizations and ranges in some cases.
42 // These are found through a simple grid search on some MPI-Sintel data,
43 // although the error (EPE) seems to be fairly insensitive to the precise values.
44 // Only the relative values matter, so we fix alpha (the smoothness constant)
45 // at unity and tweak the others.
46 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
48 bool enable_timing = true;
49 bool enable_variational_refinement = true; // Just for debugging.
50 bool enable_interpolation = false;
52 // Some global OpenGL objects.
53 // TODO: These should really be part of DISComputeFlow.
54 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
57 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
58 struct ReadInProgress {
60 string filename0, filename1;
61 string flow_filename, ppm_filename; // Either may be empty for no write.
63 stack<GLuint> spare_pbos;
64 deque<ReadInProgress> reads_in_progress;
66 int find_num_levels(int width, int height)
69 for (int w = width, h = height; w > 1 || h > 1; ) {
77 string read_file(const string &filename)
79 FILE *fp = fopen(filename.c_str(), "r");
81 perror(filename.c_str());
85 int ret = fseek(fp, 0, SEEK_END);
87 perror("fseek(SEEK_END)");
93 ret = fseek(fp, 0, SEEK_SET);
95 perror("fseek(SEEK_SET)");
101 ret = fread(&str[0], size, 1, fp);
107 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
108 size, filename.c_str());
117 GLuint compile_shader(const string &shader_src, GLenum type)
119 GLuint obj = glCreateShader(type);
120 const GLchar* source[] = { shader_src.data() };
121 const GLint length[] = { (GLint)shader_src.size() };
122 glShaderSource(obj, 1, source, length);
123 glCompileShader(obj);
125 GLchar info_log[4096];
126 GLsizei log_length = sizeof(info_log) - 1;
127 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
128 info_log[log_length] = 0;
129 if (strlen(info_log) > 0) {
130 fprintf(stderr, "Shader compile log: %s\n", info_log);
134 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
135 if (status == GL_FALSE) {
136 // Add some line numbers to easier identify compile errors.
137 string src_with_lines = "/* 1 */ ";
139 for (char ch : shader_src) {
140 src_with_lines.push_back(ch);
143 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
144 src_with_lines += buf;
148 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
160 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
162 SDL_Surface *surf = IMG_Load(filename);
163 if (surf == nullptr) {
164 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
168 // For whatever reason, SDL doesn't support converting to YUV surfaces
169 // nor grayscale, so we'll do it ourselves.
170 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
171 if (rgb_surf == nullptr) {
172 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
176 SDL_FreeSurface(surf);
178 unsigned width = rgb_surf->w, height = rgb_surf->h;
179 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
180 unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
182 // Extract the Y component, and convert to bottom-left origin.
183 for (unsigned y = 0; y < height; ++y) {
184 unsigned y2 = height - 1 - y;
185 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
187 SDL_FreeSurface(rgb_surf);
189 int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
192 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
193 glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
194 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
196 if (mipmaps == WITH_MIPMAPS) {
197 glGenerateTextureMipmap(tex);
201 *height_ret = height;
206 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
208 GLuint program = glCreateProgram();
209 glAttachShader(program, vs_obj);
210 glAttachShader(program, fs_obj);
211 glLinkProgram(program);
213 glGetProgramiv(program, GL_LINK_STATUS, &success);
214 if (success == GL_FALSE) {
215 GLchar error_log[1024] = {0};
216 glGetProgramInfoLog(program, 1024, nullptr, error_log);
217 fprintf(stderr, "Error linking program: %s\n", error_log);
223 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
226 glCreateBuffers(1, &vbo);
227 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
228 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
232 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
234 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
239 GLuint vbo = generate_vbo(size, data_size, data);
241 glBindBuffer(GL_ARRAY_BUFFER, vbo);
242 glEnableVertexArrayAttrib(vao, attrib);
243 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
244 glBindBuffer(GL_ARRAY_BUFFER, 0);
249 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
251 if (location == -1) {
255 glBindTextureUnit(texture_unit, tex);
256 glBindSampler(texture_unit, sampler);
257 glProgramUniform1i(program, location, texture_unit);
260 // A class that caches FBOs that render to a given set of textures.
261 // It never frees anything, so it is only suitable for rendering to
262 // the same (small) set of textures over and over again.
263 template<size_t num_elements>
264 class PersistentFBOSet {
266 void render_to(const array<GLuint, num_elements> &textures);
268 // Convenience wrappers.
269 void render_to(GLuint texture0, enable_if<num_elements == 1> * = nullptr) {
270 render_to({{texture0}});
273 void render_to(GLuint texture0, GLuint texture1, enable_if<num_elements == 2> * = nullptr) {
274 render_to({{texture0, texture1}});
277 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, enable_if<num_elements == 3> * = nullptr) {
278 render_to({{texture0, texture1, texture2}});
281 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3, enable_if<num_elements == 4> * = nullptr) {
282 render_to({{texture0, texture1, texture2, texture3}});
286 // TODO: Delete these on destruction.
287 map<array<GLuint, num_elements>, GLuint> fbos;
290 template<size_t num_elements>
291 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
293 auto it = fbos.find(textures);
294 if (it != fbos.end()) {
295 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
300 glCreateFramebuffers(1, &fbo);
301 GLenum bufs[num_elements];
302 for (size_t i = 0; i < num_elements; ++i) {
303 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
304 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
306 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
308 fbos[textures] = fbo;
309 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
312 // Convert RGB to grayscale, using Rec. 709 coefficients.
313 class GrayscaleConversion {
315 GrayscaleConversion();
316 void exec(GLint tex, GLint gray_tex, int width, int height);
319 PersistentFBOSet<1> fbos;
328 GrayscaleConversion::GrayscaleConversion()
330 gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
331 gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
332 gray_program = link_program(gray_vs_obj, gray_fs_obj);
334 // Set up the VAO containing all the required position/texcoord data.
335 glCreateVertexArrays(1, &gray_vao);
336 glBindVertexArray(gray_vao);
338 GLint position_attrib = glGetAttribLocation(gray_program, "position");
339 glEnableVertexArrayAttrib(gray_vao, position_attrib);
340 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
342 uniform_tex = glGetUniformLocation(gray_program, "tex");
345 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
347 glUseProgram(gray_program);
348 bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
350 glViewport(0, 0, width, height);
351 fbos.render_to(gray_tex);
352 glBindVertexArray(gray_vao);
353 glUseProgram(gray_program);
355 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
358 // Compute gradients in every point, used for the motion search.
359 // The DIS paper doesn't actually mention how these are computed,
360 // but seemingly, a 3x3 Sobel operator is used here (at least in
361 // later versions of the code), while a [1 -8 0 8 -1] kernel is
362 // used for all the derivatives in the variational refinement part
363 // (which borrows code from DeepFlow). This is inconsistent,
364 // but I guess we're better off with staying with the original
365 // decisions until we actually know having different ones would be better.
369 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
372 PersistentFBOSet<1> fbos;
375 GLuint sobel_program;
383 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
384 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
385 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
387 // Set up the VAO containing all the required position/texcoord data.
388 glCreateVertexArrays(1, &sobel_vao);
389 glBindVertexArray(sobel_vao);
391 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
392 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
393 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
395 uniform_tex = glGetUniformLocation(sobel_program, "tex");
398 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
400 glUseProgram(sobel_program);
401 bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
403 glViewport(0, 0, level_width, level_height);
404 fbos.render_to(grad0_tex);
405 glBindVertexArray(sobel_vao);
406 glUseProgram(sobel_program);
408 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
411 // Motion search to find the initial flow. See motion_search.frag for documentation.
415 void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
418 PersistentFBOSet<1> fbos;
420 GLuint motion_vs_obj;
421 GLuint motion_fs_obj;
422 GLuint motion_search_program;
423 GLuint motion_search_vao;
425 GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
426 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
429 MotionSearch::MotionSearch()
431 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
432 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
433 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
435 // Set up the VAO containing all the required position/texcoord data.
436 glCreateVertexArrays(1, &motion_search_vao);
437 glBindVertexArray(motion_search_vao);
438 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
440 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
441 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
442 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
444 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
445 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
446 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
447 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
448 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
449 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
452 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
454 glUseProgram(motion_search_program);
456 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
457 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
458 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
459 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
461 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
462 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
464 glViewport(0, 0, width_patches, height_patches);
465 fbos.render_to(flow_out_tex);
466 glBindVertexArray(motion_search_vao);
467 glUseProgram(motion_search_program);
468 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
471 // Do “densification”, ie., upsampling of the flow patches to the flow field
472 // (the same size as the image at this level). We draw one quad per patch
473 // over its entire covered area (using instancing in the vertex shader),
474 // and then weight the contributions in the pixel shader by post-warp difference.
475 // This is equation (3) in the paper.
477 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
478 // weight in the B channel. Dividing R and G by B gives the normalized values.
482 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
485 PersistentFBOSet<1> fbos;
487 GLuint densify_vs_obj;
488 GLuint densify_fs_obj;
489 GLuint densify_program;
492 GLuint uniform_patch_size, uniform_patch_spacing;
493 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
498 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
499 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
500 densify_program = link_program(densify_vs_obj, densify_fs_obj);
502 // Set up the VAO containing all the required position/texcoord data.
503 glCreateVertexArrays(1, &densify_vao);
504 glBindVertexArray(densify_vao);
505 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
507 GLint position_attrib = glGetAttribLocation(densify_program, "position");
508 glEnableVertexArrayAttrib(densify_vao, position_attrib);
509 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
511 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
512 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
513 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
514 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
515 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
518 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
520 glUseProgram(densify_program);
522 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
523 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
524 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
526 glProgramUniform2f(densify_program, uniform_patch_size,
527 float(patch_size_pixels) / level_width,
528 float(patch_size_pixels) / level_height);
530 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
531 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
532 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
533 if (height_patches == 1) patch_spacing_y = 0.0f;
534 glProgramUniform2f(densify_program, uniform_patch_spacing,
535 patch_spacing_x / level_width,
536 patch_spacing_y / level_height);
538 glViewport(0, 0, level_width, level_height);
540 glBlendFunc(GL_ONE, GL_ONE);
541 glBindVertexArray(densify_vao);
542 fbos.render_to(dense_flow_tex);
543 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
546 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
547 // I_0 and I_w. The prewarping is what enables us to solve the variational
548 // flow for du,dv instead of u,v.
550 // Also calculates the normalized flow, ie. divides by z (this is needed because
551 // Densify works by additive blending) and multiplies by the image size.
553 // See variational_refinement.txt for more information.
557 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
560 PersistentFBOSet<3> fbos;
562 GLuint prewarp_vs_obj;
563 GLuint prewarp_fs_obj;
564 GLuint prewarp_program;
567 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
572 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
573 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
574 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
576 // Set up the VAO containing all the required position/texcoord data.
577 glCreateVertexArrays(1, &prewarp_vao);
578 glBindVertexArray(prewarp_vao);
579 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
581 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
582 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
583 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
585 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
586 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
587 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
590 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
592 glUseProgram(prewarp_program);
594 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
595 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
596 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
598 glViewport(0, 0, level_width, level_height);
600 glBindVertexArray(prewarp_vao);
601 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
602 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
605 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
606 // central difference filter, since apparently, that's tradition (I haven't
607 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
608 // The coefficients come from
610 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
612 // Also computes β_0, since it depends only on I_x and I_y.
616 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
619 PersistentFBOSet<2> fbos;
621 GLuint derivatives_vs_obj;
622 GLuint derivatives_fs_obj;
623 GLuint derivatives_program;
624 GLuint derivatives_vao;
629 Derivatives::Derivatives()
631 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
632 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
633 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
635 // Set up the VAO containing all the required position/texcoord data.
636 glCreateVertexArrays(1, &derivatives_vao);
637 glBindVertexArray(derivatives_vao);
638 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
640 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
641 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
642 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
644 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
647 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
649 glUseProgram(derivatives_program);
651 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
653 glViewport(0, 0, level_width, level_height);
655 glBindVertexArray(derivatives_vao);
656 fbos.render_to(I_x_y_tex, beta_0_tex);
657 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
660 // Calculate the smoothness constraints between neighboring pixels;
661 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
662 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
663 // border color (0,0) later, so that there's zero diffusion out of
666 // See variational_refinement.txt for more information.
667 class ComputeSmoothness {
670 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
673 PersistentFBOSet<2> fbos;
675 GLuint smoothness_vs_obj;
676 GLuint smoothness_fs_obj;
677 GLuint smoothness_program;
678 GLuint smoothness_vao;
680 GLuint uniform_flow_tex, uniform_diff_flow_tex;
681 GLuint uniform_alpha;
684 ComputeSmoothness::ComputeSmoothness()
686 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
687 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
688 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
690 // Set up the VAO containing all the required position/texcoord data.
691 glCreateVertexArrays(1, &smoothness_vao);
692 glBindVertexArray(smoothness_vao);
693 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
695 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
696 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
697 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
699 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
700 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
701 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
704 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
706 glUseProgram(smoothness_program);
708 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
709 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
710 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
712 glViewport(0, 0, level_width, level_height);
715 glBindVertexArray(smoothness_vao);
716 fbos.render_to(smoothness_x_tex, smoothness_y_tex);
717 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
719 // Make sure the smoothness on the right and upper borders is zero.
720 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
721 // (we're sampling smoothness with all-zero border color), but we'd
722 // have to adjust the sampling coordinates, which is annoying.
723 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
724 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
727 // Set up the equations set (two equations in two unknowns, per pixel).
728 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
729 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
730 // floats. (Actually, we store the inverse of the diagonal elements, because
731 // we only ever need to divide by them.) This fits into four u32 values;
732 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
733 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
734 // terms that depend on other pixels, are calculated in one pass.
736 // See variational_refinement.txt for more information.
737 class SetupEquations {
740 void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height);
743 PersistentFBOSet<1> fbos;
745 GLuint equations_vs_obj;
746 GLuint equations_fs_obj;
747 GLuint equations_program;
748 GLuint equations_vao;
750 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
751 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
752 GLuint uniform_beta_0_tex;
753 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
754 GLuint uniform_gamma, uniform_delta;
757 SetupEquations::SetupEquations()
759 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
760 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
761 equations_program = link_program(equations_vs_obj, equations_fs_obj);
763 // Set up the VAO containing all the required position/texcoord data.
764 glCreateVertexArrays(1, &equations_vao);
765 glBindVertexArray(equations_vao);
766 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
768 GLint position_attrib = glGetAttribLocation(equations_program, "position");
769 glEnableVertexArrayAttrib(equations_vao, position_attrib);
770 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
772 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
773 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
774 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
775 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
776 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
777 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
778 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
779 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
780 uniform_delta = glGetUniformLocation(equations_program, "delta");
783 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
785 glUseProgram(equations_program);
787 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
788 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
789 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
790 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
791 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
792 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
793 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
794 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
795 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
797 glViewport(0, 0, level_width, level_height);
799 glBindVertexArray(equations_vao);
800 fbos.render_to(equation_tex);
801 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
804 // Actually solve the equation sets made by SetupEquations, by means of
805 // successive over-relaxation (SOR).
807 // See variational_refinement.txt for more information.
811 void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
814 PersistentFBOSet<1> fbos;
821 GLuint uniform_diff_flow_tex;
822 GLuint uniform_equation_tex;
823 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
824 GLuint uniform_phase;
829 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
830 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
831 sor_program = link_program(sor_vs_obj, sor_fs_obj);
833 // Set up the VAO containing all the required position/texcoord data.
834 glCreateVertexArrays(1, &sor_vao);
835 glBindVertexArray(sor_vao);
836 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
838 GLint position_attrib = glGetAttribLocation(sor_program, "position");
839 glEnableVertexArrayAttrib(sor_vao, position_attrib);
840 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
842 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
843 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
844 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
845 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
846 uniform_phase = glGetUniformLocation(sor_program, "phase");
849 void SOR::exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations)
851 glUseProgram(sor_program);
853 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
854 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
855 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
856 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
858 // NOTE: We bind to the texture we are rendering from, but we never write any value
859 // that we read in the same shader pass (we call discard for red values when we compute
860 // black, and vice versa), and we have barriers between the passes, so we're fine
862 glViewport(0, 0, level_width, level_height);
864 glBindVertexArray(sor_vao);
865 fbos.render_to(diff_flow_tex);
867 for (int i = 0; i < num_iterations; ++i) {
868 glProgramUniform1i(sor_program, uniform_phase, 0);
869 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
871 glProgramUniform1i(sor_program, uniform_phase, 1);
872 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
873 if (i != num_iterations - 1) {
879 // Simply add the differential flow found by the variational refinement to the base flow.
880 // The output is in base_flow_tex; we don't need to make a new texture.
884 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
887 PersistentFBOSet<1> fbos;
889 GLuint add_flow_vs_obj;
890 GLuint add_flow_fs_obj;
891 GLuint add_flow_program;
894 GLuint uniform_diff_flow_tex;
897 AddBaseFlow::AddBaseFlow()
899 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
900 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
901 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
903 // Set up the VAO containing all the required position/texcoord data.
904 glCreateVertexArrays(1, &add_flow_vao);
905 glBindVertexArray(add_flow_vao);
906 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
908 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
909 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
910 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
912 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
915 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
917 glUseProgram(add_flow_program);
919 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
921 glViewport(0, 0, level_width, level_height);
923 glBlendFunc(GL_ONE, GL_ONE);
924 glBindVertexArray(add_flow_vao);
925 fbos.render_to(base_flow_tex);
927 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
930 // Take a copy of the flow, bilinearly interpolated and scaled up.
934 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
937 PersistentFBOSet<1> fbos;
939 GLuint resize_flow_vs_obj;
940 GLuint resize_flow_fs_obj;
941 GLuint resize_flow_program;
942 GLuint resize_flow_vao;
944 GLuint uniform_flow_tex;
945 GLuint uniform_scale_factor;
948 ResizeFlow::ResizeFlow()
950 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
951 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
952 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
954 // Set up the VAO containing all the required position/texcoord data.
955 glCreateVertexArrays(1, &resize_flow_vao);
956 glBindVertexArray(resize_flow_vao);
957 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
959 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
960 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
961 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
963 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
964 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
967 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
969 glUseProgram(resize_flow_program);
971 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
973 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
975 glViewport(0, 0, output_width, output_height);
977 glBindVertexArray(resize_flow_vao);
978 fbos.render_to(out_tex);
980 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
986 pair<GLuint, GLuint> begin_timer(const string &name, int level);
992 pair<GLuint, GLuint> query;
994 vector<Timer> timers;
997 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
999 if (!enable_timing) {
1000 return make_pair(0, 0);
1004 glGenQueries(2, queries);
1005 glQueryCounter(queries[0], GL_TIMESTAMP);
1009 timer.level = level;
1010 timer.query.first = queries[0];
1011 timer.query.second = queries[1];
1012 timers.push_back(timer);
1016 void GPUTimers::print()
1018 for (const Timer &timer : timers) {
1019 // NOTE: This makes the CPU wait for the GPU.
1020 GLuint64 time_start, time_end;
1021 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
1022 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
1023 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
1024 for (int i = 0; i < timer.level * 2; ++i) {
1025 fprintf(stderr, " ");
1027 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
1031 // A simple RAII class for timing until the end of the scope.
1034 ScopedTimer(const string &name, GPUTimers *timers)
1035 : timers(timers), level(0)
1037 query = timers->begin_timer(name, level);
1040 ScopedTimer(const string &name, ScopedTimer *parent_timer)
1041 : timers(parent_timer->timers),
1042 level(parent_timer->level + 1)
1044 query = timers->begin_timer(name, level);
1054 if (enable_timing && !ended) {
1055 glQueryCounter(query.second, GL_TIMESTAMP);
1063 pair<GLuint, GLuint> query;
1069 GLuint get_texture(GLenum format, GLuint width, GLuint height);
1070 void release_texture(GLuint tex_num);
1076 GLuint width, height;
1077 bool in_use = false;
1079 vector<Texture> textures;
1082 class DISComputeFlow {
1084 DISComputeFlow(int width, int height);
1086 enum ResizeStrategy {
1088 RESIZE_FLOW_TO_FULL_SIZE
1091 // Returns a texture that must be released with release_texture()
1093 GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
1095 void release_texture(GLuint tex) {
1096 pool.release_texture(tex);
1101 GLuint initial_flow_tex;
1104 // The various passes.
1106 MotionSearch motion_search;
1109 Derivatives derivatives;
1110 ComputeSmoothness compute_smoothness;
1111 SetupEquations setup_equations;
1113 AddBaseFlow add_base_flow;
1114 ResizeFlow resize_flow;
1117 DISComputeFlow::DISComputeFlow(int width, int height)
1118 : width(width), height(height)
1120 // Make some samplers.
1121 glCreateSamplers(1, &nearest_sampler);
1122 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1123 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1124 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1125 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1127 glCreateSamplers(1, &linear_sampler);
1128 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1129 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1130 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1131 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1133 // The smoothness is sampled so that once we get to a smoothness involving
1134 // a value outside the border, the diffusivity between the two becomes zero.
1135 // Similarly, gradients are zero outside the border, since the edge is taken
1137 glCreateSamplers(1, &zero_border_sampler);
1138 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1139 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1140 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1141 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1142 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1143 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1145 // Initial flow is zero, 1x1.
1146 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1147 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1148 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1151 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1153 int prev_level_width = 1, prev_level_height = 1;
1154 GLuint prev_level_flow_tex = initial_flow_tex;
1158 ScopedTimer total_timer("Total", &timers);
1159 for (int level = coarsest_level; level >= int(finest_level); --level) {
1160 char timer_name[256];
1161 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1162 ScopedTimer level_timer(timer_name, &total_timer);
1164 int level_width = width >> level;
1165 int level_height = height >> level;
1166 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1168 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1169 // and patch_spacing=3 (the default), we put out patch centers in
1170 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1171 // lock all the centers to integer coordinates if needed.
1172 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1173 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1175 // Make sure we always read from the correct level; the chosen
1176 // mipmapping could otherwise be rather unpredictable, especially
1177 // during motion search.
1178 GLuint tex0_view, tex1_view;
1179 glGenTextures(1, &tex0_view);
1180 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1181 glGenTextures(1, &tex1_view);
1182 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1184 // Create a new texture; we could be fancy and render use a multi-level
1185 // texture, but meh.
1186 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1188 // Find the derivative.
1190 ScopedTimer timer("Sobel", &level_timer);
1191 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1194 // Motion search to find the initial flow. We use the flow from the previous
1195 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1197 // Create an output flow texture.
1198 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1202 ScopedTimer timer("Motion search", &level_timer);
1203 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1205 pool.release_texture(grad0_tex);
1209 // Set up an output texture (initially zero).
1210 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1211 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1215 ScopedTimer timer("Densification", &level_timer);
1216 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1218 pool.release_texture(flow_out_tex);
1220 // Everything below here in the loop belongs to variational refinement.
1221 ScopedTimer varref_timer("Variational refinement", &level_timer);
1223 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1224 // have to normalize it over and over again, and also save some bandwidth).
1226 // During the entire rest of the variational refinement, flow will be measured
1227 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1228 // This is because variational refinement depends so heavily on derivatives,
1229 // which are measured in intensity levels per pixel.
1230 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1231 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1232 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1234 ScopedTimer timer("Prewarping", &varref_timer);
1235 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1237 pool.release_texture(dense_flow_tex);
1238 glDeleteTextures(1, &tex0_view);
1239 glDeleteTextures(1, &tex1_view);
1241 // Calculate I_x and I_y. We're only calculating first derivatives;
1242 // the others will be taken on-the-fly in order to sample from fewer
1243 // textures overall, since sampling from the L1 cache is cheap.
1244 // (TODO: Verify that this is indeed faster than making separate
1245 // double-derivative textures.)
1246 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1247 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1249 ScopedTimer timer("First derivatives", &varref_timer);
1250 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1252 pool.release_texture(I_tex);
1254 // We need somewhere to store du and dv (the flow increment, relative
1255 // to the non-refined base flow u0 and v0). It starts at zero.
1256 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1257 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1259 // And for smoothness.
1260 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1261 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1263 // And finally for the equation set. See SetupEquations for
1264 // the storage format.
1265 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1267 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1268 // Calculate the smoothness terms between the neighboring pixels,
1269 // both in x and y direction.
1271 ScopedTimer timer("Compute smoothness", &varref_timer);
1272 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1275 // Set up the 2x2 equation system for each pixel.
1277 ScopedTimer timer("Set up equations", &varref_timer);
1278 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1281 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1282 // Note that these are to/from the same texture.
1284 ScopedTimer timer("SOR", &varref_timer);
1285 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1289 pool.release_texture(I_t_tex);
1290 pool.release_texture(I_x_y_tex);
1291 pool.release_texture(beta_0_tex);
1292 pool.release_texture(smoothness_x_tex);
1293 pool.release_texture(smoothness_y_tex);
1294 pool.release_texture(equation_tex);
1296 // Add the differential flow found by the variational refinement to the base flow,
1297 // giving the final flow estimate for this level.
1298 // The output is in diff_flow_tex; we don't need to make a new texture.
1300 // Disabling this doesn't save any time (although we could easily make it so that
1301 // it is more efficient), but it helps debug the motion search.
1302 if (enable_variational_refinement) {
1303 ScopedTimer timer("Add differential flow", &varref_timer);
1304 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1306 pool.release_texture(du_dv_tex);
1308 if (prev_level_flow_tex != initial_flow_tex) {
1309 pool.release_texture(prev_level_flow_tex);
1311 prev_level_flow_tex = base_flow_tex;
1312 prev_level_width = level_width;
1313 prev_level_height = level_height;
1319 // Scale up the flow to the final size (if needed).
1320 if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1321 return prev_level_flow_tex;
1323 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1324 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1325 pool.release_texture(prev_level_flow_tex);
1330 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1331 // radius fills most of the holes.
1336 // alpha is the time of the interpolated frame (0..1).
1337 void exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha);
1340 PersistentFBOSet<2> fbos;
1342 GLuint splat_vs_obj;
1343 GLuint splat_fs_obj;
1344 GLuint splat_program;
1347 GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1348 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1349 GLuint uniform_inv_flow_size;
1354 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1355 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1356 splat_program = link_program(splat_vs_obj, splat_fs_obj);
1358 // Set up the VAO containing all the required position/texcoord data.
1359 glCreateVertexArrays(1, &splat_vao);
1360 glBindVertexArray(splat_vao);
1361 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1363 GLint position_attrib = glGetAttribLocation(splat_program, "position");
1364 glEnableVertexArrayAttrib(splat_vao, position_attrib);
1365 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1367 uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1368 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1369 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1370 uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1371 uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1372 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1373 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1376 void Splat::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha)
1378 glUseProgram(splat_program);
1380 bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1381 bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1383 // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1384 // Move to 2.0 later.
1385 float splat_size = 1.0f; // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1386 glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1387 glProgramUniform1f(splat_program, uniform_alpha, alpha);
1388 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1390 glViewport(0, 0, width, height);
1391 glDisable(GL_BLEND);
1392 glEnable(GL_DEPTH_TEST);
1393 glDepthFunc(GL_LESS); // We store the difference between I_0 and I_1, where less difference is good. (Default 1.0 is effectively +inf, which always loses.)
1394 glBindVertexArray(splat_vao);
1396 // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1398 glCreateFramebuffers(1, &fbo);
1399 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0);
1400 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1401 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1403 // Do forward splatting.
1404 bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1405 glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1406 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1408 // Do backward splatting.
1409 bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1410 glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1411 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1413 glDisable(GL_DEPTH_TEST);
1415 glDeleteFramebuffers(1, &fbo);
1421 void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1424 PersistentFBOSet<1> fbos;
1425 GLuint blend_vs_obj;
1426 GLuint blend_fs_obj;
1427 GLuint blend_program;
1430 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1431 GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1436 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1437 blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1438 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1440 // Set up the VAO containing all the required position/texcoord data.
1441 glCreateVertexArrays(1, &blend_vao);
1442 glBindVertexArray(blend_vao);
1444 GLint position_attrib = glGetAttribLocation(blend_program, "position");
1445 glEnableVertexArrayAttrib(blend_vao, position_attrib);
1446 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1448 uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1449 uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1450 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1451 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1452 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1455 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1457 glUseProgram(blend_program);
1458 bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1459 bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1460 bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler); // May be upsampled.
1461 glProgramUniform1f(blend_program, uniform_alpha, alpha);
1462 //glProgramUniform1f(blend_program, uniform_flow_consistency_tolerance, 1.0f /
1464 glViewport(0, 0, level_width, level_height);
1465 fbos.render_to(output_tex);
1466 glBindVertexArray(blend_vao);
1467 glUseProgram(blend_program);
1468 glDisable(GL_BLEND); // A bit ironic, perhaps.
1469 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1474 Interpolate(int width, int height, int flow_level);
1476 // Returns a texture that must be released with release_texture()
1477 // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1478 // (unless flow_level == 0).
1479 GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1481 void release_texture(GLuint tex) {
1482 pool.release_texture(tex);
1486 int width, height, flow_level;
1492 Interpolate::Interpolate(int width, int height, int flow_level)
1493 : width(width), height(height), flow_level(flow_level) {}
1495 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1499 ScopedTimer total_timer("Total", &timers);
1501 // Pick out the right level to test splatting results on.
1502 GLuint tex0_view, tex1_view;
1503 glGenTextures(1, &tex0_view);
1504 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1505 glGenTextures(1, &tex1_view);
1506 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1508 int flow_width = width >> flow_level;
1509 int flow_height = height >> flow_level;
1511 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1512 GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height); // Used for ranking flows.
1514 ScopedTimer timer("Clear", &total_timer);
1515 glClearTexImage(flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1516 float infinity = 1.0f;
1517 glClearTexImage(depth_tex, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &infinity);
1520 //SDL_GL_SwapWindow(window);
1522 ScopedTimer timer("Splat", &total_timer);
1523 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1525 //SDL_GL_SwapWindow(window);
1526 pool.release_texture(depth_tex);
1527 glDeleteTextures(1, &tex0_view);
1528 glDeleteTextures(1, &tex1_view);
1530 GLuint output_tex = pool.get_texture(GL_RGB8, width, height);
1532 ScopedTimer timer("Blend", &total_timer);
1533 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1541 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1543 for (Texture &tex : textures) {
1544 if (!tex.in_use && tex.format == format &&
1545 tex.width == width && tex.height == height) {
1552 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1553 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1554 tex.format = format;
1556 tex.height = height;
1558 textures.push_back(tex);
1562 void TexturePool::release_texture(GLuint tex_num)
1564 for (Texture &tex : textures) {
1565 if (tex.tex_num == tex_num) {
1574 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1575 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1577 for (unsigned i = 0; i < width * height; ++i) {
1578 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1582 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1584 FILE *flowfp = fopen(filename, "wb");
1585 fprintf(flowfp, "FEIH");
1586 fwrite(&width, 4, 1, flowfp);
1587 fwrite(&height, 4, 1, flowfp);
1588 for (unsigned y = 0; y < height; ++y) {
1589 int yy = height - y - 1;
1590 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1595 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1597 FILE *fp = fopen(filename, "wb");
1598 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1599 for (unsigned y = 0; y < unsigned(height); ++y) {
1600 int yy = height - y - 1;
1601 for (unsigned x = 0; x < unsigned(width); ++x) {
1602 float du = dense_flow[(yy * width + x) * 2 + 0];
1603 float dv = dense_flow[(yy * width + x) * 2 + 1];
1606 flow2rgb(du, dv, &r, &g, &b);
1615 void finish_one_read(GLuint width, GLuint height)
1617 assert(!reads_in_progress.empty());
1618 ReadInProgress read = reads_in_progress.front();
1619 reads_in_progress.pop_front();
1621 unique_ptr<float[]> flow(new float[width * height * 2]);
1622 void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * 2 * sizeof(float), GL_MAP_READ_BIT); // Blocks if the read isn't done yet.
1623 memcpy(flow.get(), buf, width * height * 2 * sizeof(float));
1624 glUnmapNamedBuffer(read.pbo);
1625 spare_pbos.push(read.pbo);
1627 flip_coordinate_system(flow.get(), width, height);
1628 if (!read.flow_filename.empty()) {
1629 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1630 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1632 if (!read.ppm_filename.empty()) {
1633 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1637 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1639 if (spare_pbos.empty()) {
1640 finish_one_read(width, height);
1642 assert(!spare_pbos.empty());
1643 reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1644 glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1646 glGetTextureImage(tex, 0, GL_RG, GL_FLOAT, width * height * 2 * sizeof(float), nullptr);
1647 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1650 void compute_flow_only(int argc, char **argv, int optind)
1652 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1653 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1654 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1657 unsigned width1, height1, width2, height2;
1658 GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1659 GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1661 if (width1 != width2 || height1 != height2) {
1662 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1663 width1, height1, width2, height2);
1667 // Set up some PBOs to do asynchronous readback.
1669 glCreateBuffers(5, pbos);
1670 for (int i = 0; i < 5; ++i) {
1671 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1672 spare_pbos.push(pbos[i]);
1675 int levels = find_num_levels(width1, height1);
1676 GLuint tex0_gray, tex1_gray;
1677 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1678 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1679 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1680 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1682 GrayscaleConversion gray;
1683 gray.exec(tex0, tex0_gray, width1, height1);
1684 glDeleteTextures(1, &tex0);
1685 glGenerateTextureMipmap(tex0_gray);
1687 gray.exec(tex1, tex1_gray, width1, height1);
1688 glDeleteTextures(1, &tex1);
1689 glGenerateTextureMipmap(tex1_gray);
1691 DISComputeFlow compute_flow(width1, height1);
1692 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1694 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1695 compute_flow.release_texture(final_tex);
1697 // See if there are more flows on the command line (ie., more than three arguments),
1698 // and if so, process them.
1699 int num_flows = (argc - optind) / 3;
1700 for (int i = 1; i < num_flows; ++i) {
1701 const char *filename0 = argv[optind + i * 3 + 0];
1702 const char *filename1 = argv[optind + i * 3 + 1];
1703 const char *flow_filename = argv[optind + i * 3 + 2];
1704 GLuint width, height;
1705 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1706 if (width != width1 || height != height1) {
1707 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1708 filename0, width, height, width1, height1);
1711 gray.exec(tex0, tex0_gray, width, height);
1712 glGenerateTextureMipmap(tex0_gray);
1713 glDeleteTextures(1, &tex0);
1715 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1716 if (width != width1 || height != height1) {
1717 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1718 filename1, width, height, width1, height1);
1721 gray.exec(tex1, tex1_gray, width, height);
1722 glGenerateTextureMipmap(tex1_gray);
1723 glDeleteTextures(1, &tex1);
1725 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1727 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1728 compute_flow.release_texture(final_tex);
1730 glDeleteTextures(1, &tex0_gray);
1731 glDeleteTextures(1, &tex1_gray);
1733 while (!reads_in_progress.empty()) {
1734 finish_one_read(width1, height1);
1738 // Interpolate images based on
1740 // Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1741 // Using Optical Flow”
1743 // or at least a reasonable subset thereof. Unfinished.
1744 void interpolate_image(int argc, char **argv, int optind)
1746 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1747 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1748 //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1751 unsigned width1, height1, width2, height2;
1752 GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1753 GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1755 if (width1 != width2 || height1 != height2) {
1756 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1757 width1, height1, width2, height2);
1761 // Set up some PBOs to do asynchronous readback.
1763 glCreateBuffers(5, pbos);
1764 for (int i = 0; i < 5; ++i) {
1765 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1766 spare_pbos.push(pbos[i]);
1769 DISComputeFlow compute_flow(width1, height1);
1770 GrayscaleConversion gray;
1771 Interpolate interpolate(width1, height1, finest_level);
1772 //Interpolate interpolate(width1, height1, 0);
1774 int levels = find_num_levels(width1, height1);
1775 GLuint tex0_gray, tex1_gray;
1776 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1777 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1778 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1779 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1781 gray.exec(tex0, tex0_gray, width1, height1);
1782 glGenerateTextureMipmap(tex0_gray);
1784 gray.exec(tex1, tex1_gray, width1, height1);
1785 glGenerateTextureMipmap(tex1_gray);
1787 GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1788 GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1790 for (int frameno = 1; frameno < 60; ++frameno) {
1791 float alpha = frameno / 60.0f;
1792 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
1794 unique_ptr<uint8_t[]> rgb(new uint8_t[width1 * height1 * 3]);
1795 glGetTextureImage(interpolated_tex, 0, GL_RGB, GL_UNSIGNED_BYTE, width1 * height1 * 3, rgb.get());
1798 snprintf(buf, sizeof(buf), "interp%04d.ppm", frameno);
1799 FILE *fp = fopen(buf, "wb");
1800 fprintf(fp, "P6\n%d %d\n255\n", width1, height1);
1801 for (unsigned y = 0; y < height1; ++y) {
1802 unsigned y2 = height1 - 1 - y;
1803 fwrite(rgb.get() + y2 * width1 * 3, width1 * 3, 1, fp);
1808 //schedule_read(interpolated_tex, width1, height1, filename0, filename1, "", "halfflow.ppm");
1809 //interpolate.release_texture(interpolated_tex);
1810 //finish_one_read(width1, height1);
1813 int main(int argc, char **argv)
1815 static const option long_options[] = {
1816 { "smoothness-relative-weight", required_argument, 0, 's' }, // alpha.
1817 { "intensity-relative-weight", required_argument, 0, 'i' }, // delta.
1818 { "gradient-relative-weight", required_argument, 0, 'g' }, // gamma.
1819 { "disable-timing", no_argument, 0, 1000 },
1820 { "ignore-variational-refinement", no_argument, 0, 1001 }, // Still calculates it, just doesn't apply it.
1821 { "interpolate", no_argument, 0, 1002 }
1825 int option_index = 0;
1826 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1833 vr_alpha = atof(optarg);
1836 vr_delta = atof(optarg);
1839 vr_gamma = atof(optarg);
1842 enable_timing = false;
1845 enable_variational_refinement = false;
1848 enable_interpolation = true;
1851 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1856 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1857 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1860 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1861 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1862 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1863 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1865 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1866 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1867 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1868 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1869 window = SDL_CreateWindow("OpenGL window",
1870 SDL_WINDOWPOS_UNDEFINED,
1871 SDL_WINDOWPOS_UNDEFINED,
1873 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
1874 SDL_GLContext context = SDL_GL_CreateContext(window);
1875 assert(context != nullptr);
1877 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1878 // before all the render passes).
1879 float vertices[] = {
1885 glCreateBuffers(1, &vertex_vbo);
1886 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1887 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1889 if (enable_interpolation) {
1890 interpolate_image(argc, argv, optind);
1892 compute_flow_only(argc, argv, optind);