5 #include "gpu_timers.h"
20 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
24 // Weighting constants for the different parts of the variational refinement.
25 // These don't correspond 1:1 to the values given in the DIS paper,
26 // since we have different normalizations and ranges in some cases.
27 // These are found through a simple grid search on some MPI-Sintel data,
28 // although the error (EPE) seems to be fairly insensitive to the precise values.
29 // Only the relative values matter, so we fix alpha (the smoothness constant)
30 // at unity and tweak the others.
32 // TODO: Maybe this should not be global.
33 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
35 // Some global OpenGL objects.
36 // TODO: These should really be part of DISComputeFlow.
37 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
40 int find_num_levels(int width, int height)
43 for (int w = width, h = height; w > 1 || h > 1; ) {
51 string read_file(const string &filename)
53 FILE *fp = fopen(filename.c_str(), "r");
55 perror(filename.c_str());
59 int ret = fseek(fp, 0, SEEK_END);
61 perror("fseek(SEEK_END)");
67 ret = fseek(fp, 0, SEEK_SET);
69 perror("fseek(SEEK_SET)");
75 ret = fread(&str[0], size, 1, fp);
81 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
82 size, filename.c_str());
90 GLuint compile_shader(const string &shader_src, GLenum type)
92 GLuint obj = glCreateShader(type);
93 const GLchar *source[] = { shader_src.data() };
94 const GLint length[] = { (GLint)shader_src.size() };
95 glShaderSource(obj, 1, source, length);
98 GLchar info_log[4096];
99 GLsizei log_length = sizeof(info_log) - 1;
100 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
101 info_log[log_length] = 0;
102 if (strlen(info_log) > 0) {
103 fprintf(stderr, "Shader compile log: %s\n", info_log);
107 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
108 if (status == GL_FALSE) {
109 // Add some line numbers to easier identify compile errors.
110 string src_with_lines = "/* 1 */ ";
112 for (char ch : shader_src) {
113 src_with_lines.push_back(ch);
116 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
117 src_with_lines += buf;
121 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
128 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
130 GLuint program = glCreateProgram();
131 glAttachShader(program, vs_obj);
132 glAttachShader(program, fs_obj);
133 glLinkProgram(program);
135 glGetProgramiv(program, GL_LINK_STATUS, &success);
136 if (success == GL_FALSE) {
137 GLchar error_log[1024] = {0};
138 glGetProgramInfoLog(program, 1024, nullptr, error_log);
139 fprintf(stderr, "Error linking program: %s\n", error_log);
145 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
147 if (location == -1) {
151 glBindTextureUnit(texture_unit, tex);
152 glBindSampler(texture_unit, sampler);
153 glProgramUniform1i(program, location, texture_unit);
156 template<size_t num_elements>
157 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
159 auto it = fbos.find(textures);
160 if (it != fbos.end()) {
161 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
166 glCreateFramebuffers(1, &fbo);
167 GLenum bufs[num_elements];
168 for (size_t i = 0; i < num_elements; ++i) {
169 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
170 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
172 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
174 fbos[textures] = fbo;
175 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
178 template<size_t num_elements>
179 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_rb, const array<GLuint, num_elements> &textures)
181 auto key = make_pair(depth_rb, textures);
183 auto it = fbos.find(key);
184 if (it != fbos.end()) {
185 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
190 glCreateFramebuffers(1, &fbo);
191 GLenum bufs[num_elements];
192 glNamedFramebufferRenderbuffer(fbo, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
193 for (size_t i = 0; i < num_elements; ++i) {
194 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
195 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
197 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
200 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
203 GrayscaleConversion::GrayscaleConversion()
205 gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
206 gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
207 gray_program = link_program(gray_vs_obj, gray_fs_obj);
209 // Set up the VAO containing all the required position/texcoord data.
210 glCreateVertexArrays(1, &gray_vao);
211 glBindVertexArray(gray_vao);
213 GLint position_attrib = glGetAttribLocation(gray_program, "position");
214 glEnableVertexArrayAttrib(gray_vao, position_attrib);
215 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
217 uniform_tex = glGetUniformLocation(gray_program, "tex");
220 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height, int num_layers)
222 glUseProgram(gray_program);
223 bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
225 glViewport(0, 0, width, height);
226 fbos.render_to(gray_tex);
227 glBindVertexArray(gray_vao);
229 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
234 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
235 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
236 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
238 uniform_tex = glGetUniformLocation(sobel_program, "tex");
241 void Sobel::exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers)
243 glUseProgram(sobel_program);
244 bind_sampler(sobel_program, uniform_tex, 0, tex_view, nearest_sampler);
246 glViewport(0, 0, level_width, level_height);
247 fbos.render_to(grad_tex);
249 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
252 MotionSearch::MotionSearch(const OperatingPoint &op)
255 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
256 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
257 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
259 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
260 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
261 uniform_out_flow_size = glGetUniformLocation(motion_search_program, "out_flow_size");
262 uniform_image_tex = glGetUniformLocation(motion_search_program, "image_tex");
263 uniform_grad_tex = glGetUniformLocation(motion_search_program, "grad_tex");
264 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
265 uniform_patch_size = glGetUniformLocation(motion_search_program, "patch_size");
266 uniform_num_iterations = glGetUniformLocation(motion_search_program, "num_iterations");
269 void MotionSearch::exec(GLuint tex_view, GLuint grad_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, int num_layers)
271 glUseProgram(motion_search_program);
273 bind_sampler(motion_search_program, uniform_image_tex, 0, tex_view, linear_sampler);
274 bind_sampler(motion_search_program, uniform_grad_tex, 1, grad_tex, nearest_sampler);
275 bind_sampler(motion_search_program, uniform_flow_tex, 2, flow_tex, linear_sampler);
277 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
278 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
279 glProgramUniform2f(motion_search_program, uniform_out_flow_size, width_patches, height_patches);
280 glProgramUniform1ui(motion_search_program, uniform_patch_size, op.patch_size_pixels);
281 glProgramUniform1ui(motion_search_program, uniform_num_iterations, op.search_iterations);
283 glViewport(0, 0, width_patches, height_patches);
284 fbos.render_to(flow_out_tex);
285 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
288 Densify::Densify(const OperatingPoint &op)
291 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
292 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
293 densify_program = link_program(densify_vs_obj, densify_fs_obj);
295 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
296 uniform_image_tex = glGetUniformLocation(densify_program, "image_tex");
297 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
300 void Densify::exec(GLuint tex_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches, int num_layers)
302 glUseProgram(densify_program);
304 bind_sampler(densify_program, uniform_image_tex, 0, tex_view, linear_sampler);
305 bind_sampler(densify_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
307 glProgramUniform2f(densify_program, uniform_patch_size,
308 float(op.patch_size_pixels) / level_width,
309 float(op.patch_size_pixels) / level_height);
311 glViewport(0, 0, level_width, level_height);
313 glBlendFunc(GL_ONE, GL_ONE);
314 fbos.render_to(dense_flow_tex);
315 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
316 glClear(GL_COLOR_BUFFER_BIT);
317 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches * num_layers);
322 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
323 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
324 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
326 uniform_image_tex = glGetUniformLocation(prewarp_program, "image_tex");
327 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
330 void Prewarp::exec(GLuint tex_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height, int num_layers)
332 glUseProgram(prewarp_program);
334 bind_sampler(prewarp_program, uniform_image_tex, 0, tex_view, linear_sampler);
335 bind_sampler(prewarp_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
337 glViewport(0, 0, level_width, level_height);
339 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
340 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
343 Derivatives::Derivatives()
345 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
346 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
347 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
349 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
352 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height, int num_layers)
354 glUseProgram(derivatives_program);
356 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
358 glViewport(0, 0, level_width, level_height);
360 fbos.render_to(I_x_y_tex, beta_0_tex);
361 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
364 ComputeDiffusivity::ComputeDiffusivity()
366 diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
367 diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
368 diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
370 uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
371 uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
372 uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
373 uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
376 void ComputeDiffusivity::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
378 glUseProgram(diffusivity_program);
380 bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
381 bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
382 glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
383 glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
385 glViewport(0, 0, level_width, level_height);
388 fbos.render_to(diffusivity_tex);
389 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
392 SetupEquations::SetupEquations()
394 equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
395 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
396 equations_program = link_program(equations_vs_obj, equations_fs_obj);
398 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
399 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
400 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
401 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
402 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
403 uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
404 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
405 uniform_delta = glGetUniformLocation(equations_program, "delta");
406 uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
409 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 diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
411 glUseProgram(equations_program);
413 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
414 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
415 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
416 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
417 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
418 bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
419 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
420 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
421 glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
423 glViewport(0, 0, (level_width + 1) / 2, level_height);
425 fbos.render_to(equation_red_tex, equation_black_tex);
426 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
431 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
432 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
433 sor_program = link_program(sor_vs_obj, sor_fs_obj);
435 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
436 uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
437 uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
438 uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
439 uniform_phase = glGetUniformLocation(sor_program, "phase");
440 uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
443 void SOR::exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, int num_layers, ScopedTimer *sor_timer)
445 glUseProgram(sor_program);
447 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
448 bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
449 bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
450 bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
452 if (!zero_diff_flow) {
453 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
456 // NOTE: We bind to the texture we are rendering from, but we never write any value
457 // that we read in the same shader pass (we call discard for red values when we compute
458 // black, and vice versa), and we have barriers between the passes, so we're fine
460 glViewport(0, 0, level_width, level_height);
462 fbos.render_to(diff_flow_tex);
464 for (int i = 0; i < num_iterations; ++i) {
466 ScopedTimer timer("Red pass", sor_timer);
467 if (zero_diff_flow && i == 0) {
468 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
470 glProgramUniform1i(sor_program, uniform_phase, 0);
471 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
475 ScopedTimer timer("Black pass", sor_timer);
476 if (zero_diff_flow && i == 0) {
477 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
479 glProgramUniform1i(sor_program, uniform_phase, 1);
480 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
481 if (zero_diff_flow && i == 0) {
482 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
484 if (i != num_iterations - 1) {
491 AddBaseFlow::AddBaseFlow()
493 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
494 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
495 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
497 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
500 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers)
502 glUseProgram(add_flow_program);
504 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
506 glViewport(0, 0, level_width, level_height);
508 glBlendFunc(GL_ONE, GL_ONE);
509 fbos.render_to(base_flow_tex);
511 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
514 ResizeFlow::ResizeFlow()
516 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
517 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
518 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
520 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
521 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
524 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height, int num_layers)
526 glUseProgram(resize_flow_program);
528 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
530 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
532 glViewport(0, 0, output_width, output_height);
534 fbos.render_to(out_tex);
536 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
539 DISComputeFlow::DISComputeFlow(int width, int height, const OperatingPoint &op)
540 : width(width), height(height), op(op), motion_search(op), densify(op)
542 // Make some samplers.
543 glCreateSamplers(1, &nearest_sampler);
544 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
545 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
546 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
547 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
549 glCreateSamplers(1, &linear_sampler);
550 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
551 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
552 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
553 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
555 // The smoothness is sampled so that once we get to a smoothness involving
556 // a value outside the border, the diffusivity between the two becomes zero.
557 // Similarly, gradients are zero outside the border, since the edge is taken
559 glCreateSamplers(1, &zero_border_sampler);
560 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
561 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
562 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
563 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
564 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; // Note that zero alpha means we can also see whether we sampled outside the border or not.
565 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
567 // Initial flow is zero, 1x1.
568 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &initial_flow_tex);
569 glTextureStorage3D(initial_flow_tex, 1, GL_RG16F, 1, 1, 1);
570 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
572 // Set up the vertex data that will be shared between all passes.
579 glCreateBuffers(1, &vertex_vbo);
580 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
582 glCreateVertexArrays(1, &vao);
583 glBindVertexArray(vao);
584 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
586 GLint position_attrib = 0; // Hard-coded in every vertex shader.
587 glEnableVertexArrayAttrib(vao, position_attrib);
588 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
591 GLuint DISComputeFlow::exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy)
593 int num_layers = (flow_direction == FORWARD_AND_BACKWARD) ? 2 : 1;
594 int prev_level_width = 1, prev_level_height = 1;
595 GLuint prev_level_flow_tex = initial_flow_tex;
599 glBindVertexArray(vao);
600 glDisable(GL_DITHER);
602 ScopedTimer total_timer("Compute flow", &timers);
603 for (int level = op.coarsest_level; level >= int(op.finest_level); --level) {
604 char timer_name[256];
605 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
606 ScopedTimer level_timer(timer_name, &total_timer);
608 int level_width = width >> level;
609 int level_height = height >> level;
610 float patch_spacing_pixels = op.patch_size_pixels * (1.0f - op.patch_overlap_ratio);
612 // Make sure we have patches at least every Nth pixel, e.g. for width=9
613 // and patch_spacing=3 (the default), we put out patch centers in
614 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
615 // lock all the centers to integer coordinates if needed.
616 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
617 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
619 // Make sure we always read from the correct level; the chosen
620 // mipmapping could otherwise be rather unpredictable, especially
621 // during motion search.
623 glGenTextures(1, &tex_view);
624 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, tex, GL_R8, level, 1, 0, 2);
626 // Create a new texture to hold the gradients.
627 GLuint grad_tex = pool.get_texture(GL_R32UI, level_width, level_height, num_layers);
629 // Find the derivative.
631 ScopedTimer timer("Sobel", &level_timer);
632 sobel.exec(tex_view, grad_tex, level_width, level_height, num_layers);
635 // Motion search to find the initial flow. We use the flow from the previous
636 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
638 // Create an output flow texture.
639 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches, num_layers);
643 ScopedTimer timer("Motion search", &level_timer);
644 motion_search.exec(tex_view, grad_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches, num_layers);
646 pool.release_texture(grad_tex);
650 // Set up an output texture (cleared in Densify).
651 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height, num_layers);
655 ScopedTimer timer("Densification", &level_timer);
656 densify.exec(tex_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches, num_layers);
658 pool.release_texture(flow_out_tex);
660 // Everything below here in the loop belongs to variational refinement.
661 ScopedTimer varref_timer("Variational refinement", &level_timer);
663 // Prewarping; create I and I_t, and a normalized base flow (so we don't
664 // have to normalize it over and over again, and also save some bandwidth).
666 // During the entire rest of the variational refinement, flow will be measured
667 // in pixels, not 0..1 normalized OpenGL texture coordinates.
668 // This is because variational refinement depends so heavily on derivatives,
669 // which are measured in intensity levels per pixel.
670 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
671 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
672 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
674 ScopedTimer timer("Prewarping", &varref_timer);
675 prewarp.exec(tex_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height, num_layers);
677 pool.release_texture(dense_flow_tex);
678 glDeleteTextures(1, &tex_view);
680 // TODO: If we don't have variational refinement, we don't need I and I_t,
681 // so computing them is a waste.
682 if (op.variational_refinement) {
683 // Calculate I_x and I_y. We're only calculating first derivatives;
684 // the others will be taken on-the-fly in order to sample from fewer
685 // textures overall, since sampling from the L1 cache is cheap.
686 // (TODO: Verify that this is indeed faster than making separate
687 // double-derivative textures.)
688 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
689 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
691 ScopedTimer timer("First derivatives", &varref_timer);
692 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height, num_layers);
694 pool.release_texture(I_tex);
696 // We need somewhere to store du and dv (the flow increment, relative
697 // to the non-refined base flow u0 and v0). It's initially garbage,
698 // but not read until we've written something sane to it.
699 GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
701 // And for diffusivity.
702 GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
704 // And finally for the equation set. See SetupEquations for
705 // the storage format.
706 GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
707 GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
709 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
710 // Calculate the diffusivity term for each pixel.
712 ScopedTimer timer("Compute diffusivity", &varref_timer);
713 compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0, num_layers);
716 // Set up the 2x2 equation system for each pixel.
718 ScopedTimer timer("Set up equations", &varref_timer);
719 setup_equations.exec(I_x_y_tex, I_t_tex, diff_flow_tex, base_flow_tex, beta_0_tex, diffusivity_tex, equation_red_tex, equation_black_tex, level_width, level_height, outer_idx == 0, num_layers);
722 // Run a few SOR iterations. Note that these are to/from the same texture.
724 ScopedTimer timer("SOR", &varref_timer);
725 sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, num_layers, &timer);
729 pool.release_texture(I_t_tex);
730 pool.release_texture(I_x_y_tex);
731 pool.release_texture(beta_0_tex);
732 pool.release_texture(diffusivity_tex);
733 pool.release_texture(equation_red_tex);
734 pool.release_texture(equation_black_tex);
736 // Add the differential flow found by the variational refinement to the base flow,
737 // giving the final flow estimate for this level.
738 // The output is in base_flow_tex; we don't need to make a new texture.
740 ScopedTimer timer("Add differential flow", &varref_timer);
741 add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height, num_layers);
743 pool.release_texture(diff_flow_tex);
746 if (prev_level_flow_tex != initial_flow_tex) {
747 pool.release_texture(prev_level_flow_tex);
749 prev_level_flow_tex = base_flow_tex;
750 prev_level_width = level_width;
751 prev_level_height = level_height;
759 // Scale up the flow to the final size (if needed).
760 if (op.finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
761 return prev_level_flow_tex;
763 GLuint final_tex = pool.get_texture(GL_RG16F, width, height, num_layers);
764 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height, num_layers);
765 pool.release_texture(prev_level_flow_tex);
770 Splat::Splat(const OperatingPoint &op)
773 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
774 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
775 splat_program = link_program(splat_vs_obj, splat_fs_obj);
777 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
778 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
779 uniform_gray_tex = glGetUniformLocation(splat_program, "gray_tex");
780 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
781 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
784 void Splat::exec(GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha)
786 glUseProgram(splat_program);
788 bind_sampler(splat_program, uniform_gray_tex, 0, gray_tex, linear_sampler);
789 bind_sampler(splat_program, uniform_flow_tex, 1, bidirectional_flow_tex, nearest_sampler);
791 glProgramUniform2f(splat_program, uniform_splat_size, op.splat_size / width, op.splat_size / height);
792 glProgramUniform1f(splat_program, uniform_alpha, alpha);
793 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
795 glViewport(0, 0, width, height);
797 glEnable(GL_DEPTH_TEST);
798 glDepthMask(GL_TRUE);
799 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.)
801 fbos.render_to(depth_rb, flow_tex);
803 // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
804 // we've got it bound.
805 glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f); // Invalid flow.
806 glClearDepth(1.0f); // Effectively infinity.
807 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
809 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height * 2);
811 glDisable(GL_DEPTH_TEST);
816 fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
817 fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
818 fill_program = link_program(fill_vs_obj, fill_fs_obj);
820 uniform_tex = glGetUniformLocation(fill_program, "tex");
821 uniform_z = glGetUniformLocation(fill_program, "z");
822 uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
825 void HoleFill::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
827 glUseProgram(fill_program);
829 bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
831 glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
833 glViewport(0, 0, width, height);
835 glEnable(GL_DEPTH_TEST);
836 glDepthFunc(GL_LESS); // Only update the values > 0.999f (ie., only invalid pixels).
838 fbos.render_to(depth_rb, flow_tex); // NOTE: Reading and writing to the same texture.
840 // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
841 for (int offs = 1; offs < width; offs *= 2) {
842 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
843 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
846 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
848 // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
849 // were overwritten in the last algorithm.
850 glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
851 for (int offs = 1; offs < width; offs *= 2) {
852 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
853 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
856 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
859 glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
860 for (int offs = 1; offs < height; offs *= 2) {
861 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
862 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
865 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
868 glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
869 for (int offs = 1; offs < height; offs *= 2) {
870 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
871 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
875 glDisable(GL_DEPTH_TEST);
878 HoleBlend::HoleBlend()
880 blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER); // Reuse the vertex shader from the fill.
881 blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
882 blend_program = link_program(blend_vs_obj, blend_fs_obj);
884 uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
885 uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
886 uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
887 uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
888 uniform_z = glGetUniformLocation(blend_program, "z");
889 uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
892 void HoleBlend::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
894 glUseProgram(blend_program);
896 bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
897 bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
898 bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
899 bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
901 glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
902 glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
904 glViewport(0, 0, width, height);
906 glEnable(GL_DEPTH_TEST);
907 glDepthFunc(GL_LEQUAL); // Skip over all of the pixels that were never holes to begin with.
909 fbos.render_to(depth_rb, flow_tex); // NOTE: Reading and writing to the same texture.
911 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
913 glDisable(GL_DEPTH_TEST);
916 Blend::Blend(bool split_ycbcr_output)
917 : split_ycbcr_output(split_ycbcr_output)
919 string frag_shader = read_file("blend.frag");
920 if (split_ycbcr_output) {
921 // Insert after the first #version line.
922 size_t offset = frag_shader.find('\n');
923 assert(offset != string::npos);
924 frag_shader = frag_shader.substr(0, offset + 1) + "#define SPLIT_YCBCR_OUTPUT 1\n" + frag_shader.substr(offset + 1);
927 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
928 blend_fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
929 blend_program = link_program(blend_vs_obj, blend_fs_obj);
931 uniform_image_tex = glGetUniformLocation(blend_program, "image_tex");
932 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
933 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
934 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
937 void Blend::exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, GLuint output2_tex, int level_width, int level_height, float alpha)
939 glUseProgram(blend_program);
940 bind_sampler(blend_program, uniform_image_tex, 0, image_tex, linear_sampler);
941 bind_sampler(blend_program, uniform_flow_tex, 1, flow_tex, linear_sampler); // May be upsampled.
942 glProgramUniform1f(blend_program, uniform_alpha, alpha);
944 glViewport(0, 0, level_width, level_height);
945 if (split_ycbcr_output) {
946 fbos_split.render_to(output_tex, output2_tex);
948 fbos.render_to(output_tex);
950 glDisable(GL_BLEND); // A bit ironic, perhaps.
951 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
954 Interpolate::Interpolate(const OperatingPoint &op, bool split_ycbcr_output)
955 : flow_level(op.finest_level),
956 split_ycbcr_output(split_ycbcr_output),
958 blend(split_ycbcr_output) {
959 // Set up the vertex data that will be shared between all passes.
966 glCreateBuffers(1, &vertex_vbo);
967 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
969 glCreateVertexArrays(1, &vao);
970 glBindVertexArray(vao);
971 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
973 GLint position_attrib = 0; // Hard-coded in every vertex shader.
974 glEnableVertexArrayAttrib(vao, position_attrib);
975 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
978 pair<GLuint, GLuint> Interpolate::exec(GLuint image_tex, GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha)
982 ScopedTimer total_timer("Interpolate", &timers);
984 glBindVertexArray(vao);
985 glDisable(GL_DITHER);
987 // Pick out the right level to test splatting results on.
989 glGenTextures(1, &tex_view);
990 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, gray_tex, GL_R8, flow_level, 1, 0, 2);
992 int flow_width = width >> flow_level;
993 int flow_height = height >> flow_level;
995 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
996 GLuint depth_rb = pool.get_renderbuffer(GL_DEPTH_COMPONENT16, flow_width, flow_height); // Used for ranking flows.
999 ScopedTimer timer("Splat", &total_timer);
1000 splat.exec(tex_view, bidirectional_flow_tex, flow_tex, depth_rb, flow_width, flow_height, alpha);
1002 glDeleteTextures(1, &tex_view);
1005 temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1006 temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1007 temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1010 ScopedTimer timer("Fill holes", &total_timer);
1011 hole_fill.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1012 hole_blend.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1015 pool.release_texture(temp_tex[0]);
1016 pool.release_texture(temp_tex[1]);
1017 pool.release_texture(temp_tex[2]);
1018 pool.release_renderbuffer(depth_rb);
1020 GLuint output_tex, output2_tex = 0;
1021 if (split_ycbcr_output) {
1022 output_tex = pool.get_texture(GL_R8, width, height);
1023 output2_tex = pool.get_texture(GL_RG8, width, height);
1025 ScopedTimer timer("Blend", &total_timer);
1026 blend.exec(image_tex, flow_tex, output_tex, output2_tex, width, height, alpha);
1029 output_tex = pool.get_texture(GL_RGBA8, width, height);
1031 ScopedTimer timer("Blend", &total_timer);
1032 blend.exec(image_tex, flow_tex, output_tex, 0, width, height, alpha);
1035 pool.release_texture(flow_tex);
1041 return make_pair(output_tex, output2_tex);
1044 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers)
1047 lock_guard<mutex> lock(mu);
1048 for (Texture &tex : textures) {
1049 if (!tex.in_use && !tex.is_renderbuffer && tex.format == format &&
1050 tex.width == width && tex.height == height && tex.num_layers == num_layers) {
1058 if (num_layers == 0) {
1059 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1060 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1062 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex.tex_num);
1063 glTextureStorage3D(tex.tex_num, 1, format, width, height, num_layers);
1065 tex.format = format;
1067 tex.height = height;
1068 tex.num_layers = num_layers;
1070 tex.is_renderbuffer = false;
1072 lock_guard<mutex> lock(mu);
1073 textures.push_back(tex);
1078 GLuint TexturePool::get_renderbuffer(GLenum format, GLuint width, GLuint height)
1081 lock_guard<mutex> lock(mu);
1082 for (Texture &tex : textures) {
1083 if (!tex.in_use && tex.is_renderbuffer && tex.format == format &&
1084 tex.width == width && tex.height == height) {
1092 glCreateRenderbuffers(1, &tex.tex_num);
1093 glNamedRenderbufferStorage(tex.tex_num, format, width, height);
1095 tex.format = format;
1097 tex.height = height;
1099 tex.is_renderbuffer = true;
1101 lock_guard<mutex> lock(mu);
1102 textures.push_back(tex);
1107 void TexturePool::release_texture(GLuint tex_num)
1109 lock_guard<mutex> lock(mu);
1110 for (Texture &tex : textures) {
1111 if (!tex.is_renderbuffer && tex.tex_num == tex_num) {
1120 void TexturePool::release_renderbuffer(GLuint tex_num)
1122 lock_guard<mutex> lock(mu);
1123 for (Texture &tex : textures) {
1124 if (tex.is_renderbuffer && tex.tex_num == tex_num) {