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