]> git.sesse.net Git - nageru/blob - flow.cpp
Add a warmup option to get somewhat more consistent timings.
[nageru] / flow.cpp
1 #define NO_SDL_GLEXT 1
2
3 #include <epoxy/gl.h>
4
5 #include <SDL2/SDL.h>
6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
12
13 #include <assert.h>
14 #include <getopt.h>
15 #include <stdio.h>
16 #include <unistd.h>
17
18 #include "gpu_timers.h"
19 #include "util.h"
20
21 #include <algorithm>
22 #include <deque>
23 #include <memory>
24 #include <map>
25 #include <stack>
26 #include <vector>
27
28 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
29
30 using namespace std;
31
32 SDL_Window *window;
33
34 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
35 constexpr float patch_overlap_ratio = 0.75f;
36 constexpr unsigned coarsest_level = 5;
37 constexpr unsigned finest_level = 1;
38 constexpr unsigned patch_size_pixels = 12;
39
40 // Weighting constants for the different parts of the variational refinement.
41 // These don't correspond 1:1 to the values given in the DIS paper,
42 // since we have different normalizations and ranges in some cases.
43 // These are found through a simple grid search on some MPI-Sintel data,
44 // although the error (EPE) seems to be fairly insensitive to the precise values.
45 // Only the relative values matter, so we fix alpha (the smoothness constant)
46 // at unity and tweak the others.
47 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
48
49 bool enable_timing = true;
50 bool detailed_timing = false;
51 bool enable_warmup = false;
52 bool in_warmup = false;
53 bool enable_variational_refinement = true;  // Just for debugging.
54 bool enable_interpolation = false;
55
56 // Some global OpenGL objects.
57 // TODO: These should really be part of DISComputeFlow.
58 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
59 GLuint vertex_vbo;
60
61 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
62 struct ReadInProgress {
63         GLuint pbo;
64         string filename0, filename1;
65         string flow_filename, ppm_filename;  // Either may be empty for no write.
66 };
67 stack<GLuint> spare_pbos;
68 deque<ReadInProgress> reads_in_progress;
69
70 int find_num_levels(int width, int height)
71 {
72         int levels = 1;
73         for (int w = width, h = height; w > 1 || h > 1; ) {
74                 w >>= 1;
75                 h >>= 1;
76                 ++levels;
77         }
78         return levels;
79 }
80
81 string read_file(const string &filename)
82 {
83         FILE *fp = fopen(filename.c_str(), "r");
84         if (fp == nullptr) {
85                 perror(filename.c_str());
86                 exit(1);
87         }
88
89         int ret = fseek(fp, 0, SEEK_END);
90         if (ret == -1) {
91                 perror("fseek(SEEK_END)");
92                 exit(1);
93         }
94
95         int size = ftell(fp);
96
97         ret = fseek(fp, 0, SEEK_SET);
98         if (ret == -1) {
99                 perror("fseek(SEEK_SET)");
100                 exit(1);
101         }
102
103         string str;
104         str.resize(size);
105         ret = fread(&str[0], size, 1, fp);
106         if (ret == -1) {
107                 perror("fread");
108                 exit(1);
109         }
110         if (ret == 0) {
111                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
112                                 size, filename.c_str());
113                 exit(1);
114         }
115         fclose(fp);
116
117         return str;
118 }
119
120
121 GLuint compile_shader(const string &shader_src, GLenum type)
122 {
123         GLuint obj = glCreateShader(type);
124         const GLchar* source[] = { shader_src.data() };
125         const GLint length[] = { (GLint)shader_src.size() };
126         glShaderSource(obj, 1, source, length);
127         glCompileShader(obj);
128
129         GLchar info_log[4096];
130         GLsizei log_length = sizeof(info_log) - 1;
131         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
132         info_log[log_length] = 0;
133         if (strlen(info_log) > 0) {
134                 fprintf(stderr, "Shader compile log: %s\n", info_log);
135         }
136
137         GLint status;
138         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
139         if (status == GL_FALSE) {
140                 // Add some line numbers to easier identify compile errors.
141                 string src_with_lines = "/*   1 */ ";
142                 size_t lineno = 1;
143                 for (char ch : shader_src) {
144                         src_with_lines.push_back(ch);
145                         if (ch == '\n') {
146                                 char buf[32];
147                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
148                                 src_with_lines += buf;
149                         }
150                 }
151
152                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
153                 exit(1);
154         }
155
156         return obj;
157 }
158
159 enum MipmapPolicy {
160         WITHOUT_MIPMAPS,
161         WITH_MIPMAPS
162 };
163
164 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
165 {
166         SDL_Surface *surf = IMG_Load(filename);
167         if (surf == nullptr) {
168                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
169                 exit(1);
170         }
171
172         // For whatever reason, SDL doesn't support converting to YUV surfaces
173         // nor grayscale, so we'll do it ourselves.
174         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
175         if (rgb_surf == nullptr) {
176                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
177                 exit(1);
178         }
179
180         SDL_FreeSurface(surf);
181
182         unsigned width = rgb_surf->w, height = rgb_surf->h;
183         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
184         unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
185
186         // Extract the Y component, and convert to bottom-left origin.
187         for (unsigned y = 0; y < height; ++y) {
188                 unsigned y2 = height - 1 - y;
189                 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
190         }
191         SDL_FreeSurface(rgb_surf);
192
193         int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
194
195         GLuint tex;
196         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
197         glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
198         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
199
200         if (mipmaps == WITH_MIPMAPS) {
201                 glGenerateTextureMipmap(tex);
202         }
203
204         *width_ret = width;
205         *height_ret = height;
206
207         return tex;
208 }
209
210 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
211 {
212         GLuint program = glCreateProgram();
213         glAttachShader(program, vs_obj);
214         glAttachShader(program, fs_obj);
215         glLinkProgram(program);
216         GLint success;
217         glGetProgramiv(program, GL_LINK_STATUS, &success);
218         if (success == GL_FALSE) {
219                 GLchar error_log[1024] = {0};
220                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
221                 fprintf(stderr, "Error linking program: %s\n", error_log);
222                 exit(1);
223         }
224         return program;
225 }
226
227 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
228 {
229         if (location == -1) {
230                 return;
231         }
232
233         glBindTextureUnit(texture_unit, tex);
234         glBindSampler(texture_unit, sampler);
235         glProgramUniform1i(program, location, texture_unit);
236 }
237
238 // A class that caches FBOs that render to a given set of textures.
239 // It never frees anything, so it is only suitable for rendering to
240 // the same (small) set of textures over and over again.
241 template<size_t num_elements>
242 class PersistentFBOSet {
243 public:
244         void render_to(const array<GLuint, num_elements> &textures);
245
246         // Convenience wrappers.
247         void render_to(GLuint texture0) {
248                 render_to({{texture0}});
249         }
250
251         void render_to(GLuint texture0, GLuint texture1) {
252                 render_to({{texture0, texture1}});
253         }
254
255         void render_to(GLuint texture0, GLuint texture1, GLuint texture2) {
256                 render_to({{texture0, texture1, texture2}});
257         }
258
259         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
260                 render_to({{texture0, texture1, texture2, texture3}});
261         }
262
263 private:
264         // TODO: Delete these on destruction.
265         map<array<GLuint, num_elements>, GLuint> fbos;
266 };
267
268 template<size_t num_elements>
269 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
270 {
271         auto it = fbos.find(textures);
272         if (it != fbos.end()) {
273                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
274                 return;
275         }
276
277         GLuint fbo;
278         glCreateFramebuffers(1, &fbo);
279         GLenum bufs[num_elements];
280         for (size_t i = 0; i < num_elements; ++i) {
281                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
282                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
283         }
284         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
285
286         fbos[textures] = fbo;
287         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
288 }
289
290 // Same, but with a depth texture.
291 template<size_t num_elements>
292 class PersistentFBOSetWithDepth {
293 public:
294         void render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures);
295
296         // Convenience wrappers.
297         void render_to(GLuint depth_tex, GLuint texture0) {
298                 render_to(depth_tex, {{texture0}});
299         }
300
301         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1) {
302                 render_to(depth_tex, {{texture0, texture1}});
303         }
304
305         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2) {
306                 render_to(depth_tex, {{texture0, texture1, texture2}});
307         }
308
309         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
310                 render_to(depth_tex, {{texture0, texture1, texture2, texture3}});
311         }
312
313 private:
314         // TODO: Delete these on destruction.
315         map<pair<GLuint, array<GLuint, num_elements>>, GLuint> fbos;
316 };
317
318 template<size_t num_elements>
319 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures)
320 {
321         auto key = make_pair(depth_tex, textures);
322
323         auto it = fbos.find(key);
324         if (it != fbos.end()) {
325                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
326                 return;
327         }
328
329         GLuint fbo;
330         glCreateFramebuffers(1, &fbo);
331         GLenum bufs[num_elements];
332         glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
333         for (size_t i = 0; i < num_elements; ++i) {
334                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
335                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
336         }
337         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
338
339         fbos[key] = fbo;
340         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
341 }
342
343 // Convert RGB to grayscale, using Rec. 709 coefficients.
344 class GrayscaleConversion {
345 public:
346         GrayscaleConversion();
347         void exec(GLint tex, GLint gray_tex, int width, int height);
348
349 private:
350         PersistentFBOSet<1> fbos;
351         GLuint gray_vs_obj;
352         GLuint gray_fs_obj;
353         GLuint gray_program;
354         GLuint gray_vao;
355
356         GLuint uniform_tex;
357 };
358
359 GrayscaleConversion::GrayscaleConversion()
360 {
361         gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
362         gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
363         gray_program = link_program(gray_vs_obj, gray_fs_obj);
364
365         // Set up the VAO containing all the required position/texcoord data.
366         glCreateVertexArrays(1, &gray_vao);
367         glBindVertexArray(gray_vao);
368
369         GLint position_attrib = glGetAttribLocation(gray_program, "position");
370         glEnableVertexArrayAttrib(gray_vao, position_attrib);
371         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
372
373         uniform_tex = glGetUniformLocation(gray_program, "tex");
374 }
375
376 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
377 {
378         glUseProgram(gray_program);
379         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
380
381         glViewport(0, 0, width, height);
382         fbos.render_to(gray_tex);
383         glBindVertexArray(gray_vao);
384         glDisable(GL_BLEND);
385         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
386 }
387
388 // Compute gradients in every point, used for the motion search.
389 // The DIS paper doesn't actually mention how these are computed,
390 // but seemingly, a 3x3 Sobel operator is used here (at least in
391 // later versions of the code), while a [1 -8 0 8 -1] kernel is
392 // used for all the derivatives in the variational refinement part
393 // (which borrows code from DeepFlow). This is inconsistent,
394 // but I guess we're better off with staying with the original
395 // decisions until we actually know having different ones would be better.
396 class Sobel {
397 public:
398         Sobel();
399         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
400
401 private:
402         PersistentFBOSet<1> fbos;
403         GLuint sobel_vs_obj;
404         GLuint sobel_fs_obj;
405         GLuint sobel_program;
406
407         GLuint uniform_tex;
408 };
409
410 Sobel::Sobel()
411 {
412         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
413         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
414         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
415
416         uniform_tex = glGetUniformLocation(sobel_program, "tex");
417 }
418
419 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
420 {
421         glUseProgram(sobel_program);
422         bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
423
424         glViewport(0, 0, level_width, level_height);
425         fbos.render_to(grad0_tex);
426         glDisable(GL_BLEND);
427         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
428 }
429
430 // Motion search to find the initial flow. See motion_search.frag for documentation.
431 class MotionSearch {
432 public:
433         MotionSearch();
434         void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
435
436 private:
437         PersistentFBOSet<1> fbos;
438
439         GLuint motion_vs_obj;
440         GLuint motion_fs_obj;
441         GLuint motion_search_program;
442
443         GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
444         GLuint uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
445 };
446
447 MotionSearch::MotionSearch()
448 {
449         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
450         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
451         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
452
453         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
454         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
455         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
456         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
457         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
458 }
459
460 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
461 {
462         glUseProgram(motion_search_program);
463
464         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
465         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
466         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
467
468         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
469         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
470
471         glViewport(0, 0, width_patches, height_patches);
472         fbos.render_to(flow_out_tex);
473         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
474 }
475
476 // Do “densification”, ie., upsampling of the flow patches to the flow field
477 // (the same size as the image at this level). We draw one quad per patch
478 // over its entire covered area (using instancing in the vertex shader),
479 // and then weight the contributions in the pixel shader by post-warp difference.
480 // This is equation (3) in the paper.
481 //
482 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
483 // weight in the B channel. Dividing R and G by B gives the normalized values.
484 class Densify {
485 public:
486         Densify();
487         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
488
489 private:
490         PersistentFBOSet<1> fbos;
491
492         GLuint densify_vs_obj;
493         GLuint densify_fs_obj;
494         GLuint densify_program;
495
496         GLuint uniform_patch_size;
497         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
498 };
499
500 Densify::Densify()
501 {
502         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
503         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
504         densify_program = link_program(densify_vs_obj, densify_fs_obj);
505
506         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
507         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
508         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
509         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
510 }
511
512 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
513 {
514         glUseProgram(densify_program);
515
516         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
517         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
518         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
519
520         glProgramUniform2f(densify_program, uniform_patch_size,
521                 float(patch_size_pixels) / level_width,
522                 float(patch_size_pixels) / level_height);
523
524         glViewport(0, 0, level_width, level_height);
525         glEnable(GL_BLEND);
526         glBlendFunc(GL_ONE, GL_ONE);
527         fbos.render_to(dense_flow_tex);
528         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
529         glClear(GL_COLOR_BUFFER_BIT);
530         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
531 }
532
533 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
534 // I_0 and I_w. The prewarping is what enables us to solve the variational
535 // flow for du,dv instead of u,v.
536 //
537 // Also calculates the normalized flow, ie. divides by z (this is needed because
538 // Densify works by additive blending) and multiplies by the image size.
539 //
540 // See variational_refinement.txt for more information.
541 class Prewarp {
542 public:
543         Prewarp();
544         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
545
546 private:
547         PersistentFBOSet<3> fbos;
548
549         GLuint prewarp_vs_obj;
550         GLuint prewarp_fs_obj;
551         GLuint prewarp_program;
552
553         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
554 };
555
556 Prewarp::Prewarp()
557 {
558         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
559         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
560         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
561
562         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
563         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
564         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
565 }
566
567 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
568 {
569         glUseProgram(prewarp_program);
570
571         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
572         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
573         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
574
575         glViewport(0, 0, level_width, level_height);
576         glDisable(GL_BLEND);
577         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
578         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
579 }
580
581 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
582 // central difference filter, since apparently, that's tradition (I haven't
583 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
584 // The coefficients come from
585 //
586 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
587 //
588 // Also computes β_0, since it depends only on I_x and I_y.
589 class Derivatives {
590 public:
591         Derivatives();
592         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
593
594 private:
595         PersistentFBOSet<2> fbos;
596
597         GLuint derivatives_vs_obj;
598         GLuint derivatives_fs_obj;
599         GLuint derivatives_program;
600
601         GLuint uniform_tex;
602 };
603
604 Derivatives::Derivatives()
605 {
606         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
607         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
608         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
609
610         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
611 }
612
613 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
614 {
615         glUseProgram(derivatives_program);
616
617         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
618
619         glViewport(0, 0, level_width, level_height);
620         glDisable(GL_BLEND);
621         fbos.render_to(I_x_y_tex, beta_0_tex);
622         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
623 }
624
625 // Calculate the diffusivity for each pixels, g(x,y). Smoothness (s) will
626 // be calculated in the shaders on-the-fly by sampling in-between two
627 // neighboring g(x,y) pixels, plus a border tweak to make sure we get
628 // zero smoothness at the border.
629 //
630 // See variational_refinement.txt for more information.
631 class ComputeDiffusivity {
632 public:
633         ComputeDiffusivity();
634         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow);
635
636 private:
637         PersistentFBOSet<1> fbos;
638
639         GLuint diffusivity_vs_obj;
640         GLuint diffusivity_fs_obj;
641         GLuint diffusivity_program;
642
643         GLuint uniform_flow_tex, uniform_diff_flow_tex;
644         GLuint uniform_alpha, uniform_zero_diff_flow;
645 };
646
647 ComputeDiffusivity::ComputeDiffusivity()
648 {
649         diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
650         diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
651         diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
652
653         uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
654         uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
655         uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
656         uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
657 }
658
659 void ComputeDiffusivity::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow)
660 {
661         glUseProgram(diffusivity_program);
662
663         bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
664         bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
665         glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
666         glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
667
668         glViewport(0, 0, level_width, level_height);
669
670         glDisable(GL_BLEND);
671         fbos.render_to(diffusivity_tex);
672         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
673 }
674
675 // Set up the equations set (two equations in two unknowns, per pixel).
676 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
677 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
678 // floats. (Actually, we store the inverse of the diagonal elements, because
679 // we only ever need to divide by them.) This fits into four u32 values;
680 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
681 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
682 // terms that depend on other pixels, are calculated in one pass.
683 //
684 // The equation set is split in two; one contains only the pixels needed for
685 // the red pass, and one only for the black pass (see sor.frag). This reduces
686 // the amount of data the SOR shader has to pull in, at the cost of some
687 // complexity when the equation texture ends up with half the size and we need
688 // to adjust texture coordinates.  The contraction is done along the horizontal
689 // axis, so that on even rows (0, 2, 4, ...), the “red” texture will contain
690 // pixels 0, 2, 4, 6, etc., and on odd rows 1, 3, 5, etc..
691 //
692 // See variational_refinement.txt for more information about the actual
693 // equations in use.
694 class SetupEquations {
695 public:
696         SetupEquations();
697         void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint 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);
698
699 private:
700         PersistentFBOSet<2> fbos;
701
702         GLuint equations_vs_obj;
703         GLuint equations_fs_obj;
704         GLuint equations_program;
705
706         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
707         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
708         GLuint uniform_beta_0_tex;
709         GLuint uniform_diffusivity_tex;
710         GLuint uniform_gamma, uniform_delta, uniform_zero_diff_flow;
711 };
712
713 SetupEquations::SetupEquations()
714 {
715         equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
716         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
717         equations_program = link_program(equations_vs_obj, equations_fs_obj);
718
719         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
720         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
721         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
722         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
723         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
724         uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
725         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
726         uniform_delta = glGetUniformLocation(equations_program, "delta");
727         uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
728 }
729
730 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)
731 {
732         glUseProgram(equations_program);
733
734         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
735         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
736         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
737         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
738         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
739         bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
740         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
741         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
742         glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
743
744         glViewport(0, 0, (level_width + 1) / 2, level_height);
745         glDisable(GL_BLEND);
746         fbos.render_to({equation_red_tex, equation_black_tex});
747         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
748 }
749
750 // Actually solve the equation sets made by SetupEquations, by means of
751 // successive over-relaxation (SOR).
752 //
753 // See variational_refinement.txt for more information.
754 class SOR {
755 public:
756         SOR();
757         void 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, ScopedTimer *sor_timer);
758
759 private:
760         PersistentFBOSet<1> fbos;
761
762         GLuint sor_vs_obj;
763         GLuint sor_fs_obj;
764         GLuint sor_program;
765
766         GLuint uniform_diff_flow_tex;
767         GLuint uniform_equation_red_tex, uniform_equation_black_tex;
768         GLuint uniform_diffusivity_tex;
769         GLuint uniform_phase, uniform_num_nonzero_phases;
770 };
771
772 SOR::SOR()
773 {
774         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
775         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
776         sor_program = link_program(sor_vs_obj, sor_fs_obj);
777
778         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
779         uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
780         uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
781         uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
782         uniform_phase = glGetUniformLocation(sor_program, "phase");
783         uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
784 }
785
786 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, ScopedTimer *sor_timer)
787 {
788         glUseProgram(sor_program);
789
790         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
791         bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
792         bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
793         bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
794
795         if (!zero_diff_flow) {
796                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
797         }
798
799         // NOTE: We bind to the texture we are rendering from, but we never write any value
800         // that we read in the same shader pass (we call discard for red values when we compute
801         // black, and vice versa), and we have barriers between the passes, so we're fine
802         // as per the spec.
803         glViewport(0, 0, level_width, level_height);
804         glDisable(GL_BLEND);
805         fbos.render_to(diff_flow_tex);
806
807         for (int i = 0; i < num_iterations; ++i) {
808                 {
809                         ScopedTimer timer("Red pass", sor_timer);
810                         if (zero_diff_flow && i == 0) {
811                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
812                         }
813                         glProgramUniform1i(sor_program, uniform_phase, 0);
814                         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
815                         glTextureBarrier();
816                 }
817                 {
818                         ScopedTimer timer("Black pass", sor_timer);
819                         if (zero_diff_flow && i == 0) {
820                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
821                         }
822                         glProgramUniform1i(sor_program, uniform_phase, 1);
823                         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
824                         if (zero_diff_flow && i == 0) {
825                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
826                         }
827                         if (i != num_iterations - 1) {
828                                 glTextureBarrier();
829                         }
830                 }
831         }
832 }
833
834 // Simply add the differential flow found by the variational refinement to the base flow.
835 // The output is in base_flow_tex; we don't need to make a new texture.
836 class AddBaseFlow {
837 public:
838         AddBaseFlow();
839         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
840
841 private:
842         PersistentFBOSet<1> fbos;
843
844         GLuint add_flow_vs_obj;
845         GLuint add_flow_fs_obj;
846         GLuint add_flow_program;
847
848         GLuint uniform_diff_flow_tex;
849 };
850
851 AddBaseFlow::AddBaseFlow()
852 {
853         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
854         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
855         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
856
857         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
858 }
859
860 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
861 {
862         glUseProgram(add_flow_program);
863
864         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
865
866         glViewport(0, 0, level_width, level_height);
867         glEnable(GL_BLEND);
868         glBlendFunc(GL_ONE, GL_ONE);
869         fbos.render_to(base_flow_tex);
870
871         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
872 }
873
874 // Take a copy of the flow, bilinearly interpolated and scaled up.
875 class ResizeFlow {
876 public:
877         ResizeFlow();
878         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
879
880 private:
881         PersistentFBOSet<1> fbos;
882
883         GLuint resize_flow_vs_obj;
884         GLuint resize_flow_fs_obj;
885         GLuint resize_flow_program;
886
887         GLuint uniform_flow_tex;
888         GLuint uniform_scale_factor;
889 };
890
891 ResizeFlow::ResizeFlow()
892 {
893         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
894         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
895         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
896
897         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
898         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
899 }
900
901 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
902 {
903         glUseProgram(resize_flow_program);
904
905         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
906
907         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
908
909         glViewport(0, 0, output_width, output_height);
910         glDisable(GL_BLEND);
911         fbos.render_to(out_tex);
912
913         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
914 }
915
916 class TexturePool {
917 public:
918         GLuint get_texture(GLenum format, GLuint width, GLuint height);
919         void release_texture(GLuint tex_num);
920
921 private:
922         struct Texture {
923                 GLuint tex_num;
924                 GLenum format;
925                 GLuint width, height;
926                 bool in_use = false;
927         };
928         vector<Texture> textures;
929 };
930
931 class DISComputeFlow {
932 public:
933         DISComputeFlow(int width, int height);
934
935         enum ResizeStrategy {
936                 DO_NOT_RESIZE_FLOW,
937                 RESIZE_FLOW_TO_FULL_SIZE
938         };
939
940         // Returns a texture that must be released with release_texture()
941         // after use.
942         GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
943
944         void release_texture(GLuint tex) {
945                 pool.release_texture(tex);
946         }
947
948 private:
949         int width, height;
950         GLuint initial_flow_tex;
951         GLuint vertex_vbo, vao;
952         TexturePool pool;
953
954         // The various passes.
955         Sobel sobel;
956         MotionSearch motion_search;
957         Densify densify;
958         Prewarp prewarp;
959         Derivatives derivatives;
960         ComputeDiffusivity compute_diffusivity;
961         SetupEquations setup_equations;
962         SOR sor;
963         AddBaseFlow add_base_flow;
964         ResizeFlow resize_flow;
965 };
966
967 DISComputeFlow::DISComputeFlow(int width, int height)
968         : width(width), height(height)
969 {
970         // Make some samplers.
971         glCreateSamplers(1, &nearest_sampler);
972         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
973         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
974         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
975         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
976
977         glCreateSamplers(1, &linear_sampler);
978         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
979         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
980         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
981         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
982
983         // The smoothness is sampled so that once we get to a smoothness involving
984         // a value outside the border, the diffusivity between the two becomes zero.
985         // Similarly, gradients are zero outside the border, since the edge is taken
986         // to be constant.
987         glCreateSamplers(1, &zero_border_sampler);
988         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
989         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
990         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
991         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
992         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.
993         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
994
995         // Initial flow is zero, 1x1.
996         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
997         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
998         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
999
1000         // Set up the vertex data that will be shared between all passes.
1001         float vertices[] = {
1002                 0.0f, 1.0f,
1003                 0.0f, 0.0f,
1004                 1.0f, 1.0f,
1005                 1.0f, 0.0f,
1006         };
1007         glCreateBuffers(1, &vertex_vbo);
1008         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1009
1010         glCreateVertexArrays(1, &vao);
1011         glBindVertexArray(vao);
1012         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1013
1014         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
1015         glEnableVertexArrayAttrib(vao, position_attrib);
1016         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1017 }
1018
1019 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1020 {
1021         int prev_level_width = 1, prev_level_height = 1;
1022         GLuint prev_level_flow_tex = initial_flow_tex;
1023
1024         GPUTimers timers;
1025
1026         glBindVertexArray(vao);
1027
1028         ScopedTimer total_timer("Total", &timers);
1029         for (int level = coarsest_level; level >= int(finest_level); --level) {
1030                 char timer_name[256];
1031                 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
1032                 ScopedTimer level_timer(timer_name, &total_timer);
1033
1034                 int level_width = width >> level;
1035                 int level_height = height >> level;
1036                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1037
1038                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1039                 // and patch_spacing=3 (the default), we put out patch centers in
1040                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1041                 // lock all the centers to integer coordinates if needed.
1042                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1043                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1044
1045                 // Make sure we always read from the correct level; the chosen
1046                 // mipmapping could otherwise be rather unpredictable, especially
1047                 // during motion search.
1048                 GLuint tex0_view, tex1_view;
1049                 glGenTextures(1, &tex0_view);
1050                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1051                 glGenTextures(1, &tex1_view);
1052                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1053
1054                 // Create a new texture; we could be fancy and render use a multi-level
1055                 // texture, but meh.
1056                 GLuint grad0_tex = pool.get_texture(GL_R32UI, level_width, level_height);
1057
1058                 // Find the derivative.
1059                 {
1060                         ScopedTimer timer("Sobel", &level_timer);
1061                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1062                 }
1063
1064                 // Motion search to find the initial flow. We use the flow from the previous
1065                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1066
1067                 // Create an output flow texture.
1068                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1069
1070                 // And draw.
1071                 {
1072                         ScopedTimer timer("Motion search", &level_timer);
1073                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1074                 }
1075                 pool.release_texture(grad0_tex);
1076
1077                 // Densification.
1078
1079                 // Set up an output texture (cleared in Densify).
1080                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1081
1082                 // And draw.
1083                 {
1084                         ScopedTimer timer("Densification", &level_timer);
1085                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1086                 }
1087                 pool.release_texture(flow_out_tex);
1088
1089                 // Everything below here in the loop belongs to variational refinement.
1090                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1091
1092                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1093                 // have to normalize it over and over again, and also save some bandwidth).
1094                 //
1095                 // During the entire rest of the variational refinement, flow will be measured
1096                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1097                 // This is because variational refinement depends so heavily on derivatives,
1098                 // which are measured in intensity levels per pixel.
1099                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1100                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1101                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1102                 {
1103                         ScopedTimer timer("Prewarping", &varref_timer);
1104                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1105                 }
1106                 pool.release_texture(dense_flow_tex);
1107                 glDeleteTextures(1, &tex0_view);
1108                 glDeleteTextures(1, &tex1_view);
1109
1110                 // Calculate I_x and I_y. We're only calculating first derivatives;
1111                 // the others will be taken on-the-fly in order to sample from fewer
1112                 // textures overall, since sampling from the L1 cache is cheap.
1113                 // (TODO: Verify that this is indeed faster than making separate
1114                 // double-derivative textures.)
1115                 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1116                 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1117                 {
1118                         ScopedTimer timer("First derivatives", &varref_timer);
1119                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1120                 }
1121                 pool.release_texture(I_tex);
1122
1123                 // We need somewhere to store du and dv (the flow increment, relative
1124                 // to the non-refined base flow u0 and v0). It's initially garbage,
1125                 // but not read until we've written something sane to it.
1126                 GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1127
1128                 // And for diffusivity.
1129                 GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height);
1130
1131                 // And finally for the equation set. See SetupEquations for
1132                 // the storage format.
1133                 GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height);
1134                 GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height);
1135
1136                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1137                         // Calculate the diffusivity term for each pixel.
1138                         {
1139                                 ScopedTimer timer("Compute diffusivity", &varref_timer);
1140                                 compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0);
1141                         }
1142
1143                         // Set up the 2x2 equation system for each pixel.
1144                         {
1145                                 ScopedTimer timer("Set up equations", &varref_timer);
1146                                 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);
1147                         }
1148
1149                         // Run a few SOR iterations. Note that these are to/from the same texture.
1150                         {
1151                                 ScopedTimer timer("SOR", &varref_timer);
1152                                 sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, &timer);
1153                         }
1154                 }
1155
1156                 pool.release_texture(I_t_tex);
1157                 pool.release_texture(I_x_y_tex);
1158                 pool.release_texture(beta_0_tex);
1159                 pool.release_texture(diffusivity_tex);
1160                 pool.release_texture(equation_red_tex);
1161                 pool.release_texture(equation_black_tex);
1162
1163                 // Add the differential flow found by the variational refinement to the base flow,
1164                 // giving the final flow estimate for this level.
1165                 // The output is in diff_flow_tex; we don't need to make a new texture.
1166                 //
1167                 // Disabling this doesn't save any time (although we could easily make it so that
1168                 // it is more efficient), but it helps debug the motion search.
1169                 if (enable_variational_refinement) {
1170                         ScopedTimer timer("Add differential flow", &varref_timer);
1171                         add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height);
1172                 }
1173                 pool.release_texture(diff_flow_tex);
1174
1175                 if (prev_level_flow_tex != initial_flow_tex) {
1176                         pool.release_texture(prev_level_flow_tex);
1177                 }
1178                 prev_level_flow_tex = base_flow_tex;
1179                 prev_level_width = level_width;
1180                 prev_level_height = level_height;
1181         }
1182         total_timer.end();
1183
1184         if (!in_warmup) {
1185                 timers.print();
1186         }
1187
1188         // Scale up the flow to the final size (if needed).
1189         if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1190                 return prev_level_flow_tex;
1191         } else {
1192                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1193                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1194                 pool.release_texture(prev_level_flow_tex);
1195                 return final_tex;
1196         }
1197 }
1198
1199 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1200 // radius fills most of the holes.
1201 class Splat {
1202 public:
1203         Splat();
1204
1205         // alpha is the time of the interpolated frame (0..1).
1206         void exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha);
1207
1208 private:
1209         PersistentFBOSetWithDepth<1> fbos;
1210
1211         GLuint splat_vs_obj;
1212         GLuint splat_fs_obj;
1213         GLuint splat_program;
1214
1215         GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1216         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1217         GLuint uniform_inv_flow_size;
1218 };
1219
1220 Splat::Splat()
1221 {
1222         splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1223         splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1224         splat_program = link_program(splat_vs_obj, splat_fs_obj);
1225
1226         uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1227         uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1228         uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1229         uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1230         uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1231         uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1232         uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1233 }
1234
1235 void Splat::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha)
1236 {
1237         glUseProgram(splat_program);
1238
1239         bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1240         bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1241
1242         // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1243         // Move to 2.0 later, or even 4.0.
1244         // (Since we have hole filling, it's not critical, but larger values seem to do
1245         // better than hole filling for large motion, blurs etc.)
1246         float splat_size = 1.0f;  // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1247         glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1248         glProgramUniform1f(splat_program, uniform_alpha, alpha);
1249         glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1250
1251         glViewport(0, 0, width, height);
1252         glDisable(GL_BLEND);
1253         glEnable(GL_DEPTH_TEST);
1254         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.)
1255
1256         fbos.render_to(depth_tex, flow_tex);
1257
1258         // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
1259         // we've got it bound.
1260         glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f);  // Invalid flow.
1261         glClearDepth(1.0f);  // Effectively infinity.
1262         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1263
1264         // Do forward splatting.
1265         bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1266         glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1267         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1268
1269         // Do backward splatting.
1270         bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1271         glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1272         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1273
1274         glDisable(GL_DEPTH_TEST);
1275 }
1276
1277 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1278 // that's fairly simple (given that most holes are really small) and also hopefully
1279 // cheap should the holes not be so small. Conceptually, we look for the first
1280 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1281 // the first non-hole to the right of us, then up and down, and then average them
1282 // all together. It's going to create “stars” if the holes are big, but OK, that's
1283 // a tradeoff.
1284 //
1285 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1286 // on even for shaders that do discard (this typically kills early Z, but hopefully
1287 // not hierarchical Z); we set up Z so that only holes are written to, which means
1288 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1289 // fullscreen quads should just be discarded outright, really.
1290 class HoleFill {
1291 public:
1292         HoleFill();
1293
1294         // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1295         // from the down, left, right and up, respectively. Use HoleBlend to merge
1296         // them into one.
1297         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1298
1299 private:
1300         PersistentFBOSetWithDepth<1> fbos;
1301
1302         GLuint fill_vs_obj;
1303         GLuint fill_fs_obj;
1304         GLuint fill_program;
1305
1306         GLuint uniform_tex;
1307         GLuint uniform_z, uniform_sample_offset;
1308 };
1309
1310 HoleFill::HoleFill()
1311 {
1312         fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1313         fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1314         fill_program = link_program(fill_vs_obj, fill_fs_obj);
1315
1316         uniform_tex = glGetUniformLocation(fill_program, "tex");
1317         uniform_z = glGetUniformLocation(fill_program, "z");
1318         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1319 }
1320
1321 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1322 {
1323         glUseProgram(fill_program);
1324
1325         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1326
1327         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1328
1329         glViewport(0, 0, width, height);
1330         glDisable(GL_BLEND);
1331         glEnable(GL_DEPTH_TEST);
1332         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
1333
1334         fbos.render_to(depth_tex, flow_tex);  // NOTE: Reading and writing to the same texture.
1335
1336         // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1337         for (int offs = 1; offs < width; offs *= 2) {
1338                 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1339                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1340                 glTextureBarrier();
1341         }
1342         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1343
1344         // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1345         // were overwritten in the last algorithm.
1346         glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1347         for (int offs = 1; offs < width; offs *= 2) {
1348                 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1349                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1350                 glTextureBarrier();
1351         }
1352         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1353
1354         // Up.
1355         glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1356         for (int offs = 1; offs < height; offs *= 2) {
1357                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1358                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1359                 glTextureBarrier();
1360         }
1361         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1362
1363         // Down.
1364         glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1365         for (int offs = 1; offs < height; offs *= 2) {
1366                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1367                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1368                 glTextureBarrier();
1369         }
1370
1371         glDisable(GL_DEPTH_TEST);
1372 }
1373
1374 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1375 // holes become the average of their four neighbors.
1376 class HoleBlend {
1377 public:
1378         HoleBlend();
1379
1380         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1381
1382 private:
1383         PersistentFBOSetWithDepth<1> fbos;
1384
1385         GLuint blend_vs_obj;
1386         GLuint blend_fs_obj;
1387         GLuint blend_program;
1388
1389         GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1390         GLuint uniform_z, uniform_sample_offset;
1391 };
1392
1393 HoleBlend::HoleBlend()
1394 {
1395         blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);  // Reuse the vertex shader from the fill.
1396         blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1397         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1398
1399         uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1400         uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1401         uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1402         uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1403         uniform_z = glGetUniformLocation(blend_program, "z");
1404         uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1405 }
1406
1407 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1408 {
1409         glUseProgram(blend_program);
1410
1411         bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1412         bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1413         bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1414         bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1415
1416         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1417         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1418
1419         glViewport(0, 0, width, height);
1420         glDisable(GL_BLEND);
1421         glEnable(GL_DEPTH_TEST);
1422         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
1423
1424         fbos.render_to(depth_tex, flow_tex);  // NOTE: Reading and writing to the same texture.
1425
1426         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1427
1428         glDisable(GL_DEPTH_TEST);
1429 }
1430
1431 class Blend {
1432 public:
1433         Blend();
1434         void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1435
1436 private:
1437         PersistentFBOSet<1> fbos;
1438         GLuint blend_vs_obj;
1439         GLuint blend_fs_obj;
1440         GLuint blend_program;
1441
1442         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1443         GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1444 };
1445
1446 Blend::Blend()
1447 {
1448         blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1449         blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1450         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1451
1452         uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1453         uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1454         uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1455         uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1456         uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1457 }
1458
1459 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1460 {
1461         glUseProgram(blend_program);
1462         bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1463         bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1464         bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler);  // May be upsampled.
1465         glProgramUniform1f(blend_program, uniform_alpha, alpha);
1466
1467         glViewport(0, 0, level_width, level_height);
1468         fbos.render_to(output_tex);
1469         glDisable(GL_BLEND);  // A bit ironic, perhaps.
1470         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1471 }
1472
1473 class Interpolate {
1474 public:
1475         Interpolate(int width, int height, int flow_level);
1476
1477         // Returns a texture that must be released with release_texture()
1478         // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1479         // (unless flow_level == 0).
1480         GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1481
1482         void release_texture(GLuint tex) {
1483                 pool.release_texture(tex);
1484         }
1485
1486 private:
1487         int width, height, flow_level;
1488         GLuint vertex_vbo, vao;
1489         TexturePool pool;
1490
1491         Splat splat;
1492         HoleFill hole_fill;
1493         HoleBlend hole_blend;
1494         Blend blend;
1495 };
1496
1497 Interpolate::Interpolate(int width, int height, int flow_level)
1498         : width(width), height(height), flow_level(flow_level) {
1499         // Set up the vertex data that will be shared between all passes.
1500         float vertices[] = {
1501                 0.0f, 1.0f,
1502                 0.0f, 0.0f,
1503                 1.0f, 1.0f,
1504                 1.0f, 0.0f,
1505         };
1506         glCreateBuffers(1, &vertex_vbo);
1507         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1508
1509         glCreateVertexArrays(1, &vao);
1510         glBindVertexArray(vao);
1511         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1512
1513         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
1514         glEnableVertexArrayAttrib(vao, position_attrib);
1515         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1516 }
1517
1518 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1519 {
1520         GPUTimers timers;
1521
1522         ScopedTimer total_timer("Total", &timers);
1523
1524         glBindVertexArray(vao);
1525
1526         // Pick out the right level to test splatting results on.
1527         GLuint tex0_view, tex1_view;
1528         glGenTextures(1, &tex0_view);
1529         glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1530         glGenTextures(1, &tex1_view);
1531         glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1532
1533         int flow_width = width >> flow_level;
1534         int flow_height = height >> flow_level;
1535
1536         GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1537         GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height);  // Used for ranking flows.
1538
1539         {
1540                 ScopedTimer timer("Splat", &total_timer);
1541                 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1542         }
1543         glDeleteTextures(1, &tex0_view);
1544         glDeleteTextures(1, &tex1_view);
1545
1546         GLuint temp_tex[3];
1547         temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1548         temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1549         temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1550
1551         {
1552                 ScopedTimer timer("Fill holes", &total_timer);
1553                 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1554                 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1555         }
1556
1557         pool.release_texture(temp_tex[0]);
1558         pool.release_texture(temp_tex[1]);
1559         pool.release_texture(temp_tex[2]);
1560         pool.release_texture(depth_tex);
1561
1562         GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1563         {
1564                 ScopedTimer timer("Blend", &total_timer);
1565                 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1566         }
1567         pool.release_texture(flow_tex);
1568         total_timer.end();
1569         if (!in_warmup) {
1570                 timers.print();
1571         }
1572
1573         return output_tex;
1574 }
1575
1576 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1577 {
1578         for (Texture &tex : textures) {
1579                 if (!tex.in_use && tex.format == format &&
1580                     tex.width == width && tex.height == height) {
1581                         tex.in_use = true;
1582                         return tex.tex_num;
1583                 }
1584         }
1585
1586         Texture tex;
1587         glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1588         glTextureStorage2D(tex.tex_num, 1, format, width, height);
1589         tex.format = format;
1590         tex.width = width;
1591         tex.height = height;
1592         tex.in_use = true;
1593         textures.push_back(tex);
1594         return tex.tex_num;
1595 }
1596
1597 void TexturePool::release_texture(GLuint tex_num)
1598 {
1599         for (Texture &tex : textures) {
1600                 if (tex.tex_num == tex_num) {
1601                         assert(tex.in_use);
1602                         tex.in_use = false;
1603                         return;
1604                 }
1605         }
1606         assert(false);
1607 }
1608
1609 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1610 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1611 {
1612         for (unsigned i = 0; i < width * height; ++i) {
1613                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1614         }
1615 }
1616
1617 // Not relevant for RGB.
1618 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1619 {
1620 }
1621
1622 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1623 {
1624         FILE *flowfp = fopen(filename, "wb");
1625         fprintf(flowfp, "FEIH");
1626         fwrite(&width, 4, 1, flowfp);
1627         fwrite(&height, 4, 1, flowfp);
1628         for (unsigned y = 0; y < height; ++y) {
1629                 int yy = height - y - 1;
1630                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1631         }
1632         fclose(flowfp);
1633 }
1634
1635 // Not relevant for RGB.
1636 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1637 {
1638         assert(false);
1639 }
1640
1641 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1642 {
1643         FILE *fp = fopen(filename, "wb");
1644         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1645         for (unsigned y = 0; y < unsigned(height); ++y) {
1646                 int yy = height - y - 1;
1647                 for (unsigned x = 0; x < unsigned(width); ++x) {
1648                         float du = dense_flow[(yy * width + x) * 2 + 0];
1649                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1650
1651                         uint8_t r, g, b;
1652                         flow2rgb(du, dv, &r, &g, &b);
1653                         putc(r, fp);
1654                         putc(g, fp);
1655                         putc(b, fp);
1656                 }
1657         }
1658         fclose(fp);
1659 }
1660
1661 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1662 {
1663         unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1664
1665         FILE *fp = fopen(filename, "wb");
1666         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1667         for (unsigned y = 0; y < height; ++y) {
1668                 unsigned y2 = height - 1 - y;
1669                 for (size_t x = 0; x < width; ++x) {
1670                         memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1671                 }
1672                 fwrite(rgb_line.get(), width * 3, 1, fp);
1673         }
1674         fclose(fp);
1675 }
1676
1677 struct FlowType {
1678         using type = float;
1679         static constexpr GLenum gl_format = GL_RG;
1680         static constexpr GLenum gl_type = GL_FLOAT;
1681         static constexpr int num_channels = 2;
1682 };
1683
1684 struct RGBAType {
1685         using type = uint8_t;
1686         static constexpr GLenum gl_format = GL_RGBA;
1687         static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1688         static constexpr int num_channels = 4;
1689 };
1690
1691 template <class Type>
1692 void finish_one_read(GLuint width, GLuint height)
1693 {
1694         using T = typename Type::type;
1695         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1696
1697         assert(!reads_in_progress.empty());
1698         ReadInProgress read = reads_in_progress.front();
1699         reads_in_progress.pop_front();
1700
1701         unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1702         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1703         memcpy(flow.get(), buf, width * height * bytes_per_pixel);  // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1704         glUnmapNamedBuffer(read.pbo);
1705         spare_pbos.push(read.pbo);
1706
1707         flip_coordinate_system(flow.get(), width, height);
1708         if (!read.flow_filename.empty()) {
1709                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1710                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1711         }
1712         if (!read.ppm_filename.empty()) {
1713                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1714         }
1715 }
1716
1717 template <class Type>
1718 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1719 {
1720         using T = typename Type::type;
1721         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1722
1723         if (spare_pbos.empty()) {
1724                 finish_one_read<Type>(width, height);
1725         }
1726         assert(!spare_pbos.empty());
1727         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1728         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1729         spare_pbos.pop();
1730         glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1731         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1732 }
1733
1734 void compute_flow_only(int argc, char **argv, int optind)
1735 {
1736         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1737         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1738         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1739
1740         // Load pictures.
1741         unsigned width1, height1, width2, height2;
1742         GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1743         GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1744
1745         if (width1 != width2 || height1 != height2) {
1746                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1747                         width1, height1, width2, height2);
1748                 exit(1);
1749         }
1750
1751         // Set up some PBOs to do asynchronous readback.
1752         GLuint pbos[5];
1753         glCreateBuffers(5, pbos);
1754         for (int i = 0; i < 5; ++i) {
1755                 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1756                 spare_pbos.push(pbos[i]);
1757         }
1758
1759         int levels = find_num_levels(width1, height1);
1760         GLuint tex0_gray, tex1_gray;
1761         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1762         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1763         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1764         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1765
1766         GrayscaleConversion gray;
1767         gray.exec(tex0, tex0_gray, width1, height1);
1768         glDeleteTextures(1, &tex0);
1769         glGenerateTextureMipmap(tex0_gray);
1770
1771         gray.exec(tex1, tex1_gray, width1, height1);
1772         glDeleteTextures(1, &tex1);
1773         glGenerateTextureMipmap(tex1_gray);
1774
1775         DISComputeFlow compute_flow(width1, height1);
1776
1777         if (enable_warmup) {
1778                 in_warmup = true;
1779                 for (int i = 0; i < 10; ++i) {
1780                         GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1781                         compute_flow.release_texture(final_tex);
1782                 }
1783                 in_warmup = false;
1784         }
1785
1786         GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1787
1788         schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1789         compute_flow.release_texture(final_tex);
1790
1791         // See if there are more flows on the command line (ie., more than three arguments),
1792         // and if so, process them.
1793         int num_flows = (argc - optind) / 3;
1794         for (int i = 1; i < num_flows; ++i) {
1795                 const char *filename0 = argv[optind + i * 3 + 0];
1796                 const char *filename1 = argv[optind + i * 3 + 1];
1797                 const char *flow_filename = argv[optind + i * 3 + 2];
1798                 GLuint width, height;
1799                 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1800                 if (width != width1 || height != height1) {
1801                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1802                                 filename0, width, height, width1, height1);
1803                         exit(1);
1804                 }
1805                 gray.exec(tex0, tex0_gray, width, height);
1806                 glGenerateTextureMipmap(tex0_gray);
1807                 glDeleteTextures(1, &tex0);
1808
1809                 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1810                 if (width != width1 || height != height1) {
1811                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1812                                 filename1, width, height, width1, height1);
1813                         exit(1);
1814                 }
1815                 gray.exec(tex1, tex1_gray, width, height);
1816                 glGenerateTextureMipmap(tex1_gray);
1817                 glDeleteTextures(1, &tex1);
1818
1819                 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1820
1821                 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1822                 compute_flow.release_texture(final_tex);
1823         }
1824         glDeleteTextures(1, &tex0_gray);
1825         glDeleteTextures(1, &tex1_gray);
1826
1827         while (!reads_in_progress.empty()) {
1828                 finish_one_read<FlowType>(width1, height1);
1829         }
1830 }
1831
1832 // Interpolate images based on
1833 //
1834 //   Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1835 //   Using Optical Flow”
1836 //
1837 // or at least a reasonable subset thereof. Unfinished.
1838 void interpolate_image(int argc, char **argv, int optind)
1839 {
1840         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1841         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1842         //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1843
1844         // Load pictures.
1845         unsigned width1, height1, width2, height2;
1846         GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1847         GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1848
1849         if (width1 != width2 || height1 != height2) {
1850                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1851                         width1, height1, width2, height2);
1852                 exit(1);
1853         }
1854
1855         // Set up some PBOs to do asynchronous readback.
1856         GLuint pbos[5];
1857         glCreateBuffers(5, pbos);
1858         for (int i = 0; i < 5; ++i) {
1859                 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1860                 spare_pbos.push(pbos[i]);
1861         }
1862
1863         DISComputeFlow compute_flow(width1, height1);
1864         GrayscaleConversion gray;
1865         Interpolate interpolate(width1, height1, finest_level);
1866
1867         int levels = find_num_levels(width1, height1);
1868         GLuint tex0_gray, tex1_gray;
1869         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1870         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1871         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1872         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1873
1874         gray.exec(tex0, tex0_gray, width1, height1);
1875         glGenerateTextureMipmap(tex0_gray);
1876
1877         gray.exec(tex1, tex1_gray, width1, height1);
1878         glGenerateTextureMipmap(tex1_gray);
1879
1880         if (enable_warmup) {
1881                 in_warmup = true;
1882                 for (int i = 0; i < 10; ++i) {
1883                         GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1884                         GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1885                         GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, 0.5f);
1886                         compute_flow.release_texture(forward_flow_tex);
1887                         compute_flow.release_texture(backward_flow_tex);
1888                         interpolate.release_texture(interpolated_tex);
1889                 }
1890                 in_warmup = false;
1891         }
1892
1893         GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1894         GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1895
1896         for (int frameno = 1; frameno < 60; ++frameno) {
1897                 char ppm_filename[256];
1898                 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
1899
1900                 float alpha = frameno / 60.0f;
1901                 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
1902
1903                 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
1904                 interpolate.release_texture(interpolated_tex);
1905         }
1906
1907         while (!reads_in_progress.empty()) {
1908                 finish_one_read<RGBAType>(width1, height1);
1909         }
1910 }
1911
1912 int main(int argc, char **argv)
1913 {
1914         static const option long_options[] = {
1915                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
1916                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
1917                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
1918                 { "disable-timing", no_argument, 0, 1000 },
1919                 { "detailed-timing", no_argument, 0, 1003 },
1920                 { "ignore-variational-refinement", no_argument, 0, 1001 },  // Still calculates it, just doesn't apply it.
1921                 { "interpolate", no_argument, 0, 1002 },
1922                 { "warmup", no_argument, 0, 1004 }
1923         };
1924
1925         for ( ;; ) {
1926                 int option_index = 0;
1927                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1928
1929                 if (c == -1) {
1930                         break;
1931                 }
1932                 switch (c) {
1933                 case 's':
1934                         vr_alpha = atof(optarg);
1935                         break;
1936                 case 'i':
1937                         vr_delta = atof(optarg);
1938                         break;
1939                 case 'g':
1940                         vr_gamma = atof(optarg);
1941                         break;
1942                 case 1000:
1943                         enable_timing = false;
1944                         break;
1945                 case 1001:
1946                         enable_variational_refinement = false;
1947                         break;
1948                 case 1002:
1949                         enable_interpolation = true;
1950                         break;
1951                 case 1003:
1952                         detailed_timing = true;
1953                         break;
1954                 case 1004:
1955                         enable_warmup = true;
1956                         break;
1957                 default:
1958                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1959                         exit(1);
1960                 };
1961         }
1962
1963         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1964                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1965                 exit(1);
1966         }
1967         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1968         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1969         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1970         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1971
1972         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1973         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1974         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1975         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1976         window = SDL_CreateWindow("OpenGL window",
1977                 SDL_WINDOWPOS_UNDEFINED,
1978                 SDL_WINDOWPOS_UNDEFINED,
1979                 64, 64,
1980                 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
1981         SDL_GLContext context = SDL_GL_CreateContext(window);
1982         assert(context != nullptr);
1983
1984         glDisable(GL_DITHER);
1985
1986         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1987         // before all the render passes).
1988         float vertices[] = {
1989                 0.0f, 1.0f,
1990                 0.0f, 0.0f,
1991                 1.0f, 1.0f,
1992                 1.0f, 0.0f,
1993         };
1994         glCreateBuffers(1, &vertex_vbo);
1995         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1996         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1997
1998         if (enable_interpolation) {
1999                 interpolate_image(argc, argv, optind);
2000         } else {
2001                 compute_flow_only(argc, argv, optind);
2002         }
2003 }