]> git.sesse.net Git - nageru/blob - flow.cpp
e672fe6f6d8fefb8ecc97935b73af79ee3495f8e
[nageru] / flow.cpp
1 #define NO_SDL_GLEXT 1
2
3 #include "flow.h"
4
5 #include "gpu_timers.h"
6 #include "util.h"
7
8 #include <algorithm>
9 #include <assert.h>
10 #include <deque>
11 #include <epoxy/gl.h>
12 #include <map>
13 #include <memory>
14 #include <stack>
15 #include <stdio.h>
16 #include <string.h>
17 #include <unistd.h>
18 #include <vector>
19
20 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
21
22 using namespace std;
23
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.
31 //
32 // TODO: Maybe this should not be global.
33 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
34
35 // Some global OpenGL objects.
36 // TODO: These should really be part of DISComputeFlow.
37 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
38 GLuint vertex_vbo;
39
40 int find_num_levels(int width, int height)
41 {
42         int levels = 1;
43         for (int w = width, h = height; w > 1 || h > 1; ) {
44                 w >>= 1;
45                 h >>= 1;
46                 ++levels;
47         }
48         return levels;
49 }
50
51 string read_file(const string &filename)
52 {
53         FILE *fp = fopen(filename.c_str(), "r");
54         if (fp == nullptr) {
55                 perror(filename.c_str());
56                 exit(1);
57         }
58
59         int ret = fseek(fp, 0, SEEK_END);
60         if (ret == -1) {
61                 perror("fseek(SEEK_END)");
62                 exit(1);
63         }
64
65         int size = ftell(fp);
66
67         ret = fseek(fp, 0, SEEK_SET);
68         if (ret == -1) {
69                 perror("fseek(SEEK_SET)");
70                 exit(1);
71         }
72
73         string str;
74         str.resize(size);
75         ret = fread(&str[0], size, 1, fp);
76         if (ret == -1) {
77                 perror("fread");
78                 exit(1);
79         }
80         if (ret == 0) {
81                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
82                         size, filename.c_str());
83                 exit(1);
84         }
85         fclose(fp);
86
87         return str;
88 }
89
90 GLuint compile_shader(const string &shader_src, GLenum type)
91 {
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);
96         glCompileShader(obj);
97
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);
104         }
105
106         GLint status;
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 */ ";
111                 size_t lineno = 1;
112                 for (char ch : shader_src) {
113                         src_with_lines.push_back(ch);
114                         if (ch == '\n') {
115                                 char buf[32];
116                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
117                                 src_with_lines += buf;
118                         }
119                 }
120
121                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
122                 exit(1);
123         }
124
125         return obj;
126 }
127
128 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
129 {
130         GLuint program = glCreateProgram();
131         glAttachShader(program, vs_obj);
132         glAttachShader(program, fs_obj);
133         glLinkProgram(program);
134         GLint success;
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);
140                 exit(1);
141         }
142         return program;
143 }
144
145 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
146 {
147         if (location == -1) {
148                 return;
149         }
150
151         glBindTextureUnit(texture_unit, tex);
152         glBindSampler(texture_unit, sampler);
153         glProgramUniform1i(program, location, texture_unit);
154 }
155
156 template<size_t num_elements>
157 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
158 {
159         auto it = fbos.find(textures);
160         if (it != fbos.end()) {
161                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
162                 return;
163         }
164
165         GLuint fbo;
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;
171         }
172         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
173
174         fbos[textures] = fbo;
175         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
176 }
177
178 template<size_t num_elements>
179 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_rb, const array<GLuint, num_elements> &textures)
180 {
181         auto key = make_pair(depth_rb, textures);
182
183         auto it = fbos.find(key);
184         if (it != fbos.end()) {
185                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
186                 return;
187         }
188
189         GLuint fbo;
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;
196         }
197         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
198
199         fbos[key] = fbo;
200         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
201 }
202
203 GrayscaleConversion::GrayscaleConversion()
204 {
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);
208
209         // Set up the VAO containing all the required position/texcoord data.
210         glCreateVertexArrays(1, &gray_vao);
211         glBindVertexArray(gray_vao);
212
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));
216
217         uniform_tex = glGetUniformLocation(gray_program, "tex");
218 }
219
220 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height, int num_layers)
221 {
222         glUseProgram(gray_program);
223         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
224
225         glViewport(0, 0, width, height);
226         fbos.render_to(gray_tex);
227         glBindVertexArray(gray_vao);
228         glDisable(GL_BLEND);
229         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
230 }
231
232 Sobel::Sobel()
233 {
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);
237
238         uniform_tex = glGetUniformLocation(sobel_program, "tex");
239 }
240
241 void Sobel::exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers)
242 {
243         glUseProgram(sobel_program);
244         bind_sampler(sobel_program, uniform_tex, 0, tex_view, nearest_sampler);
245
246         glViewport(0, 0, level_width, level_height);
247         fbos.render_to(grad_tex);
248         glDisable(GL_BLEND);
249         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
250 }
251
252 MotionSearch::MotionSearch(const OperatingPoint &op)
253         : op(op)
254 {
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);
258
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");
267 }
268
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)
270 {
271         glUseProgram(motion_search_program);
272
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);
276
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);
282
283         glViewport(0, 0, width_patches, height_patches);
284         fbos.render_to(flow_out_tex);
285         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
286 }
287
288 Densify::Densify(const OperatingPoint &op)
289         : op(op)
290 {
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);
294
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");
298 }
299
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)
301 {
302         glUseProgram(densify_program);
303
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);
306
307         glProgramUniform2f(densify_program, uniform_patch_size,
308                 float(op.patch_size_pixels) / level_width,
309                 float(op.patch_size_pixels) / level_height);
310
311         glViewport(0, 0, level_width, level_height);
312         glEnable(GL_BLEND);
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);
318 }
319
320 Prewarp::Prewarp()
321 {
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);
325
326         uniform_image_tex = glGetUniformLocation(prewarp_program, "image_tex");
327         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
328 }
329
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)
331 {
332         glUseProgram(prewarp_program);
333
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);
336
337         glViewport(0, 0, level_width, level_height);
338         glDisable(GL_BLEND);
339         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
340         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
341 }
342
343 Derivatives::Derivatives()
344 {
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);
348
349         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
350 }
351
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)
353 {
354         glUseProgram(derivatives_program);
355
356         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
357
358         glViewport(0, 0, level_width, level_height);
359         glDisable(GL_BLEND);
360         fbos.render_to(I_x_y_tex, beta_0_tex);
361         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
362 }
363
364 ComputeDiffusivity::ComputeDiffusivity()
365 {
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);
369
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");
374 }
375
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)
377 {
378         glUseProgram(diffusivity_program);
379
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);
384
385         glViewport(0, 0, level_width, level_height);
386
387         glDisable(GL_BLEND);
388         fbos.render_to(diffusivity_tex);
389         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
390 }
391
392 SetupEquations::SetupEquations()
393 {
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);
397
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");
407 }
408
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)
410 {
411         glUseProgram(equations_program);
412
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);
422
423         glViewport(0, 0, (level_width + 1) / 2, level_height);
424         glDisable(GL_BLEND);
425         fbos.render_to(equation_red_tex, equation_black_tex);
426         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
427 }
428
429 SOR::SOR()
430 {
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);
434
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");
441 }
442
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)
444 {
445         glUseProgram(sor_program);
446
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);
451
452         if (!zero_diff_flow) {
453                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
454         }
455
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
459         // as per the spec.
460         glViewport(0, 0, level_width, level_height);
461         glDisable(GL_BLEND);
462         fbos.render_to(diff_flow_tex);
463
464         for (int i = 0; i < num_iterations; ++i) {
465                 {
466                         ScopedTimer timer("Red pass", sor_timer);
467                         if (zero_diff_flow && i == 0) {
468                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
469                         }
470                         glProgramUniform1i(sor_program, uniform_phase, 0);
471                         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
472                         glTextureBarrier();
473                 }
474                 {
475                         ScopedTimer timer("Black pass", sor_timer);
476                         if (zero_diff_flow && i == 0) {
477                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
478                         }
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);
483                         }
484                         if (i != num_iterations - 1) {
485                                 glTextureBarrier();
486                         }
487                 }
488         }
489 }
490
491 AddBaseFlow::AddBaseFlow()
492 {
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);
496
497         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
498 }
499
500 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers)
501 {
502         glUseProgram(add_flow_program);
503
504         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
505
506         glViewport(0, 0, level_width, level_height);
507         glEnable(GL_BLEND);
508         glBlendFunc(GL_ONE, GL_ONE);
509         fbos.render_to(base_flow_tex);
510
511         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
512 }
513
514 ResizeFlow::ResizeFlow()
515 {
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);
519
520         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
521         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
522 }
523
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)
525 {
526         glUseProgram(resize_flow_program);
527
528         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
529
530         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
531
532         glViewport(0, 0, output_width, output_height);
533         glDisable(GL_BLEND);
534         fbos.render_to(out_tex);
535
536         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
537 }
538
539 DISComputeFlow::DISComputeFlow(int width, int height, const OperatingPoint &op)
540         : width(width), height(height), op(op), motion_search(op), densify(op)
541 {
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);
548
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);
554
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
558         // to be constant.
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);
566
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);
571
572         // Set up the vertex data that will be shared between all passes.
573         float vertices[] = {
574                 0.0f, 1.0f,
575                 0.0f, 0.0f,
576                 1.0f, 1.0f,
577                 1.0f, 0.0f,
578         };
579         glCreateBuffers(1, &vertex_vbo);
580         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
581
582         glCreateVertexArrays(1, &vao);
583         glBindVertexArray(vao);
584         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
585
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));
589 }
590
591 GLuint DISComputeFlow::exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy)
592 {
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;
596
597         GPUTimers timers;
598
599         glBindVertexArray(vao);
600         glDisable(GL_DITHER);
601
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);
607
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);
611
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);
618
619                 // Make sure we always read from the correct level; the chosen
620                 // mipmapping could otherwise be rather unpredictable, especially
621                 // during motion search.
622                 GLuint tex_view;
623                 glGenTextures(1, &tex_view);
624                 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, tex, GL_R8, level, 1, 0, 2);
625
626                 // Create a new texture to hold the gradients.
627                 GLuint grad_tex = pool.get_texture(GL_R32UI, level_width, level_height, num_layers);
628
629                 // Find the derivative.
630                 {
631                         ScopedTimer timer("Sobel", &level_timer);
632                         sobel.exec(tex_view, grad_tex, level_width, level_height, num_layers);
633                 }
634
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.
637
638                 // Create an output flow texture.
639                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches, num_layers);
640
641                 // And draw.
642                 {
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);
645                 }
646                 pool.release_texture(grad_tex);
647
648                 // Densification.
649
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);
652
653                 // And draw.
654                 {
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);
657                 }
658                 pool.release_texture(flow_out_tex);
659
660                 // Everything below here in the loop belongs to variational refinement.
661                 ScopedTimer varref_timer("Variational refinement", &level_timer);
662
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).
665                 //
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);
673                 {
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);
676                 }
677                 pool.release_texture(dense_flow_tex);
678                 glDeleteTextures(1, &tex_view);
679
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);
690                         {
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);
693                         }
694                         pool.release_texture(I_tex);
695
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);
700
701                         // And for diffusivity.
702                         GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
703
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);
708
709                         for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
710                                 // Calculate the diffusivity term for each pixel.
711                                 {
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);
714                                 }
715
716                                 // Set up the 2x2 equation system for each pixel.
717                                 {
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);
720                                 }
721
722                                 // Run a few SOR iterations. Note that these are to/from the same texture.
723                                 {
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);
726                                 }
727                         }
728
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);
735
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.
739                         {
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);
742                         }
743                         pool.release_texture(diff_flow_tex);
744                 }
745
746                 if (prev_level_flow_tex != initial_flow_tex) {
747                         pool.release_texture(prev_level_flow_tex);
748                 }
749                 prev_level_flow_tex = base_flow_tex;
750                 prev_level_width = level_width;
751                 prev_level_height = level_height;
752         }
753         total_timer.end();
754
755         if (!in_warmup) {
756                 timers.print();
757         }
758
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;
762         } else {
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);
766                 return final_tex;
767         }
768 }
769
770 Splat::Splat(const OperatingPoint &op)
771         : op(op)
772 {
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);
776
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");
782 }
783
784 void Splat::exec(GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha)
785 {
786         glUseProgram(splat_program);
787
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);
790
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);
794
795         glViewport(0, 0, width, height);
796         glDisable(GL_BLEND);
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.)
800
801         fbos.render_to(depth_rb, flow_tex);
802
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);
808
809         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height * 2);
810
811         glDisable(GL_DEPTH_TEST);
812 }
813
814 HoleFill::HoleFill()
815 {
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);
819
820         uniform_tex = glGetUniformLocation(fill_program, "tex");
821         uniform_z = glGetUniformLocation(fill_program, "z");
822         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
823 }
824
825 void HoleFill::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
826 {
827         glUseProgram(fill_program);
828
829         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
830
831         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
832
833         glViewport(0, 0, width, height);
834         glDisable(GL_BLEND);
835         glEnable(GL_DEPTH_TEST);
836         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
837
838         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
839
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);
844                 glTextureBarrier();
845         }
846         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
847
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);
854                 glTextureBarrier();
855         }
856         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
857
858         // Up.
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);
863                 glTextureBarrier();
864         }
865         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
866
867         // Down.
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);
872                 glTextureBarrier();
873         }
874
875         glDisable(GL_DEPTH_TEST);
876 }
877
878 HoleBlend::HoleBlend()
879 {
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);
883
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");
890 }
891
892 void HoleBlend::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
893 {
894         glUseProgram(blend_program);
895
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);
900
901         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
902         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
903
904         glViewport(0, 0, width, height);
905         glDisable(GL_BLEND);
906         glEnable(GL_DEPTH_TEST);
907         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
908
909         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
910
911         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
912
913         glDisable(GL_DEPTH_TEST);
914 }
915
916 Blend::Blend(bool split_ycbcr_output)
917         : split_ycbcr_output(split_ycbcr_output)
918 {
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);
925         }
926
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);
930
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");
935 }
936
937 void Blend::exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, GLuint output2_tex, int level_width, int level_height, float alpha)
938 {
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);
943
944         glViewport(0, 0, level_width, level_height);
945         if (split_ycbcr_output) {
946                 fbos_split.render_to(output_tex, output2_tex);
947         } else {
948                 fbos.render_to(output_tex);
949         }
950         glDisable(GL_BLEND);  // A bit ironic, perhaps.
951         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
952 }
953
954 Interpolate::Interpolate(const OperatingPoint &op, bool split_ycbcr_output)
955         : flow_level(op.finest_level),
956           split_ycbcr_output(split_ycbcr_output),
957           splat(op),
958           blend(split_ycbcr_output) {
959         // Set up the vertex data that will be shared between all passes.
960         float vertices[] = {
961                 0.0f, 1.0f,
962                 0.0f, 0.0f,
963                 1.0f, 1.0f,
964                 1.0f, 0.0f,
965         };
966         glCreateBuffers(1, &vertex_vbo);
967         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
968
969         glCreateVertexArrays(1, &vao);
970         glBindVertexArray(vao);
971         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
972
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));
976 }
977
978 pair<GLuint, GLuint> Interpolate::exec(GLuint image_tex, GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha)
979 {
980         GPUTimers timers;
981
982         ScopedTimer total_timer("Interpolate", &timers);
983
984         glBindVertexArray(vao);
985         glDisable(GL_DITHER);
986
987         // Pick out the right level to test splatting results on.
988         GLuint tex_view;
989         glGenTextures(1, &tex_view);
990         glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, gray_tex, GL_R8, flow_level, 1, 0, 2);
991
992         int flow_width = width >> flow_level;
993         int flow_height = height >> flow_level;
994
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.
997
998         {
999                 ScopedTimer timer("Splat", &total_timer);
1000                 splat.exec(tex_view, bidirectional_flow_tex, flow_tex, depth_rb, flow_width, flow_height, alpha);
1001         }
1002         glDeleteTextures(1, &tex_view);
1003
1004         GLuint temp_tex[3];
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);
1008
1009         {
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);
1013         }
1014
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);
1019
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);
1024                 {
1025                         ScopedTimer timer("Blend", &total_timer);
1026                         blend.exec(image_tex, flow_tex, output_tex, output2_tex, width, height, alpha);
1027                 }
1028         } else {
1029                 output_tex = pool.get_texture(GL_RGBA8, width, height);
1030                 {
1031                         ScopedTimer timer("Blend", &total_timer);
1032                         blend.exec(image_tex, flow_tex, output_tex, 0, width, height, alpha);
1033                 }
1034         }
1035         pool.release_texture(flow_tex);
1036         total_timer.end();
1037         if (!in_warmup) {
1038                 timers.print();
1039         }
1040
1041         return make_pair(output_tex, output2_tex);
1042 }
1043
1044 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers)
1045 {
1046         {
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) {
1051                                 tex.in_use = true;
1052                                 return tex.tex_num;
1053                         }
1054                 }
1055         }
1056
1057         Texture tex;
1058         if (num_layers == 0) {
1059                 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1060                 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1061         } else {
1062                 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex.tex_num);
1063                 glTextureStorage3D(tex.tex_num, 1, format, width, height, num_layers);
1064         }
1065         tex.format = format;
1066         tex.width = width;
1067         tex.height = height;
1068         tex.num_layers = num_layers;
1069         tex.in_use = true;
1070         tex.is_renderbuffer = false;
1071         {
1072                 lock_guard<mutex> lock(mu);
1073                 textures.push_back(tex);
1074         }
1075         return tex.tex_num;
1076 }
1077
1078 GLuint TexturePool::get_renderbuffer(GLenum format, GLuint width, GLuint height)
1079 {
1080         {
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) {
1085                                 tex.in_use = true;
1086                                 return tex.tex_num;
1087                         }
1088                 }
1089         }
1090
1091         Texture tex;
1092         glCreateRenderbuffers(1, &tex.tex_num);
1093         glNamedRenderbufferStorage(tex.tex_num, format, width, height);
1094
1095         tex.format = format;
1096         tex.width = width;
1097         tex.height = height;
1098         tex.in_use = true;
1099         tex.is_renderbuffer = true;
1100         {
1101                 lock_guard<mutex> lock(mu);
1102                 textures.push_back(tex);
1103         }
1104         return tex.tex_num;
1105 }
1106
1107 void TexturePool::release_texture(GLuint tex_num)
1108 {
1109         lock_guard<mutex> lock(mu);
1110         for (Texture &tex : textures) {
1111                 if (!tex.is_renderbuffer && tex.tex_num == tex_num) {
1112                         assert(tex.in_use);
1113                         tex.in_use = false;
1114                         return;
1115                 }
1116         }
1117         assert(false);
1118 }
1119
1120 void TexturePool::release_renderbuffer(GLuint tex_num)
1121 {
1122         lock_guard<mutex> lock(mu);
1123         for (Texture &tex : textures) {
1124                 if (tex.is_renderbuffer && tex.tex_num == tex_num) {
1125                         assert(tex.in_use);
1126                         tex.in_use = false;
1127                         return;
1128                 }
1129         }
1130         //assert(false);
1131 }