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))
31 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
32 constexpr float patch_overlap_ratio = 0.75f;
33 constexpr unsigned coarsest_level = 5;
34 constexpr unsigned finest_level = 1;
35 constexpr unsigned patch_size_pixels = 12;
37 // Weighting constants for the different parts of the variational refinement.
38 // These don't correspond 1:1 to the values given in the DIS paper,
39 // since we have different normalizations and ranges in some cases.
40 // These are found through a simple grid search on some MPI-Sintel data,
41 // although the error (EPE) seems to be fairly insensitive to the precise values.
42 // Only the relative values matter, so we fix alpha (the smoothness constant)
43 // at unity and tweak the others.
44 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
46 bool enable_timing = true;
47 bool enable_variational_refinement = true; // Just for debugging.
49 // Some global OpenGL objects.
50 // TODO: These should really be part of DISComputeFlow.
51 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
54 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
55 struct ReadInProgress {
57 string filename0, filename1;
58 string flow_filename, ppm_filename; // Either may be empty for no write.
60 stack<GLuint> spare_pbos;
61 deque<ReadInProgress> reads_in_progress;
63 string read_file(const string &filename)
65 FILE *fp = fopen(filename.c_str(), "r");
67 perror(filename.c_str());
71 int ret = fseek(fp, 0, SEEK_END);
73 perror("fseek(SEEK_END)");
79 ret = fseek(fp, 0, SEEK_SET);
81 perror("fseek(SEEK_SET)");
87 ret = fread(&str[0], size, 1, fp);
93 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
94 size, filename.c_str());
103 GLuint compile_shader(const string &shader_src, GLenum type)
105 GLuint obj = glCreateShader(type);
106 const GLchar* source[] = { shader_src.data() };
107 const GLint length[] = { (GLint)shader_src.size() };
108 glShaderSource(obj, 1, source, length);
109 glCompileShader(obj);
111 GLchar info_log[4096];
112 GLsizei log_length = sizeof(info_log) - 1;
113 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
114 info_log[log_length] = 0;
115 if (strlen(info_log) > 0) {
116 fprintf(stderr, "Shader compile log: %s\n", info_log);
120 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
121 if (status == GL_FALSE) {
122 // Add some line numbers to easier identify compile errors.
123 string src_with_lines = "/* 1 */ ";
125 for (char ch : shader_src) {
126 src_with_lines.push_back(ch);
129 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
130 src_with_lines += buf;
134 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
141 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
143 SDL_Surface *surf = IMG_Load(filename);
144 if (surf == nullptr) {
145 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
149 // For whatever reason, SDL doesn't support converting to YUV surfaces
150 // nor grayscale, so we'll do it (slowly) ourselves.
151 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
152 if (rgb_surf == nullptr) {
153 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
157 SDL_FreeSurface(surf);
159 unsigned width = rgb_surf->w, height = rgb_surf->h;
160 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
161 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
163 // Extract the Y component, and convert to bottom-left origin.
164 for (unsigned y = 0; y < height; ++y) {
165 unsigned y2 = height - 1 - y;
166 for (unsigned x = 0; x < width; ++x) {
167 uint8_t r = sptr[(y2 * width + x) * 4 + 3];
168 uint8_t g = sptr[(y2 * width + x) * 4 + 2];
169 uint8_t b = sptr[(y2 * width + x) * 4 + 1];
172 pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
175 SDL_FreeSurface(rgb_surf);
178 for (int w = width, h = height; w > 1 || h > 1; ) {
185 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
186 glTextureStorage2D(tex, levels, GL_R8, width, height);
187 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
188 glGenerateTextureMipmap(tex);
191 *height_ret = height;
196 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
198 GLuint program = glCreateProgram();
199 glAttachShader(program, vs_obj);
200 glAttachShader(program, fs_obj);
201 glLinkProgram(program);
203 glGetProgramiv(program, GL_LINK_STATUS, &success);
204 if (success == GL_FALSE) {
205 GLchar error_log[1024] = {0};
206 glGetProgramInfoLog(program, 1024, nullptr, error_log);
207 fprintf(stderr, "Error linking program: %s\n", error_log);
213 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
216 glCreateBuffers(1, &vbo);
217 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
218 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
222 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
224 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
229 GLuint vbo = generate_vbo(size, data_size, data);
231 glBindBuffer(GL_ARRAY_BUFFER, vbo);
232 glEnableVertexArrayAttrib(vao, attrib);
233 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
234 glBindBuffer(GL_ARRAY_BUFFER, 0);
239 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
241 if (location == -1) {
245 glBindTextureUnit(texture_unit, tex);
246 glBindSampler(texture_unit, sampler);
247 glProgramUniform1i(program, location, texture_unit);
250 // A class that caches FBOs that render to a given set of textures.
251 // It never frees anything, so it is only suitable for rendering to
252 // the same (small) set of textures over and over again.
253 template<size_t num_elements>
254 class PersistentFBOSet {
256 void render_to(const array<GLuint, num_elements> &textures);
258 // Convenience wrappers.
259 void render_to(GLuint texture0, enable_if<num_elements == 1> * = nullptr) {
260 render_to({{texture0}});
263 void render_to(GLuint texture0, GLuint texture1, enable_if<num_elements == 2> * = nullptr) {
264 render_to({{texture0, texture1}});
267 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, enable_if<num_elements == 3> * = nullptr) {
268 render_to({{texture0, texture1, texture2}});
271 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3, enable_if<num_elements == 4> * = nullptr) {
272 render_to({{texture0, texture1, texture2, texture3}});
276 // TODO: Delete these on destruction.
277 map<array<GLuint, num_elements>, GLuint> fbos;
280 template<size_t num_elements>
281 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
283 auto it = fbos.find(textures);
284 if (it != fbos.end()) {
285 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
290 glCreateFramebuffers(1, &fbo);
291 GLenum bufs[num_elements];
292 for (size_t i = 0; i < num_elements; ++i) {
293 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
294 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
296 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
298 fbos[textures] = fbo;
299 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
302 // Compute gradients in every point, used for the motion search.
303 // The DIS paper doesn't actually mention how these are computed,
304 // but seemingly, a 3x3 Sobel operator is used here (at least in
305 // later versions of the code), while a [1 -8 0 8 -1] kernel is
306 // used for all the derivatives in the variational refinement part
307 // (which borrows code from DeepFlow). This is inconsistent,
308 // but I guess we're better off with staying with the original
309 // decisions until we actually know having different ones would be better.
313 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
316 PersistentFBOSet<1> fbos;
319 GLuint sobel_program;
322 GLuint uniform_tex, uniform_image_size;
327 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
328 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
329 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
331 // Set up the VAO containing all the required position/texcoord data.
332 glCreateVertexArrays(1, &sobel_vao);
333 glBindVertexArray(sobel_vao);
335 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
336 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
337 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
339 uniform_tex = glGetUniformLocation(sobel_program, "tex");
342 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
344 glUseProgram(sobel_program);
345 glBindTextureUnit(0, tex0_view);
346 glBindSampler(0, nearest_sampler);
347 glProgramUniform1i(sobel_program, uniform_tex, 0);
349 glViewport(0, 0, level_width, level_height);
350 fbos.render_to(grad0_tex);
351 glBindVertexArray(sobel_vao);
352 glUseProgram(sobel_program);
354 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
357 // Motion search to find the initial flow. See motion_search.frag for documentation.
361 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);
364 PersistentFBOSet<1> fbos;
366 GLuint motion_vs_obj;
367 GLuint motion_fs_obj;
368 GLuint motion_search_program;
369 GLuint motion_search_vao;
371 GLuint uniform_image_size, uniform_inv_image_size, uniform_flow_size, uniform_inv_prev_level_size;
372 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
375 MotionSearch::MotionSearch()
377 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
378 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
379 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
381 // Set up the VAO containing all the required position/texcoord data.
382 glCreateVertexArrays(1, &motion_search_vao);
383 glBindVertexArray(motion_search_vao);
384 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
386 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
387 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
388 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
390 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
391 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
392 uniform_flow_size = glGetUniformLocation(motion_search_program, "flow_size");
393 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
394 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
395 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
396 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
397 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
400 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)
402 glUseProgram(motion_search_program);
404 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
405 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
406 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
407 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
409 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
410 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
411 glProgramUniform2f(motion_search_program, uniform_flow_size, width_patches, height_patches);
412 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
414 glViewport(0, 0, width_patches, height_patches);
415 fbos.render_to(flow_out_tex);
416 glBindVertexArray(motion_search_vao);
417 glUseProgram(motion_search_program);
418 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
421 // Do “densification”, ie., upsampling of the flow patches to the flow field
422 // (the same size as the image at this level). We draw one quad per patch
423 // over its entire covered area (using instancing in the vertex shader),
424 // and then weight the contributions in the pixel shader by post-warp difference.
425 // This is equation (3) in the paper.
427 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
428 // weight in the B channel. Dividing R and G by B gives the normalized values.
432 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);
435 PersistentFBOSet<1> fbos;
437 GLuint densify_vs_obj;
438 GLuint densify_fs_obj;
439 GLuint densify_program;
442 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
443 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
444 GLuint uniform_flow_size;
449 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
450 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
451 densify_program = link_program(densify_vs_obj, densify_fs_obj);
453 // Set up the VAO containing all the required position/texcoord data.
454 glCreateVertexArrays(1, &densify_vao);
455 glBindVertexArray(densify_vao);
456 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
458 GLint position_attrib = glGetAttribLocation(densify_program, "position");
459 glEnableVertexArrayAttrib(densify_vao, position_attrib);
460 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
462 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
463 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
464 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
465 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
466 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
467 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
468 uniform_flow_size = glGetUniformLocation(densify_program, "flow_size");
471 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)
473 glUseProgram(densify_program);
475 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
476 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
477 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
479 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
480 glProgramUniform2f(densify_program, uniform_patch_size,
481 float(patch_size_pixels) / level_width,
482 float(patch_size_pixels) / level_height);
483 glProgramUniform2f(densify_program, uniform_flow_size,
487 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
488 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
489 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
490 if (height_patches == 1) patch_spacing_y = 0.0f;
491 glProgramUniform2f(densify_program, uniform_patch_spacing,
492 patch_spacing_x / level_width,
493 patch_spacing_y / level_height);
495 glViewport(0, 0, level_width, level_height);
497 glBlendFunc(GL_ONE, GL_ONE);
498 glBindVertexArray(densify_vao);
499 fbos.render_to(dense_flow_tex);
500 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
503 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
504 // I_0 and I_w. The prewarping is what enables us to solve the variational
505 // flow for du,dv instead of u,v.
507 // Also calculates the normalized flow, ie. divides by z (this is needed because
508 // Densify works by additive blending) and multiplies by the image size.
510 // See variational_refinement.txt for more information.
514 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);
517 PersistentFBOSet<3> fbos;
519 GLuint prewarp_vs_obj;
520 GLuint prewarp_fs_obj;
521 GLuint prewarp_program;
524 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
525 GLuint uniform_image_size;
530 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
531 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
532 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
534 // Set up the VAO containing all the required position/texcoord data.
535 glCreateVertexArrays(1, &prewarp_vao);
536 glBindVertexArray(prewarp_vao);
537 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
539 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
540 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
541 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
543 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
544 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
545 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
547 uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
550 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)
552 glUseProgram(prewarp_program);
554 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
555 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
556 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
558 glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
560 glViewport(0, 0, level_width, level_height);
562 glBindVertexArray(prewarp_vao);
563 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
564 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
567 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
568 // central difference filter, since apparently, that's tradition (I haven't
569 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
570 // The coefficients come from
572 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
574 // Also computes β_0, since it depends only on I_x and I_y.
578 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
581 PersistentFBOSet<2> fbos;
583 GLuint derivatives_vs_obj;
584 GLuint derivatives_fs_obj;
585 GLuint derivatives_program;
586 GLuint derivatives_vao;
591 Derivatives::Derivatives()
593 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
594 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
595 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
597 // Set up the VAO containing all the required position/texcoord data.
598 glCreateVertexArrays(1, &derivatives_vao);
599 glBindVertexArray(derivatives_vao);
600 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
602 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
603 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
604 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
606 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
609 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
611 glUseProgram(derivatives_program);
613 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
615 glViewport(0, 0, level_width, level_height);
617 glBindVertexArray(derivatives_vao);
618 fbos.render_to(I_x_y_tex, beta_0_tex);
619 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
622 // Calculate the smoothness constraints between neighboring pixels;
623 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
624 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
625 // border color (0,0) later, so that there's zero diffusion out of
628 // See variational_refinement.txt for more information.
629 class ComputeSmoothness {
632 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
635 PersistentFBOSet<2> fbos;
637 GLuint smoothness_vs_obj;
638 GLuint smoothness_fs_obj;
639 GLuint smoothness_program;
640 GLuint smoothness_vao;
642 GLuint uniform_flow_tex, uniform_diff_flow_tex;
643 GLuint uniform_alpha;
646 ComputeSmoothness::ComputeSmoothness()
648 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
649 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
650 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
652 // Set up the VAO containing all the required position/texcoord data.
653 glCreateVertexArrays(1, &smoothness_vao);
654 glBindVertexArray(smoothness_vao);
655 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
657 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
658 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
659 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
661 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
662 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
663 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
666 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
668 glUseProgram(smoothness_program);
670 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
671 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
672 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
674 glViewport(0, 0, level_width, level_height);
677 glBindVertexArray(smoothness_vao);
678 fbos.render_to(smoothness_x_tex, smoothness_y_tex);
679 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
681 // Make sure the smoothness on the right and upper borders is zero.
682 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
683 // (we're sampling smoothness with all-zero border color), but we'd
684 // have to adjust the sampling coordinates, which is annoying.
685 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
686 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
689 // Set up the equations set (two equations in two unknowns, per pixel).
690 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
691 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
692 // floats. (Actually, we store the inverse of the diagonal elements, because
693 // we only ever need to divide by them.) This fits into four u32 values;
694 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
695 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
696 // terms that depend on other pixels, are calculated in one pass.
698 // See variational_refinement.txt for more information.
699 class SetupEquations {
702 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);
705 PersistentFBOSet<1> fbos;
707 GLuint equations_vs_obj;
708 GLuint equations_fs_obj;
709 GLuint equations_program;
710 GLuint equations_vao;
712 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
713 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
714 GLuint uniform_beta_0_tex;
715 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
716 GLuint uniform_gamma, uniform_delta;
719 SetupEquations::SetupEquations()
721 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
722 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
723 equations_program = link_program(equations_vs_obj, equations_fs_obj);
725 // Set up the VAO containing all the required position/texcoord data.
726 glCreateVertexArrays(1, &equations_vao);
727 glBindVertexArray(equations_vao);
728 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
730 GLint position_attrib = glGetAttribLocation(equations_program, "position");
731 glEnableVertexArrayAttrib(equations_vao, position_attrib);
732 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
734 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
735 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
736 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
737 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
738 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
739 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
740 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
741 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
742 uniform_delta = glGetUniformLocation(equations_program, "delta");
745 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)
747 glUseProgram(equations_program);
749 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
750 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
751 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
752 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
753 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
754 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
755 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
756 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
757 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
759 glViewport(0, 0, level_width, level_height);
761 glBindVertexArray(equations_vao);
762 fbos.render_to(equation_tex);
763 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
766 // Actually solve the equation sets made by SetupEquations, by means of
767 // successive over-relaxation (SOR).
769 // See variational_refinement.txt for more information.
773 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);
776 PersistentFBOSet<1> fbos;
783 GLuint uniform_diff_flow_tex;
784 GLuint uniform_equation_tex;
785 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
786 GLuint uniform_image_size, uniform_phase;
791 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
792 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
793 sor_program = link_program(sor_vs_obj, sor_fs_obj);
795 // Set up the VAO containing all the required position/texcoord data.
796 glCreateVertexArrays(1, &sor_vao);
797 glBindVertexArray(sor_vao);
798 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
800 GLint position_attrib = glGetAttribLocation(sor_program, "position");
801 glEnableVertexArrayAttrib(sor_vao, position_attrib);
802 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
804 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
805 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
806 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
807 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
808 uniform_image_size = glGetUniformLocation(sor_program, "image_size");
809 uniform_phase = glGetUniformLocation(sor_program, "phase");
812 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)
814 glUseProgram(sor_program);
816 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
817 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
818 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
819 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
821 glProgramUniform2f(sor_program, uniform_image_size, level_width, level_height);
823 // NOTE: We bind to the texture we are rendering from, but we never write any value
824 // that we read in the same shader pass (we call discard for red values when we compute
825 // black, and vice versa), and we have barriers between the passes, so we're fine
827 glViewport(0, 0, level_width, level_height);
829 glBindVertexArray(sor_vao);
830 fbos.render_to(diff_flow_tex);
832 for (int i = 0; i < num_iterations; ++i) {
833 glProgramUniform1i(sor_program, uniform_phase, 0);
834 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
836 glProgramUniform1i(sor_program, uniform_phase, 1);
837 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
838 if (i != num_iterations - 1) {
844 // Simply add the differential flow found by the variational refinement to the base flow.
845 // The output is in base_flow_tex; we don't need to make a new texture.
849 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
852 PersistentFBOSet<1> fbos;
854 GLuint add_flow_vs_obj;
855 GLuint add_flow_fs_obj;
856 GLuint add_flow_program;
859 GLuint uniform_diff_flow_tex;
862 AddBaseFlow::AddBaseFlow()
864 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
865 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
866 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
868 // Set up the VAO containing all the required position/texcoord data.
869 glCreateVertexArrays(1, &add_flow_vao);
870 glBindVertexArray(add_flow_vao);
871 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
873 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
874 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
875 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
877 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
880 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
882 glUseProgram(add_flow_program);
884 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
886 glViewport(0, 0, level_width, level_height);
888 glBlendFunc(GL_ONE, GL_ONE);
889 glBindVertexArray(add_flow_vao);
890 fbos.render_to(base_flow_tex);
892 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
895 // Take a copy of the flow, bilinearly interpolated and scaled up.
899 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
902 PersistentFBOSet<1> fbos;
904 GLuint resize_flow_vs_obj;
905 GLuint resize_flow_fs_obj;
906 GLuint resize_flow_program;
907 GLuint resize_flow_vao;
909 GLuint uniform_flow_tex;
910 GLuint uniform_scale_factor;
913 ResizeFlow::ResizeFlow()
915 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
916 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
917 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
919 // Set up the VAO containing all the required position/texcoord data.
920 glCreateVertexArrays(1, &resize_flow_vao);
921 glBindVertexArray(resize_flow_vao);
922 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
924 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
925 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
926 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
928 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
929 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
932 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
934 glUseProgram(resize_flow_program);
936 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
938 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
940 glViewport(0, 0, output_width, output_height);
942 glBindVertexArray(resize_flow_vao);
943 fbos.render_to(out_tex);
945 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
951 pair<GLuint, GLuint> begin_timer(const string &name, int level);
957 pair<GLuint, GLuint> query;
959 vector<Timer> timers;
962 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
964 if (!enable_timing) {
965 return make_pair(0, 0);
969 glGenQueries(2, queries);
970 glQueryCounter(queries[0], GL_TIMESTAMP);
975 timer.query.first = queries[0];
976 timer.query.second = queries[1];
977 timers.push_back(timer);
981 void GPUTimers::print()
983 for (const Timer &timer : timers) {
984 // NOTE: This makes the CPU wait for the GPU.
985 GLuint64 time_start, time_end;
986 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
987 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
988 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
989 for (int i = 0; i < timer.level * 2; ++i) {
990 fprintf(stderr, " ");
992 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
996 // A simple RAII class for timing until the end of the scope.
999 ScopedTimer(const string &name, GPUTimers *timers)
1000 : timers(timers), level(0)
1002 query = timers->begin_timer(name, level);
1005 ScopedTimer(const string &name, ScopedTimer *parent_timer)
1006 : timers(parent_timer->timers),
1007 level(parent_timer->level + 1)
1009 query = timers->begin_timer(name, level);
1019 if (enable_timing && !ended) {
1020 glQueryCounter(query.second, GL_TIMESTAMP);
1028 pair<GLuint, GLuint> query;
1032 class DISComputeFlow {
1034 DISComputeFlow(int width, int height);
1036 // Returns a texture that must be released with release_texture()
1038 GLuint exec(GLuint tex0, GLuint tex1);
1039 void release_texture(GLuint tex);
1043 GLuint initial_flow_tex;
1045 // The various passes.
1047 MotionSearch motion_search;
1050 Derivatives derivatives;
1051 ComputeSmoothness compute_smoothness;
1052 SetupEquations setup_equations;
1054 AddBaseFlow add_base_flow;
1055 ResizeFlow resize_flow;
1060 GLuint width, height;
1061 bool in_use = false;
1063 vector<Texture> textures;
1065 GLuint get_texture(GLenum format, GLuint width, GLuint height);
1068 DISComputeFlow::DISComputeFlow(int width, int height)
1069 : width(width), height(height)
1071 // Make some samplers.
1072 glCreateSamplers(1, &nearest_sampler);
1073 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1074 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1075 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1076 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1078 glCreateSamplers(1, &linear_sampler);
1079 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1080 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1081 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1082 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1084 // The smoothness is sampled so that once we get to a smoothness involving
1085 // a value outside the border, the diffusivity between the two becomes zero.
1086 // Similarly, gradients are zero outside the border, since the edge is taken
1088 glCreateSamplers(1, &zero_border_sampler);
1089 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1090 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1091 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1092 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1093 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1094 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1096 // Initial flow is zero, 1x1.
1097 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1098 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1099 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1102 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1)
1104 for (const Texture &tex : textures) {
1105 assert(!tex.in_use);
1108 int prev_level_width = 1, prev_level_height = 1;
1109 GLuint prev_level_flow_tex = initial_flow_tex;
1113 ScopedTimer total_timer("Total", &timers);
1114 for (int level = coarsest_level; level >= int(finest_level); --level) {
1115 char timer_name[256];
1116 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1117 ScopedTimer level_timer(timer_name, &total_timer);
1119 int level_width = width >> level;
1120 int level_height = height >> level;
1121 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1123 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1124 // and patch_spacing=3 (the default), we put out patch centers in
1125 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1126 // lock all the centers to integer coordinates if needed.
1127 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1128 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1130 // Make sure we always read from the correct level; the chosen
1131 // mipmapping could otherwise be rather unpredictable, especially
1132 // during motion search.
1133 // TODO: create these beforehand, and stop leaking them.
1134 GLuint tex0_view, tex1_view;
1135 glGenTextures(1, &tex0_view);
1136 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1137 glGenTextures(1, &tex1_view);
1138 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1140 // Create a new texture; we could be fancy and render use a multi-level
1141 // texture, but meh.
1142 GLuint grad0_tex = get_texture(GL_RG16F, level_width, level_height);
1144 // Find the derivative.
1146 ScopedTimer timer("Sobel", &level_timer);
1147 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1150 // Motion search to find the initial flow. We use the flow from the previous
1151 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1153 // Create an output flow texture.
1154 GLuint flow_out_tex = get_texture(GL_RGB16F, width_patches, height_patches);
1158 ScopedTimer timer("Motion search", &level_timer);
1159 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);
1161 release_texture(grad0_tex);
1165 // Set up an output texture (initially zero).
1166 GLuint dense_flow_tex = get_texture(GL_RGB16F, level_width, level_height);
1167 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1171 ScopedTimer timer("Densification", &level_timer);
1172 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1174 release_texture(flow_out_tex);
1176 // Everything below here in the loop belongs to variational refinement.
1177 ScopedTimer varref_timer("Variational refinement", &level_timer);
1179 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1180 // have to normalize it over and over again, and also save some bandwidth).
1182 // During the entire rest of the variational refinement, flow will be measured
1183 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1184 // This is because variational refinement depends so heavily on derivatives,
1185 // which are measured in intensity levels per pixel.
1186 GLuint I_tex = get_texture(GL_R16F, level_width, level_height);
1187 GLuint I_t_tex = get_texture(GL_R16F, level_width, level_height);
1188 GLuint base_flow_tex = get_texture(GL_RG16F, level_width, level_height);
1190 ScopedTimer timer("Prewarping", &varref_timer);
1191 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1193 release_texture(dense_flow_tex);
1195 // Calculate I_x and I_y. We're only calculating first derivatives;
1196 // the others will be taken on-the-fly in order to sample from fewer
1197 // textures overall, since sampling from the L1 cache is cheap.
1198 // (TODO: Verify that this is indeed faster than making separate
1199 // double-derivative textures.)
1200 GLuint I_x_y_tex = get_texture(GL_RG16F, level_width, level_height);
1201 GLuint beta_0_tex = get_texture(GL_R16F, level_width, level_height);
1203 ScopedTimer timer("First derivatives", &varref_timer);
1204 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1206 release_texture(I_tex);
1208 // We need somewhere to store du and dv (the flow increment, relative
1209 // to the non-refined base flow u0 and v0). It starts at zero.
1210 GLuint du_dv_tex = get_texture(GL_RG16F, level_width, level_height);
1211 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1213 // And for smoothness.
1214 GLuint smoothness_x_tex = get_texture(GL_R16F, level_width, level_height);
1215 GLuint smoothness_y_tex = get_texture(GL_R16F, level_width, level_height);
1217 // And finally for the equation set. See SetupEquations for
1218 // the storage format.
1219 GLuint equation_tex = get_texture(GL_RGBA32UI, level_width, level_height);
1221 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1222 // Calculate the smoothness terms between the neighboring pixels,
1223 // both in x and y direction.
1225 ScopedTimer timer("Compute smoothness", &varref_timer);
1226 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1229 // Set up the 2x2 equation system for each pixel.
1231 ScopedTimer timer("Set up equations", &varref_timer);
1232 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);
1235 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1236 // Note that these are to/from the same texture.
1238 ScopedTimer timer("SOR", &varref_timer);
1239 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1243 release_texture(I_t_tex);
1244 release_texture(I_x_y_tex);
1245 release_texture(beta_0_tex);
1246 release_texture(smoothness_x_tex);
1247 release_texture(smoothness_y_tex);
1248 release_texture(equation_tex);
1250 // Add the differential flow found by the variational refinement to the base flow,
1251 // giving the final flow estimate for this level.
1252 // The output is in diff_flow_tex; we don't need to make a new texture.
1254 // Disabling this doesn't save any time (although we could easily make it so that
1255 // it is more efficient), but it helps debug the motion search.
1256 if (enable_variational_refinement) {
1257 ScopedTimer timer("Add differential flow", &varref_timer);
1258 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1260 release_texture(du_dv_tex);
1262 if (prev_level_flow_tex != initial_flow_tex) {
1263 release_texture(prev_level_flow_tex);
1265 prev_level_flow_tex = base_flow_tex;
1266 prev_level_width = level_width;
1267 prev_level_height = level_height;
1273 // Scale up the flow to the final size (if needed).
1274 if (finest_level == 0) {
1275 return prev_level_flow_tex;
1277 GLuint final_tex = get_texture(GL_RG16F, width, height);
1278 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1279 release_texture(prev_level_flow_tex);
1284 GLuint DISComputeFlow::get_texture(GLenum format, GLuint width, GLuint height)
1286 for (Texture &tex : textures) {
1287 if (!tex.in_use && tex.format == format &&
1288 tex.width == width && tex.height == height) {
1295 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1296 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1297 tex.format = format;
1299 tex.height = height;
1301 textures.push_back(tex);
1305 void DISComputeFlow::release_texture(GLuint tex_num)
1307 for (Texture &tex : textures) {
1308 if (tex.tex_num == tex_num) {
1317 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1318 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1320 for (unsigned i = 0; i < width * height; ++i) {
1321 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1325 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1327 FILE *flowfp = fopen(filename, "wb");
1328 fprintf(flowfp, "FEIH");
1329 fwrite(&width, 4, 1, flowfp);
1330 fwrite(&height, 4, 1, flowfp);
1331 for (unsigned y = 0; y < height; ++y) {
1332 int yy = height - y - 1;
1333 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1338 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1340 FILE *fp = fopen(filename, "wb");
1341 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1342 for (unsigned y = 0; y < unsigned(height); ++y) {
1343 int yy = height - y - 1;
1344 for (unsigned x = 0; x < unsigned(width); ++x) {
1345 float du = dense_flow[(yy * width + x) * 2 + 0];
1346 float dv = dense_flow[(yy * width + x) * 2 + 1];
1349 flow2rgb(du, dv, &r, &g, &b);
1358 void finish_one_read(GLuint width, GLuint height)
1360 assert(!reads_in_progress.empty());
1361 ReadInProgress read = reads_in_progress.front();
1362 reads_in_progress.pop_front();
1364 unique_ptr<float[]> flow(new float[width * height * 2]);
1365 void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * 2 * sizeof(float), GL_MAP_READ_BIT); // Blocks if the read isn't done yet.
1366 memcpy(flow.get(), buf, width * height * 2 * sizeof(float));
1367 glUnmapNamedBuffer(read.pbo);
1368 spare_pbos.push(read.pbo);
1370 flip_coordinate_system(flow.get(), width, height);
1371 if (!read.flow_filename.empty()) {
1372 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1373 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1375 if (!read.ppm_filename.empty()) {
1376 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1380 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1382 if (spare_pbos.empty()) {
1383 finish_one_read(width, height);
1385 assert(!spare_pbos.empty());
1386 reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1387 glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1389 glGetTextureImage(tex, 0, GL_RG, GL_FLOAT, width * height * 2 * sizeof(float), nullptr);
1390 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1393 int main(int argc, char **argv)
1395 static const option long_options[] = {
1396 { "smoothness-relative-weight", required_argument, 0, 's' }, // alpha.
1397 { "intensity-relative-weight", required_argument, 0, 'i' }, // delta.
1398 { "gradient-relative-weight", required_argument, 0, 'g' }, // gamma.
1399 { "disable-timing", no_argument, 0, 1000 },
1400 { "ignore-variational-refinement", no_argument, 0, 1001 } // Still calculates it, just doesn't apply it.
1404 int option_index = 0;
1405 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1412 vr_alpha = atof(optarg);
1415 vr_delta = atof(optarg);
1418 vr_gamma = atof(optarg);
1421 enable_timing = false;
1424 enable_variational_refinement = false;
1427 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1432 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1433 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1436 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1437 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1438 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1439 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1441 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1442 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1443 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1444 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1445 SDL_Window *window = SDL_CreateWindow("OpenGL window",
1446 SDL_WINDOWPOS_UNDEFINED,
1447 SDL_WINDOWPOS_UNDEFINED,
1450 SDL_GLContext context = SDL_GL_CreateContext(window);
1451 assert(context != nullptr);
1453 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1454 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1455 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1458 unsigned width1, height1, width2, height2;
1459 GLuint tex0 = load_texture(filename0, &width1, &height1);
1460 GLuint tex1 = load_texture(filename1, &width2, &height2);
1462 if (width1 != width2 || height1 != height2) {
1463 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1464 width1, height1, width2, height2);
1468 // Set up some PBOs to do asynchronous readback.
1470 glCreateBuffers(5, pbos);
1471 for (int i = 0; i < 5; ++i) {
1472 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1473 spare_pbos.push(pbos[i]);
1476 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1477 // before all the render passes).
1478 float vertices[] = {
1484 glCreateBuffers(1, &vertex_vbo);
1485 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1486 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1488 DISComputeFlow compute_flow(width1, height1);
1489 GLuint final_tex = compute_flow.exec(tex0, tex1);
1491 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1492 compute_flow.release_texture(final_tex);
1494 // See if there are more flows on the command line (ie., more than three arguments),
1495 // and if so, process them.
1496 int num_flows = (argc - optind) / 3;
1497 for (int i = 1; i < num_flows; ++i) {
1498 const char *filename0 = argv[optind + i * 3 + 0];
1499 const char *filename1 = argv[optind + i * 3 + 1];
1500 const char *flow_filename = argv[optind + i * 3 + 2];
1501 GLuint width, height;
1502 GLuint tex0 = load_texture(filename0, &width, &height);
1503 if (width != width1 || height != height1) {
1504 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1505 filename0, width, height, width1, height1);
1509 GLuint tex1 = load_texture(filename1, &width, &height);
1510 if (width != width1 || height != height1) {
1511 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1512 filename1, width, height, width1, height1);
1516 GLuint final_tex = compute_flow.exec(tex0, tex1);
1517 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1518 compute_flow.release_texture(final_tex);
1521 while (!reads_in_progress.empty()) {
1522 finish_one_read(width1, height1);