]> git.sesse.net Git - nageru/blob - flow.cpp
Fix some Clang warnings.
[nageru] / flow.cpp
1 #define NO_SDL_GLEXT 1
2
3 #include <epoxy/gl.h>
4
5 #include <assert.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <unistd.h>
9
10 #include "flow.h"
11 #include "gpu_timers.h"
12 #include "util.h"
13
14 #include <algorithm>
15 #include <deque>
16 #include <memory>
17 #include <map>
18 #include <stack>
19 #include <vector>
20
21 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
22
23 using namespace std;
24
25 // Weighting constants for the different parts of the variational refinement.
26 // These don't correspond 1:1 to the values given in the DIS paper,
27 // since we have different normalizations and ranges in some cases.
28 // These are found through a simple grid search on some MPI-Sintel data,
29 // although the error (EPE) seems to be fairly insensitive to the precise values.
30 // Only the relative values matter, so we fix alpha (the smoothness constant)
31 // at unity and tweak the others.
32 //
33 // TODO: Maybe this should not be global.
34 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
35
36 // Some global OpenGL objects.
37 // TODO: These should really be part of DISComputeFlow.
38 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
39 GLuint vertex_vbo;
40
41 int find_num_levels(int width, int height)
42 {
43         int levels = 1;
44         for (int w = width, h = height; w > 1 || h > 1; ) {
45                 w >>= 1;
46                 h >>= 1;
47                 ++levels;
48         }
49         return levels;
50 }
51
52 string read_file(const string &filename)
53 {
54         FILE *fp = fopen(filename.c_str(), "r");
55         if (fp == nullptr) {
56                 perror(filename.c_str());
57                 exit(1);
58         }
59
60         int ret = fseek(fp, 0, SEEK_END);
61         if (ret == -1) {
62                 perror("fseek(SEEK_END)");
63                 exit(1);
64         }
65
66         int size = ftell(fp);
67
68         ret = fseek(fp, 0, SEEK_SET);
69         if (ret == -1) {
70                 perror("fseek(SEEK_SET)");
71                 exit(1);
72         }
73
74         string str;
75         str.resize(size);
76         ret = fread(&str[0], size, 1, fp);
77         if (ret == -1) {
78                 perror("fread");
79                 exit(1);
80         }
81         if (ret == 0) {
82                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
83                                 size, filename.c_str());
84                 exit(1);
85         }
86         fclose(fp);
87
88         return str;
89 }
90
91
92 GLuint compile_shader(const string &shader_src, GLenum type)
93 {
94         GLuint obj = glCreateShader(type);
95         const GLchar* source[] = { shader_src.data() };
96         const GLint length[] = { (GLint)shader_src.size() };
97         glShaderSource(obj, 1, source, length);
98         glCompileShader(obj);
99
100         GLchar info_log[4096];
101         GLsizei log_length = sizeof(info_log) - 1;
102         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
103         info_log[log_length] = 0;
104         if (strlen(info_log) > 0) {
105                 fprintf(stderr, "Shader compile log: %s\n", info_log);
106         }
107
108         GLint status;
109         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
110         if (status == GL_FALSE) {
111                 // Add some line numbers to easier identify compile errors.
112                 string src_with_lines = "/*   1 */ ";
113                 size_t lineno = 1;
114                 for (char ch : shader_src) {
115                         src_with_lines.push_back(ch);
116                         if (ch == '\n') {
117                                 char buf[32];
118                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
119                                 src_with_lines += buf;
120                         }
121                 }
122
123                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
124                 exit(1);
125         }
126
127         return obj;
128 }
129
130 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
131 {
132         GLuint program = glCreateProgram();
133         glAttachShader(program, vs_obj);
134         glAttachShader(program, fs_obj);
135         glLinkProgram(program);
136         GLint success;
137         glGetProgramiv(program, GL_LINK_STATUS, &success);
138         if (success == GL_FALSE) {
139                 GLchar error_log[1024] = {0};
140                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
141                 fprintf(stderr, "Error linking program: %s\n", error_log);
142                 exit(1);
143         }
144         return program;
145 }
146
147 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
148 {
149         if (location == -1) {
150                 return;
151         }
152
153         glBindTextureUnit(texture_unit, tex);
154         glBindSampler(texture_unit, sampler);
155         glProgramUniform1i(program, location, texture_unit);
156 }
157
158 template<size_t num_elements>
159 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
160 {
161         auto it = fbos.find(textures);
162         if (it != fbos.end()) {
163                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
164                 return;
165         }
166
167         GLuint fbo;
168         glCreateFramebuffers(1, &fbo);
169         GLenum bufs[num_elements];
170         for (size_t i = 0; i < num_elements; ++i) {
171                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
172                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
173         }
174         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
175
176         fbos[textures] = fbo;
177         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
178 }
179
180 template<size_t num_elements>
181 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_rb, const array<GLuint, num_elements> &textures)
182 {
183         auto key = make_pair(depth_rb, textures);
184
185         auto it = fbos.find(key);
186         if (it != fbos.end()) {
187                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
188                 return;
189         }
190
191         GLuint fbo;
192         glCreateFramebuffers(1, &fbo);
193         GLenum bufs[num_elements];
194         glNamedFramebufferRenderbuffer(fbo, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
195         for (size_t i = 0; i < num_elements; ++i) {
196                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
197                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
198         }
199         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
200
201         fbos[key] = fbo;
202         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
203 }
204
205 GrayscaleConversion::GrayscaleConversion()
206 {
207         gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
208         gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
209         gray_program = link_program(gray_vs_obj, gray_fs_obj);
210
211         // Set up the VAO containing all the required position/texcoord data.
212         glCreateVertexArrays(1, &gray_vao);
213         glBindVertexArray(gray_vao);
214
215         GLint position_attrib = glGetAttribLocation(gray_program, "position");
216         glEnableVertexArrayAttrib(gray_vao, position_attrib);
217         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
218
219         uniform_tex = glGetUniformLocation(gray_program, "tex");
220 }
221
222 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height, int num_layers)
223 {
224         glUseProgram(gray_program);
225         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
226
227         glViewport(0, 0, width, height);
228         fbos.render_to(gray_tex);
229         glBindVertexArray(gray_vao);
230         glDisable(GL_BLEND);
231         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
232 }
233
234 Sobel::Sobel()
235 {
236         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
237         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
238         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
239
240         uniform_tex = glGetUniformLocation(sobel_program, "tex");
241 }
242
243 void Sobel::exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers)
244 {
245         glUseProgram(sobel_program);
246         bind_sampler(sobel_program, uniform_tex, 0, tex_view, nearest_sampler);
247
248         glViewport(0, 0, level_width, level_height);
249         fbos.render_to(grad_tex);
250         glDisable(GL_BLEND);
251         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
252 }
253
254 MotionSearch::MotionSearch(const OperatingPoint &op)
255         : op(op)
256 {
257         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
258         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
259         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
260
261         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
262         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
263         uniform_out_flow_size = glGetUniformLocation(motion_search_program, "out_flow_size");
264         uniform_image_tex = glGetUniformLocation(motion_search_program, "image_tex");
265         uniform_grad_tex = glGetUniformLocation(motion_search_program, "grad_tex");
266         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
267         uniform_patch_size = glGetUniformLocation(motion_search_program, "patch_size");
268         uniform_num_iterations = glGetUniformLocation(motion_search_program, "num_iterations");
269 }
270
271 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)
272 {
273         glUseProgram(motion_search_program);
274
275         bind_sampler(motion_search_program, uniform_image_tex, 0, tex_view, linear_sampler);
276         bind_sampler(motion_search_program, uniform_grad_tex, 1, grad_tex, nearest_sampler);
277         bind_sampler(motion_search_program, uniform_flow_tex, 2, flow_tex, linear_sampler);
278
279         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
280         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
281         glProgramUniform2f(motion_search_program, uniform_out_flow_size, width_patches, height_patches);
282         glProgramUniform1ui(motion_search_program, uniform_patch_size, op.patch_size_pixels);
283         glProgramUniform1ui(motion_search_program, uniform_num_iterations, op.search_iterations);
284
285         glViewport(0, 0, width_patches, height_patches);
286         fbos.render_to(flow_out_tex);
287         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
288 }
289
290 Densify::Densify(const OperatingPoint &op)
291         : op(op)
292 {
293         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
294         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
295         densify_program = link_program(densify_vs_obj, densify_fs_obj);
296
297         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
298         uniform_image_tex = glGetUniformLocation(densify_program, "image_tex");
299         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
300 }
301
302 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)
303 {
304         glUseProgram(densify_program);
305
306         bind_sampler(densify_program, uniform_image_tex, 0, tex_view, linear_sampler);
307         bind_sampler(densify_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
308
309         glProgramUniform2f(densify_program, uniform_patch_size,
310                 float(op.patch_size_pixels) / level_width,
311                 float(op.patch_size_pixels) / level_height);
312
313         glViewport(0, 0, level_width, level_height);
314         glEnable(GL_BLEND);
315         glBlendFunc(GL_ONE, GL_ONE);
316         fbos.render_to(dense_flow_tex);
317         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
318         glClear(GL_COLOR_BUFFER_BIT);
319         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches * num_layers);
320 }
321
322 Prewarp::Prewarp()
323 {
324         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
325         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
326         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
327
328         uniform_image_tex = glGetUniformLocation(prewarp_program, "image_tex");
329         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
330 }
331
332 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)
333 {
334         glUseProgram(prewarp_program);
335
336         bind_sampler(prewarp_program, uniform_image_tex, 0, tex_view, linear_sampler);
337         bind_sampler(prewarp_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
338
339         glViewport(0, 0, level_width, level_height);
340         glDisable(GL_BLEND);
341         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
342         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
343 }
344
345 Derivatives::Derivatives()
346 {
347         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
348         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
349         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
350
351         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
352 }
353
354 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height, int num_layers)
355 {
356         glUseProgram(derivatives_program);
357
358         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
359
360         glViewport(0, 0, level_width, level_height);
361         glDisable(GL_BLEND);
362         fbos.render_to(I_x_y_tex, beta_0_tex);
363         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
364 }
365
366 ComputeDiffusivity::ComputeDiffusivity()
367 {
368         diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
369         diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
370         diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
371
372         uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
373         uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
374         uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
375         uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
376 }
377
378 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)
379 {
380         glUseProgram(diffusivity_program);
381
382         bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
383         bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
384         glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
385         glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
386
387         glViewport(0, 0, level_width, level_height);
388
389         glDisable(GL_BLEND);
390         fbos.render_to(diffusivity_tex);
391         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
392 }
393
394 SetupEquations::SetupEquations()
395 {
396         equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
397         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
398         equations_program = link_program(equations_vs_obj, equations_fs_obj);
399
400         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
401         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
402         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
403         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
404         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
405         uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
406         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
407         uniform_delta = glGetUniformLocation(equations_program, "delta");
408         uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
409 }
410
411 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)
412 {
413         glUseProgram(equations_program);
414
415         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
416         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
417         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
418         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
419         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
420         bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
421         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
422         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
423         glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
424
425         glViewport(0, 0, (level_width + 1) / 2, level_height);
426         glDisable(GL_BLEND);
427         fbos.render_to(equation_red_tex, equation_black_tex);
428         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
429 }
430
431 SOR::SOR()
432 {
433         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
434         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
435         sor_program = link_program(sor_vs_obj, sor_fs_obj);
436
437         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
438         uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
439         uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
440         uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
441         uniform_phase = glGetUniformLocation(sor_program, "phase");
442         uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
443 }
444
445 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)
446 {
447         glUseProgram(sor_program);
448
449         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
450         bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
451         bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
452         bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
453
454         if (!zero_diff_flow) {
455                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
456         }
457
458         // NOTE: We bind to the texture we are rendering from, but we never write any value
459         // that we read in the same shader pass (we call discard for red values when we compute
460         // black, and vice versa), and we have barriers between the passes, so we're fine
461         // as per the spec.
462         glViewport(0, 0, level_width, level_height);
463         glDisable(GL_BLEND);
464         fbos.render_to(diff_flow_tex);
465
466         for (int i = 0; i < num_iterations; ++i) {
467                 {
468                         ScopedTimer timer("Red pass", sor_timer);
469                         if (zero_diff_flow && i == 0) {
470                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
471                         }
472                         glProgramUniform1i(sor_program, uniform_phase, 0);
473                         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
474                         glTextureBarrier();
475                 }
476                 {
477                         ScopedTimer timer("Black pass", sor_timer);
478                         if (zero_diff_flow && i == 0) {
479                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
480                         }
481                         glProgramUniform1i(sor_program, uniform_phase, 1);
482                         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
483                         if (zero_diff_flow && i == 0) {
484                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
485                         }
486                         if (i != num_iterations - 1) {
487                                 glTextureBarrier();
488                         }
489                 }
490         }
491 }
492
493 AddBaseFlow::AddBaseFlow()
494 {
495         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
496         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
497         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
498
499         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
500 }
501
502 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers)
503 {
504         glUseProgram(add_flow_program);
505
506         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
507
508         glViewport(0, 0, level_width, level_height);
509         glEnable(GL_BLEND);
510         glBlendFunc(GL_ONE, GL_ONE);
511         fbos.render_to(base_flow_tex);
512
513         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
514 }
515
516 ResizeFlow::ResizeFlow()
517 {
518         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
519         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
520         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
521
522         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
523         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
524 }
525
526 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height, int num_layers)
527 {
528         glUseProgram(resize_flow_program);
529
530         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
531
532         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
533
534         glViewport(0, 0, output_width, output_height);
535         glDisable(GL_BLEND);
536         fbos.render_to(out_tex);
537
538         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
539 }
540
541 DISComputeFlow::DISComputeFlow(int width, int height, const OperatingPoint &op)
542         : width(width), height(height), op(op), motion_search(op), densify(op)
543 {
544         // Make some samplers.
545         glCreateSamplers(1, &nearest_sampler);
546         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
547         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
548         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
549         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
550
551         glCreateSamplers(1, &linear_sampler);
552         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
553         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
554         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
555         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
556
557         // The smoothness is sampled so that once we get to a smoothness involving
558         // a value outside the border, the diffusivity between the two becomes zero.
559         // Similarly, gradients are zero outside the border, since the edge is taken
560         // to be constant.
561         glCreateSamplers(1, &zero_border_sampler);
562         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
563         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
564         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
565         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
566         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.
567         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
568
569         // Initial flow is zero, 1x1.
570         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &initial_flow_tex);
571         glTextureStorage3D(initial_flow_tex, 1, GL_RG16F, 1, 1, 1);
572         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
573
574         // Set up the vertex data that will be shared between all passes.
575         float vertices[] = {
576                 0.0f, 1.0f,
577                 0.0f, 0.0f,
578                 1.0f, 1.0f,
579                 1.0f, 0.0f,
580         };
581         glCreateBuffers(1, &vertex_vbo);
582         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
583
584         glCreateVertexArrays(1, &vao);
585         glBindVertexArray(vao);
586         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
587
588         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
589         glEnableVertexArrayAttrib(vao, position_attrib);
590         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
591 }
592
593 GLuint DISComputeFlow::exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy)
594 {
595         int num_layers = (flow_direction == FORWARD_AND_BACKWARD) ? 2 : 1;
596         int prev_level_width = 1, prev_level_height = 1;
597         GLuint prev_level_flow_tex = initial_flow_tex;
598
599         GPUTimers timers;
600
601         glBindVertexArray(vao);
602         glDisable(GL_DITHER);
603
604         ScopedTimer total_timer("Compute flow", &timers);
605         for (int level = op.coarsest_level; level >= int(op.finest_level); --level) {
606                 char timer_name[256];
607                 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
608                 ScopedTimer level_timer(timer_name, &total_timer);
609
610                 int level_width = width >> level;
611                 int level_height = height >> level;
612                 float patch_spacing_pixels = op.patch_size_pixels * (1.0f - op.patch_overlap_ratio);
613
614                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
615                 // and patch_spacing=3 (the default), we put out patch centers in
616                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
617                 // lock all the centers to integer coordinates if needed.
618                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
619                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
620
621                 // Make sure we always read from the correct level; the chosen
622                 // mipmapping could otherwise be rather unpredictable, especially
623                 // during motion search.
624                 GLuint tex_view;
625                 glGenTextures(1, &tex_view);
626                 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, tex, GL_R8, level, 1, 0, 2);
627
628                 // Create a new texture to hold the gradients.
629                 GLuint grad_tex = pool.get_texture(GL_R32UI, level_width, level_height, num_layers);
630
631                 // Find the derivative.
632                 {
633                         ScopedTimer timer("Sobel", &level_timer);
634                         sobel.exec(tex_view, grad_tex, level_width, level_height, num_layers);
635                 }
636
637                 // Motion search to find the initial flow. We use the flow from the previous
638                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
639
640                 // Create an output flow texture.
641                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches, num_layers);
642
643                 // And draw.
644                 {
645                         ScopedTimer timer("Motion search", &level_timer);
646                         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);
647                 }
648                 pool.release_texture(grad_tex);
649
650                 // Densification.
651
652                 // Set up an output texture (cleared in Densify).
653                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height, num_layers);
654
655                 // And draw.
656                 {
657                         ScopedTimer timer("Densification", &level_timer);
658                         densify.exec(tex_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches, num_layers);
659                 }
660                 pool.release_texture(flow_out_tex);
661
662                 // Everything below here in the loop belongs to variational refinement.
663                 ScopedTimer varref_timer("Variational refinement", &level_timer);
664
665                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
666                 // have to normalize it over and over again, and also save some bandwidth).
667                 //
668                 // During the entire rest of the variational refinement, flow will be measured
669                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
670                 // This is because variational refinement depends so heavily on derivatives,
671                 // which are measured in intensity levels per pixel.
672                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
673                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
674                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
675                 {
676                         ScopedTimer timer("Prewarping", &varref_timer);
677                         prewarp.exec(tex_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height, num_layers);
678                 }
679                 pool.release_texture(dense_flow_tex);
680                 glDeleteTextures(1, &tex_view);
681
682                 // TODO: If we don't have variational refinement, we don't need I and I_t,
683                 // so computing them is a waste.
684                 if (op.variational_refinement) {
685                         // Calculate I_x and I_y. We're only calculating first derivatives;
686                         // the others will be taken on-the-fly in order to sample from fewer
687                         // textures overall, since sampling from the L1 cache is cheap.
688                         // (TODO: Verify that this is indeed faster than making separate
689                         // double-derivative textures.)
690                         GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
691                         GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
692                         {
693                                 ScopedTimer timer("First derivatives", &varref_timer);
694                                 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height, num_layers);
695                         }
696                         pool.release_texture(I_tex);
697
698                         // We need somewhere to store du and dv (the flow increment, relative
699                         // to the non-refined base flow u0 and v0). It's initially garbage,
700                         // but not read until we've written something sane to it.
701                         GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
702
703                         // And for diffusivity.
704                         GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
705
706                         // And finally for the equation set. See SetupEquations for
707                         // the storage format.
708                         GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
709                         GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
710
711                         for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
712                                 // Calculate the diffusivity term for each pixel.
713                                 {
714                                         ScopedTimer timer("Compute diffusivity", &varref_timer);
715                                         compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0, num_layers);
716                                 }
717
718                                 // Set up the 2x2 equation system for each pixel.
719                                 {
720                                         ScopedTimer timer("Set up equations", &varref_timer);
721                                         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                                 }
723
724                                 // Run a few SOR iterations. Note that these are to/from the same texture.
725                                 {
726                                         ScopedTimer timer("SOR", &varref_timer);
727                                         sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, num_layers, &timer);
728                                 }
729                         }
730
731                         pool.release_texture(I_t_tex);
732                         pool.release_texture(I_x_y_tex);
733                         pool.release_texture(beta_0_tex);
734                         pool.release_texture(diffusivity_tex);
735                         pool.release_texture(equation_red_tex);
736                         pool.release_texture(equation_black_tex);
737
738                         // Add the differential flow found by the variational refinement to the base flow,
739                         // giving the final flow estimate for this level.
740                         // The output is in base_flow_tex; we don't need to make a new texture.
741                         {
742                                 ScopedTimer timer("Add differential flow", &varref_timer);
743                                 add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height, num_layers);
744                         }
745                         pool.release_texture(diff_flow_tex);
746                 }
747
748                 if (prev_level_flow_tex != initial_flow_tex) {
749                         pool.release_texture(prev_level_flow_tex);
750                 }
751                 prev_level_flow_tex = base_flow_tex;
752                 prev_level_width = level_width;
753                 prev_level_height = level_height;
754         }
755         total_timer.end();
756
757         if (!in_warmup) {
758                 timers.print();
759         }
760
761         // Scale up the flow to the final size (if needed).
762         if (op.finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
763                 return prev_level_flow_tex;
764         } else {
765                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height, num_layers);
766                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height, num_layers);
767                 pool.release_texture(prev_level_flow_tex);
768                 return final_tex;
769         }
770 }
771
772 Splat::Splat(const OperatingPoint &op)
773         : op(op)
774 {
775         splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
776         splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
777         splat_program = link_program(splat_vs_obj, splat_fs_obj);
778
779         uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
780         uniform_alpha = glGetUniformLocation(splat_program, "alpha");
781         uniform_gray_tex = glGetUniformLocation(splat_program, "gray_tex");
782         uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
783         uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
784 }
785
786 void Splat::exec(GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha)
787 {
788         glUseProgram(splat_program);
789
790         bind_sampler(splat_program, uniform_gray_tex, 0, gray_tex, linear_sampler);
791         bind_sampler(splat_program, uniform_flow_tex, 1, bidirectional_flow_tex, nearest_sampler);
792
793         glProgramUniform2f(splat_program, uniform_splat_size, op.splat_size / width, op.splat_size / height);
794         glProgramUniform1f(splat_program, uniform_alpha, alpha);
795         glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
796
797         glViewport(0, 0, width, height);
798         glDisable(GL_BLEND);
799         glEnable(GL_DEPTH_TEST);
800         glDepthMask(GL_TRUE);
801         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.)
802
803         fbos.render_to(depth_rb, flow_tex);
804
805         // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
806         // we've got it bound.
807         glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f);  // Invalid flow.
808         glClearDepth(1.0f);  // Effectively infinity.
809         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
810
811         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height * 2);
812
813         glDisable(GL_DEPTH_TEST);
814 }
815
816 HoleFill::HoleFill()
817 {
818         fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
819         fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
820         fill_program = link_program(fill_vs_obj, fill_fs_obj);
821
822         uniform_tex = glGetUniformLocation(fill_program, "tex");
823         uniform_z = glGetUniformLocation(fill_program, "z");
824         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
825 }
826
827 void HoleFill::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
828 {
829         glUseProgram(fill_program);
830
831         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
832
833         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
834
835         glViewport(0, 0, width, height);
836         glDisable(GL_BLEND);
837         glEnable(GL_DEPTH_TEST);
838         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
839
840         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
841
842         // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
843         for (int offs = 1; offs < width; offs *= 2) {
844                 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
845                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
846                 glTextureBarrier();
847         }
848         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
849
850         // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
851         // were overwritten in the last algorithm.
852         glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
853         for (int offs = 1; offs < width; offs *= 2) {
854                 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
855                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
856                 glTextureBarrier();
857         }
858         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
859
860         // Up.
861         glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
862         for (int offs = 1; offs < height; offs *= 2) {
863                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
864                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
865                 glTextureBarrier();
866         }
867         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
868
869         // Down.
870         glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
871         for (int offs = 1; offs < height; offs *= 2) {
872                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
873                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
874                 glTextureBarrier();
875         }
876
877         glDisable(GL_DEPTH_TEST);
878 }
879
880 HoleBlend::HoleBlend()
881 {
882         blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);  // Reuse the vertex shader from the fill.
883         blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
884         blend_program = link_program(blend_vs_obj, blend_fs_obj);
885
886         uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
887         uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
888         uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
889         uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
890         uniform_z = glGetUniformLocation(blend_program, "z");
891         uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
892 }
893
894 void HoleBlend::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
895 {
896         glUseProgram(blend_program);
897
898         bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
899         bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
900         bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
901         bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
902
903         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
904         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
905
906         glViewport(0, 0, width, height);
907         glDisable(GL_BLEND);
908         glEnable(GL_DEPTH_TEST);
909         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
910
911         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
912
913         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
914
915         glDisable(GL_DEPTH_TEST);
916 }
917
918 Blend::Blend(bool split_ycbcr_output)
919         : split_ycbcr_output(split_ycbcr_output)
920 {
921         string frag_shader = read_file("blend.frag");
922         if (split_ycbcr_output) {
923                 // Insert after the first #version line.
924                 size_t offset = frag_shader.find('\n');
925                 assert(offset != string::npos);
926                 frag_shader = frag_shader.substr(0, offset + 1) + "#define SPLIT_YCBCR_OUTPUT 1\n" + frag_shader.substr(offset + 1);
927         }
928
929         blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
930         blend_fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
931         blend_program = link_program(blend_vs_obj, blend_fs_obj);
932
933         uniform_image_tex = glGetUniformLocation(blend_program, "image_tex");
934         uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
935         uniform_alpha = glGetUniformLocation(blend_program, "alpha");
936         uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
937 }
938
939 void Blend::exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, GLuint output2_tex, int level_width, int level_height, float alpha)
940 {
941         glUseProgram(blend_program);
942         bind_sampler(blend_program, uniform_image_tex, 0, image_tex, linear_sampler);
943         bind_sampler(blend_program, uniform_flow_tex, 1, flow_tex, linear_sampler);  // May be upsampled.
944         glProgramUniform1f(blend_program, uniform_alpha, alpha);
945
946         glViewport(0, 0, level_width, level_height);
947         if (split_ycbcr_output) {
948                 fbos_split.render_to(output_tex, output2_tex);
949         } else {
950                 fbos.render_to(output_tex);
951         }
952         glDisable(GL_BLEND);  // A bit ironic, perhaps.
953         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
954 }
955
956 Interpolate::Interpolate(const OperatingPoint &op, bool split_ycbcr_output)
957         : flow_level(op.finest_level),
958           split_ycbcr_output(split_ycbcr_output),
959           splat(op),
960           blend(split_ycbcr_output) {
961         // Set up the vertex data that will be shared between all passes.
962         float vertices[] = {
963                 0.0f, 1.0f,
964                 0.0f, 0.0f,
965                 1.0f, 1.0f,
966                 1.0f, 0.0f,
967         };
968         glCreateBuffers(1, &vertex_vbo);
969         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
970
971         glCreateVertexArrays(1, &vao);
972         glBindVertexArray(vao);
973         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
974
975         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
976         glEnableVertexArrayAttrib(vao, position_attrib);
977         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
978 }
979
980 pair<GLuint, GLuint> Interpolate::exec(GLuint image_tex, GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha)
981 {
982         GPUTimers timers;
983
984         ScopedTimer total_timer("Interpolate", &timers);
985
986         glBindVertexArray(vao);
987         glDisable(GL_DITHER);
988
989         // Pick out the right level to test splatting results on.
990         GLuint tex_view;
991         glGenTextures(1, &tex_view);
992         glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, gray_tex, GL_R8, flow_level, 1, 0, 2);
993
994         int flow_width = width >> flow_level;
995         int flow_height = height >> flow_level;
996
997         GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
998         GLuint depth_rb = pool.get_renderbuffer(GL_DEPTH_COMPONENT16, flow_width, flow_height);  // Used for ranking flows.
999
1000         {
1001                 ScopedTimer timer("Splat", &total_timer);
1002                 splat.exec(tex_view, bidirectional_flow_tex, flow_tex, depth_rb, flow_width, flow_height, alpha);
1003         }
1004         glDeleteTextures(1, &tex_view);
1005
1006         GLuint temp_tex[3];
1007         temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1008         temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1009         temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1010
1011         {
1012                 ScopedTimer timer("Fill holes", &total_timer);
1013                 hole_fill.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1014                 hole_blend.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1015         }
1016
1017         pool.release_texture(temp_tex[0]);
1018         pool.release_texture(temp_tex[1]);
1019         pool.release_texture(temp_tex[2]);
1020         pool.release_renderbuffer(depth_rb);
1021
1022         GLuint output_tex, output2_tex = 0;
1023         if (split_ycbcr_output) {
1024                 output_tex = pool.get_texture(GL_R8, width, height);
1025                 output2_tex = pool.get_texture(GL_RG8, width, height);
1026                 {
1027                         ScopedTimer timer("Blend", &total_timer);
1028                         blend.exec(image_tex, flow_tex, output_tex, output2_tex, width, height, alpha);
1029                 }
1030         } else {
1031                 output_tex = pool.get_texture(GL_RGBA8, width, height);
1032                 {
1033                         ScopedTimer timer("Blend", &total_timer);
1034                         blend.exec(image_tex, flow_tex, output_tex, 0, width, height, alpha);
1035                 }
1036         }
1037         pool.release_texture(flow_tex);
1038         total_timer.end();
1039         if (!in_warmup) {
1040                 timers.print();
1041         }
1042
1043         return make_pair(output_tex, output2_tex);
1044 }
1045
1046 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers)
1047 {
1048         {
1049                 lock_guard<mutex> lock(mu);
1050                 for (Texture &tex : textures) {
1051                         if (!tex.in_use && !tex.is_renderbuffer && tex.format == format &&
1052                             tex.width == width && tex.height == height && tex.num_layers == num_layers) {
1053                                 tex.in_use = true;
1054                                 return tex.tex_num;
1055                         }
1056                 }
1057         }
1058
1059         Texture tex;
1060         if (num_layers == 0) {
1061                 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1062                 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1063         } else {
1064                 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex.tex_num);
1065                 glTextureStorage3D(tex.tex_num, 1, format, width, height, num_layers);
1066         }
1067         tex.format = format;
1068         tex.width = width;
1069         tex.height = height;
1070         tex.num_layers = num_layers;
1071         tex.in_use = true;
1072         tex.is_renderbuffer = false;
1073         {
1074                 lock_guard<mutex> lock(mu);
1075                 textures.push_back(tex);
1076         }
1077         return tex.tex_num;
1078 }
1079
1080 GLuint TexturePool::get_renderbuffer(GLenum format, GLuint width, GLuint height)
1081 {
1082         {
1083                 lock_guard<mutex> lock(mu);
1084                 for (Texture &tex : textures) {
1085                         if (!tex.in_use && tex.is_renderbuffer && tex.format == format &&
1086                             tex.width == width && tex.height == height) {
1087                                 tex.in_use = true;
1088                                 return tex.tex_num;
1089                         }
1090                 }
1091         }
1092
1093         Texture tex;
1094         glCreateRenderbuffers(1, &tex.tex_num);
1095         glNamedRenderbufferStorage(tex.tex_num, format, width, height);
1096
1097         tex.format = format;
1098         tex.width = width;
1099         tex.height = height;
1100         tex.in_use = true;
1101         tex.is_renderbuffer = true;
1102         {
1103                 lock_guard<mutex> lock(mu);
1104                 textures.push_back(tex);
1105         }
1106         return tex.tex_num;
1107 }
1108
1109 void TexturePool::release_texture(GLuint tex_num)
1110 {
1111         lock_guard<mutex> lock(mu);
1112         for (Texture &tex : textures) {
1113                 if (!tex.is_renderbuffer && tex.tex_num == tex_num) {
1114                         assert(tex.in_use);
1115                         tex.in_use = false;
1116                         return;
1117                 }
1118         }
1119         assert(false);
1120 }
1121
1122 void TexturePool::release_renderbuffer(GLuint tex_num)
1123 {
1124         lock_guard<mutex> lock(mu);
1125         for (Texture &tex : textures) {
1126                 if (tex.is_renderbuffer && tex.tex_num == tex_num) {
1127                         assert(tex.in_use);
1128                         tex.in_use = false;
1129                         return;
1130                 }
1131         }
1132         //assert(false);
1133 }