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