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>
18 #include "gpu_timers.h"
28 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
34 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
35 constexpr float patch_overlap_ratio = 0.75f;
36 constexpr unsigned coarsest_level = 5;
37 constexpr unsigned finest_level = 1;
38 constexpr unsigned patch_size_pixels = 12;
40 // Weighting constants for the different parts of the variational refinement.
41 // These don't correspond 1:1 to the values given in the DIS paper,
42 // since we have different normalizations and ranges in some cases.
43 // These are found through a simple grid search on some MPI-Sintel data,
44 // although the error (EPE) seems to be fairly insensitive to the precise values.
45 // Only the relative values matter, so we fix alpha (the smoothness constant)
46 // at unity and tweak the others.
47 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
49 bool enable_timing = true;
50 bool detailed_timing = false;
51 bool enable_warmup = false;
52 bool in_warmup = false;
53 bool enable_variational_refinement = true; // Just for debugging.
54 bool enable_interpolation = false;
56 // Some global OpenGL objects.
57 // TODO: These should really be part of DISComputeFlow.
58 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
61 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
62 struct ReadInProgress {
64 string filename0, filename1;
65 string flow_filename, ppm_filename; // Either may be empty for no write.
67 stack<GLuint> spare_pbos;
68 deque<ReadInProgress> reads_in_progress;
70 int find_num_levels(int width, int height)
73 for (int w = width, h = height; w > 1 || h > 1; ) {
81 string read_file(const string &filename)
83 FILE *fp = fopen(filename.c_str(), "r");
85 perror(filename.c_str());
89 int ret = fseek(fp, 0, SEEK_END);
91 perror("fseek(SEEK_END)");
97 ret = fseek(fp, 0, SEEK_SET);
99 perror("fseek(SEEK_SET)");
105 ret = fread(&str[0], size, 1, fp);
111 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
112 size, filename.c_str());
121 GLuint compile_shader(const string &shader_src, GLenum type)
123 GLuint obj = glCreateShader(type);
124 const GLchar* source[] = { shader_src.data() };
125 const GLint length[] = { (GLint)shader_src.size() };
126 glShaderSource(obj, 1, source, length);
127 glCompileShader(obj);
129 GLchar info_log[4096];
130 GLsizei log_length = sizeof(info_log) - 1;
131 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
132 info_log[log_length] = 0;
133 if (strlen(info_log) > 0) {
134 fprintf(stderr, "Shader compile log: %s\n", info_log);
138 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
139 if (status == GL_FALSE) {
140 // Add some line numbers to easier identify compile errors.
141 string src_with_lines = "/* 1 */ ";
143 for (char ch : shader_src) {
144 src_with_lines.push_back(ch);
147 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
148 src_with_lines += buf;
152 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
164 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
166 SDL_Surface *surf = IMG_Load(filename);
167 if (surf == nullptr) {
168 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
172 // For whatever reason, SDL doesn't support converting to YUV surfaces
173 // nor grayscale, so we'll do it ourselves.
174 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
175 if (rgb_surf == nullptr) {
176 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
180 SDL_FreeSurface(surf);
182 unsigned width = rgb_surf->w, height = rgb_surf->h;
183 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
184 unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
186 // Extract the Y component, and convert to bottom-left origin.
187 for (unsigned y = 0; y < height; ++y) {
188 unsigned y2 = height - 1 - y;
189 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
191 SDL_FreeSurface(rgb_surf);
193 int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
196 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
197 glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
198 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
200 if (mipmaps == WITH_MIPMAPS) {
201 glGenerateTextureMipmap(tex);
205 *height_ret = height;
210 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
212 GLuint program = glCreateProgram();
213 glAttachShader(program, vs_obj);
214 glAttachShader(program, fs_obj);
215 glLinkProgram(program);
217 glGetProgramiv(program, GL_LINK_STATUS, &success);
218 if (success == GL_FALSE) {
219 GLchar error_log[1024] = {0};
220 glGetProgramInfoLog(program, 1024, nullptr, error_log);
221 fprintf(stderr, "Error linking program: %s\n", error_log);
227 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
229 if (location == -1) {
233 glBindTextureUnit(texture_unit, tex);
234 glBindSampler(texture_unit, sampler);
235 glProgramUniform1i(program, location, texture_unit);
238 // A class that caches FBOs that render to a given set of textures.
239 // It never frees anything, so it is only suitable for rendering to
240 // the same (small) set of textures over and over again.
241 template<size_t num_elements>
242 class PersistentFBOSet {
244 void render_to(const array<GLuint, num_elements> &textures);
246 // Convenience wrappers.
247 void render_to(GLuint texture0) {
248 render_to({{texture0}});
251 void render_to(GLuint texture0, GLuint texture1) {
252 render_to({{texture0, texture1}});
255 void render_to(GLuint texture0, GLuint texture1, GLuint texture2) {
256 render_to({{texture0, texture1, texture2}});
259 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
260 render_to({{texture0, texture1, texture2, texture3}});
264 // TODO: Delete these on destruction.
265 map<array<GLuint, num_elements>, GLuint> fbos;
268 template<size_t num_elements>
269 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
271 auto it = fbos.find(textures);
272 if (it != fbos.end()) {
273 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
278 glCreateFramebuffers(1, &fbo);
279 GLenum bufs[num_elements];
280 for (size_t i = 0; i < num_elements; ++i) {
281 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
282 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
284 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
286 fbos[textures] = fbo;
287 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
290 // Same, but with a depth texture.
291 template<size_t num_elements>
292 class PersistentFBOSetWithDepth {
294 void render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures);
296 // Convenience wrappers.
297 void render_to(GLuint depth_tex, GLuint texture0) {
298 render_to(depth_tex, {{texture0}});
301 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1) {
302 render_to(depth_tex, {{texture0, texture1}});
305 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2) {
306 render_to(depth_tex, {{texture0, texture1, texture2}});
309 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
310 render_to(depth_tex, {{texture0, texture1, texture2, texture3}});
314 // TODO: Delete these on destruction.
315 map<pair<GLuint, array<GLuint, num_elements>>, GLuint> fbos;
318 template<size_t num_elements>
319 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures)
321 auto key = make_pair(depth_tex, textures);
323 auto it = fbos.find(key);
324 if (it != fbos.end()) {
325 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
330 glCreateFramebuffers(1, &fbo);
331 GLenum bufs[num_elements];
332 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
333 for (size_t i = 0; i < num_elements; ++i) {
334 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
335 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
337 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
340 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
343 // Convert RGB to grayscale, using Rec. 709 coefficients.
344 class GrayscaleConversion {
346 GrayscaleConversion();
347 void exec(GLint tex, GLint gray_tex, int width, int height);
350 PersistentFBOSet<1> fbos;
359 GrayscaleConversion::GrayscaleConversion()
361 gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
362 gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
363 gray_program = link_program(gray_vs_obj, gray_fs_obj);
365 // Set up the VAO containing all the required position/texcoord data.
366 glCreateVertexArrays(1, &gray_vao);
367 glBindVertexArray(gray_vao);
369 GLint position_attrib = glGetAttribLocation(gray_program, "position");
370 glEnableVertexArrayAttrib(gray_vao, position_attrib);
371 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
373 uniform_tex = glGetUniformLocation(gray_program, "tex");
376 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
378 glUseProgram(gray_program);
379 bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
381 glViewport(0, 0, width, height);
382 fbos.render_to(gray_tex);
383 glBindVertexArray(gray_vao);
385 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
388 // Compute gradients in every point, used for the motion search.
389 // The DIS paper doesn't actually mention how these are computed,
390 // but seemingly, a 3x3 Sobel operator is used here (at least in
391 // later versions of the code), while a [1 -8 0 8 -1] kernel is
392 // used for all the derivatives in the variational refinement part
393 // (which borrows code from DeepFlow). This is inconsistent,
394 // but I guess we're better off with staying with the original
395 // decisions until we actually know having different ones would be better.
399 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
402 PersistentFBOSet<1> fbos;
405 GLuint sobel_program;
412 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
413 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
414 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
416 uniform_tex = glGetUniformLocation(sobel_program, "tex");
419 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
421 glUseProgram(sobel_program);
422 bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
424 glViewport(0, 0, level_width, level_height);
425 fbos.render_to(grad0_tex);
427 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
430 // Motion search to find the initial flow. See motion_search.frag for documentation.
434 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);
437 PersistentFBOSet<1> fbos;
439 GLuint motion_vs_obj;
440 GLuint motion_fs_obj;
441 GLuint motion_search_program;
443 GLuint uniform_inv_image_size, uniform_inv_prev_level_size, uniform_out_flow_size;
444 GLuint uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
447 MotionSearch::MotionSearch()
449 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
450 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
451 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
453 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
454 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
455 uniform_out_flow_size = glGetUniformLocation(motion_search_program, "out_flow_size");
456 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
457 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
458 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
461 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)
463 glUseProgram(motion_search_program);
465 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
466 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
467 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
469 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
470 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
471 glProgramUniform2f(motion_search_program, uniform_out_flow_size, width_patches, height_patches);
473 glViewport(0, 0, width_patches, height_patches);
474 fbos.render_to(flow_out_tex);
475 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
478 // Do “densification”, ie., upsampling of the flow patches to the flow field
479 // (the same size as the image at this level). We draw one quad per patch
480 // over its entire covered area (using instancing in the vertex shader),
481 // and then weight the contributions in the pixel shader by post-warp difference.
482 // This is equation (3) in the paper.
484 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
485 // weight in the B channel. Dividing R and G by B gives the normalized values.
489 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);
492 PersistentFBOSet<1> fbos;
494 GLuint densify_vs_obj;
495 GLuint densify_fs_obj;
496 GLuint densify_program;
498 GLuint uniform_patch_size;
499 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
504 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
505 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
506 densify_program = link_program(densify_vs_obj, densify_fs_obj);
508 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
509 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
510 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
511 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
514 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)
516 glUseProgram(densify_program);
518 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
519 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
520 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
522 glProgramUniform2f(densify_program, uniform_patch_size,
523 float(patch_size_pixels) / level_width,
524 float(patch_size_pixels) / level_height);
526 glViewport(0, 0, level_width, level_height);
528 glBlendFunc(GL_ONE, GL_ONE);
529 fbos.render_to(dense_flow_tex);
530 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
531 glClear(GL_COLOR_BUFFER_BIT);
532 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
535 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
536 // I_0 and I_w. The prewarping is what enables us to solve the variational
537 // flow for du,dv instead of u,v.
539 // Also calculates the normalized flow, ie. divides by z (this is needed because
540 // Densify works by additive blending) and multiplies by the image size.
542 // See variational_refinement.txt for more information.
546 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);
549 PersistentFBOSet<3> fbos;
551 GLuint prewarp_vs_obj;
552 GLuint prewarp_fs_obj;
553 GLuint prewarp_program;
555 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
560 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
561 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
562 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
564 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
565 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
566 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
569 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)
571 glUseProgram(prewarp_program);
573 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
574 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
575 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
577 glViewport(0, 0, level_width, level_height);
579 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
580 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
583 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
584 // central difference filter, since apparently, that's tradition (I haven't
585 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
586 // The coefficients come from
588 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
590 // Also computes β_0, since it depends only on I_x and I_y.
594 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
597 PersistentFBOSet<2> fbos;
599 GLuint derivatives_vs_obj;
600 GLuint derivatives_fs_obj;
601 GLuint derivatives_program;
606 Derivatives::Derivatives()
608 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
609 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
610 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
612 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
615 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
617 glUseProgram(derivatives_program);
619 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
621 glViewport(0, 0, level_width, level_height);
623 fbos.render_to(I_x_y_tex, beta_0_tex);
624 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
627 // Calculate the diffusivity for each pixels, g(x,y). Smoothness (s) will
628 // be calculated in the shaders on-the-fly by sampling in-between two
629 // neighboring g(x,y) pixels, plus a border tweak to make sure we get
630 // zero smoothness at the border.
632 // See variational_refinement.txt for more information.
633 class ComputeDiffusivity {
635 ComputeDiffusivity();
636 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow);
639 PersistentFBOSet<1> fbos;
641 GLuint diffusivity_vs_obj;
642 GLuint diffusivity_fs_obj;
643 GLuint diffusivity_program;
645 GLuint uniform_flow_tex, uniform_diff_flow_tex;
646 GLuint uniform_alpha, uniform_zero_diff_flow;
649 ComputeDiffusivity::ComputeDiffusivity()
651 diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
652 diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
653 diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
655 uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
656 uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
657 uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
658 uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
661 void ComputeDiffusivity::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow)
663 glUseProgram(diffusivity_program);
665 bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
666 bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
667 glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
668 glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
670 glViewport(0, 0, level_width, level_height);
673 fbos.render_to(diffusivity_tex);
674 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
677 // Set up the equations set (two equations in two unknowns, per pixel).
678 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
679 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
680 // floats. (Actually, we store the inverse of the diagonal elements, because
681 // we only ever need to divide by them.) This fits into four u32 values;
682 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
683 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
684 // terms that depend on other pixels, are calculated in one pass.
686 // The equation set is split in two; one contains only the pixels needed for
687 // the red pass, and one only for the black pass (see sor.frag). This reduces
688 // the amount of data the SOR shader has to pull in, at the cost of some
689 // complexity when the equation texture ends up with half the size and we need
690 // to adjust texture coordinates. The contraction is done along the horizontal
691 // axis, so that on even rows (0, 2, 4, ...), the “red” texture will contain
692 // pixels 0, 2, 4, 6, etc., and on odd rows 1, 3, 5, etc..
694 // See variational_refinement.txt for more information about the actual
696 class SetupEquations {
699 void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow);
702 PersistentFBOSet<2> fbos;
704 GLuint equations_vs_obj;
705 GLuint equations_fs_obj;
706 GLuint equations_program;
708 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
709 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
710 GLuint uniform_beta_0_tex;
711 GLuint uniform_diffusivity_tex;
712 GLuint uniform_gamma, uniform_delta, uniform_zero_diff_flow;
715 SetupEquations::SetupEquations()
717 equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
718 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
719 equations_program = link_program(equations_vs_obj, equations_fs_obj);
721 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
722 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
723 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
724 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
725 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
726 uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
727 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
728 uniform_delta = glGetUniformLocation(equations_program, "delta");
729 uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
732 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 diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow)
734 glUseProgram(equations_program);
736 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
737 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
738 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
739 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
740 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
741 bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
742 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
743 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
744 glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
746 glViewport(0, 0, (level_width + 1) / 2, level_height);
748 fbos.render_to({equation_red_tex, equation_black_tex});
749 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
752 // Actually solve the equation sets made by SetupEquations, by means of
753 // successive over-relaxation (SOR).
755 // See variational_refinement.txt for more information.
759 void exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, ScopedTimer *sor_timer);
762 PersistentFBOSet<1> fbos;
768 GLuint uniform_diff_flow_tex;
769 GLuint uniform_equation_red_tex, uniform_equation_black_tex;
770 GLuint uniform_diffusivity_tex;
771 GLuint uniform_phase, uniform_num_nonzero_phases;
776 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
777 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
778 sor_program = link_program(sor_vs_obj, sor_fs_obj);
780 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
781 uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
782 uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
783 uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
784 uniform_phase = glGetUniformLocation(sor_program, "phase");
785 uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
788 void SOR::exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, ScopedTimer *sor_timer)
790 glUseProgram(sor_program);
792 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
793 bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
794 bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
795 bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
797 if (!zero_diff_flow) {
798 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
801 // NOTE: We bind to the texture we are rendering from, but we never write any value
802 // that we read in the same shader pass (we call discard for red values when we compute
803 // black, and vice versa), and we have barriers between the passes, so we're fine
805 glViewport(0, 0, level_width, level_height);
807 fbos.render_to(diff_flow_tex);
809 for (int i = 0; i < num_iterations; ++i) {
811 ScopedTimer timer("Red pass", sor_timer);
812 if (zero_diff_flow && i == 0) {
813 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
815 glProgramUniform1i(sor_program, uniform_phase, 0);
816 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
820 ScopedTimer timer("Black pass", sor_timer);
821 if (zero_diff_flow && i == 0) {
822 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
824 glProgramUniform1i(sor_program, uniform_phase, 1);
825 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
826 if (zero_diff_flow && i == 0) {
827 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
829 if (i != num_iterations - 1) {
836 // Simply add the differential flow found by the variational refinement to the base flow.
837 // The output is in base_flow_tex; we don't need to make a new texture.
841 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
844 PersistentFBOSet<1> fbos;
846 GLuint add_flow_vs_obj;
847 GLuint add_flow_fs_obj;
848 GLuint add_flow_program;
850 GLuint uniform_diff_flow_tex;
853 AddBaseFlow::AddBaseFlow()
855 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
856 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
857 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
859 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
862 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
864 glUseProgram(add_flow_program);
866 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
868 glViewport(0, 0, level_width, level_height);
870 glBlendFunc(GL_ONE, GL_ONE);
871 fbos.render_to(base_flow_tex);
873 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
876 // Take a copy of the flow, bilinearly interpolated and scaled up.
880 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
883 PersistentFBOSet<1> fbos;
885 GLuint resize_flow_vs_obj;
886 GLuint resize_flow_fs_obj;
887 GLuint resize_flow_program;
889 GLuint uniform_flow_tex;
890 GLuint uniform_scale_factor;
893 ResizeFlow::ResizeFlow()
895 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
896 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
897 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
899 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
900 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
903 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
905 glUseProgram(resize_flow_program);
907 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
909 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
911 glViewport(0, 0, output_width, output_height);
913 fbos.render_to(out_tex);
915 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
920 GLuint get_texture(GLenum format, GLuint width, GLuint height);
921 void release_texture(GLuint tex_num);
927 GLuint width, height;
930 vector<Texture> textures;
933 class DISComputeFlow {
935 DISComputeFlow(int width, int height);
937 enum ResizeStrategy {
939 RESIZE_FLOW_TO_FULL_SIZE
942 // Returns a texture that must be released with release_texture()
944 GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
946 void release_texture(GLuint tex) {
947 pool.release_texture(tex);
952 GLuint initial_flow_tex;
953 GLuint vertex_vbo, vao;
956 // The various passes.
958 MotionSearch motion_search;
961 Derivatives derivatives;
962 ComputeDiffusivity compute_diffusivity;
963 SetupEquations setup_equations;
965 AddBaseFlow add_base_flow;
966 ResizeFlow resize_flow;
969 DISComputeFlow::DISComputeFlow(int width, int height)
970 : width(width), height(height)
972 // Make some samplers.
973 glCreateSamplers(1, &nearest_sampler);
974 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
975 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
976 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
977 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
979 glCreateSamplers(1, &linear_sampler);
980 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
981 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
982 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
983 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
985 // The smoothness is sampled so that once we get to a smoothness involving
986 // a value outside the border, the diffusivity between the two becomes zero.
987 // Similarly, gradients are zero outside the border, since the edge is taken
989 glCreateSamplers(1, &zero_border_sampler);
990 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
991 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
992 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
993 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
994 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; // Note that zero alpha means we can also see whether we sampled outside the border or not.
995 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
997 // Initial flow is zero, 1x1.
998 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
999 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1000 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1002 // Set up the vertex data that will be shared between all passes.
1003 float vertices[] = {
1009 glCreateBuffers(1, &vertex_vbo);
1010 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1012 glCreateVertexArrays(1, &vao);
1013 glBindVertexArray(vao);
1014 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1016 GLint position_attrib = 0; // Hard-coded in every vertex shader.
1017 glEnableVertexArrayAttrib(vao, position_attrib);
1018 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1021 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1023 int prev_level_width = 1, prev_level_height = 1;
1024 GLuint prev_level_flow_tex = initial_flow_tex;
1028 glBindVertexArray(vao);
1030 ScopedTimer total_timer("Compute flow", &timers);
1031 for (int level = coarsest_level; level >= int(finest_level); --level) {
1032 char timer_name[256];
1033 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
1034 ScopedTimer level_timer(timer_name, &total_timer);
1036 int level_width = width >> level;
1037 int level_height = height >> level;
1038 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1040 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1041 // and patch_spacing=3 (the default), we put out patch centers in
1042 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1043 // lock all the centers to integer coordinates if needed.
1044 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1045 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1047 // Make sure we always read from the correct level; the chosen
1048 // mipmapping could otherwise be rather unpredictable, especially
1049 // during motion search.
1050 GLuint tex0_view, tex1_view;
1051 glGenTextures(1, &tex0_view);
1052 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1053 glGenTextures(1, &tex1_view);
1054 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1056 // Create a new texture; we could be fancy and render use a multi-level
1057 // texture, but meh.
1058 GLuint grad0_tex = pool.get_texture(GL_R32UI, level_width, level_height);
1060 // Find the derivative.
1062 ScopedTimer timer("Sobel", &level_timer);
1063 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1066 // Motion search to find the initial flow. We use the flow from the previous
1067 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1069 // Create an output flow texture.
1070 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1074 ScopedTimer timer("Motion search", &level_timer);
1075 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);
1077 pool.release_texture(grad0_tex);
1081 // Set up an output texture (cleared in Densify).
1082 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1086 ScopedTimer timer("Densification", &level_timer);
1087 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1089 pool.release_texture(flow_out_tex);
1091 // Everything below here in the loop belongs to variational refinement.
1092 ScopedTimer varref_timer("Variational refinement", &level_timer);
1094 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1095 // have to normalize it over and over again, and also save some bandwidth).
1097 // During the entire rest of the variational refinement, flow will be measured
1098 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1099 // This is because variational refinement depends so heavily on derivatives,
1100 // which are measured in intensity levels per pixel.
1101 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1102 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1103 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1105 ScopedTimer timer("Prewarping", &varref_timer);
1106 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1108 pool.release_texture(dense_flow_tex);
1109 glDeleteTextures(1, &tex0_view);
1110 glDeleteTextures(1, &tex1_view);
1112 // Calculate I_x and I_y. We're only calculating first derivatives;
1113 // the others will be taken on-the-fly in order to sample from fewer
1114 // textures overall, since sampling from the L1 cache is cheap.
1115 // (TODO: Verify that this is indeed faster than making separate
1116 // double-derivative textures.)
1117 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1118 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1120 ScopedTimer timer("First derivatives", &varref_timer);
1121 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1123 pool.release_texture(I_tex);
1125 // We need somewhere to store du and dv (the flow increment, relative
1126 // to the non-refined base flow u0 and v0). It's initially garbage,
1127 // but not read until we've written something sane to it.
1128 GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1130 // And for diffusivity.
1131 GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height);
1133 // And finally for the equation set. See SetupEquations for
1134 // the storage format.
1135 GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height);
1136 GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height);
1138 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1139 // Calculate the diffusivity term for each pixel.
1141 ScopedTimer timer("Compute diffusivity", &varref_timer);
1142 compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0);
1145 // Set up the 2x2 equation system for each pixel.
1147 ScopedTimer timer("Set up equations", &varref_timer);
1148 setup_equations.exec(I_x_y_tex, I_t_tex, diff_flow_tex, base_flow_tex, beta_0_tex, diffusivity_tex, equation_red_tex, equation_black_tex, level_width, level_height, outer_idx == 0);
1151 // Run a few SOR iterations. Note that these are to/from the same texture.
1153 ScopedTimer timer("SOR", &varref_timer);
1154 sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, &timer);
1158 pool.release_texture(I_t_tex);
1159 pool.release_texture(I_x_y_tex);
1160 pool.release_texture(beta_0_tex);
1161 pool.release_texture(diffusivity_tex);
1162 pool.release_texture(equation_red_tex);
1163 pool.release_texture(equation_black_tex);
1165 // Add the differential flow found by the variational refinement to the base flow,
1166 // giving the final flow estimate for this level.
1167 // The output is in diff_flow_tex; we don't need to make a new texture.
1169 // Disabling this doesn't save any time (although we could easily make it so that
1170 // it is more efficient), but it helps debug the motion search.
1171 if (enable_variational_refinement) {
1172 ScopedTimer timer("Add differential flow", &varref_timer);
1173 add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height);
1175 pool.release_texture(diff_flow_tex);
1177 if (prev_level_flow_tex != initial_flow_tex) {
1178 pool.release_texture(prev_level_flow_tex);
1180 prev_level_flow_tex = base_flow_tex;
1181 prev_level_width = level_width;
1182 prev_level_height = level_height;
1190 // Scale up the flow to the final size (if needed).
1191 if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1192 return prev_level_flow_tex;
1194 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1195 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1196 pool.release_texture(prev_level_flow_tex);
1201 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1202 // radius fills most of the holes.
1207 // alpha is the time of the interpolated frame (0..1).
1208 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);
1211 PersistentFBOSetWithDepth<1> fbos;
1213 GLuint splat_vs_obj;
1214 GLuint splat_fs_obj;
1215 GLuint splat_program;
1217 GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1218 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1219 GLuint uniform_inv_flow_size;
1224 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1225 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1226 splat_program = link_program(splat_vs_obj, splat_fs_obj);
1228 uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1229 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1230 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1231 uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1232 uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1233 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1234 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1237 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)
1239 glUseProgram(splat_program);
1241 bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1242 bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1244 // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1245 // Move to 2.0 later, or even 4.0.
1246 // (Since we have hole filling, it's not critical, but larger values seem to do
1247 // better than hole filling for large motion, blurs etc.)
1248 float splat_size = 1.0f; // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1249 glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1250 glProgramUniform1f(splat_program, uniform_alpha, alpha);
1251 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1253 glViewport(0, 0, width, height);
1254 glDisable(GL_BLEND);
1255 glEnable(GL_DEPTH_TEST);
1256 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.)
1258 fbos.render_to(depth_tex, flow_tex);
1260 // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
1261 // we've got it bound.
1262 glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f); // Invalid flow.
1263 glClearDepth(1.0f); // Effectively infinity.
1264 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1266 // Do forward splatting.
1267 bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1268 glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1269 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1271 // Do backward splatting.
1272 bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1273 glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1274 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1276 glDisable(GL_DEPTH_TEST);
1279 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1280 // that's fairly simple (given that most holes are really small) and also hopefully
1281 // cheap should the holes not be so small. Conceptually, we look for the first
1282 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1283 // the first non-hole to the right of us, then up and down, and then average them
1284 // all together. It's going to create “stars” if the holes are big, but OK, that's
1287 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1288 // on even for shaders that do discard (this typically kills early Z, but hopefully
1289 // not hierarchical Z); we set up Z so that only holes are written to, which means
1290 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1291 // fullscreen quads should just be discarded outright, really.
1296 // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1297 // from the down, left, right and up, respectively. Use HoleBlend to merge
1299 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1302 PersistentFBOSetWithDepth<1> fbos;
1306 GLuint fill_program;
1309 GLuint uniform_z, uniform_sample_offset;
1312 HoleFill::HoleFill()
1314 fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1315 fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1316 fill_program = link_program(fill_vs_obj, fill_fs_obj);
1318 uniform_tex = glGetUniformLocation(fill_program, "tex");
1319 uniform_z = glGetUniformLocation(fill_program, "z");
1320 uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1323 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1325 glUseProgram(fill_program);
1327 bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1329 glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1331 glViewport(0, 0, width, height);
1332 glDisable(GL_BLEND);
1333 glEnable(GL_DEPTH_TEST);
1334 glDepthFunc(GL_LESS); // Only update the values > 0.999f (ie., only invalid pixels).
1336 fbos.render_to(depth_tex, flow_tex); // NOTE: Reading and writing to the same texture.
1338 // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1339 for (int offs = 1; offs < width; offs *= 2) {
1340 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1341 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1344 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1346 // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1347 // were overwritten in the last algorithm.
1348 glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1349 for (int offs = 1; offs < width; offs *= 2) {
1350 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1351 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1354 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1357 glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1358 for (int offs = 1; offs < height; offs *= 2) {
1359 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1360 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1363 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1366 glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1367 for (int offs = 1; offs < height; offs *= 2) {
1368 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1369 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1373 glDisable(GL_DEPTH_TEST);
1376 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1377 // holes become the average of their four neighbors.
1382 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1385 PersistentFBOSetWithDepth<1> fbos;
1387 GLuint blend_vs_obj;
1388 GLuint blend_fs_obj;
1389 GLuint blend_program;
1391 GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1392 GLuint uniform_z, uniform_sample_offset;
1395 HoleBlend::HoleBlend()
1397 blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER); // Reuse the vertex shader from the fill.
1398 blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1399 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1401 uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1402 uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1403 uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1404 uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1405 uniform_z = glGetUniformLocation(blend_program, "z");
1406 uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1409 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1411 glUseProgram(blend_program);
1413 bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1414 bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1415 bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1416 bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1418 glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1419 glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1421 glViewport(0, 0, width, height);
1422 glDisable(GL_BLEND);
1423 glEnable(GL_DEPTH_TEST);
1424 glDepthFunc(GL_LEQUAL); // Skip over all of the pixels that were never holes to begin with.
1426 fbos.render_to(depth_tex, flow_tex); // NOTE: Reading and writing to the same texture.
1428 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1430 glDisable(GL_DEPTH_TEST);
1436 void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1439 PersistentFBOSet<1> fbos;
1440 GLuint blend_vs_obj;
1441 GLuint blend_fs_obj;
1442 GLuint blend_program;
1444 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1445 GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1450 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1451 blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1452 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1454 uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1455 uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1456 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1457 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1458 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1461 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1463 glUseProgram(blend_program);
1464 bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1465 bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1466 bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler); // May be upsampled.
1467 glProgramUniform1f(blend_program, uniform_alpha, alpha);
1469 glViewport(0, 0, level_width, level_height);
1470 fbos.render_to(output_tex);
1471 glDisable(GL_BLEND); // A bit ironic, perhaps.
1472 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1477 Interpolate(int width, int height, int flow_level);
1479 // Returns a texture that must be released with release_texture()
1480 // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1481 // (unless flow_level == 0).
1482 GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1484 void release_texture(GLuint tex) {
1485 pool.release_texture(tex);
1489 int width, height, flow_level;
1490 GLuint vertex_vbo, vao;
1495 HoleBlend hole_blend;
1499 Interpolate::Interpolate(int width, int height, int flow_level)
1500 : width(width), height(height), flow_level(flow_level) {
1501 // Set up the vertex data that will be shared between all passes.
1502 float vertices[] = {
1508 glCreateBuffers(1, &vertex_vbo);
1509 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1511 glCreateVertexArrays(1, &vao);
1512 glBindVertexArray(vao);
1513 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1515 GLint position_attrib = 0; // Hard-coded in every vertex shader.
1516 glEnableVertexArrayAttrib(vao, position_attrib);
1517 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1520 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1524 ScopedTimer total_timer("Interpolate", &timers);
1526 glBindVertexArray(vao);
1528 // Pick out the right level to test splatting results on.
1529 GLuint tex0_view, tex1_view;
1530 glGenTextures(1, &tex0_view);
1531 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1532 glGenTextures(1, &tex1_view);
1533 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1535 int flow_width = width >> flow_level;
1536 int flow_height = height >> flow_level;
1538 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1539 GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height); // Used for ranking flows.
1542 ScopedTimer timer("Splat", &total_timer);
1543 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1545 glDeleteTextures(1, &tex0_view);
1546 glDeleteTextures(1, &tex1_view);
1549 temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1550 temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1551 temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1554 ScopedTimer timer("Fill holes", &total_timer);
1555 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1556 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1559 pool.release_texture(temp_tex[0]);
1560 pool.release_texture(temp_tex[1]);
1561 pool.release_texture(temp_tex[2]);
1562 pool.release_texture(depth_tex);
1564 GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1566 ScopedTimer timer("Blend", &total_timer);
1567 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1569 pool.release_texture(flow_tex);
1578 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1580 for (Texture &tex : textures) {
1581 if (!tex.in_use && tex.format == format &&
1582 tex.width == width && tex.height == height) {
1589 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1590 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1591 tex.format = format;
1593 tex.height = height;
1595 textures.push_back(tex);
1599 void TexturePool::release_texture(GLuint tex_num)
1601 for (Texture &tex : textures) {
1602 if (tex.tex_num == tex_num) {
1611 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1612 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1614 for (unsigned i = 0; i < width * height; ++i) {
1615 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1619 // Not relevant for RGB.
1620 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1624 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1626 FILE *flowfp = fopen(filename, "wb");
1627 fprintf(flowfp, "FEIH");
1628 fwrite(&width, 4, 1, flowfp);
1629 fwrite(&height, 4, 1, flowfp);
1630 for (unsigned y = 0; y < height; ++y) {
1631 int yy = height - y - 1;
1632 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1637 // Not relevant for RGB.
1638 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1643 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1645 FILE *fp = fopen(filename, "wb");
1646 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1647 for (unsigned y = 0; y < unsigned(height); ++y) {
1648 int yy = height - y - 1;
1649 for (unsigned x = 0; x < unsigned(width); ++x) {
1650 float du = dense_flow[(yy * width + x) * 2 + 0];
1651 float dv = dense_flow[(yy * width + x) * 2 + 1];
1654 flow2rgb(du, dv, &r, &g, &b);
1663 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1665 unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1667 FILE *fp = fopen(filename, "wb");
1668 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1669 for (unsigned y = 0; y < height; ++y) {
1670 unsigned y2 = height - 1 - y;
1671 for (size_t x = 0; x < width; ++x) {
1672 memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1674 fwrite(rgb_line.get(), width * 3, 1, fp);
1681 static constexpr GLenum gl_format = GL_RG;
1682 static constexpr GLenum gl_type = GL_FLOAT;
1683 static constexpr int num_channels = 2;
1687 using type = uint8_t;
1688 static constexpr GLenum gl_format = GL_RGBA;
1689 static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1690 static constexpr int num_channels = 4;
1693 template <class Type>
1694 void finish_one_read(GLuint width, GLuint height)
1696 using T = typename Type::type;
1697 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1699 assert(!reads_in_progress.empty());
1700 ReadInProgress read = reads_in_progress.front();
1701 reads_in_progress.pop_front();
1703 unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1704 void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT); // Blocks if the read isn't done yet.
1705 memcpy(flow.get(), buf, width * height * bytes_per_pixel); // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1706 glUnmapNamedBuffer(read.pbo);
1707 spare_pbos.push(read.pbo);
1709 flip_coordinate_system(flow.get(), width, height);
1710 if (!read.flow_filename.empty()) {
1711 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1712 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1714 if (!read.ppm_filename.empty()) {
1715 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1719 template <class Type>
1720 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1722 using T = typename Type::type;
1723 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1725 if (spare_pbos.empty()) {
1726 finish_one_read<Type>(width, height);
1728 assert(!spare_pbos.empty());
1729 reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1730 glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1732 glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1733 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1736 void compute_flow_only(int argc, char **argv, int optind)
1738 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1739 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1740 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1743 unsigned width1, height1, width2, height2;
1744 GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1745 GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1747 if (width1 != width2 || height1 != height2) {
1748 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1749 width1, height1, width2, height2);
1753 // Set up some PBOs to do asynchronous readback.
1755 glCreateBuffers(5, pbos);
1756 for (int i = 0; i < 5; ++i) {
1757 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1758 spare_pbos.push(pbos[i]);
1761 int levels = find_num_levels(width1, height1);
1762 GLuint tex0_gray, tex1_gray;
1763 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1764 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1765 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1766 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1768 GrayscaleConversion gray;
1769 gray.exec(tex0, tex0_gray, width1, height1);
1770 glDeleteTextures(1, &tex0);
1771 glGenerateTextureMipmap(tex0_gray);
1773 gray.exec(tex1, tex1_gray, width1, height1);
1774 glDeleteTextures(1, &tex1);
1775 glGenerateTextureMipmap(tex1_gray);
1777 DISComputeFlow compute_flow(width1, height1);
1779 if (enable_warmup) {
1781 for (int i = 0; i < 10; ++i) {
1782 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1783 compute_flow.release_texture(final_tex);
1788 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1790 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1791 compute_flow.release_texture(final_tex);
1793 // See if there are more flows on the command line (ie., more than three arguments),
1794 // and if so, process them.
1795 int num_flows = (argc - optind) / 3;
1796 for (int i = 1; i < num_flows; ++i) {
1797 const char *filename0 = argv[optind + i * 3 + 0];
1798 const char *filename1 = argv[optind + i * 3 + 1];
1799 const char *flow_filename = argv[optind + i * 3 + 2];
1800 GLuint width, height;
1801 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1802 if (width != width1 || height != height1) {
1803 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1804 filename0, width, height, width1, height1);
1807 gray.exec(tex0, tex0_gray, width, height);
1808 glGenerateTextureMipmap(tex0_gray);
1809 glDeleteTextures(1, &tex0);
1811 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1812 if (width != width1 || height != height1) {
1813 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1814 filename1, width, height, width1, height1);
1817 gray.exec(tex1, tex1_gray, width, height);
1818 glGenerateTextureMipmap(tex1_gray);
1819 glDeleteTextures(1, &tex1);
1821 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1823 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1824 compute_flow.release_texture(final_tex);
1826 glDeleteTextures(1, &tex0_gray);
1827 glDeleteTextures(1, &tex1_gray);
1829 while (!reads_in_progress.empty()) {
1830 finish_one_read<FlowType>(width1, height1);
1834 // Interpolate images based on
1836 // Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1837 // Using Optical Flow”
1839 // or at least a reasonable subset thereof. Unfinished.
1840 void interpolate_image(int argc, char **argv, int optind)
1842 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1843 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1844 //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1847 unsigned width1, height1, width2, height2;
1848 GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1849 GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1851 if (width1 != width2 || height1 != height2) {
1852 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1853 width1, height1, width2, height2);
1857 // Set up some PBOs to do asynchronous readback.
1859 glCreateBuffers(5, pbos);
1860 for (int i = 0; i < 5; ++i) {
1861 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1862 spare_pbos.push(pbos[i]);
1865 DISComputeFlow compute_flow(width1, height1);
1866 GrayscaleConversion gray;
1867 Interpolate interpolate(width1, height1, finest_level);
1869 int levels = find_num_levels(width1, height1);
1870 GLuint tex0_gray, tex1_gray;
1871 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1872 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1873 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1874 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1876 gray.exec(tex0, tex0_gray, width1, height1);
1877 glGenerateTextureMipmap(tex0_gray);
1879 gray.exec(tex1, tex1_gray, width1, height1);
1880 glGenerateTextureMipmap(tex1_gray);
1882 if (enable_warmup) {
1884 for (int i = 0; i < 10; ++i) {
1885 GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1886 GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1887 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, 0.5f);
1888 compute_flow.release_texture(forward_flow_tex);
1889 compute_flow.release_texture(backward_flow_tex);
1890 interpolate.release_texture(interpolated_tex);
1895 GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1896 GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1898 for (int frameno = 1; frameno < 60; ++frameno) {
1899 char ppm_filename[256];
1900 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
1902 float alpha = frameno / 60.0f;
1903 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
1905 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
1906 interpolate.release_texture(interpolated_tex);
1909 while (!reads_in_progress.empty()) {
1910 finish_one_read<RGBAType>(width1, height1);
1914 int main(int argc, char **argv)
1916 static const option long_options[] = {
1917 { "smoothness-relative-weight", required_argument, 0, 's' }, // alpha.
1918 { "intensity-relative-weight", required_argument, 0, 'i' }, // delta.
1919 { "gradient-relative-weight", required_argument, 0, 'g' }, // gamma.
1920 { "disable-timing", no_argument, 0, 1000 },
1921 { "detailed-timing", no_argument, 0, 1003 },
1922 { "ignore-variational-refinement", no_argument, 0, 1001 }, // Still calculates it, just doesn't apply it.
1923 { "interpolate", no_argument, 0, 1002 },
1924 { "warmup", no_argument, 0, 1004 }
1928 int option_index = 0;
1929 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1936 vr_alpha = atof(optarg);
1939 vr_delta = atof(optarg);
1942 vr_gamma = atof(optarg);
1945 enable_timing = false;
1948 enable_variational_refinement = false;
1951 enable_interpolation = true;
1954 detailed_timing = true;
1957 enable_warmup = true;
1960 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1965 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1966 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1969 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1970 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1971 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1972 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1974 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1975 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1976 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1977 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1978 window = SDL_CreateWindow("OpenGL window",
1979 SDL_WINDOWPOS_UNDEFINED,
1980 SDL_WINDOWPOS_UNDEFINED,
1982 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
1983 SDL_GLContext context = SDL_GL_CreateContext(window);
1984 assert(context != nullptr);
1986 glDisable(GL_DITHER);
1988 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1989 // before all the render passes).
1990 float vertices[] = {
1996 glCreateBuffers(1, &vertex_vbo);
1997 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1998 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
2000 if (enable_interpolation) {
2001 interpolate_image(argc, argv, optind);
2003 compute_flow_only(argc, argv, optind);