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;
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_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
513 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
514 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
517 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)
519 glUseProgram(densify_program);
521 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
522 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
523 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
525 glProgramUniform2f(densify_program, uniform_patch_size,
526 float(patch_size_pixels) / level_width,
527 float(patch_size_pixels) / level_height);
529 glViewport(0, 0, level_width, level_height);
531 glBlendFunc(GL_ONE, GL_ONE);
532 glBindVertexArray(densify_vao);
533 fbos.render_to(dense_flow_tex);
534 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
537 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
538 // I_0 and I_w. The prewarping is what enables us to solve the variational
539 // flow for du,dv instead of u,v.
541 // Also calculates the normalized flow, ie. divides by z (this is needed because
542 // Densify works by additive blending) and multiplies by the image size.
544 // See variational_refinement.txt for more information.
548 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);
551 PersistentFBOSet<3> fbos;
553 GLuint prewarp_vs_obj;
554 GLuint prewarp_fs_obj;
555 GLuint prewarp_program;
558 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
563 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
564 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
565 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
567 // Set up the VAO containing all the required position/texcoord data.
568 glCreateVertexArrays(1, &prewarp_vao);
569 glBindVertexArray(prewarp_vao);
570 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
572 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
573 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
574 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
576 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
577 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
578 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
581 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)
583 glUseProgram(prewarp_program);
585 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
586 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
587 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
589 glViewport(0, 0, level_width, level_height);
591 glBindVertexArray(prewarp_vao);
592 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
593 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
596 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
597 // central difference filter, since apparently, that's tradition (I haven't
598 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
599 // The coefficients come from
601 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
603 // Also computes β_0, since it depends only on I_x and I_y.
607 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
610 PersistentFBOSet<2> fbos;
612 GLuint derivatives_vs_obj;
613 GLuint derivatives_fs_obj;
614 GLuint derivatives_program;
615 GLuint derivatives_vao;
620 Derivatives::Derivatives()
622 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
623 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
624 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
626 // Set up the VAO containing all the required position/texcoord data.
627 glCreateVertexArrays(1, &derivatives_vao);
628 glBindVertexArray(derivatives_vao);
629 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
631 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
632 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
633 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
635 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
638 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
640 glUseProgram(derivatives_program);
642 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
644 glViewport(0, 0, level_width, level_height);
646 glBindVertexArray(derivatives_vao);
647 fbos.render_to(I_x_y_tex, beta_0_tex);
648 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
651 // Calculate the smoothness constraints between neighboring pixels;
652 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
653 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
654 // border color (0,0) later, so that there's zero diffusion out of
657 // See variational_refinement.txt for more information.
658 class ComputeSmoothness {
661 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
664 PersistentFBOSet<2> fbos;
666 GLuint smoothness_vs_obj;
667 GLuint smoothness_fs_obj;
668 GLuint smoothness_program;
669 GLuint smoothness_vao;
671 GLuint uniform_flow_tex, uniform_diff_flow_tex;
672 GLuint uniform_alpha;
675 ComputeSmoothness::ComputeSmoothness()
677 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
678 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
679 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
681 // Set up the VAO containing all the required position/texcoord data.
682 glCreateVertexArrays(1, &smoothness_vao);
683 glBindVertexArray(smoothness_vao);
684 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
686 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
687 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
688 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
690 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
691 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
692 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
695 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
697 glUseProgram(smoothness_program);
699 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
700 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
701 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
703 glViewport(0, 0, level_width, level_height);
706 glBindVertexArray(smoothness_vao);
707 fbos.render_to(smoothness_x_tex, smoothness_y_tex);
708 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
710 // Make sure the smoothness on the right and upper borders is zero.
711 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
712 // (we're sampling smoothness with all-zero border color), but we'd
713 // have to adjust the sampling coordinates, which is annoying.
714 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
715 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
718 // Set up the equations set (two equations in two unknowns, per pixel).
719 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
720 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
721 // floats. (Actually, we store the inverse of the diagonal elements, because
722 // we only ever need to divide by them.) This fits into four u32 values;
723 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
724 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
725 // terms that depend on other pixels, are calculated in one pass.
727 // See variational_refinement.txt for more information.
728 class SetupEquations {
731 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);
734 PersistentFBOSet<1> fbos;
736 GLuint equations_vs_obj;
737 GLuint equations_fs_obj;
738 GLuint equations_program;
739 GLuint equations_vao;
741 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
742 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
743 GLuint uniform_beta_0_tex;
744 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
745 GLuint uniform_gamma, uniform_delta;
748 SetupEquations::SetupEquations()
750 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
751 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
752 equations_program = link_program(equations_vs_obj, equations_fs_obj);
754 // Set up the VAO containing all the required position/texcoord data.
755 glCreateVertexArrays(1, &equations_vao);
756 glBindVertexArray(equations_vao);
757 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
759 GLint position_attrib = glGetAttribLocation(equations_program, "position");
760 glEnableVertexArrayAttrib(equations_vao, position_attrib);
761 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
763 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
764 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
765 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
766 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
767 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
768 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
769 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
770 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
771 uniform_delta = glGetUniformLocation(equations_program, "delta");
774 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)
776 glUseProgram(equations_program);
778 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
779 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
780 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
781 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
782 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
783 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
784 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
785 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
786 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
788 glViewport(0, 0, level_width, level_height);
790 glBindVertexArray(equations_vao);
791 fbos.render_to(equation_tex);
792 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
795 // Actually solve the equation sets made by SetupEquations, by means of
796 // successive over-relaxation (SOR).
798 // See variational_refinement.txt for more information.
802 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);
805 PersistentFBOSet<1> fbos;
812 GLuint uniform_diff_flow_tex;
813 GLuint uniform_equation_tex;
814 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
815 GLuint uniform_phase;
820 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
821 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
822 sor_program = link_program(sor_vs_obj, sor_fs_obj);
824 // Set up the VAO containing all the required position/texcoord data.
825 glCreateVertexArrays(1, &sor_vao);
826 glBindVertexArray(sor_vao);
827 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
829 GLint position_attrib = glGetAttribLocation(sor_program, "position");
830 glEnableVertexArrayAttrib(sor_vao, position_attrib);
831 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
833 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
834 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
835 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
836 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
837 uniform_phase = glGetUniformLocation(sor_program, "phase");
840 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)
842 glUseProgram(sor_program);
844 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
845 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
846 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
847 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
849 // NOTE: We bind to the texture we are rendering from, but we never write any value
850 // that we read in the same shader pass (we call discard for red values when we compute
851 // black, and vice versa), and we have barriers between the passes, so we're fine
853 glViewport(0, 0, level_width, level_height);
855 glBindVertexArray(sor_vao);
856 fbos.render_to(diff_flow_tex);
858 for (int i = 0; i < num_iterations; ++i) {
859 glProgramUniform1i(sor_program, uniform_phase, 0);
860 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
862 glProgramUniform1i(sor_program, uniform_phase, 1);
863 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
864 if (i != num_iterations - 1) {
870 // Simply add the differential flow found by the variational refinement to the base flow.
871 // The output is in base_flow_tex; we don't need to make a new texture.
875 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
878 PersistentFBOSet<1> fbos;
880 GLuint add_flow_vs_obj;
881 GLuint add_flow_fs_obj;
882 GLuint add_flow_program;
885 GLuint uniform_diff_flow_tex;
888 AddBaseFlow::AddBaseFlow()
890 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
891 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
892 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
894 // Set up the VAO containing all the required position/texcoord data.
895 glCreateVertexArrays(1, &add_flow_vao);
896 glBindVertexArray(add_flow_vao);
897 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
899 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
900 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
901 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
903 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
906 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
908 glUseProgram(add_flow_program);
910 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
912 glViewport(0, 0, level_width, level_height);
914 glBlendFunc(GL_ONE, GL_ONE);
915 glBindVertexArray(add_flow_vao);
916 fbos.render_to(base_flow_tex);
918 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
921 // Take a copy of the flow, bilinearly interpolated and scaled up.
925 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
928 PersistentFBOSet<1> fbos;
930 GLuint resize_flow_vs_obj;
931 GLuint resize_flow_fs_obj;
932 GLuint resize_flow_program;
933 GLuint resize_flow_vao;
935 GLuint uniform_flow_tex;
936 GLuint uniform_scale_factor;
939 ResizeFlow::ResizeFlow()
941 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
942 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
943 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
945 // Set up the VAO containing all the required position/texcoord data.
946 glCreateVertexArrays(1, &resize_flow_vao);
947 glBindVertexArray(resize_flow_vao);
948 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
950 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
951 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
952 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
954 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
955 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
958 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
960 glUseProgram(resize_flow_program);
962 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
964 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
966 glViewport(0, 0, output_width, output_height);
968 glBindVertexArray(resize_flow_vao);
969 fbos.render_to(out_tex);
971 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
977 pair<GLuint, GLuint> begin_timer(const string &name, int level);
983 pair<GLuint, GLuint> query;
985 vector<Timer> timers;
988 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
990 if (!enable_timing) {
991 return make_pair(0, 0);
995 glGenQueries(2, queries);
996 glQueryCounter(queries[0], GL_TIMESTAMP);
1000 timer.level = level;
1001 timer.query.first = queries[0];
1002 timer.query.second = queries[1];
1003 timers.push_back(timer);
1007 void GPUTimers::print()
1009 for (const Timer &timer : timers) {
1010 // NOTE: This makes the CPU wait for the GPU.
1011 GLuint64 time_start, time_end;
1012 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
1013 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
1014 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
1015 for (int i = 0; i < timer.level * 2; ++i) {
1016 fprintf(stderr, " ");
1018 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
1022 // A simple RAII class for timing until the end of the scope.
1025 ScopedTimer(const string &name, GPUTimers *timers)
1026 : timers(timers), level(0)
1028 query = timers->begin_timer(name, level);
1031 ScopedTimer(const string &name, ScopedTimer *parent_timer)
1032 : timers(parent_timer->timers),
1033 level(parent_timer->level + 1)
1035 query = timers->begin_timer(name, level);
1045 if (enable_timing && !ended) {
1046 glQueryCounter(query.second, GL_TIMESTAMP);
1054 pair<GLuint, GLuint> query;
1060 GLuint get_texture(GLenum format, GLuint width, GLuint height);
1061 void release_texture(GLuint tex_num);
1067 GLuint width, height;
1068 bool in_use = false;
1070 vector<Texture> textures;
1073 class DISComputeFlow {
1075 DISComputeFlow(int width, int height);
1077 enum ResizeStrategy {
1079 RESIZE_FLOW_TO_FULL_SIZE
1082 // Returns a texture that must be released with release_texture()
1084 GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
1086 void release_texture(GLuint tex) {
1087 pool.release_texture(tex);
1092 GLuint initial_flow_tex;
1095 // The various passes.
1097 MotionSearch motion_search;
1100 Derivatives derivatives;
1101 ComputeSmoothness compute_smoothness;
1102 SetupEquations setup_equations;
1104 AddBaseFlow add_base_flow;
1105 ResizeFlow resize_flow;
1108 DISComputeFlow::DISComputeFlow(int width, int height)
1109 : width(width), height(height)
1111 // Make some samplers.
1112 glCreateSamplers(1, &nearest_sampler);
1113 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1114 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1115 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1116 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1118 glCreateSamplers(1, &linear_sampler);
1119 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1120 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1121 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1122 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1124 // The smoothness is sampled so that once we get to a smoothness involving
1125 // a value outside the border, the diffusivity between the two becomes zero.
1126 // Similarly, gradients are zero outside the border, since the edge is taken
1128 glCreateSamplers(1, &zero_border_sampler);
1129 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1130 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1131 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1132 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1133 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1134 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1136 // Initial flow is zero, 1x1.
1137 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1138 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1139 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1142 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1144 int prev_level_width = 1, prev_level_height = 1;
1145 GLuint prev_level_flow_tex = initial_flow_tex;
1149 ScopedTimer total_timer("Total", &timers);
1150 for (int level = coarsest_level; level >= int(finest_level); --level) {
1151 char timer_name[256];
1152 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1153 ScopedTimer level_timer(timer_name, &total_timer);
1155 int level_width = width >> level;
1156 int level_height = height >> level;
1157 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1159 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1160 // and patch_spacing=3 (the default), we put out patch centers in
1161 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1162 // lock all the centers to integer coordinates if needed.
1163 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1164 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1166 // Make sure we always read from the correct level; the chosen
1167 // mipmapping could otherwise be rather unpredictable, especially
1168 // during motion search.
1169 GLuint tex0_view, tex1_view;
1170 glGenTextures(1, &tex0_view);
1171 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1172 glGenTextures(1, &tex1_view);
1173 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1175 // Create a new texture; we could be fancy and render use a multi-level
1176 // texture, but meh.
1177 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1179 // Find the derivative.
1181 ScopedTimer timer("Sobel", &level_timer);
1182 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1185 // Motion search to find the initial flow. We use the flow from the previous
1186 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1188 // Create an output flow texture.
1189 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1193 ScopedTimer timer("Motion search", &level_timer);
1194 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);
1196 pool.release_texture(grad0_tex);
1200 // Set up an output texture (initially zero).
1201 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1202 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1206 ScopedTimer timer("Densification", &level_timer);
1207 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1209 pool.release_texture(flow_out_tex);
1211 // Everything below here in the loop belongs to variational refinement.
1212 ScopedTimer varref_timer("Variational refinement", &level_timer);
1214 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1215 // have to normalize it over and over again, and also save some bandwidth).
1217 // During the entire rest of the variational refinement, flow will be measured
1218 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1219 // This is because variational refinement depends so heavily on derivatives,
1220 // which are measured in intensity levels per pixel.
1221 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1222 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1223 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1225 ScopedTimer timer("Prewarping", &varref_timer);
1226 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1228 pool.release_texture(dense_flow_tex);
1229 glDeleteTextures(1, &tex0_view);
1230 glDeleteTextures(1, &tex1_view);
1232 // Calculate I_x and I_y. We're only calculating first derivatives;
1233 // the others will be taken on-the-fly in order to sample from fewer
1234 // textures overall, since sampling from the L1 cache is cheap.
1235 // (TODO: Verify that this is indeed faster than making separate
1236 // double-derivative textures.)
1237 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1238 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1240 ScopedTimer timer("First derivatives", &varref_timer);
1241 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1243 pool.release_texture(I_tex);
1245 // We need somewhere to store du and dv (the flow increment, relative
1246 // to the non-refined base flow u0 and v0). It starts at zero.
1247 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1248 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1250 // And for smoothness.
1251 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1252 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1254 // And finally for the equation set. See SetupEquations for
1255 // the storage format.
1256 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1258 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1259 // Calculate the smoothness terms between the neighboring pixels,
1260 // both in x and y direction.
1262 ScopedTimer timer("Compute smoothness", &varref_timer);
1263 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1266 // Set up the 2x2 equation system for each pixel.
1268 ScopedTimer timer("Set up equations", &varref_timer);
1269 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);
1272 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1273 // Note that these are to/from the same texture.
1275 ScopedTimer timer("SOR", &varref_timer);
1276 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1280 pool.release_texture(I_t_tex);
1281 pool.release_texture(I_x_y_tex);
1282 pool.release_texture(beta_0_tex);
1283 pool.release_texture(smoothness_x_tex);
1284 pool.release_texture(smoothness_y_tex);
1285 pool.release_texture(equation_tex);
1287 // Add the differential flow found by the variational refinement to the base flow,
1288 // giving the final flow estimate for this level.
1289 // The output is in diff_flow_tex; we don't need to make a new texture.
1291 // Disabling this doesn't save any time (although we could easily make it so that
1292 // it is more efficient), but it helps debug the motion search.
1293 if (enable_variational_refinement) {
1294 ScopedTimer timer("Add differential flow", &varref_timer);
1295 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1297 pool.release_texture(du_dv_tex);
1299 if (prev_level_flow_tex != initial_flow_tex) {
1300 pool.release_texture(prev_level_flow_tex);
1302 prev_level_flow_tex = base_flow_tex;
1303 prev_level_width = level_width;
1304 prev_level_height = level_height;
1310 // Scale up the flow to the final size (if needed).
1311 if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1312 return prev_level_flow_tex;
1314 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1315 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1316 pool.release_texture(prev_level_flow_tex);
1321 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1322 // radius fills most of the holes.
1327 // alpha is the time of the interpolated frame (0..1).
1328 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);
1331 PersistentFBOSet<2> fbos;
1333 GLuint splat_vs_obj;
1334 GLuint splat_fs_obj;
1335 GLuint splat_program;
1338 GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1339 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1340 GLuint uniform_inv_flow_size;
1345 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1346 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1347 splat_program = link_program(splat_vs_obj, splat_fs_obj);
1349 // Set up the VAO containing all the required position/texcoord data.
1350 glCreateVertexArrays(1, &splat_vao);
1351 glBindVertexArray(splat_vao);
1352 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1354 GLint position_attrib = glGetAttribLocation(splat_program, "position");
1355 glEnableVertexArrayAttrib(splat_vao, position_attrib);
1356 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1358 uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1359 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1360 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1361 uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1362 uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1363 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1364 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1367 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)
1369 glUseProgram(splat_program);
1371 bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1372 bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1374 // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1375 // Move to 2.0 later, or even 4.0.
1376 // (Since we have hole filling, it's not critical, but larger values seem to do
1377 // better than hole filling for large motion, blurs etc.)
1378 float splat_size = 1.0f; // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1379 glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1380 glProgramUniform1f(splat_program, uniform_alpha, alpha);
1381 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1383 glViewport(0, 0, width, height);
1384 glDisable(GL_BLEND);
1385 glEnable(GL_DEPTH_TEST);
1386 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.)
1387 glBindVertexArray(splat_vao);
1389 // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1391 glCreateFramebuffers(1, &fbo);
1392 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0);
1393 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1394 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1396 // Do forward splatting.
1397 bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1398 glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1399 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1401 // Do backward splatting.
1402 bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1403 glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1404 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1406 glDisable(GL_DEPTH_TEST);
1408 glDeleteFramebuffers(1, &fbo);
1411 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1412 // that's fairly simple (given that most holes are really small) and also hopefully
1413 // cheap should the holes not be so small. Conceptually, we look for the first
1414 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1415 // the first non-hole to the right of us, then up and down, and then average them
1416 // all together. It's going to create “stars” if the holes are big, but OK, that's
1419 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1420 // on even for shaders that do discard (this typically kills early Z, but hopefully
1421 // not hierarchical Z); we set up Z so that only holes are written to, which means
1422 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1423 // fullscreen quads should just be discarded outright, really.
1428 // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1429 // from the down, left, right and up, respectively. Use HoleBlend to merge
1431 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1434 PersistentFBOSet<2> fbos;
1438 GLuint fill_program;
1442 GLuint uniform_z, uniform_sample_offset;
1445 HoleFill::HoleFill()
1447 fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1448 fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1449 fill_program = link_program(fill_vs_obj, fill_fs_obj);
1451 // Set up the VAO containing all the required position/texcoord data.
1452 glCreateVertexArrays(1, &fill_vao);
1453 glBindVertexArray(fill_vao);
1454 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1456 GLint position_attrib = glGetAttribLocation(fill_program, "position");
1457 glEnableVertexArrayAttrib(fill_vao, position_attrib);
1458 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1460 uniform_tex = glGetUniformLocation(fill_program, "tex");
1461 uniform_z = glGetUniformLocation(fill_program, "z");
1462 uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1465 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1467 glUseProgram(fill_program);
1469 bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1471 glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1473 glViewport(0, 0, width, height);
1474 glDisable(GL_BLEND);
1475 glEnable(GL_DEPTH_TEST);
1476 glDepthFunc(GL_LESS); // Only update the values > 0.999f (ie., only invalid pixels).
1477 glBindVertexArray(fill_vao);
1479 // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1481 glCreateFramebuffers(1, &fbo);
1482 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0); // NOTE: Reading and writing to the same texture.
1483 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1484 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1486 // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1487 for (int offs = 1; offs < width; offs *= 2) {
1488 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1489 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1492 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1494 // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1495 // were overwritten in the last algorithm.
1496 glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1497 for (int offs = 1; offs < width; offs *= 2) {
1498 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1499 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1502 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1505 glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1506 for (int offs = 1; offs < height; offs *= 2) {
1507 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1508 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1511 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1514 glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1515 for (int offs = 1; offs < height; offs *= 2) {
1516 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1517 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1521 glDisable(GL_DEPTH_TEST);
1523 glDeleteFramebuffers(1, &fbo);
1526 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1527 // holes become the average of their four neighbors.
1532 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1535 PersistentFBOSet<2> fbos;
1537 GLuint blend_vs_obj;
1538 GLuint blend_fs_obj;
1539 GLuint blend_program;
1542 GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1543 GLuint uniform_z, uniform_sample_offset;
1546 HoleBlend::HoleBlend()
1548 blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER); // Reuse the vertex shader from the fill.
1549 blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1550 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1552 // Set up the VAO containing all the required position/texcoord data.
1553 glCreateVertexArrays(1, &blend_vao);
1554 glBindVertexArray(blend_vao);
1555 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1557 GLint position_attrib = glGetAttribLocation(blend_program, "position");
1558 glEnableVertexArrayAttrib(blend_vao, position_attrib);
1559 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1561 uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1562 uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1563 uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1564 uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1565 uniform_z = glGetUniformLocation(blend_program, "z");
1566 uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1569 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1571 glUseProgram(blend_program);
1573 bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1574 bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1575 bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1576 bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1578 glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1579 glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1581 glViewport(0, 0, width, height);
1582 glDisable(GL_BLEND);
1583 glEnable(GL_DEPTH_TEST);
1584 glDepthFunc(GL_LEQUAL); // Skip over all of the pixels that were never holes to begin with.
1585 glBindVertexArray(blend_vao);
1587 // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1589 glCreateFramebuffers(1, &fbo);
1590 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0); // NOTE: Reading and writing to the same texture.
1591 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1592 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1594 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1596 glDisable(GL_DEPTH_TEST);
1598 glDeleteFramebuffers(1, &fbo);
1604 void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1607 PersistentFBOSet<1> fbos;
1608 GLuint blend_vs_obj;
1609 GLuint blend_fs_obj;
1610 GLuint blend_program;
1613 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1614 GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1619 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1620 blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1621 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1623 // Set up the VAO containing all the required position/texcoord data.
1624 glCreateVertexArrays(1, &blend_vao);
1625 glBindVertexArray(blend_vao);
1627 GLint position_attrib = glGetAttribLocation(blend_program, "position");
1628 glEnableVertexArrayAttrib(blend_vao, position_attrib);
1629 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1631 uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1632 uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1633 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1634 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1635 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1638 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1640 glUseProgram(blend_program);
1641 bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1642 bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1643 bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler); // May be upsampled.
1644 glProgramUniform1f(blend_program, uniform_alpha, alpha);
1645 //glProgramUniform1f(blend_program, uniform_flow_consistency_tolerance, 1.0f /
1647 glViewport(0, 0, level_width, level_height);
1648 fbos.render_to(output_tex);
1649 glBindVertexArray(blend_vao);
1650 glUseProgram(blend_program);
1651 glDisable(GL_BLEND); // A bit ironic, perhaps.
1652 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1657 Interpolate(int width, int height, int flow_level);
1659 // Returns a texture that must be released with release_texture()
1660 // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1661 // (unless flow_level == 0).
1662 GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1664 void release_texture(GLuint tex) {
1665 pool.release_texture(tex);
1669 int width, height, flow_level;
1673 HoleBlend hole_blend;
1677 Interpolate::Interpolate(int width, int height, int flow_level)
1678 : width(width), height(height), flow_level(flow_level) {}
1680 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1684 ScopedTimer total_timer("Total", &timers);
1686 // Pick out the right level to test splatting results on.
1687 GLuint tex0_view, tex1_view;
1688 glGenTextures(1, &tex0_view);
1689 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1690 glGenTextures(1, &tex1_view);
1691 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1693 int flow_width = width >> flow_level;
1694 int flow_height = height >> flow_level;
1696 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1697 GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height); // Used for ranking flows.
1699 ScopedTimer timer("Clear", &total_timer);
1700 float invalid_flow[] = { 1000.0f, 1000.0f };
1701 glClearTexImage(flow_tex, 0, GL_RG, GL_FLOAT, invalid_flow);
1702 float infinity = 1.0f;
1703 glClearTexImage(depth_tex, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &infinity);
1707 ScopedTimer timer("Splat", &total_timer);
1708 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1710 glDeleteTextures(1, &tex0_view);
1711 glDeleteTextures(1, &tex1_view);
1714 temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1715 temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1716 temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1719 ScopedTimer timer("Fill holes", &total_timer);
1720 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1721 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1724 pool.release_texture(temp_tex[0]);
1725 pool.release_texture(temp_tex[1]);
1726 pool.release_texture(temp_tex[2]);
1727 pool.release_texture(depth_tex);
1729 GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1731 ScopedTimer timer("Blend", &total_timer);
1732 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1740 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1742 for (Texture &tex : textures) {
1743 if (!tex.in_use && tex.format == format &&
1744 tex.width == width && tex.height == height) {
1751 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1752 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1753 tex.format = format;
1755 tex.height = height;
1757 textures.push_back(tex);
1761 void TexturePool::release_texture(GLuint tex_num)
1763 for (Texture &tex : textures) {
1764 if (tex.tex_num == tex_num) {
1773 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1774 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1776 for (unsigned i = 0; i < width * height; ++i) {
1777 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1781 // Not relevant for RGB.
1782 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1786 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1788 FILE *flowfp = fopen(filename, "wb");
1789 fprintf(flowfp, "FEIH");
1790 fwrite(&width, 4, 1, flowfp);
1791 fwrite(&height, 4, 1, flowfp);
1792 for (unsigned y = 0; y < height; ++y) {
1793 int yy = height - y - 1;
1794 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1799 // Not relevant for RGB.
1800 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1805 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1807 FILE *fp = fopen(filename, "wb");
1808 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1809 for (unsigned y = 0; y < unsigned(height); ++y) {
1810 int yy = height - y - 1;
1811 for (unsigned x = 0; x < unsigned(width); ++x) {
1812 float du = dense_flow[(yy * width + x) * 2 + 0];
1813 float dv = dense_flow[(yy * width + x) * 2 + 1];
1816 flow2rgb(du, dv, &r, &g, &b);
1825 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1827 unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1829 FILE *fp = fopen(filename, "wb");
1830 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1831 for (unsigned y = 0; y < height; ++y) {
1832 unsigned y2 = height - 1 - y;
1833 for (size_t x = 0; x < width; ++x) {
1834 memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1836 fwrite(rgb_line.get(), width * 3, 1, fp);
1843 static constexpr GLenum gl_format = GL_RG;
1844 static constexpr GLenum gl_type = GL_FLOAT;
1845 static constexpr int num_channels = 2;
1849 using type = uint8_t;
1850 static constexpr GLenum gl_format = GL_RGBA;
1851 static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1852 static constexpr int num_channels = 4;
1855 template <class Type>
1856 void finish_one_read(GLuint width, GLuint height)
1858 using T = typename Type::type;
1859 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1861 assert(!reads_in_progress.empty());
1862 ReadInProgress read = reads_in_progress.front();
1863 reads_in_progress.pop_front();
1865 unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1866 void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT); // Blocks if the read isn't done yet.
1867 memcpy(flow.get(), buf, width * height * bytes_per_pixel); // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1868 glUnmapNamedBuffer(read.pbo);
1869 spare_pbos.push(read.pbo);
1871 flip_coordinate_system(flow.get(), width, height);
1872 if (!read.flow_filename.empty()) {
1873 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1874 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1876 if (!read.ppm_filename.empty()) {
1877 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1881 template <class Type>
1882 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1884 using T = typename Type::type;
1885 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1887 if (spare_pbos.empty()) {
1888 finish_one_read<Type>(width, height);
1890 assert(!spare_pbos.empty());
1891 reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1892 glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1894 glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1895 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1898 void compute_flow_only(int argc, char **argv, int optind)
1900 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1901 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1902 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1905 unsigned width1, height1, width2, height2;
1906 GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1907 GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1909 if (width1 != width2 || height1 != height2) {
1910 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1911 width1, height1, width2, height2);
1915 // Set up some PBOs to do asynchronous readback.
1917 glCreateBuffers(5, pbos);
1918 for (int i = 0; i < 5; ++i) {
1919 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1920 spare_pbos.push(pbos[i]);
1923 int levels = find_num_levels(width1, height1);
1924 GLuint tex0_gray, tex1_gray;
1925 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1926 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1927 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1928 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1930 GrayscaleConversion gray;
1931 gray.exec(tex0, tex0_gray, width1, height1);
1932 glDeleteTextures(1, &tex0);
1933 glGenerateTextureMipmap(tex0_gray);
1935 gray.exec(tex1, tex1_gray, width1, height1);
1936 glDeleteTextures(1, &tex1);
1937 glGenerateTextureMipmap(tex1_gray);
1939 DISComputeFlow compute_flow(width1, height1);
1940 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1942 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1943 compute_flow.release_texture(final_tex);
1945 // See if there are more flows on the command line (ie., more than three arguments),
1946 // and if so, process them.
1947 int num_flows = (argc - optind) / 3;
1948 for (int i = 1; i < num_flows; ++i) {
1949 const char *filename0 = argv[optind + i * 3 + 0];
1950 const char *filename1 = argv[optind + i * 3 + 1];
1951 const char *flow_filename = argv[optind + i * 3 + 2];
1952 GLuint width, height;
1953 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1954 if (width != width1 || height != height1) {
1955 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1956 filename0, width, height, width1, height1);
1959 gray.exec(tex0, tex0_gray, width, height);
1960 glGenerateTextureMipmap(tex0_gray);
1961 glDeleteTextures(1, &tex0);
1963 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1964 if (width != width1 || height != height1) {
1965 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1966 filename1, width, height, width1, height1);
1969 gray.exec(tex1, tex1_gray, width, height);
1970 glGenerateTextureMipmap(tex1_gray);
1971 glDeleteTextures(1, &tex1);
1973 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1975 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1976 compute_flow.release_texture(final_tex);
1978 glDeleteTextures(1, &tex0_gray);
1979 glDeleteTextures(1, &tex1_gray);
1981 while (!reads_in_progress.empty()) {
1982 finish_one_read<FlowType>(width1, height1);
1986 // Interpolate images based on
1988 // Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1989 // Using Optical Flow”
1991 // or at least a reasonable subset thereof. Unfinished.
1992 void interpolate_image(int argc, char **argv, int optind)
1994 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1995 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1996 //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1999 unsigned width1, height1, width2, height2;
2000 GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
2001 GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
2003 if (width1 != width2 || height1 != height2) {
2004 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
2005 width1, height1, width2, height2);
2009 // Set up some PBOs to do asynchronous readback.
2011 glCreateBuffers(5, pbos);
2012 for (int i = 0; i < 5; ++i) {
2013 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
2014 spare_pbos.push(pbos[i]);
2017 DISComputeFlow compute_flow(width1, height1);
2018 GrayscaleConversion gray;
2019 Interpolate interpolate(width1, height1, finest_level);
2021 int levels = find_num_levels(width1, height1);
2022 GLuint tex0_gray, tex1_gray;
2023 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
2024 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
2025 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
2026 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
2028 gray.exec(tex0, tex0_gray, width1, height1);
2029 glGenerateTextureMipmap(tex0_gray);
2031 gray.exec(tex1, tex1_gray, width1, height1);
2032 glGenerateTextureMipmap(tex1_gray);
2034 GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
2035 GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
2037 for (int frameno = 1; frameno < 60; ++frameno) {
2038 char ppm_filename[256];
2039 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
2041 float alpha = frameno / 60.0f;
2042 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
2044 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
2045 interpolate.release_texture(interpolated_tex);
2048 while (!reads_in_progress.empty()) {
2049 finish_one_read<RGBAType>(width1, height1);
2053 int main(int argc, char **argv)
2055 static const option long_options[] = {
2056 { "smoothness-relative-weight", required_argument, 0, 's' }, // alpha.
2057 { "intensity-relative-weight", required_argument, 0, 'i' }, // delta.
2058 { "gradient-relative-weight", required_argument, 0, 'g' }, // gamma.
2059 { "disable-timing", no_argument, 0, 1000 },
2060 { "ignore-variational-refinement", no_argument, 0, 1001 }, // Still calculates it, just doesn't apply it.
2061 { "interpolate", no_argument, 0, 1002 }
2065 int option_index = 0;
2066 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
2073 vr_alpha = atof(optarg);
2076 vr_delta = atof(optarg);
2079 vr_gamma = atof(optarg);
2082 enable_timing = false;
2085 enable_variational_refinement = false;
2088 enable_interpolation = true;
2091 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
2096 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
2097 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
2100 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
2101 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
2102 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
2103 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2105 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2106 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
2107 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
2108 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
2109 window = SDL_CreateWindow("OpenGL window",
2110 SDL_WINDOWPOS_UNDEFINED,
2111 SDL_WINDOWPOS_UNDEFINED,
2113 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
2114 SDL_GLContext context = SDL_GL_CreateContext(window);
2115 assert(context != nullptr);
2117 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
2118 // before all the render passes).
2119 float vertices[] = {
2125 glCreateBuffers(1, &vertex_vbo);
2126 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
2127 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
2129 if (enable_interpolation) {
2130 interpolate_image(argc, argv, optind);
2132 compute_flow_only(argc, argv, optind);