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