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>
25 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
29 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
30 constexpr float patch_overlap_ratio = 0.75f;
31 constexpr unsigned coarsest_level = 5;
32 constexpr unsigned finest_level = 1;
33 constexpr unsigned patch_size_pixels = 12;
35 // Weighting constants for the different parts of the variational refinement.
36 // These don't correspond 1:1 to the values given in the DIS paper,
37 // since we have different normalizations and ranges in some cases.
38 float vr_gamma = 10.0f, vr_delta = 5.0f, vr_alpha = 10.0f;
40 bool enable_timing = true;
41 bool enable_variational_refinement = true; // Just for debugging.
43 // Some global OpenGL objects.
44 // TODO: These should really be part of DISComputeFlow.
45 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
48 string read_file(const string &filename)
50 FILE *fp = fopen(filename.c_str(), "r");
52 perror(filename.c_str());
56 int ret = fseek(fp, 0, SEEK_END);
58 perror("fseek(SEEK_END)");
64 ret = fseek(fp, 0, SEEK_SET);
66 perror("fseek(SEEK_SET)");
72 ret = fread(&str[0], size, 1, fp);
78 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
79 size, filename.c_str());
88 GLuint compile_shader(const string &shader_src, GLenum type)
90 GLuint obj = glCreateShader(type);
91 const GLchar* source[] = { shader_src.data() };
92 const GLint length[] = { (GLint)shader_src.size() };
93 glShaderSource(obj, 1, source, length);
96 GLchar info_log[4096];
97 GLsizei log_length = sizeof(info_log) - 1;
98 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
99 info_log[log_length] = 0;
100 if (strlen(info_log) > 0) {
101 fprintf(stderr, "Shader compile log: %s\n", info_log);
105 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
106 if (status == GL_FALSE) {
107 // Add some line numbers to easier identify compile errors.
108 string src_with_lines = "/* 1 */ ";
110 for (char ch : shader_src) {
111 src_with_lines.push_back(ch);
114 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
115 src_with_lines += buf;
119 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
126 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
128 SDL_Surface *surf = IMG_Load(filename);
129 if (surf == nullptr) {
130 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
134 // For whatever reason, SDL doesn't support converting to YUV surfaces
135 // nor grayscale, so we'll do it (slowly) ourselves.
136 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
137 if (rgb_surf == nullptr) {
138 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
142 SDL_FreeSurface(surf);
144 unsigned width = rgb_surf->w, height = rgb_surf->h;
145 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
146 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
148 // Extract the Y component, and convert to bottom-left origin.
149 for (unsigned y = 0; y < height; ++y) {
150 unsigned y2 = height - 1 - y;
151 for (unsigned x = 0; x < width; ++x) {
152 uint8_t r = sptr[(y2 * width + x) * 4 + 3];
153 uint8_t g = sptr[(y2 * width + x) * 4 + 2];
154 uint8_t b = sptr[(y2 * width + x) * 4 + 1];
157 pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
160 SDL_FreeSurface(rgb_surf);
163 for (int w = width, h = height; w > 1 || h > 1; ) {
170 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
171 glTextureStorage2D(tex, levels, GL_R8, width, height);
172 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
173 glGenerateTextureMipmap(tex);
176 *height_ret = height;
181 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
183 GLuint program = glCreateProgram();
184 glAttachShader(program, vs_obj);
185 glAttachShader(program, fs_obj);
186 glLinkProgram(program);
188 glGetProgramiv(program, GL_LINK_STATUS, &success);
189 if (success == GL_FALSE) {
190 GLchar error_log[1024] = {0};
191 glGetProgramInfoLog(program, 1024, nullptr, error_log);
192 fprintf(stderr, "Error linking program: %s\n", error_log);
198 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
201 glCreateBuffers(1, &vbo);
202 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
203 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
207 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
209 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
214 GLuint vbo = generate_vbo(size, data_size, data);
216 glBindBuffer(GL_ARRAY_BUFFER, vbo);
217 glEnableVertexArrayAttrib(vao, attrib);
218 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
219 glBindBuffer(GL_ARRAY_BUFFER, 0);
224 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
226 if (location == -1) {
230 glBindTextureUnit(texture_unit, tex);
231 glBindSampler(texture_unit, sampler);
232 glProgramUniform1i(program, location, texture_unit);
235 // A class that caches FBOs that render to a given set of textures.
236 // It never frees anything, so it is only suitable for rendering to
237 // the same (small) set of textures over and over again.
238 template<size_t num_elements>
239 class PersistentFBOSet {
241 void render_to(const array<GLuint, num_elements> &textures);
243 // Convenience wrappers.
244 void render_to(GLuint texture0, enable_if<num_elements == 1> * = nullptr) {
245 render_to({{texture0}});
248 void render_to(GLuint texture0, GLuint texture1, enable_if<num_elements == 2> * = nullptr) {
249 render_to({{texture0, texture1}});
252 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, enable_if<num_elements == 3> * = nullptr) {
253 render_to({{texture0, texture1, texture2}});
256 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3, enable_if<num_elements == 4> * = nullptr) {
257 render_to({{texture0, texture1, texture2, texture3}});
261 // TODO: Delete these on destruction.
262 map<array<GLuint, num_elements>, GLuint> fbos;
265 template<size_t num_elements>
266 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
268 auto it = fbos.find(textures);
269 if (it != fbos.end()) {
270 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
275 glCreateFramebuffers(1, &fbo);
276 GLenum bufs[num_elements];
277 for (size_t i = 0; i < num_elements; ++i) {
278 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
279 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
281 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
283 fbos[textures] = fbo;
284 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
287 // Compute gradients in every point, used for the motion search.
288 // The DIS paper doesn't actually mention how these are computed,
289 // but seemingly, a 3x3 Sobel operator is used here (at least in
290 // later versions of the code), while a [1 -8 0 8 -1] kernel is
291 // used for all the derivatives in the variational refinement part
292 // (which borrows code from DeepFlow). This is inconsistent,
293 // but I guess we're better off with staying with the original
294 // decisions until we actually know having different ones would be better.
298 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
301 PersistentFBOSet<1> fbos;
304 GLuint sobel_program;
307 GLuint uniform_tex, uniform_image_size;
312 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
313 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
314 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
316 // Set up the VAO containing all the required position/texcoord data.
317 glCreateVertexArrays(1, &sobel_vao);
318 glBindVertexArray(sobel_vao);
320 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
321 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
322 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
324 uniform_tex = glGetUniformLocation(sobel_program, "tex");
327 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
329 glUseProgram(sobel_program);
330 glBindTextureUnit(0, tex0_view);
331 glBindSampler(0, nearest_sampler);
332 glProgramUniform1i(sobel_program, uniform_tex, 0);
334 glViewport(0, 0, level_width, level_height);
335 fbos.render_to(grad0_tex);
336 glBindVertexArray(sobel_vao);
337 glUseProgram(sobel_program);
339 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
342 // Motion search to find the initial flow. See motion_search.frag for documentation.
346 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);
349 PersistentFBOSet<1> fbos;
351 GLuint motion_vs_obj;
352 GLuint motion_fs_obj;
353 GLuint motion_search_program;
354 GLuint motion_search_vao;
356 GLuint uniform_image_size, uniform_inv_image_size, uniform_inv_flow_size, uniform_inv_prev_level_size;
357 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
360 MotionSearch::MotionSearch()
362 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
363 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
364 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
366 // Set up the VAO containing all the required position/texcoord data.
367 glCreateVertexArrays(1, &motion_search_vao);
368 glBindVertexArray(motion_search_vao);
369 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
371 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
372 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
373 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
375 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
376 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
377 uniform_inv_flow_size = glGetUniformLocation(motion_search_program, "inv_flow_size");
378 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
379 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
380 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
381 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
382 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
385 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)
387 glUseProgram(motion_search_program);
389 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
390 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
391 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
392 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
394 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
395 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
396 glProgramUniform2f(motion_search_program, uniform_inv_flow_size, 1.0f / width_patches, 1.0f / height_patches);
397 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
399 glViewport(0, 0, width_patches, height_patches);
400 fbos.render_to(flow_out_tex);
401 glBindVertexArray(motion_search_vao);
402 glUseProgram(motion_search_program);
403 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
406 // Do “densification”, ie., upsampling of the flow patches to the flow field
407 // (the same size as the image at this level). We draw one quad per patch
408 // over its entire covered area (using instancing in the vertex shader),
409 // and then weight the contributions in the pixel shader by post-warp difference.
410 // This is equation (3) in the paper.
412 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
413 // weight in the B channel. Dividing R and G by B gives the normalized values.
417 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);
420 PersistentFBOSet<1> fbos;
422 GLuint densify_vs_obj;
423 GLuint densify_fs_obj;
424 GLuint densify_program;
427 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
428 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
433 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
434 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
435 densify_program = link_program(densify_vs_obj, densify_fs_obj);
437 // Set up the VAO containing all the required position/texcoord data.
438 glCreateVertexArrays(1, &densify_vao);
439 glBindVertexArray(densify_vao);
440 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
442 GLint position_attrib = glGetAttribLocation(densify_program, "position");
443 glEnableVertexArrayAttrib(densify_vao, position_attrib);
444 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
446 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
447 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
448 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
449 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
450 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
451 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
454 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)
456 glUseProgram(densify_program);
458 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
459 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
460 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
462 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
463 glProgramUniform2f(densify_program, uniform_patch_size,
464 float(patch_size_pixels) / level_width,
465 float(patch_size_pixels) / level_height);
467 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
468 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
469 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
470 if (height_patches == 1) patch_spacing_y = 0.0f;
471 glProgramUniform2f(densify_program, uniform_patch_spacing,
472 patch_spacing_x / level_width,
473 patch_spacing_y / level_height);
475 glViewport(0, 0, level_width, level_height);
477 glBlendFunc(GL_ONE, GL_ONE);
478 glBindVertexArray(densify_vao);
479 fbos.render_to(dense_flow_tex);
480 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
483 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
484 // I_0 and I_w. The prewarping is what enables us to solve the variational
485 // flow for du,dv instead of u,v.
487 // Also calculates the normalized flow, ie. divides by z (this is needed because
488 // Densify works by additive blending) and multiplies by the image size.
490 // See variational_refinement.txt for more information.
494 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);
497 PersistentFBOSet<3> fbos;
499 GLuint prewarp_vs_obj;
500 GLuint prewarp_fs_obj;
501 GLuint prewarp_program;
504 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
505 GLuint uniform_image_size;
510 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
511 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
512 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
514 // Set up the VAO containing all the required position/texcoord data.
515 glCreateVertexArrays(1, &prewarp_vao);
516 glBindVertexArray(prewarp_vao);
517 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
519 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
520 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
521 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
523 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
524 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
525 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
527 uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
530 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)
532 glUseProgram(prewarp_program);
534 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
535 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
536 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
538 glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
540 glViewport(0, 0, level_width, level_height);
542 glBindVertexArray(prewarp_vao);
543 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
544 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
547 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
548 // central difference filter, since apparently, that's tradition (I haven't
549 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
550 // The coefficients come from
552 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
554 // Also computes β_0, since it depends only on I_x and I_y.
558 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
561 PersistentFBOSet<2> fbos;
563 GLuint derivatives_vs_obj;
564 GLuint derivatives_fs_obj;
565 GLuint derivatives_program;
566 GLuint derivatives_vao;
571 Derivatives::Derivatives()
573 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
574 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
575 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
577 // Set up the VAO containing all the required position/texcoord data.
578 glCreateVertexArrays(1, &derivatives_vao);
579 glBindVertexArray(derivatives_vao);
580 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
582 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
583 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
584 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
586 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
589 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
591 glUseProgram(derivatives_program);
593 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
595 glViewport(0, 0, level_width, level_height);
597 glBindVertexArray(derivatives_vao);
598 fbos.render_to(I_x_y_tex, beta_0_tex);
599 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
602 // Calculate the smoothness constraints between neighboring pixels;
603 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
604 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
605 // border color (0,0) later, so that there's zero diffusion out of
608 // See variational_refinement.txt for more information.
609 class ComputeSmoothness {
612 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
615 PersistentFBOSet<2> fbos;
617 GLuint smoothness_vs_obj;
618 GLuint smoothness_fs_obj;
619 GLuint smoothness_program;
620 GLuint smoothness_vao;
622 GLuint uniform_flow_tex, uniform_diff_flow_tex;
623 GLuint uniform_alpha;
626 ComputeSmoothness::ComputeSmoothness()
628 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
629 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
630 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
632 // Set up the VAO containing all the required position/texcoord data.
633 glCreateVertexArrays(1, &smoothness_vao);
634 glBindVertexArray(smoothness_vao);
635 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
637 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
638 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
639 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
641 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
642 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
643 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
646 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
648 glUseProgram(smoothness_program);
650 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
651 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
652 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
654 glViewport(0, 0, level_width, level_height);
657 glBindVertexArray(smoothness_vao);
658 fbos.render_to(smoothness_x_tex, smoothness_y_tex);
659 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
661 // Make sure the smoothness on the right and upper borders is zero.
662 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
663 // (we're sampling smoothness with all-zero border color), but we'd
664 // have to adjust the sampling coordinates, which is annoying.
665 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
666 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
669 // Set up the equations set (two equations in two unknowns, per pixel).
670 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
671 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
672 // floats. (Actually, we store the inverse of the diagonal elements, because
673 // we only ever need to divide by them.) This fits into four u32 values;
674 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
675 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
676 // terms that depend on other pixels, are calculated in one pass.
678 // See variational_refinement.txt for more information.
679 class SetupEquations {
682 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);
685 PersistentFBOSet<1> fbos;
687 GLuint equations_vs_obj;
688 GLuint equations_fs_obj;
689 GLuint equations_program;
690 GLuint equations_vao;
692 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
693 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
694 GLuint uniform_beta_0_tex;
695 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
696 GLuint uniform_gamma, uniform_delta;
699 SetupEquations::SetupEquations()
701 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
702 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
703 equations_program = link_program(equations_vs_obj, equations_fs_obj);
705 // Set up the VAO containing all the required position/texcoord data.
706 glCreateVertexArrays(1, &equations_vao);
707 glBindVertexArray(equations_vao);
708 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
710 GLint position_attrib = glGetAttribLocation(equations_program, "position");
711 glEnableVertexArrayAttrib(equations_vao, position_attrib);
712 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
714 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
715 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
716 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
717 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
718 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
719 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
720 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
721 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
722 uniform_delta = glGetUniformLocation(equations_program, "delta");
725 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)
727 glUseProgram(equations_program);
729 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
730 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
731 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
732 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
733 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
734 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
735 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
736 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
737 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
739 glViewport(0, 0, level_width, level_height);
741 glBindVertexArray(equations_vao);
742 fbos.render_to(equation_tex);
743 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
746 // Actually solve the equation sets made by SetupEquations, by means of
747 // successive over-relaxation (SOR).
749 // See variational_refinement.txt for more information.
753 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);
756 PersistentFBOSet<1> fbos;
763 GLuint uniform_diff_flow_tex;
764 GLuint uniform_equation_tex;
765 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
770 sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
771 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
772 sor_program = link_program(sor_vs_obj, sor_fs_obj);
774 // Set up the VAO containing all the required position/texcoord data.
775 glCreateVertexArrays(1, &sor_vao);
776 glBindVertexArray(sor_vao);
777 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
779 GLint position_attrib = glGetAttribLocation(sor_program, "position");
780 glEnableVertexArrayAttrib(sor_vao, position_attrib);
781 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
783 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
784 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
785 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
786 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
789 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)
791 glUseProgram(sor_program);
793 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
794 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
795 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
796 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
798 glViewport(0, 0, level_width, level_height);
800 glBindVertexArray(sor_vao);
801 fbos.render_to(diff_flow_tex); // NOTE: Bind to same as we render from!
803 for (int i = 0; i < num_iterations; ++i) {
804 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
805 if (i != num_iterations - 1) {
811 // Simply add the differential flow found by the variational refinement to the base flow.
812 // The output is in base_flow_tex; we don't need to make a new texture.
816 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
819 PersistentFBOSet<1> fbos;
821 GLuint add_flow_vs_obj;
822 GLuint add_flow_fs_obj;
823 GLuint add_flow_program;
826 GLuint uniform_diff_flow_tex;
829 AddBaseFlow::AddBaseFlow()
831 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
832 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
833 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
835 // Set up the VAO containing all the required position/texcoord data.
836 glCreateVertexArrays(1, &add_flow_vao);
837 glBindVertexArray(add_flow_vao);
838 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
840 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
841 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
842 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
844 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
847 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
849 glUseProgram(add_flow_program);
851 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
853 glViewport(0, 0, level_width, level_height);
855 glBlendFunc(GL_ONE, GL_ONE);
856 glBindVertexArray(add_flow_vao);
857 fbos.render_to(base_flow_tex);
859 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
862 // Take a copy of the flow, bilinearly interpolated and scaled up.
866 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
869 PersistentFBOSet<1> fbos;
871 GLuint resize_flow_vs_obj;
872 GLuint resize_flow_fs_obj;
873 GLuint resize_flow_program;
874 GLuint resize_flow_vao;
876 GLuint uniform_flow_tex;
877 GLuint uniform_scale_factor;
880 ResizeFlow::ResizeFlow()
882 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
883 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
884 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
886 // Set up the VAO containing all the required position/texcoord data.
887 glCreateVertexArrays(1, &resize_flow_vao);
888 glBindVertexArray(resize_flow_vao);
889 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
891 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
892 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
893 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
895 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
896 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
899 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
901 glUseProgram(resize_flow_program);
903 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
905 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
907 glViewport(0, 0, output_width, output_height);
909 glBindVertexArray(resize_flow_vao);
910 fbos.render_to(out_tex);
912 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
918 pair<GLuint, GLuint> begin_timer(const string &name, int level);
924 pair<GLuint, GLuint> query;
926 vector<Timer> timers;
929 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
931 if (!enable_timing) {
932 return make_pair(0, 0);
936 glGenQueries(2, queries);
937 glQueryCounter(queries[0], GL_TIMESTAMP);
942 timer.query.first = queries[0];
943 timer.query.second = queries[1];
944 timers.push_back(timer);
948 void GPUTimers::print()
950 for (const Timer &timer : timers) {
951 // NOTE: This makes the CPU wait for the GPU.
952 GLuint64 time_start, time_end;
953 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
954 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
955 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
956 for (int i = 0; i < timer.level * 2; ++i) {
957 fprintf(stderr, " ");
959 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
963 // A simple RAII class for timing until the end of the scope.
966 ScopedTimer(const string &name, GPUTimers *timers)
967 : timers(timers), level(0)
969 query = timers->begin_timer(name, level);
972 ScopedTimer(const string &name, ScopedTimer *parent_timer)
973 : timers(parent_timer->timers),
974 level(parent_timer->level + 1)
976 query = timers->begin_timer(name, level);
986 if (enable_timing && !ended) {
987 glQueryCounter(query.second, GL_TIMESTAMP);
995 pair<GLuint, GLuint> query;
999 class DISComputeFlow {
1001 DISComputeFlow(int width, int height);
1003 // Returns a texture that must be released with release_texture()
1005 GLuint exec(GLuint tex0, GLuint tex1);
1006 void release_texture(GLuint tex);
1010 GLuint initial_flow_tex;
1012 // The various passes.
1014 MotionSearch motion_search;
1017 Derivatives derivatives;
1018 ComputeSmoothness compute_smoothness;
1019 SetupEquations setup_equations;
1021 AddBaseFlow add_base_flow;
1022 ResizeFlow resize_flow;
1027 GLuint width, height;
1028 bool in_use = false;
1030 vector<Texture> textures;
1032 GLuint get_texture(GLenum format, GLuint width, GLuint height);
1035 DISComputeFlow::DISComputeFlow(int width, int height)
1036 : width(width), height(height)
1038 // Make some samplers.
1039 glCreateSamplers(1, &nearest_sampler);
1040 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1041 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1042 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1043 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1045 glCreateSamplers(1, &linear_sampler);
1046 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1047 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1048 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1049 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1051 // The smoothness is sampled so that once we get to a smoothness involving
1052 // a value outside the border, the diffusivity between the two becomes zero.
1053 glCreateSamplers(1, &smoothness_sampler);
1054 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1055 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1056 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1057 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1058 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1059 glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1061 // Initial flow is zero, 1x1.
1062 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1063 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1064 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1067 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1)
1069 for (const Texture &tex : textures) {
1070 assert(!tex.in_use);
1073 int prev_level_width = 1, prev_level_height = 1;
1074 GLuint prev_level_flow_tex = initial_flow_tex;
1078 ScopedTimer total_timer("Total", &timers);
1079 for (int level = coarsest_level; level >= int(finest_level); --level) {
1080 char timer_name[256];
1081 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1082 ScopedTimer level_timer(timer_name, &total_timer);
1084 int level_width = width >> level;
1085 int level_height = height >> level;
1086 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1087 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
1088 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
1090 // Make sure we always read from the correct level; the chosen
1091 // mipmapping could otherwise be rather unpredictable, especially
1092 // during motion search.
1093 // TODO: create these beforehand, and stop leaking them.
1094 GLuint tex0_view, tex1_view;
1095 glGenTextures(1, &tex0_view);
1096 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1097 glGenTextures(1, &tex1_view);
1098 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1100 // Create a new texture; we could be fancy and render use a multi-level
1101 // texture, but meh.
1102 GLuint grad0_tex = get_texture(GL_RG16F, level_width, level_height);
1104 // Find the derivative.
1106 ScopedTimer timer("Sobel", &level_timer);
1107 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1110 // Motion search to find the initial flow. We use the flow from the previous
1111 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1113 // Create an output flow texture.
1114 GLuint flow_out_tex = get_texture(GL_RGB16F, width_patches, height_patches);
1118 ScopedTimer timer("Motion search", &level_timer);
1119 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);
1121 release_texture(grad0_tex);
1125 // Set up an output texture (initially zero).
1126 GLuint dense_flow_tex = get_texture(GL_RGB16F, level_width, level_height);
1127 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1131 ScopedTimer timer("Densification", &level_timer);
1132 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1134 release_texture(flow_out_tex);
1136 // Everything below here in the loop belongs to variational refinement.
1137 ScopedTimer varref_timer("Variational refinement", &level_timer);
1139 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1140 // have to normalize it over and over again, and also save some bandwidth).
1142 // During the entire rest of the variational refinement, flow will be measured
1143 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1144 // This is because variational refinement depends so heavily on derivatives,
1145 // which are measured in intensity levels per pixel.
1146 GLuint I_tex = get_texture(GL_R16F, level_width, level_height);
1147 GLuint I_t_tex = get_texture(GL_R16F, level_width, level_height);
1148 GLuint base_flow_tex = get_texture(GL_RG16F, level_width, level_height);
1150 ScopedTimer timer("Prewarping", &varref_timer);
1151 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1153 release_texture(dense_flow_tex);
1155 // Calculate I_x and I_y. We're only calculating first derivatives;
1156 // the others will be taken on-the-fly in order to sample from fewer
1157 // textures overall, since sampling from the L1 cache is cheap.
1158 // (TODO: Verify that this is indeed faster than making separate
1159 // double-derivative textures.)
1160 GLuint I_x_y_tex = get_texture(GL_RG16F, level_width, level_height);
1161 GLuint beta_0_tex = get_texture(GL_R16F, level_width, level_height);
1163 ScopedTimer timer("First derivatives", &varref_timer);
1164 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1166 release_texture(I_tex);
1168 // We need somewhere to store du and dv (the flow increment, relative
1169 // to the non-refined base flow u0 and v0). It starts at zero.
1170 GLuint du_dv_tex = get_texture(GL_RG16F, level_width, level_height);
1171 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1173 // And for smoothness.
1174 GLuint smoothness_x_tex = get_texture(GL_R16F, level_width, level_height);
1175 GLuint smoothness_y_tex = get_texture(GL_R16F, level_width, level_height);
1177 // And finally for the equation set. See SetupEquations for
1178 // the storage format.
1179 GLuint equation_tex = get_texture(GL_RGBA32UI, level_width, level_height);
1181 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1182 // Calculate the smoothness terms between the neighboring pixels,
1183 // both in x and y direction.
1185 ScopedTimer timer("Compute smoothness", &varref_timer);
1186 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1189 // Set up the 2x2 equation system for each pixel.
1191 ScopedTimer timer("Set up equations", &varref_timer);
1192 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);
1195 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1196 // Note that these are to/from the same texture.
1198 ScopedTimer timer("SOR", &varref_timer);
1199 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1203 release_texture(I_t_tex);
1204 release_texture(I_x_y_tex);
1205 release_texture(beta_0_tex);
1206 release_texture(smoothness_x_tex);
1207 release_texture(smoothness_y_tex);
1208 release_texture(equation_tex);
1210 // Add the differential flow found by the variational refinement to the base flow,
1211 // giving the final flow estimate for this level.
1212 // The output is in diff_flow_tex; we don't need to make a new texture.
1214 // Disabling this doesn't save any time (although we could easily make it so that
1215 // it is more efficient), but it helps debug the motion search.
1216 if (enable_variational_refinement) {
1217 ScopedTimer timer("Add differential flow", &varref_timer);
1218 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1220 release_texture(du_dv_tex);
1222 if (prev_level_flow_tex != initial_flow_tex) {
1223 release_texture(prev_level_flow_tex);
1225 prev_level_flow_tex = base_flow_tex;
1226 prev_level_width = level_width;
1227 prev_level_height = level_height;
1233 // Scale up the flow to the final size (if needed).
1234 if (finest_level == 0) {
1235 return prev_level_flow_tex;
1237 GLuint final_tex = get_texture(GL_RG16F, width, height);
1238 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1239 release_texture(prev_level_flow_tex);
1244 GLuint DISComputeFlow::get_texture(GLenum format, GLuint width, GLuint height)
1246 for (Texture &tex : textures) {
1247 if (!tex.in_use && tex.format == format &&
1248 tex.width == width && tex.height == height) {
1255 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1256 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1257 tex.format = format;
1259 tex.height = height;
1261 textures.push_back(tex);
1265 void DISComputeFlow::release_texture(GLuint tex_num)
1267 for (Texture &tex : textures) {
1268 if (tex.tex_num == tex_num) {
1277 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1278 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1280 for (unsigned i = 0; i < width * height; ++i) {
1281 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1285 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1287 FILE *flowfp = fopen(filename, "wb");
1288 fprintf(flowfp, "FEIH");
1289 fwrite(&width, 4, 1, flowfp);
1290 fwrite(&height, 4, 1, flowfp);
1291 for (unsigned y = 0; y < height; ++y) {
1292 int yy = height - y - 1;
1293 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1298 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1300 FILE *fp = fopen(filename, "wb");
1301 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1302 for (unsigned y = 0; y < unsigned(height); ++y) {
1303 int yy = height - y - 1;
1304 for (unsigned x = 0; x < unsigned(width); ++x) {
1305 float du = dense_flow[(yy * width + x) * 2 + 0];
1306 float dv = dense_flow[(yy * width + x) * 2 + 1];
1309 flow2rgb(du, dv, &r, &g, &b);
1318 int main(int argc, char **argv)
1320 static const option long_options[] = {
1321 { "alpha", required_argument, 0, 'a' },
1322 { "delta", required_argument, 0, 'd' },
1323 { "gamma", required_argument, 0, 'g' },
1324 { "disable-timing", no_argument, 0, 1000 },
1325 { "ignore-variational-refinement", no_argument, 0, 1001 } // Still calculates it, just doesn't apply it.
1329 int option_index = 0;
1330 int c = getopt_long(argc, argv, "a:d:g:", long_options, &option_index);
1337 vr_alpha = atof(optarg);
1340 vr_delta = atof(optarg);
1343 vr_gamma = atof(optarg);
1346 enable_timing = false;
1349 enable_variational_refinement = false;
1352 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1357 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1358 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1361 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1362 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1363 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1364 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1366 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1367 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1368 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1369 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1370 SDL_Window *window = SDL_CreateWindow("OpenGL window",
1371 SDL_WINDOWPOS_UNDEFINED,
1372 SDL_WINDOWPOS_UNDEFINED,
1375 SDL_GLContext context = SDL_GL_CreateContext(window);
1376 assert(context != nullptr);
1378 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1379 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1380 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1381 fprintf(stderr, "%s %s -> %s\n", filename0, filename1, flow_filename);
1384 unsigned width1, height1, width2, height2;
1385 GLuint tex0 = load_texture(filename0, &width1, &height1);
1386 GLuint tex1 = load_texture(filename1, &width2, &height2);
1388 if (width1 != width2 || height1 != height2) {
1389 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1390 width1, height1, width2, height2);
1394 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1395 // before all the render passes).
1396 float vertices[] = {
1402 glCreateBuffers(1, &vertex_vbo);
1403 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1404 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1406 DISComputeFlow compute_flow(width1, height1);
1407 GLuint final_tex = compute_flow.exec(tex0, tex1);
1409 unique_ptr<float[]> dense_flow(new float[width1 * height1 * 2]);
1410 glGetTextureImage(final_tex, 0, GL_RG, GL_FLOAT, width1 * height1 * 2 * sizeof(float), dense_flow.get());
1412 compute_flow.release_texture(final_tex);
1414 flip_coordinate_system(dense_flow.get(), width1, height1);
1415 write_flow(flow_filename, dense_flow.get(), width1, height1);
1416 write_ppm("flow.ppm", dense_flow.get(), width1, height1);
1420 // See if there are more flows on the command line (ie., more than three arguments),
1421 // and if so, process them.
1422 int num_flows = (argc - optind) / 3;
1423 for (int i = 1; i < num_flows; ++i) {
1424 const char *filename0 = argv[optind + i * 3 + 0];
1425 const char *filename1 = argv[optind + i * 3 + 1];
1426 const char *flow_filename = argv[optind + i * 3 + 2];
1427 fprintf(stderr, "%s %s -> %s\n", filename0, filename1, flow_filename);
1429 GLuint width, height;
1430 GLuint tex0 = load_texture(filename0, &width, &height);
1431 if (width != width1 || height != height1) {
1432 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1433 filename0, width, height, width1, height1);
1437 GLuint tex1 = load_texture(filename1, &width, &height);
1438 if (width != width1 || height != height1) {
1439 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1440 filename1, width, height, width1, height1);
1444 GLuint final_tex = compute_flow.exec(tex0, tex1);
1446 unique_ptr<float[]> dense_flow(new float[width * height * 2]);
1447 glGetTextureImage(final_tex, 0, GL_RG, GL_FLOAT, width * height * 2 * sizeof(float), dense_flow.get());
1449 compute_flow.release_texture(final_tex);
1451 flip_coordinate_system(dense_flow.get(), width, height);
1452 write_flow(flow_filename, dense_flow.get(), width, height);
1455 fprintf(stderr, "err = %d\n", glGetError());