6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
18 #include "gpu_timers.h"
28 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
34 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
35 constexpr float patch_overlap_ratio = 0.75f;
36 constexpr unsigned coarsest_level = 5;
37 constexpr unsigned finest_level = 1;
38 constexpr unsigned patch_size_pixels = 12;
40 // Weighting constants for the different parts of the variational refinement.
41 // These don't correspond 1:1 to the values given in the DIS paper,
42 // since we have different normalizations and ranges in some cases.
43 // These are found through a simple grid search on some MPI-Sintel data,
44 // although the error (EPE) seems to be fairly insensitive to the precise values.
45 // Only the relative values matter, so we fix alpha (the smoothness constant)
46 // at unity and tweak the others.
47 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
49 bool enable_timing = true;
50 bool detailed_timing = false;
51 bool enable_variational_refinement = true; // Just for debugging.
52 bool enable_interpolation = false;
54 // Some global OpenGL objects.
55 // TODO: These should really be part of DISComputeFlow.
56 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
59 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
60 struct ReadInProgress {
62 string filename0, filename1;
63 string flow_filename, ppm_filename; // Either may be empty for no write.
65 stack<GLuint> spare_pbos;
66 deque<ReadInProgress> reads_in_progress;
68 int find_num_levels(int width, int height)
71 for (int w = width, h = height; w > 1 || h > 1; ) {
79 string read_file(const string &filename)
81 FILE *fp = fopen(filename.c_str(), "r");
83 perror(filename.c_str());
87 int ret = fseek(fp, 0, SEEK_END);
89 perror("fseek(SEEK_END)");
95 ret = fseek(fp, 0, SEEK_SET);
97 perror("fseek(SEEK_SET)");
103 ret = fread(&str[0], size, 1, fp);
109 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
110 size, filename.c_str());
119 GLuint compile_shader(const string &shader_src, GLenum type)
121 GLuint obj = glCreateShader(type);
122 const GLchar* source[] = { shader_src.data() };
123 const GLint length[] = { (GLint)shader_src.size() };
124 glShaderSource(obj, 1, source, length);
125 glCompileShader(obj);
127 GLchar info_log[4096];
128 GLsizei log_length = sizeof(info_log) - 1;
129 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
130 info_log[log_length] = 0;
131 if (strlen(info_log) > 0) {
132 fprintf(stderr, "Shader compile log: %s\n", info_log);
136 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
137 if (status == GL_FALSE) {
138 // Add some line numbers to easier identify compile errors.
139 string src_with_lines = "/* 1 */ ";
141 for (char ch : shader_src) {
142 src_with_lines.push_back(ch);
145 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
146 src_with_lines += buf;
150 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
162 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
164 SDL_Surface *surf = IMG_Load(filename);
165 if (surf == nullptr) {
166 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
170 // For whatever reason, SDL doesn't support converting to YUV surfaces
171 // nor grayscale, so we'll do it ourselves.
172 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
173 if (rgb_surf == nullptr) {
174 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
178 SDL_FreeSurface(surf);
180 unsigned width = rgb_surf->w, height = rgb_surf->h;
181 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
182 unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
184 // Extract the Y component, and convert to bottom-left origin.
185 for (unsigned y = 0; y < height; ++y) {
186 unsigned y2 = height - 1 - y;
187 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
189 SDL_FreeSurface(rgb_surf);
191 int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
194 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
195 glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
196 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
198 if (mipmaps == WITH_MIPMAPS) {
199 glGenerateTextureMipmap(tex);
203 *height_ret = height;
208 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
210 GLuint program = glCreateProgram();
211 glAttachShader(program, vs_obj);
212 glAttachShader(program, fs_obj);
213 glLinkProgram(program);
215 glGetProgramiv(program, GL_LINK_STATUS, &success);
216 if (success == GL_FALSE) {
217 GLchar error_log[1024] = {0};
218 glGetProgramInfoLog(program, 1024, nullptr, error_log);
219 fprintf(stderr, "Error linking program: %s\n", error_log);
225 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
228 glCreateBuffers(1, &vbo);
229 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
230 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
234 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
236 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
241 GLuint vbo = generate_vbo(size, data_size, data);
243 glBindBuffer(GL_ARRAY_BUFFER, vbo);
244 glEnableVertexArrayAttrib(vao, attrib);
245 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
246 glBindBuffer(GL_ARRAY_BUFFER, 0);
251 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
253 if (location == -1) {
257 glBindTextureUnit(texture_unit, tex);
258 glBindSampler(texture_unit, sampler);
259 glProgramUniform1i(program, location, texture_unit);
262 // A class that caches FBOs that render to a given set of textures.
263 // It never frees anything, so it is only suitable for rendering to
264 // the same (small) set of textures over and over again.
265 template<size_t num_elements>
266 class PersistentFBOSet {
268 void render_to(const array<GLuint, num_elements> &textures);
270 // Convenience wrappers.
271 void render_to(GLuint texture0) {
272 render_to({{texture0}});
275 void render_to(GLuint texture0, GLuint texture1) {
276 render_to({{texture0, texture1}});
279 void render_to(GLuint texture0, GLuint texture1, GLuint texture2) {
280 render_to({{texture0, texture1, texture2}});
283 void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
284 render_to({{texture0, texture1, texture2, texture3}});
288 // TODO: Delete these on destruction.
289 map<array<GLuint, num_elements>, GLuint> fbos;
292 template<size_t num_elements>
293 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
295 auto it = fbos.find(textures);
296 if (it != fbos.end()) {
297 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
302 glCreateFramebuffers(1, &fbo);
303 GLenum bufs[num_elements];
304 for (size_t i = 0; i < num_elements; ++i) {
305 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
306 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
308 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
310 fbos[textures] = fbo;
311 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
314 // Same, but with a depth texture.
315 template<size_t num_elements>
316 class PersistentFBOSetWithDepth {
318 void render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures);
320 // Convenience wrappers.
321 void render_to(GLuint depth_tex, GLuint texture0) {
322 render_to(depth_tex, {{texture0}});
325 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1) {
326 render_to(depth_tex, {{texture0, texture1}});
329 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2) {
330 render_to(depth_tex, {{texture0, texture1, texture2}});
333 void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
334 render_to(depth_tex, {{texture0, texture1, texture2, texture3}});
338 // TODO: Delete these on destruction.
339 map<pair<GLuint, array<GLuint, num_elements>>, GLuint> fbos;
342 template<size_t num_elements>
343 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures)
345 auto key = make_pair(depth_tex, textures);
347 auto it = fbos.find(key);
348 if (it != fbos.end()) {
349 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
354 glCreateFramebuffers(1, &fbo);
355 GLenum bufs[num_elements];
356 glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
357 for (size_t i = 0; i < num_elements; ++i) {
358 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
359 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
361 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
364 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
367 // Convert RGB to grayscale, using Rec. 709 coefficients.
368 class GrayscaleConversion {
370 GrayscaleConversion();
371 void exec(GLint tex, GLint gray_tex, int width, int height);
374 PersistentFBOSet<1> fbos;
383 GrayscaleConversion::GrayscaleConversion()
385 gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
386 gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
387 gray_program = link_program(gray_vs_obj, gray_fs_obj);
389 // Set up the VAO containing all the required position/texcoord data.
390 glCreateVertexArrays(1, &gray_vao);
391 glBindVertexArray(gray_vao);
393 GLint position_attrib = glGetAttribLocation(gray_program, "position");
394 glEnableVertexArrayAttrib(gray_vao, position_attrib);
395 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
397 uniform_tex = glGetUniformLocation(gray_program, "tex");
400 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
402 glUseProgram(gray_program);
403 bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
405 glViewport(0, 0, width, height);
406 fbos.render_to(gray_tex);
407 glBindVertexArray(gray_vao);
408 glUseProgram(gray_program);
410 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
413 // Compute gradients in every point, used for the motion search.
414 // The DIS paper doesn't actually mention how these are computed,
415 // but seemingly, a 3x3 Sobel operator is used here (at least in
416 // later versions of the code), while a [1 -8 0 8 -1] kernel is
417 // used for all the derivatives in the variational refinement part
418 // (which borrows code from DeepFlow). This is inconsistent,
419 // but I guess we're better off with staying with the original
420 // decisions until we actually know having different ones would be better.
424 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
427 PersistentFBOSet<1> fbos;
430 GLuint sobel_program;
438 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
439 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
440 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
442 // Set up the VAO containing all the required position/texcoord data.
443 glCreateVertexArrays(1, &sobel_vao);
444 glBindVertexArray(sobel_vao);
446 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
447 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
448 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
450 uniform_tex = glGetUniformLocation(sobel_program, "tex");
453 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
455 glUseProgram(sobel_program);
456 bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
458 glViewport(0, 0, level_width, level_height);
459 fbos.render_to(grad0_tex);
460 glBindVertexArray(sobel_vao);
461 glUseProgram(sobel_program);
463 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
466 // Motion search to find the initial flow. See motion_search.frag for documentation.
470 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);
473 PersistentFBOSet<1> fbos;
475 GLuint motion_vs_obj;
476 GLuint motion_fs_obj;
477 GLuint motion_search_program;
478 GLuint motion_search_vao;
480 GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
481 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
484 MotionSearch::MotionSearch()
486 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
487 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
488 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
490 // Set up the VAO containing all the required position/texcoord data.
491 glCreateVertexArrays(1, &motion_search_vao);
492 glBindVertexArray(motion_search_vao);
493 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
495 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
496 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
497 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
499 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
500 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
501 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
502 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
503 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
504 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
507 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)
509 glUseProgram(motion_search_program);
511 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
512 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
513 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
514 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
516 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
517 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
519 glViewport(0, 0, width_patches, height_patches);
520 fbos.render_to(flow_out_tex);
521 glBindVertexArray(motion_search_vao);
522 glUseProgram(motion_search_program);
523 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
526 // Do “densification”, ie., upsampling of the flow patches to the flow field
527 // (the same size as the image at this level). We draw one quad per patch
528 // over its entire covered area (using instancing in the vertex shader),
529 // and then weight the contributions in the pixel shader by post-warp difference.
530 // This is equation (3) in the paper.
532 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
533 // weight in the B channel. Dividing R and G by B gives the normalized values.
537 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);
540 PersistentFBOSet<1> fbos;
542 GLuint densify_vs_obj;
543 GLuint densify_fs_obj;
544 GLuint densify_program;
547 GLuint uniform_patch_size;
548 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
553 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
554 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
555 densify_program = link_program(densify_vs_obj, densify_fs_obj);
557 // Set up the VAO containing all the required position/texcoord data.
558 glCreateVertexArrays(1, &densify_vao);
559 glBindVertexArray(densify_vao);
560 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
562 GLint position_attrib = glGetAttribLocation(densify_program, "position");
563 glEnableVertexArrayAttrib(densify_vao, position_attrib);
564 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
566 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
567 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
568 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
569 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
572 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)
574 glUseProgram(densify_program);
576 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
577 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
578 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
580 glProgramUniform2f(densify_program, uniform_patch_size,
581 float(patch_size_pixels) / level_width,
582 float(patch_size_pixels) / level_height);
584 glViewport(0, 0, level_width, level_height);
586 glBlendFunc(GL_ONE, GL_ONE);
587 glBindVertexArray(densify_vao);
588 fbos.render_to(dense_flow_tex);
589 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
592 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
593 // I_0 and I_w. The prewarping is what enables us to solve the variational
594 // flow for du,dv instead of u,v.
596 // Also calculates the normalized flow, ie. divides by z (this is needed because
597 // Densify works by additive blending) and multiplies by the image size.
599 // See variational_refinement.txt for more information.
603 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);
606 PersistentFBOSet<3> fbos;
608 GLuint prewarp_vs_obj;
609 GLuint prewarp_fs_obj;
610 GLuint prewarp_program;
613 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
618 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
619 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
620 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
622 // Set up the VAO containing all the required position/texcoord data.
623 glCreateVertexArrays(1, &prewarp_vao);
624 glBindVertexArray(prewarp_vao);
625 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
627 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
628 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
629 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
631 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
632 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
633 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
636 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)
638 glUseProgram(prewarp_program);
640 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
641 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
642 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
644 glViewport(0, 0, level_width, level_height);
646 glBindVertexArray(prewarp_vao);
647 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
648 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
651 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
652 // central difference filter, since apparently, that's tradition (I haven't
653 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
654 // The coefficients come from
656 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
658 // Also computes β_0, since it depends only on I_x and I_y.
662 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
665 PersistentFBOSet<2> fbos;
667 GLuint derivatives_vs_obj;
668 GLuint derivatives_fs_obj;
669 GLuint derivatives_program;
670 GLuint derivatives_vao;
675 Derivatives::Derivatives()
677 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
678 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
679 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
681 // Set up the VAO containing all the required position/texcoord data.
682 glCreateVertexArrays(1, &derivatives_vao);
683 glBindVertexArray(derivatives_vao);
684 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
686 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
687 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
688 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
690 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
693 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
695 glUseProgram(derivatives_program);
697 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
699 glViewport(0, 0, level_width, level_height);
701 glBindVertexArray(derivatives_vao);
702 fbos.render_to(I_x_y_tex, beta_0_tex);
703 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
706 // Calculate the smoothness constraints between neighboring pixels;
707 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
708 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
709 // border color (0,0) later, so that there's zero diffusion out of
712 // See variational_refinement.txt for more information.
713 class ComputeSmoothness {
716 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
719 PersistentFBOSet<2> fbos;
721 GLuint smoothness_vs_obj;
722 GLuint smoothness_fs_obj;
723 GLuint smoothness_program;
724 GLuint smoothness_vao;
726 GLuint uniform_flow_tex, uniform_diff_flow_tex;
727 GLuint uniform_alpha;
730 ComputeSmoothness::ComputeSmoothness()
732 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
733 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
734 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
736 // Set up the VAO containing all the required position/texcoord data.
737 glCreateVertexArrays(1, &smoothness_vao);
738 glBindVertexArray(smoothness_vao);
739 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
741 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
742 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
743 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
745 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
746 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
747 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
750 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
752 glUseProgram(smoothness_program);
754 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
755 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
756 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
758 glViewport(0, 0, level_width, level_height);
761 glBindVertexArray(smoothness_vao);
762 fbos.render_to(smoothness_x_tex, smoothness_y_tex);
763 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
765 // Make sure the smoothness on the right and upper borders is zero.
766 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
767 // (we're sampling smoothness with all-zero border color), but we'd
768 // have to adjust the sampling coordinates, which is annoying.
769 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
770 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
773 // Set up the equations set (two equations in two unknowns, per pixel).
774 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
775 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
776 // floats. (Actually, we store the inverse of the diagonal elements, because
777 // we only ever need to divide by them.) This fits into four u32 values;
778 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
779 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
780 // terms that depend on other pixels, are calculated in one pass.
782 // See variational_refinement.txt for more information.
783 class SetupEquations {
786 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);
789 PersistentFBOSet<1> fbos;
791 GLuint equations_vs_obj;
792 GLuint equations_fs_obj;
793 GLuint equations_program;
794 GLuint equations_vao;
796 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
797 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
798 GLuint uniform_beta_0_tex;
799 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
800 GLuint uniform_gamma, uniform_delta;
803 SetupEquations::SetupEquations()
805 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
806 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
807 equations_program = link_program(equations_vs_obj, equations_fs_obj);
809 // Set up the VAO containing all the required position/texcoord data.
810 glCreateVertexArrays(1, &equations_vao);
811 glBindVertexArray(equations_vao);
812 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
814 GLint position_attrib = glGetAttribLocation(equations_program, "position");
815 glEnableVertexArrayAttrib(equations_vao, position_attrib);
816 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
818 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
819 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
820 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
821 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
822 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
823 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
824 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
825 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
826 uniform_delta = glGetUniformLocation(equations_program, "delta");
829 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)
831 glUseProgram(equations_program);
833 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
834 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
835 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
836 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
837 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
838 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
839 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
840 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
841 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
843 glViewport(0, 0, level_width, level_height);
845 glBindVertexArray(equations_vao);
846 fbos.render_to(equation_tex);
847 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
850 // Actually solve the equation sets made by SetupEquations, by means of
851 // successive over-relaxation (SOR).
853 // See variational_refinement.txt for more information.
857 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, ScopedTimer *sor_timer);
860 PersistentFBOSet<1> fbos;
867 GLuint uniform_diff_flow_tex;
868 GLuint uniform_equation_tex;
869 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
870 GLuint uniform_phase;
875 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
876 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
877 sor_program = link_program(sor_vs_obj, sor_fs_obj);
879 // Set up the VAO containing all the required position/texcoord data.
880 glCreateVertexArrays(1, &sor_vao);
881 glBindVertexArray(sor_vao);
882 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
884 GLint position_attrib = glGetAttribLocation(sor_program, "position");
885 glEnableVertexArrayAttrib(sor_vao, position_attrib);
886 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
888 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
889 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
890 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
891 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
892 uniform_phase = glGetUniformLocation(sor_program, "phase");
895 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, ScopedTimer *sor_timer)
897 glUseProgram(sor_program);
899 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
900 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
901 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
902 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
904 // NOTE: We bind to the texture we are rendering from, but we never write any value
905 // that we read in the same shader pass (we call discard for red values when we compute
906 // black, and vice versa), and we have barriers between the passes, so we're fine
908 glViewport(0, 0, level_width, level_height);
910 glBindVertexArray(sor_vao);
911 fbos.render_to(diff_flow_tex);
913 for (int i = 0; i < num_iterations; ++i) {
915 ScopedTimer timer("Red pass", sor_timer);
916 glProgramUniform1i(sor_program, uniform_phase, 0);
917 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
921 ScopedTimer timer("Black pass", sor_timer);
922 glProgramUniform1i(sor_program, uniform_phase, 1);
923 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
924 if (i != num_iterations - 1) {
931 // Simply add the differential flow found by the variational refinement to the base flow.
932 // The output is in base_flow_tex; we don't need to make a new texture.
936 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
939 PersistentFBOSet<1> fbos;
941 GLuint add_flow_vs_obj;
942 GLuint add_flow_fs_obj;
943 GLuint add_flow_program;
946 GLuint uniform_diff_flow_tex;
949 AddBaseFlow::AddBaseFlow()
951 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
952 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
953 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
955 // Set up the VAO containing all the required position/texcoord data.
956 glCreateVertexArrays(1, &add_flow_vao);
957 glBindVertexArray(add_flow_vao);
958 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
960 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
961 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
962 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
964 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
967 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
969 glUseProgram(add_flow_program);
971 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
973 glViewport(0, 0, level_width, level_height);
975 glBlendFunc(GL_ONE, GL_ONE);
976 glBindVertexArray(add_flow_vao);
977 fbos.render_to(base_flow_tex);
979 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
982 // Take a copy of the flow, bilinearly interpolated and scaled up.
986 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
989 PersistentFBOSet<1> fbos;
991 GLuint resize_flow_vs_obj;
992 GLuint resize_flow_fs_obj;
993 GLuint resize_flow_program;
994 GLuint resize_flow_vao;
996 GLuint uniform_flow_tex;
997 GLuint uniform_scale_factor;
1000 ResizeFlow::ResizeFlow()
1002 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1003 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
1004 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
1006 // Set up the VAO containing all the required position/texcoord data.
1007 glCreateVertexArrays(1, &resize_flow_vao);
1008 glBindVertexArray(resize_flow_vao);
1009 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1011 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
1012 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
1013 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1015 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
1016 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
1019 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
1021 glUseProgram(resize_flow_program);
1023 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
1025 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
1027 glViewport(0, 0, output_width, output_height);
1028 glDisable(GL_BLEND);
1029 glBindVertexArray(resize_flow_vao);
1030 fbos.render_to(out_tex);
1032 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1037 GLuint get_texture(GLenum format, GLuint width, GLuint height);
1038 void release_texture(GLuint tex_num);
1044 GLuint width, height;
1045 bool in_use = false;
1047 vector<Texture> textures;
1050 class DISComputeFlow {
1052 DISComputeFlow(int width, int height);
1054 enum ResizeStrategy {
1056 RESIZE_FLOW_TO_FULL_SIZE
1059 // Returns a texture that must be released with release_texture()
1061 GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
1063 void release_texture(GLuint tex) {
1064 pool.release_texture(tex);
1069 GLuint initial_flow_tex;
1072 // The various passes.
1074 MotionSearch motion_search;
1077 Derivatives derivatives;
1078 ComputeSmoothness compute_smoothness;
1079 SetupEquations setup_equations;
1081 AddBaseFlow add_base_flow;
1082 ResizeFlow resize_flow;
1085 DISComputeFlow::DISComputeFlow(int width, int height)
1086 : width(width), height(height)
1088 // Make some samplers.
1089 glCreateSamplers(1, &nearest_sampler);
1090 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1091 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1092 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1093 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1095 glCreateSamplers(1, &linear_sampler);
1096 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1097 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1098 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1099 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1101 // The smoothness is sampled so that once we get to a smoothness involving
1102 // a value outside the border, the diffusivity between the two becomes zero.
1103 // Similarly, gradients are zero outside the border, since the edge is taken
1105 glCreateSamplers(1, &zero_border_sampler);
1106 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1107 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1108 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1109 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1110 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1111 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1113 // Initial flow is zero, 1x1.
1114 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1115 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1116 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1119 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1121 int prev_level_width = 1, prev_level_height = 1;
1122 GLuint prev_level_flow_tex = initial_flow_tex;
1126 ScopedTimer total_timer("Total", &timers);
1127 for (int level = coarsest_level; level >= int(finest_level); --level) {
1128 char timer_name[256];
1129 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
1130 ScopedTimer level_timer(timer_name, &total_timer);
1132 int level_width = width >> level;
1133 int level_height = height >> level;
1134 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1136 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1137 // and patch_spacing=3 (the default), we put out patch centers in
1138 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1139 // lock all the centers to integer coordinates if needed.
1140 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1141 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1143 // Make sure we always read from the correct level; the chosen
1144 // mipmapping could otherwise be rather unpredictable, especially
1145 // during motion search.
1146 GLuint tex0_view, tex1_view;
1147 glGenTextures(1, &tex0_view);
1148 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1149 glGenTextures(1, &tex1_view);
1150 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1152 // Create a new texture; we could be fancy and render use a multi-level
1153 // texture, but meh.
1154 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1156 // Find the derivative.
1158 ScopedTimer timer("Sobel", &level_timer);
1159 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1162 // Motion search to find the initial flow. We use the flow from the previous
1163 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1165 // Create an output flow texture.
1166 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1170 ScopedTimer timer("Motion search", &level_timer);
1171 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);
1173 pool.release_texture(grad0_tex);
1177 // Set up an output texture (initially zero).
1178 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1179 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1183 ScopedTimer timer("Densification", &level_timer);
1184 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1186 pool.release_texture(flow_out_tex);
1188 // Everything below here in the loop belongs to variational refinement.
1189 ScopedTimer varref_timer("Variational refinement", &level_timer);
1191 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1192 // have to normalize it over and over again, and also save some bandwidth).
1194 // During the entire rest of the variational refinement, flow will be measured
1195 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1196 // This is because variational refinement depends so heavily on derivatives,
1197 // which are measured in intensity levels per pixel.
1198 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1199 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1200 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1202 ScopedTimer timer("Prewarping", &varref_timer);
1203 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1205 pool.release_texture(dense_flow_tex);
1206 glDeleteTextures(1, &tex0_view);
1207 glDeleteTextures(1, &tex1_view);
1209 // Calculate I_x and I_y. We're only calculating first derivatives;
1210 // the others will be taken on-the-fly in order to sample from fewer
1211 // textures overall, since sampling from the L1 cache is cheap.
1212 // (TODO: Verify that this is indeed faster than making separate
1213 // double-derivative textures.)
1214 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1215 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1217 ScopedTimer timer("First derivatives", &varref_timer);
1218 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1220 pool.release_texture(I_tex);
1222 // We need somewhere to store du and dv (the flow increment, relative
1223 // to the non-refined base flow u0 and v0). It starts at zero.
1224 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1225 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1227 // And for smoothness.
1228 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1229 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1231 // And finally for the equation set. See SetupEquations for
1232 // the storage format.
1233 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1235 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1236 // Calculate the smoothness terms between the neighboring pixels,
1237 // both in x and y direction.
1239 ScopedTimer timer("Compute smoothness", &varref_timer);
1240 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1243 // Set up the 2x2 equation system for each pixel.
1245 ScopedTimer timer("Set up equations", &varref_timer);
1246 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);
1249 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1250 // Note that these are to/from the same texture.
1252 ScopedTimer timer("SOR", &varref_timer);
1253 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5, &timer);
1257 pool.release_texture(I_t_tex);
1258 pool.release_texture(I_x_y_tex);
1259 pool.release_texture(beta_0_tex);
1260 pool.release_texture(smoothness_x_tex);
1261 pool.release_texture(smoothness_y_tex);
1262 pool.release_texture(equation_tex);
1264 // Add the differential flow found by the variational refinement to the base flow,
1265 // giving the final flow estimate for this level.
1266 // The output is in diff_flow_tex; we don't need to make a new texture.
1268 // Disabling this doesn't save any time (although we could easily make it so that
1269 // it is more efficient), but it helps debug the motion search.
1270 if (enable_variational_refinement) {
1271 ScopedTimer timer("Add differential flow", &varref_timer);
1272 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1274 pool.release_texture(du_dv_tex);
1276 if (prev_level_flow_tex != initial_flow_tex) {
1277 pool.release_texture(prev_level_flow_tex);
1279 prev_level_flow_tex = base_flow_tex;
1280 prev_level_width = level_width;
1281 prev_level_height = level_height;
1287 // Scale up the flow to the final size (if needed).
1288 if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1289 return prev_level_flow_tex;
1291 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1292 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1293 pool.release_texture(prev_level_flow_tex);
1298 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1299 // radius fills most of the holes.
1304 // alpha is the time of the interpolated frame (0..1).
1305 void exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha);
1308 PersistentFBOSetWithDepth<1> fbos;
1310 GLuint splat_vs_obj;
1311 GLuint splat_fs_obj;
1312 GLuint splat_program;
1315 GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1316 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1317 GLuint uniform_inv_flow_size;
1322 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1323 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1324 splat_program = link_program(splat_vs_obj, splat_fs_obj);
1326 // Set up the VAO containing all the required position/texcoord data.
1327 glCreateVertexArrays(1, &splat_vao);
1328 glBindVertexArray(splat_vao);
1329 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1331 GLint position_attrib = glGetAttribLocation(splat_program, "position");
1332 glEnableVertexArrayAttrib(splat_vao, position_attrib);
1333 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1335 uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1336 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1337 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1338 uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1339 uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1340 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1341 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1344 void Splat::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha)
1346 glUseProgram(splat_program);
1348 bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1349 bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1351 // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1352 // Move to 2.0 later, or even 4.0.
1353 // (Since we have hole filling, it's not critical, but larger values seem to do
1354 // better than hole filling for large motion, blurs etc.)
1355 float splat_size = 1.0f; // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1356 glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1357 glProgramUniform1f(splat_program, uniform_alpha, alpha);
1358 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1360 glViewport(0, 0, width, height);
1361 glDisable(GL_BLEND);
1362 glEnable(GL_DEPTH_TEST);
1363 glDepthFunc(GL_LESS); // We store the difference between I_0 and I_1, where less difference is good. (Default 1.0 is effectively +inf, which always loses.)
1364 glBindVertexArray(splat_vao);
1366 fbos.render_to(depth_tex, flow_tex);
1368 // Do forward splatting.
1369 bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1370 glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1371 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1373 // Do backward splatting.
1374 bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1375 glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1376 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1378 glDisable(GL_DEPTH_TEST);
1381 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1382 // that's fairly simple (given that most holes are really small) and also hopefully
1383 // cheap should the holes not be so small. Conceptually, we look for the first
1384 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1385 // the first non-hole to the right of us, then up and down, and then average them
1386 // all together. It's going to create “stars” if the holes are big, but OK, that's
1389 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1390 // on even for shaders that do discard (this typically kills early Z, but hopefully
1391 // not hierarchical Z); we set up Z so that only holes are written to, which means
1392 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1393 // fullscreen quads should just be discarded outright, really.
1398 // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1399 // from the down, left, right and up, respectively. Use HoleBlend to merge
1401 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1404 PersistentFBOSetWithDepth<1> fbos;
1408 GLuint fill_program;
1412 GLuint uniform_z, uniform_sample_offset;
1415 HoleFill::HoleFill()
1417 fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1418 fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1419 fill_program = link_program(fill_vs_obj, fill_fs_obj);
1421 // Set up the VAO containing all the required position/texcoord data.
1422 glCreateVertexArrays(1, &fill_vao);
1423 glBindVertexArray(fill_vao);
1424 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1426 GLint position_attrib = glGetAttribLocation(fill_program, "position");
1427 glEnableVertexArrayAttrib(fill_vao, position_attrib);
1428 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1430 uniform_tex = glGetUniformLocation(fill_program, "tex");
1431 uniform_z = glGetUniformLocation(fill_program, "z");
1432 uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1435 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1437 glUseProgram(fill_program);
1439 bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1441 glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1443 glViewport(0, 0, width, height);
1444 glDisable(GL_BLEND);
1445 glEnable(GL_DEPTH_TEST);
1446 glDepthFunc(GL_LESS); // Only update the values > 0.999f (ie., only invalid pixels).
1447 glBindVertexArray(fill_vao);
1449 fbos.render_to(depth_tex, flow_tex); // NOTE: Reading and writing to the same texture.
1451 // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1452 for (int offs = 1; offs < width; offs *= 2) {
1453 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1454 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1457 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1459 // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1460 // were overwritten in the last algorithm.
1461 glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1462 for (int offs = 1; offs < width; offs *= 2) {
1463 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1464 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1467 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1470 glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1471 for (int offs = 1; offs < height; offs *= 2) {
1472 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1473 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1476 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1479 glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1480 for (int offs = 1; offs < height; offs *= 2) {
1481 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1482 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1486 glDisable(GL_DEPTH_TEST);
1489 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1490 // holes become the average of their four neighbors.
1495 void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1498 PersistentFBOSetWithDepth<1> fbos;
1500 GLuint blend_vs_obj;
1501 GLuint blend_fs_obj;
1502 GLuint blend_program;
1505 GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1506 GLuint uniform_z, uniform_sample_offset;
1509 HoleBlend::HoleBlend()
1511 blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER); // Reuse the vertex shader from the fill.
1512 blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1513 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1515 // Set up the VAO containing all the required position/texcoord data.
1516 glCreateVertexArrays(1, &blend_vao);
1517 glBindVertexArray(blend_vao);
1518 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1520 GLint position_attrib = glGetAttribLocation(blend_program, "position");
1521 glEnableVertexArrayAttrib(blend_vao, position_attrib);
1522 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1524 uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1525 uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1526 uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1527 uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1528 uniform_z = glGetUniformLocation(blend_program, "z");
1529 uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1532 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1534 glUseProgram(blend_program);
1536 bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1537 bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1538 bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1539 bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1541 glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1542 glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1544 glViewport(0, 0, width, height);
1545 glDisable(GL_BLEND);
1546 glEnable(GL_DEPTH_TEST);
1547 glDepthFunc(GL_LEQUAL); // Skip over all of the pixels that were never holes to begin with.
1548 glBindVertexArray(blend_vao);
1550 fbos.render_to(depth_tex, flow_tex); // NOTE: Reading and writing to the same texture.
1552 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1554 glDisable(GL_DEPTH_TEST);
1560 void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1563 PersistentFBOSet<1> fbos;
1564 GLuint blend_vs_obj;
1565 GLuint blend_fs_obj;
1566 GLuint blend_program;
1569 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1570 GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1575 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1576 blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1577 blend_program = link_program(blend_vs_obj, blend_fs_obj);
1579 // Set up the VAO containing all the required position/texcoord data.
1580 glCreateVertexArrays(1, &blend_vao);
1581 glBindVertexArray(blend_vao);
1583 GLint position_attrib = glGetAttribLocation(blend_program, "position");
1584 glEnableVertexArrayAttrib(blend_vao, position_attrib);
1585 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1587 uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1588 uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1589 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1590 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1591 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1594 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1596 glUseProgram(blend_program);
1597 bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1598 bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1599 bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler); // May be upsampled.
1600 glProgramUniform1f(blend_program, uniform_alpha, alpha);
1601 //glProgramUniform1f(blend_program, uniform_flow_consistency_tolerance, 1.0f /
1603 glViewport(0, 0, level_width, level_height);
1604 fbos.render_to(output_tex);
1605 glBindVertexArray(blend_vao);
1606 glUseProgram(blend_program);
1607 glDisable(GL_BLEND); // A bit ironic, perhaps.
1608 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1613 Interpolate(int width, int height, int flow_level);
1615 // Returns a texture that must be released with release_texture()
1616 // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1617 // (unless flow_level == 0).
1618 GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1620 void release_texture(GLuint tex) {
1621 pool.release_texture(tex);
1625 int width, height, flow_level;
1629 HoleBlend hole_blend;
1633 Interpolate::Interpolate(int width, int height, int flow_level)
1634 : width(width), height(height), flow_level(flow_level) {}
1636 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1640 ScopedTimer total_timer("Total", &timers);
1642 // Pick out the right level to test splatting results on.
1643 GLuint tex0_view, tex1_view;
1644 glGenTextures(1, &tex0_view);
1645 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1646 glGenTextures(1, &tex1_view);
1647 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1649 int flow_width = width >> flow_level;
1650 int flow_height = height >> flow_level;
1652 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1653 GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height); // Used for ranking flows.
1655 ScopedTimer timer("Clear", &total_timer);
1656 float invalid_flow[] = { 1000.0f, 1000.0f };
1657 glClearTexImage(flow_tex, 0, GL_RG, GL_FLOAT, invalid_flow);
1658 float infinity = 1.0f;
1659 glClearTexImage(depth_tex, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &infinity);
1663 ScopedTimer timer("Splat", &total_timer);
1664 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1666 glDeleteTextures(1, &tex0_view);
1667 glDeleteTextures(1, &tex1_view);
1670 temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1671 temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1672 temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1675 ScopedTimer timer("Fill holes", &total_timer);
1676 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1677 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1680 pool.release_texture(temp_tex[0]);
1681 pool.release_texture(temp_tex[1]);
1682 pool.release_texture(temp_tex[2]);
1683 pool.release_texture(depth_tex);
1685 GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1687 ScopedTimer timer("Blend", &total_timer);
1688 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1696 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1698 for (Texture &tex : textures) {
1699 if (!tex.in_use && tex.format == format &&
1700 tex.width == width && tex.height == height) {
1707 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1708 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1709 tex.format = format;
1711 tex.height = height;
1713 textures.push_back(tex);
1717 void TexturePool::release_texture(GLuint tex_num)
1719 for (Texture &tex : textures) {
1720 if (tex.tex_num == tex_num) {
1729 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1730 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1732 for (unsigned i = 0; i < width * height; ++i) {
1733 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1737 // Not relevant for RGB.
1738 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1742 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1744 FILE *flowfp = fopen(filename, "wb");
1745 fprintf(flowfp, "FEIH");
1746 fwrite(&width, 4, 1, flowfp);
1747 fwrite(&height, 4, 1, flowfp);
1748 for (unsigned y = 0; y < height; ++y) {
1749 int yy = height - y - 1;
1750 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1755 // Not relevant for RGB.
1756 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1761 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1763 FILE *fp = fopen(filename, "wb");
1764 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1765 for (unsigned y = 0; y < unsigned(height); ++y) {
1766 int yy = height - y - 1;
1767 for (unsigned x = 0; x < unsigned(width); ++x) {
1768 float du = dense_flow[(yy * width + x) * 2 + 0];
1769 float dv = dense_flow[(yy * width + x) * 2 + 1];
1772 flow2rgb(du, dv, &r, &g, &b);
1781 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1783 unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1785 FILE *fp = fopen(filename, "wb");
1786 fprintf(fp, "P6\n%d %d\n255\n", width, height);
1787 for (unsigned y = 0; y < height; ++y) {
1788 unsigned y2 = height - 1 - y;
1789 for (size_t x = 0; x < width; ++x) {
1790 memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1792 fwrite(rgb_line.get(), width * 3, 1, fp);
1799 static constexpr GLenum gl_format = GL_RG;
1800 static constexpr GLenum gl_type = GL_FLOAT;
1801 static constexpr int num_channels = 2;
1805 using type = uint8_t;
1806 static constexpr GLenum gl_format = GL_RGBA;
1807 static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1808 static constexpr int num_channels = 4;
1811 template <class Type>
1812 void finish_one_read(GLuint width, GLuint height)
1814 using T = typename Type::type;
1815 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1817 assert(!reads_in_progress.empty());
1818 ReadInProgress read = reads_in_progress.front();
1819 reads_in_progress.pop_front();
1821 unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1822 void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT); // Blocks if the read isn't done yet.
1823 memcpy(flow.get(), buf, width * height * bytes_per_pixel); // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1824 glUnmapNamedBuffer(read.pbo);
1825 spare_pbos.push(read.pbo);
1827 flip_coordinate_system(flow.get(), width, height);
1828 if (!read.flow_filename.empty()) {
1829 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1830 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1832 if (!read.ppm_filename.empty()) {
1833 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1837 template <class Type>
1838 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1840 using T = typename Type::type;
1841 constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1843 if (spare_pbos.empty()) {
1844 finish_one_read<Type>(width, height);
1846 assert(!spare_pbos.empty());
1847 reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1848 glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1850 glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1851 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1854 void compute_flow_only(int argc, char **argv, int optind)
1856 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1857 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1858 const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1861 unsigned width1, height1, width2, height2;
1862 GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1863 GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1865 if (width1 != width2 || height1 != height2) {
1866 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1867 width1, height1, width2, height2);
1871 // Set up some PBOs to do asynchronous readback.
1873 glCreateBuffers(5, pbos);
1874 for (int i = 0; i < 5; ++i) {
1875 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1876 spare_pbos.push(pbos[i]);
1879 int levels = find_num_levels(width1, height1);
1880 GLuint tex0_gray, tex1_gray;
1881 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1882 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1883 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1884 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1886 GrayscaleConversion gray;
1887 gray.exec(tex0, tex0_gray, width1, height1);
1888 glDeleteTextures(1, &tex0);
1889 glGenerateTextureMipmap(tex0_gray);
1891 gray.exec(tex1, tex1_gray, width1, height1);
1892 glDeleteTextures(1, &tex1);
1893 glGenerateTextureMipmap(tex1_gray);
1895 DISComputeFlow compute_flow(width1, height1);
1896 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1898 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1899 compute_flow.release_texture(final_tex);
1901 // See if there are more flows on the command line (ie., more than three arguments),
1902 // and if so, process them.
1903 int num_flows = (argc - optind) / 3;
1904 for (int i = 1; i < num_flows; ++i) {
1905 const char *filename0 = argv[optind + i * 3 + 0];
1906 const char *filename1 = argv[optind + i * 3 + 1];
1907 const char *flow_filename = argv[optind + i * 3 + 2];
1908 GLuint width, height;
1909 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1910 if (width != width1 || height != height1) {
1911 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1912 filename0, width, height, width1, height1);
1915 gray.exec(tex0, tex0_gray, width, height);
1916 glGenerateTextureMipmap(tex0_gray);
1917 glDeleteTextures(1, &tex0);
1919 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1920 if (width != width1 || height != height1) {
1921 fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1922 filename1, width, height, width1, height1);
1925 gray.exec(tex1, tex1_gray, width, height);
1926 glGenerateTextureMipmap(tex1_gray);
1927 glDeleteTextures(1, &tex1);
1929 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1931 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1932 compute_flow.release_texture(final_tex);
1934 glDeleteTextures(1, &tex0_gray);
1935 glDeleteTextures(1, &tex1_gray);
1937 while (!reads_in_progress.empty()) {
1938 finish_one_read<FlowType>(width1, height1);
1942 // Interpolate images based on
1944 // Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1945 // Using Optical Flow”
1947 // or at least a reasonable subset thereof. Unfinished.
1948 void interpolate_image(int argc, char **argv, int optind)
1950 const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1951 const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1952 //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1955 unsigned width1, height1, width2, height2;
1956 GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1957 GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1959 if (width1 != width2 || height1 != height2) {
1960 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1961 width1, height1, width2, height2);
1965 // Set up some PBOs to do asynchronous readback.
1967 glCreateBuffers(5, pbos);
1968 for (int i = 0; i < 5; ++i) {
1969 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1970 spare_pbos.push(pbos[i]);
1973 DISComputeFlow compute_flow(width1, height1);
1974 GrayscaleConversion gray;
1975 Interpolate interpolate(width1, height1, finest_level);
1977 int levels = find_num_levels(width1, height1);
1978 GLuint tex0_gray, tex1_gray;
1979 glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1980 glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1981 glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1982 glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1984 gray.exec(tex0, tex0_gray, width1, height1);
1985 glGenerateTextureMipmap(tex0_gray);
1987 gray.exec(tex1, tex1_gray, width1, height1);
1988 glGenerateTextureMipmap(tex1_gray);
1990 GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1991 GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1993 for (int frameno = 1; frameno < 60; ++frameno) {
1994 char ppm_filename[256];
1995 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
1997 float alpha = frameno / 60.0f;
1998 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
2000 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
2001 interpolate.release_texture(interpolated_tex);
2004 while (!reads_in_progress.empty()) {
2005 finish_one_read<RGBAType>(width1, height1);
2009 int main(int argc, char **argv)
2011 static const option long_options[] = {
2012 { "smoothness-relative-weight", required_argument, 0, 's' }, // alpha.
2013 { "intensity-relative-weight", required_argument, 0, 'i' }, // delta.
2014 { "gradient-relative-weight", required_argument, 0, 'g' }, // gamma.
2015 { "disable-timing", no_argument, 0, 1000 },
2016 { "detailed-timing", no_argument, 0, 1003 },
2017 { "ignore-variational-refinement", no_argument, 0, 1001 }, // Still calculates it, just doesn't apply it.
2018 { "interpolate", no_argument, 0, 1002 }
2022 int option_index = 0;
2023 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
2030 vr_alpha = atof(optarg);
2033 vr_delta = atof(optarg);
2036 vr_gamma = atof(optarg);
2039 enable_timing = false;
2042 enable_variational_refinement = false;
2045 enable_interpolation = true;
2048 detailed_timing = true;
2051 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
2056 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
2057 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
2060 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
2061 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
2062 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
2063 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2065 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2066 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
2067 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
2068 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
2069 window = SDL_CreateWindow("OpenGL window",
2070 SDL_WINDOWPOS_UNDEFINED,
2071 SDL_WINDOWPOS_UNDEFINED,
2073 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
2074 SDL_GLContext context = SDL_GL_CreateContext(window);
2075 assert(context != nullptr);
2077 glDisable(GL_DITHER);
2079 // FIXME: Should be part of DISComputeFlow (but needs to be initialized
2080 // before all the render passes).
2081 float vertices[] = {
2087 glCreateBuffers(1, &vertex_vbo);
2088 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
2089 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
2091 if (enable_interpolation) {
2092 interpolate_image(argc, argv, optind);
2094 compute_flow_only(argc, argv, optind);