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