]> git.sesse.net Git - nageru/blob - flow.cpp
Tweak the default variational refinement weights (optimized on alley_2).
[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 "util.h"
19
20 #include <algorithm>
21 #include <deque>
22 #include <memory>
23 #include <map>
24 #include <stack>
25 #include <vector>
26
27 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
28
29 using namespace std;
30
31 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
32 constexpr float patch_overlap_ratio = 0.75f;
33 constexpr unsigned coarsest_level = 5;
34 constexpr unsigned finest_level = 1;
35 constexpr unsigned patch_size_pixels = 12;
36
37 // Weighting constants for the different parts of the variational refinement.
38 // These don't correspond 1:1 to the values given in the DIS paper,
39 // since we have different normalizations and ranges in some cases.
40 // These are found through a simple grid search on some MPI-Sintel data,
41 // although the error (EPE) seems to be fairly insensitive to the precise values.
42 // Only the relative values matter, so we fix alpha (the smoothness constant)
43 // at unity and tweak the others.
44 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
45
46 bool enable_timing = true;
47 bool enable_variational_refinement = true;  // Just for debugging.
48
49 // Some global OpenGL objects.
50 // TODO: These should really be part of DISComputeFlow.
51 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
52 GLuint vertex_vbo;
53
54 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
55 struct ReadInProgress {
56         GLuint pbo;
57         string filename0, filename1;
58         string flow_filename, ppm_filename;  // Either may be empty for no write.
59 };
60 stack<GLuint> spare_pbos;
61 deque<ReadInProgress> reads_in_progress;
62
63 string read_file(const string &filename)
64 {
65         FILE *fp = fopen(filename.c_str(), "r");
66         if (fp == nullptr) {
67                 perror(filename.c_str());
68                 exit(1);
69         }
70
71         int ret = fseek(fp, 0, SEEK_END);
72         if (ret == -1) {
73                 perror("fseek(SEEK_END)");
74                 exit(1);
75         }
76
77         int size = ftell(fp);
78
79         ret = fseek(fp, 0, SEEK_SET);
80         if (ret == -1) {
81                 perror("fseek(SEEK_SET)");
82                 exit(1);
83         }
84
85         string str;
86         str.resize(size);
87         ret = fread(&str[0], size, 1, fp);
88         if (ret == -1) {
89                 perror("fread");
90                 exit(1);
91         }
92         if (ret == 0) {
93                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
94                                 size, filename.c_str());
95                 exit(1);
96         }
97         fclose(fp);
98
99         return str;
100 }
101
102
103 GLuint compile_shader(const string &shader_src, GLenum type)
104 {
105         GLuint obj = glCreateShader(type);
106         const GLchar* source[] = { shader_src.data() };
107         const GLint length[] = { (GLint)shader_src.size() };
108         glShaderSource(obj, 1, source, length);
109         glCompileShader(obj);
110
111         GLchar info_log[4096];
112         GLsizei log_length = sizeof(info_log) - 1;
113         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
114         info_log[log_length] = 0;
115         if (strlen(info_log) > 0) {
116                 fprintf(stderr, "Shader compile log: %s\n", info_log);
117         }
118
119         GLint status;
120         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
121         if (status == GL_FALSE) {
122                 // Add some line numbers to easier identify compile errors.
123                 string src_with_lines = "/*   1 */ ";
124                 size_t lineno = 1;
125                 for (char ch : shader_src) {
126                         src_with_lines.push_back(ch);
127                         if (ch == '\n') {
128                                 char buf[32];
129                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
130                                 src_with_lines += buf;
131                         }
132                 }
133
134                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
135                 exit(1);
136         }
137
138         return obj;
139 }
140
141 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
142 {
143         SDL_Surface *surf = IMG_Load(filename);
144         if (surf == nullptr) {
145                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
146                 exit(1);
147         }
148
149         // For whatever reason, SDL doesn't support converting to YUV surfaces
150         // nor grayscale, so we'll do it (slowly) ourselves.
151         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
152         if (rgb_surf == nullptr) {
153                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
154                 exit(1);
155         }
156
157         SDL_FreeSurface(surf);
158
159         unsigned width = rgb_surf->w, height = rgb_surf->h;
160         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
161         unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
162
163         // Extract the Y component, and convert to bottom-left origin.
164         for (unsigned y = 0; y < height; ++y) {
165                 unsigned y2 = height - 1 - y;
166                 for (unsigned x = 0; x < width; ++x) {
167                         uint8_t r = sptr[(y2 * width + x) * 4 + 3];
168                         uint8_t g = sptr[(y2 * width + x) * 4 + 2];
169                         uint8_t b = sptr[(y2 * width + x) * 4 + 1];
170
171                         // Rec. 709.
172                         pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
173                 }
174         }
175         SDL_FreeSurface(rgb_surf);
176
177         int levels = 1;
178         for (int w = width, h = height; w > 1 || h > 1; ) {
179                 w >>= 1;
180                 h >>= 1;
181                 ++levels;
182         }
183
184         GLuint tex;
185         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
186         glTextureStorage2D(tex, levels, GL_R8, width, height);
187         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
188         glGenerateTextureMipmap(tex);
189
190         *width_ret = width;
191         *height_ret = height;
192
193         return tex;
194 }
195
196 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
197 {
198         GLuint program = glCreateProgram();
199         glAttachShader(program, vs_obj);
200         glAttachShader(program, fs_obj);
201         glLinkProgram(program);
202         GLint success;
203         glGetProgramiv(program, GL_LINK_STATUS, &success);
204         if (success == GL_FALSE) {
205                 GLchar error_log[1024] = {0};
206                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
207                 fprintf(stderr, "Error linking program: %s\n", error_log);
208                 exit(1);
209         }
210         return program;
211 }
212
213 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
214 {
215         GLuint vbo;
216         glCreateBuffers(1, &vbo);
217         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
218         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
219         return vbo;
220 }
221
222 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
223 {
224         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
225         if (attrib == -1) {
226                 return -1;
227         }
228
229         GLuint vbo = generate_vbo(size, data_size, data);
230
231         glBindBuffer(GL_ARRAY_BUFFER, vbo);
232         glEnableVertexArrayAttrib(vao, attrib);
233         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
234         glBindBuffer(GL_ARRAY_BUFFER, 0);
235
236         return vbo;
237 }
238
239 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
240 {
241         if (location == -1) {
242                 return;
243         }
244
245         glBindTextureUnit(texture_unit, tex);
246         glBindSampler(texture_unit, sampler);
247         glProgramUniform1i(program, location, texture_unit);
248 }
249
250 // A class that caches FBOs that render to a given set of textures.
251 // It never frees anything, so it is only suitable for rendering to
252 // the same (small) set of textures over and over again.
253 template<size_t num_elements>
254 class PersistentFBOSet {
255 public:
256         void render_to(const array<GLuint, num_elements> &textures);
257
258         // Convenience wrappers.
259         void render_to(GLuint texture0, enable_if<num_elements == 1> * = nullptr) {
260                 render_to({{texture0}});
261         }
262
263         void render_to(GLuint texture0, GLuint texture1, enable_if<num_elements == 2> * = nullptr) {
264                 render_to({{texture0, texture1}});
265         }
266
267         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, enable_if<num_elements == 3> * = nullptr) {
268                 render_to({{texture0, texture1, texture2}});
269         }
270
271         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3, enable_if<num_elements == 4> * = nullptr) {
272                 render_to({{texture0, texture1, texture2, texture3}});
273         }
274
275 private:
276         // TODO: Delete these on destruction.
277         map<array<GLuint, num_elements>, GLuint> fbos;
278 };
279
280 template<size_t num_elements>
281 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
282 {
283         auto it = fbos.find(textures);
284         if (it != fbos.end()) {
285                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
286                 return;
287         }
288
289         GLuint fbo;
290         glCreateFramebuffers(1, &fbo);
291         GLenum bufs[num_elements];
292         for (size_t i = 0; i < num_elements; ++i) {
293                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
294                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
295         }
296         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
297
298         fbos[textures] = fbo;
299         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
300 }
301
302 // Compute gradients in every point, used for the motion search.
303 // The DIS paper doesn't actually mention how these are computed,
304 // but seemingly, a 3x3 Sobel operator is used here (at least in
305 // later versions of the code), while a [1 -8 0 8 -1] kernel is
306 // used for all the derivatives in the variational refinement part
307 // (which borrows code from DeepFlow). This is inconsistent,
308 // but I guess we're better off with staying with the original
309 // decisions until we actually know having different ones would be better.
310 class Sobel {
311 public:
312         Sobel();
313         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
314
315 private:
316         PersistentFBOSet<1> fbos;
317         GLuint sobel_vs_obj;
318         GLuint sobel_fs_obj;
319         GLuint sobel_program;
320         GLuint sobel_vao;
321
322         GLuint uniform_tex, uniform_image_size;
323 };
324
325 Sobel::Sobel()
326 {
327         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
328         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
329         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
330
331         // Set up the VAO containing all the required position/texcoord data.
332         glCreateVertexArrays(1, &sobel_vao);
333         glBindVertexArray(sobel_vao);
334
335         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
336         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
337         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
338
339         uniform_tex = glGetUniformLocation(sobel_program, "tex");
340 }
341
342 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
343 {
344         glUseProgram(sobel_program);
345         glBindTextureUnit(0, tex0_view);
346         glBindSampler(0, nearest_sampler);
347         glProgramUniform1i(sobel_program, uniform_tex, 0);
348
349         glViewport(0, 0, level_width, level_height);
350         fbos.render_to(grad0_tex);
351         glBindVertexArray(sobel_vao);
352         glUseProgram(sobel_program);
353         glDisable(GL_BLEND);
354         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
355 }
356
357 // Motion search to find the initial flow. See motion_search.frag for documentation.
358 class MotionSearch {
359 public:
360         MotionSearch();
361         void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
362
363 private:
364         PersistentFBOSet<1> fbos;
365
366         GLuint motion_vs_obj;
367         GLuint motion_fs_obj;
368         GLuint motion_search_program;
369         GLuint motion_search_vao;
370
371         GLuint uniform_image_size, uniform_inv_image_size, uniform_inv_flow_size, uniform_inv_prev_level_size;
372         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
373 };
374
375 MotionSearch::MotionSearch()
376 {
377         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
378         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
379         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
380
381         // Set up the VAO containing all the required position/texcoord data.
382         glCreateVertexArrays(1, &motion_search_vao);
383         glBindVertexArray(motion_search_vao);
384         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
385
386         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
387         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
388         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
389
390         uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
391         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
392         uniform_inv_flow_size = glGetUniformLocation(motion_search_program, "inv_flow_size");
393         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
394         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
395         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
396         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
397         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
398 }
399
400 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
401 {
402         glUseProgram(motion_search_program);
403
404         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
405         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
406         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
407         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
408
409         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
410         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
411         glProgramUniform2f(motion_search_program, uniform_inv_flow_size, 1.0f / width_patches, 1.0f / height_patches);
412         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
413
414         glViewport(0, 0, width_patches, height_patches);
415         fbos.render_to(flow_out_tex);
416         glBindVertexArray(motion_search_vao);
417         glUseProgram(motion_search_program);
418         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
419 }
420
421 // Do “densification”, ie., upsampling of the flow patches to the flow field
422 // (the same size as the image at this level). We draw one quad per patch
423 // over its entire covered area (using instancing in the vertex shader),
424 // and then weight the contributions in the pixel shader by post-warp difference.
425 // This is equation (3) in the paper.
426 //
427 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
428 // weight in the B channel. Dividing R and G by B gives the normalized values.
429 class Densify {
430 public:
431         Densify();
432         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
433
434 private:
435         PersistentFBOSet<1> fbos;
436
437         GLuint densify_vs_obj;
438         GLuint densify_fs_obj;
439         GLuint densify_program;
440         GLuint densify_vao;
441
442         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
443         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
444 };
445
446 Densify::Densify()
447 {
448         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
449         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
450         densify_program = link_program(densify_vs_obj, densify_fs_obj);
451
452         // Set up the VAO containing all the required position/texcoord data.
453         glCreateVertexArrays(1, &densify_vao);
454         glBindVertexArray(densify_vao);
455         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
456
457         GLint position_attrib = glGetAttribLocation(densify_program, "position");
458         glEnableVertexArrayAttrib(densify_vao, position_attrib);
459         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
460
461         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
462         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
463         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
464         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
465         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
466         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
467 }
468
469 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
470 {
471         glUseProgram(densify_program);
472
473         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
474         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
475         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
476
477         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
478         glProgramUniform2f(densify_program, uniform_patch_size,
479                 float(patch_size_pixels) / level_width,
480                 float(patch_size_pixels) / level_height);
481
482         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
483         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
484         if (width_patches == 1) patch_spacing_x = 0.0f;  // Avoid infinities.
485         if (height_patches == 1) patch_spacing_y = 0.0f;
486         glProgramUniform2f(densify_program, uniform_patch_spacing,
487                 patch_spacing_x / level_width,
488                 patch_spacing_y / level_height);
489
490         glViewport(0, 0, level_width, level_height);
491         glEnable(GL_BLEND);
492         glBlendFunc(GL_ONE, GL_ONE);
493         glBindVertexArray(densify_vao);
494         fbos.render_to(dense_flow_tex);
495         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
496 }
497
498 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
499 // I_0 and I_w. The prewarping is what enables us to solve the variational
500 // flow for du,dv instead of u,v.
501 //
502 // Also calculates the normalized flow, ie. divides by z (this is needed because
503 // Densify works by additive blending) and multiplies by the image size.
504 //
505 // See variational_refinement.txt for more information.
506 class Prewarp {
507 public:
508         Prewarp();
509         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
510
511 private:
512         PersistentFBOSet<3> fbos;
513
514         GLuint prewarp_vs_obj;
515         GLuint prewarp_fs_obj;
516         GLuint prewarp_program;
517         GLuint prewarp_vao;
518
519         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
520         GLuint uniform_image_size;
521 };
522
523 Prewarp::Prewarp()
524 {
525         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
526         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
527         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
528
529         // Set up the VAO containing all the required position/texcoord data.
530         glCreateVertexArrays(1, &prewarp_vao);
531         glBindVertexArray(prewarp_vao);
532         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
533
534         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
535         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
536         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
537
538         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
539         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
540         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
541
542         uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
543 }
544
545 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
546 {
547         glUseProgram(prewarp_program);
548
549         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
550         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
551         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
552
553         glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
554
555         glViewport(0, 0, level_width, level_height);
556         glDisable(GL_BLEND);
557         glBindVertexArray(prewarp_vao);
558         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
559         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
560 }
561
562 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
563 // central difference filter, since apparently, that's tradition (I haven't
564 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
565 // The coefficients come from
566 //
567 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
568 //
569 // Also computes β_0, since it depends only on I_x and I_y.
570 class Derivatives {
571 public:
572         Derivatives();
573         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
574
575 private:
576         PersistentFBOSet<2> fbos;
577
578         GLuint derivatives_vs_obj;
579         GLuint derivatives_fs_obj;
580         GLuint derivatives_program;
581         GLuint derivatives_vao;
582
583         GLuint uniform_tex;
584 };
585
586 Derivatives::Derivatives()
587 {
588         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
589         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
590         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
591
592         // Set up the VAO containing all the required position/texcoord data.
593         glCreateVertexArrays(1, &derivatives_vao);
594         glBindVertexArray(derivatives_vao);
595         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
596
597         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
598         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
599         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
600
601         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
602 }
603
604 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
605 {
606         glUseProgram(derivatives_program);
607
608         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
609
610         glViewport(0, 0, level_width, level_height);
611         glDisable(GL_BLEND);
612         glBindVertexArray(derivatives_vao);
613         fbos.render_to(I_x_y_tex, beta_0_tex);
614         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
615 }
616
617 // Calculate the smoothness constraints between neighboring pixels;
618 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
619 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
620 // border color (0,0) later, so that there's zero diffusion out of
621 // the border.
622 //
623 // See variational_refinement.txt for more information.
624 class ComputeSmoothness {
625 public:
626         ComputeSmoothness();
627         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
628
629 private:
630         PersistentFBOSet<2> fbos;
631
632         GLuint smoothness_vs_obj;
633         GLuint smoothness_fs_obj;
634         GLuint smoothness_program;
635         GLuint smoothness_vao;
636
637         GLuint uniform_flow_tex, uniform_diff_flow_tex;
638         GLuint uniform_alpha;
639 };
640
641 ComputeSmoothness::ComputeSmoothness()
642 {
643         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
644         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
645         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
646
647         // Set up the VAO containing all the required position/texcoord data.
648         glCreateVertexArrays(1, &smoothness_vao);
649         glBindVertexArray(smoothness_vao);
650         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
651
652         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
653         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
654         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
655
656         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
657         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
658         uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
659 }
660
661 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
662 {
663         glUseProgram(smoothness_program);
664
665         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
666         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
667         glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
668
669         glViewport(0, 0, level_width, level_height);
670
671         glDisable(GL_BLEND);
672         glBindVertexArray(smoothness_vao);
673         fbos.render_to(smoothness_x_tex, smoothness_y_tex);
674         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
675
676         // Make sure the smoothness on the right and upper borders is zero.
677         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
678         // (we're sampling smoothness with all-zero border color), but we'd
679         // have to adjust the sampling coordinates, which is annoying.
680         glClearTexSubImage(smoothness_x_tex, 0,  level_width - 1, 0, 0,   1, level_height, 1,  GL_RED, GL_FLOAT, nullptr);
681         glClearTexSubImage(smoothness_y_tex, 0,  0, level_height - 1, 0,  level_width, 1, 1,   GL_RED, GL_FLOAT, nullptr);
682 }
683
684 // Set up the equations set (two equations in two unknowns, per pixel).
685 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
686 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
687 // floats. (Actually, we store the inverse of the diagonal elements, because
688 // we only ever need to divide by them.) This fits into four u32 values;
689 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
690 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
691 // terms that depend on other pixels, are calculated in one pass.
692 //
693 // See variational_refinement.txt for more information.
694 class SetupEquations {
695 public:
696         SetupEquations();
697         void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height);
698
699 private:
700         PersistentFBOSet<1> fbos;
701
702         GLuint equations_vs_obj;
703         GLuint equations_fs_obj;
704         GLuint equations_program;
705         GLuint equations_vao;
706
707         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
708         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
709         GLuint uniform_beta_0_tex;
710         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
711         GLuint uniform_gamma, uniform_delta;
712 };
713
714 SetupEquations::SetupEquations()
715 {
716         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
717         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
718         equations_program = link_program(equations_vs_obj, equations_fs_obj);
719
720         // Set up the VAO containing all the required position/texcoord data.
721         glCreateVertexArrays(1, &equations_vao);
722         glBindVertexArray(equations_vao);
723         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
724
725         GLint position_attrib = glGetAttribLocation(equations_program, "position");
726         glEnableVertexArrayAttrib(equations_vao, position_attrib);
727         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
728
729         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
730         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
731         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
732         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
733         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
734         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
735         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
736         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
737         uniform_delta = glGetUniformLocation(equations_program, "delta");
738 }
739
740 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
741 {
742         glUseProgram(equations_program);
743
744         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
745         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
746         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
747         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
748         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
749         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
750         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
751         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
752         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
753
754         glViewport(0, 0, level_width, level_height);
755         glDisable(GL_BLEND);
756         glBindVertexArray(equations_vao);
757         fbos.render_to(equation_tex);
758         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
759 }
760
761 // Actually solve the equation sets made by SetupEquations, by means of
762 // successive over-relaxation (SOR).
763 //
764 // See variational_refinement.txt for more information.
765 class SOR {
766 public:
767         SOR();
768         void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
769
770 private:
771         PersistentFBOSet<1> fbos;
772
773         GLuint sor_vs_obj;
774         GLuint sor_fs_obj;
775         GLuint sor_program;
776         GLuint sor_vao;
777
778         GLuint uniform_diff_flow_tex;
779         GLuint uniform_equation_tex;
780         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
781 };
782
783 SOR::SOR()
784 {
785         sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
786         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
787         sor_program = link_program(sor_vs_obj, sor_fs_obj);
788
789         // Set up the VAO containing all the required position/texcoord data.
790         glCreateVertexArrays(1, &sor_vao);
791         glBindVertexArray(sor_vao);
792         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
793
794         GLint position_attrib = glGetAttribLocation(sor_program, "position");
795         glEnableVertexArrayAttrib(sor_vao, position_attrib);
796         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
797
798         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
799         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
800         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
801         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
802 }
803
804 void SOR::exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations)
805 {
806         glUseProgram(sor_program);
807
808         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
809         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
810         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
811         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
812
813         glViewport(0, 0, level_width, level_height);
814         glDisable(GL_BLEND);
815         glBindVertexArray(sor_vao);
816         fbos.render_to(diff_flow_tex);  // NOTE: Bind to same as we render from!
817
818         for (int i = 0; i < num_iterations; ++i) {
819                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
820                 if (i != num_iterations - 1) {
821                         glTextureBarrier();
822                 }
823         }
824 }
825
826 // Simply add the differential flow found by the variational refinement to the base flow.
827 // The output is in base_flow_tex; we don't need to make a new texture.
828 class AddBaseFlow {
829 public:
830         AddBaseFlow();
831         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
832
833 private:
834         PersistentFBOSet<1> fbos;
835
836         GLuint add_flow_vs_obj;
837         GLuint add_flow_fs_obj;
838         GLuint add_flow_program;
839         GLuint add_flow_vao;
840
841         GLuint uniform_diff_flow_tex;
842 };
843
844 AddBaseFlow::AddBaseFlow()
845 {
846         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
847         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
848         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
849
850         // Set up the VAO containing all the required position/texcoord data.
851         glCreateVertexArrays(1, &add_flow_vao);
852         glBindVertexArray(add_flow_vao);
853         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
854
855         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
856         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
857         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
858
859         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
860 }
861
862 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
863 {
864         glUseProgram(add_flow_program);
865
866         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
867
868         glViewport(0, 0, level_width, level_height);
869         glEnable(GL_BLEND);
870         glBlendFunc(GL_ONE, GL_ONE);
871         glBindVertexArray(add_flow_vao);
872         fbos.render_to(base_flow_tex);
873
874         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
875 }
876
877 // Take a copy of the flow, bilinearly interpolated and scaled up.
878 class ResizeFlow {
879 public:
880         ResizeFlow();
881         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
882
883 private:
884         PersistentFBOSet<1> fbos;
885
886         GLuint resize_flow_vs_obj;
887         GLuint resize_flow_fs_obj;
888         GLuint resize_flow_program;
889         GLuint resize_flow_vao;
890
891         GLuint uniform_flow_tex;
892         GLuint uniform_scale_factor;
893 };
894
895 ResizeFlow::ResizeFlow()
896 {
897         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
898         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
899         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
900
901         // Set up the VAO containing all the required position/texcoord data.
902         glCreateVertexArrays(1, &resize_flow_vao);
903         glBindVertexArray(resize_flow_vao);
904         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
905
906         GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
907         glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
908         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
909
910         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
911         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
912 }
913
914 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
915 {
916         glUseProgram(resize_flow_program);
917
918         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
919
920         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
921
922         glViewport(0, 0, output_width, output_height);
923         glDisable(GL_BLEND);
924         glBindVertexArray(resize_flow_vao);
925         fbos.render_to(out_tex);
926
927         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
928 }
929
930 class GPUTimers {
931 public:
932         void print();
933         pair<GLuint, GLuint> begin_timer(const string &name, int level);
934
935 private:
936         struct Timer {
937                 string name;
938                 int level;
939                 pair<GLuint, GLuint> query;
940         };
941         vector<Timer> timers;
942 };
943
944 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
945 {
946         if (!enable_timing) {
947                 return make_pair(0, 0);
948         }
949
950         GLuint queries[2];
951         glGenQueries(2, queries);
952         glQueryCounter(queries[0], GL_TIMESTAMP);
953
954         Timer timer;
955         timer.name = name;
956         timer.level = level;
957         timer.query.first = queries[0];
958         timer.query.second = queries[1];
959         timers.push_back(timer);
960         return timer.query;
961 }
962
963 void GPUTimers::print()
964 {
965         for (const Timer &timer : timers) {
966                 // NOTE: This makes the CPU wait for the GPU.
967                 GLuint64 time_start, time_end;
968                 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
969                 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
970                 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
971                 for (int i = 0; i < timer.level * 2; ++i) {
972                         fprintf(stderr, " ");
973                 }
974                 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
975         }
976 }
977
978 // A simple RAII class for timing until the end of the scope.
979 class ScopedTimer {
980 public:
981         ScopedTimer(const string &name, GPUTimers *timers)
982                 : timers(timers), level(0)
983         {
984                 query = timers->begin_timer(name, level);
985         }
986
987         ScopedTimer(const string &name, ScopedTimer *parent_timer)
988                 : timers(parent_timer->timers),
989                   level(parent_timer->level + 1)
990         {
991                 query = timers->begin_timer(name, level);
992         }
993
994         ~ScopedTimer()
995         {
996                 end();
997         }
998
999         void end()
1000         {
1001                 if (enable_timing && !ended) {
1002                         glQueryCounter(query.second, GL_TIMESTAMP);
1003                         ended = true;
1004                 }
1005         }
1006
1007 private:
1008         GPUTimers *timers;
1009         int level;
1010         pair<GLuint, GLuint> query;
1011         bool ended = false;
1012 };
1013
1014 class DISComputeFlow {
1015 public:
1016         DISComputeFlow(int width, int height);
1017
1018         // Returns a texture that must be released with release_texture()
1019         // after use.
1020         GLuint exec(GLuint tex0, GLuint tex1);
1021         void release_texture(GLuint tex);
1022
1023 private:
1024         int width, height;
1025         GLuint initial_flow_tex;
1026
1027         // The various passes.
1028         Sobel sobel;
1029         MotionSearch motion_search;
1030         Densify densify;
1031         Prewarp prewarp;
1032         Derivatives derivatives;
1033         ComputeSmoothness compute_smoothness;
1034         SetupEquations setup_equations;
1035         SOR sor;
1036         AddBaseFlow add_base_flow;
1037         ResizeFlow resize_flow;
1038
1039         struct Texture {
1040                 GLuint tex_num;
1041                 GLenum format;
1042                 GLuint width, height;
1043                 bool in_use = false;
1044         };
1045         vector<Texture> textures;
1046
1047         GLuint get_texture(GLenum format, GLuint width, GLuint height);
1048 };
1049
1050 DISComputeFlow::DISComputeFlow(int width, int height)
1051         : width(width), height(height)
1052 {
1053         // Make some samplers.
1054         glCreateSamplers(1, &nearest_sampler);
1055         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1056         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1057         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1058         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1059
1060         glCreateSamplers(1, &linear_sampler);
1061         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1062         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1063         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1064         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1065
1066         // The smoothness is sampled so that once we get to a smoothness involving
1067         // a value outside the border, the diffusivity between the two becomes zero.
1068         // Similarly, gradients are zero outside the border, since the edge is taken
1069         // to be constant.
1070         glCreateSamplers(1, &zero_border_sampler);
1071         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1072         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1073         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1074         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1075         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1076         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1077
1078         // Initial flow is zero, 1x1.
1079         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1080         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1081         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1082 }
1083
1084 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1)
1085 {
1086         for (const Texture &tex : textures) {
1087                 assert(!tex.in_use);
1088         }
1089
1090         int prev_level_width = 1, prev_level_height = 1;
1091         GLuint prev_level_flow_tex = initial_flow_tex;
1092
1093         GPUTimers timers;
1094
1095         ScopedTimer total_timer("Total", &timers);
1096         for (int level = coarsest_level; level >= int(finest_level); --level) {
1097                 char timer_name[256];
1098                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1099                 ScopedTimer level_timer(timer_name, &total_timer);
1100
1101                 int level_width = width >> level;
1102                 int level_height = height >> level;
1103                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1104                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
1105                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
1106
1107                 // Make sure we always read from the correct level; the chosen
1108                 // mipmapping could otherwise be rather unpredictable, especially
1109                 // during motion search.
1110                 // TODO: create these beforehand, and stop leaking them.
1111                 GLuint tex0_view, tex1_view;
1112                 glGenTextures(1, &tex0_view);
1113                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1114                 glGenTextures(1, &tex1_view);
1115                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1116
1117                 // Create a new texture; we could be fancy and render use a multi-level
1118                 // texture, but meh.
1119                 GLuint grad0_tex = get_texture(GL_RG16F, level_width, level_height);
1120
1121                 // Find the derivative.
1122                 {
1123                         ScopedTimer timer("Sobel", &level_timer);
1124                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1125                 }
1126
1127                 // Motion search to find the initial flow. We use the flow from the previous
1128                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1129
1130                 // Create an output flow texture.
1131                 GLuint flow_out_tex = get_texture(GL_RGB16F, width_patches, height_patches);
1132
1133                 // And draw.
1134                 {
1135                         ScopedTimer timer("Motion search", &level_timer);
1136                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1137                 }
1138                 release_texture(grad0_tex);
1139
1140                 // Densification.
1141
1142                 // Set up an output texture (initially zero).
1143                 GLuint dense_flow_tex = get_texture(GL_RGB16F, level_width, level_height);
1144                 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1145
1146                 // And draw.
1147                 {
1148                         ScopedTimer timer("Densification", &level_timer);
1149                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1150                 }
1151                 release_texture(flow_out_tex);
1152
1153                 // Everything below here in the loop belongs to variational refinement.
1154                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1155
1156                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1157                 // have to normalize it over and over again, and also save some bandwidth).
1158                 //
1159                 // During the entire rest of the variational refinement, flow will be measured
1160                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1161                 // This is because variational refinement depends so heavily on derivatives,
1162                 // which are measured in intensity levels per pixel.
1163                 GLuint I_tex = get_texture(GL_R16F, level_width, level_height);
1164                 GLuint I_t_tex = get_texture(GL_R16F, level_width, level_height);
1165                 GLuint base_flow_tex = get_texture(GL_RG16F, level_width, level_height);
1166                 {
1167                         ScopedTimer timer("Prewarping", &varref_timer);
1168                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1169                 }
1170                 release_texture(dense_flow_tex);
1171
1172                 // Calculate I_x and I_y. We're only calculating first derivatives;
1173                 // the others will be taken on-the-fly in order to sample from fewer
1174                 // textures overall, since sampling from the L1 cache is cheap.
1175                 // (TODO: Verify that this is indeed faster than making separate
1176                 // double-derivative textures.)
1177                 GLuint I_x_y_tex = get_texture(GL_RG16F, level_width, level_height);
1178                 GLuint beta_0_tex = get_texture(GL_R16F, level_width, level_height);
1179                 {
1180                         ScopedTimer timer("First derivatives", &varref_timer);
1181                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1182                 }
1183                 release_texture(I_tex);
1184
1185                 // We need somewhere to store du and dv (the flow increment, relative
1186                 // to the non-refined base flow u0 and v0). It starts at zero.
1187                 GLuint du_dv_tex = get_texture(GL_RG16F, level_width, level_height);
1188                 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1189
1190                 // And for smoothness.
1191                 GLuint smoothness_x_tex = get_texture(GL_R16F, level_width, level_height);
1192                 GLuint smoothness_y_tex = get_texture(GL_R16F, level_width, level_height);
1193
1194                 // And finally for the equation set. See SetupEquations for
1195                 // the storage format.
1196                 GLuint equation_tex = get_texture(GL_RGBA32UI, level_width, level_height);
1197
1198                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1199                         // Calculate the smoothness terms between the neighboring pixels,
1200                         // both in x and y direction.
1201                         {
1202                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1203                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1204                         }
1205
1206                         // Set up the 2x2 equation system for each pixel.
1207                         {
1208                                 ScopedTimer timer("Set up equations", &varref_timer);
1209                                 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1210                         }
1211
1212                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1213                         // Note that these are to/from the same texture.
1214                         {
1215                                 ScopedTimer timer("SOR", &varref_timer);
1216                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1217                         }
1218                 }
1219
1220                 release_texture(I_t_tex);
1221                 release_texture(I_x_y_tex);
1222                 release_texture(beta_0_tex);
1223                 release_texture(smoothness_x_tex);
1224                 release_texture(smoothness_y_tex);
1225                 release_texture(equation_tex);
1226
1227                 // Add the differential flow found by the variational refinement to the base flow,
1228                 // giving the final flow estimate for this level.
1229                 // The output is in diff_flow_tex; we don't need to make a new texture.
1230                 //
1231                 // Disabling this doesn't save any time (although we could easily make it so that
1232                 // it is more efficient), but it helps debug the motion search.
1233                 if (enable_variational_refinement) {
1234                         ScopedTimer timer("Add differential flow", &varref_timer);
1235                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1236                 }
1237                 release_texture(du_dv_tex);
1238
1239                 if (prev_level_flow_tex != initial_flow_tex) {
1240                         release_texture(prev_level_flow_tex);
1241                 }
1242                 prev_level_flow_tex = base_flow_tex;
1243                 prev_level_width = level_width;
1244                 prev_level_height = level_height;
1245         }
1246         total_timer.end();
1247
1248         timers.print();
1249
1250         // Scale up the flow to the final size (if needed).
1251         if (finest_level == 0) {
1252                 return prev_level_flow_tex;
1253         } else {
1254                 GLuint final_tex = get_texture(GL_RG16F, width, height);
1255                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1256                 release_texture(prev_level_flow_tex);
1257                 return final_tex;
1258         }
1259 }
1260
1261 GLuint DISComputeFlow::get_texture(GLenum format, GLuint width, GLuint height)
1262 {
1263         for (Texture &tex : textures) {
1264                 if (!tex.in_use && tex.format == format &&
1265                     tex.width == width && tex.height == height) {
1266                         tex.in_use = true;
1267                         return tex.tex_num;
1268                 }
1269         }
1270
1271         Texture tex;
1272         glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1273         glTextureStorage2D(tex.tex_num, 1, format, width, height);
1274         tex.format = format;
1275         tex.width = width;
1276         tex.height = height;
1277         tex.in_use = true;
1278         textures.push_back(tex);
1279         return tex.tex_num;
1280 }
1281
1282 void DISComputeFlow::release_texture(GLuint tex_num)
1283 {
1284         for (Texture &tex : textures) {
1285                 if (tex.tex_num == tex_num) {
1286                         assert(tex.in_use);
1287                         tex.in_use = false;
1288                         return;
1289                 }
1290         }
1291         assert(false);
1292 }
1293
1294 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1295 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1296 {
1297         for (unsigned i = 0; i < width * height; ++i) {
1298                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1299         }
1300 }
1301
1302 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1303 {
1304         FILE *flowfp = fopen(filename, "wb");
1305         fprintf(flowfp, "FEIH");
1306         fwrite(&width, 4, 1, flowfp);
1307         fwrite(&height, 4, 1, flowfp);
1308         for (unsigned y = 0; y < height; ++y) {
1309                 int yy = height - y - 1;
1310                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1311         }
1312         fclose(flowfp);
1313 }
1314
1315 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1316 {
1317         FILE *fp = fopen(filename, "wb");
1318         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1319         for (unsigned y = 0; y < unsigned(height); ++y) {
1320                 int yy = height - y - 1;
1321                 for (unsigned x = 0; x < unsigned(width); ++x) {
1322                         float du = dense_flow[(yy * width + x) * 2 + 0];
1323                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1324
1325                         uint8_t r, g, b;
1326                         flow2rgb(du, dv, &r, &g, &b);
1327                         putc(r, fp);
1328                         putc(g, fp);
1329                         putc(b, fp);
1330                 }
1331         }
1332         fclose(fp);
1333 }
1334
1335 void finish_one_read(GLuint width, GLuint height)
1336 {
1337         assert(!reads_in_progress.empty());
1338         ReadInProgress read = reads_in_progress.front();
1339         reads_in_progress.pop_front();
1340
1341         unique_ptr<float[]> flow(new float[width * height * 2]);
1342         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * 2 * sizeof(float), GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1343         memcpy(flow.get(), buf, width * height * 2 * sizeof(float));
1344         glUnmapNamedBuffer(read.pbo);
1345         spare_pbos.push(read.pbo);
1346
1347         flip_coordinate_system(flow.get(), width, height);
1348         if (!read.flow_filename.empty()) {
1349                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1350                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1351         }
1352         if (!read.ppm_filename.empty()) {
1353                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1354         }
1355 }
1356
1357 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1358 {
1359         if (spare_pbos.empty()) {
1360                 finish_one_read(width, height);
1361         }
1362         assert(!spare_pbos.empty());
1363         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1364         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1365         spare_pbos.pop();
1366         glGetTextureImage(tex, 0, GL_RG, GL_FLOAT, width * height * 2 * sizeof(float), nullptr);
1367         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1368 }
1369
1370 int main(int argc, char **argv)
1371 {
1372         static const option long_options[] = {
1373                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
1374                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
1375                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
1376                 { "disable-timing", no_argument, 0, 1000 },
1377                 { "ignore-variational-refinement", no_argument, 0, 1001 }  // Still calculates it, just doesn't apply it.
1378         };
1379
1380         for ( ;; ) {
1381                 int option_index = 0;
1382                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1383
1384                 if (c == -1) {
1385                         break;
1386                 }
1387                 switch (c) {
1388                 case 's':
1389                         vr_alpha = atof(optarg);
1390                         break;
1391                 case 'i':
1392                         vr_delta = atof(optarg);
1393                         break;
1394                 case 'g':
1395                         vr_gamma = atof(optarg);
1396                         break;
1397                 case 1000:
1398                         enable_timing = false;
1399                         break;
1400                 case 1001:
1401                         enable_variational_refinement = false;
1402                         break;
1403                 default:
1404                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1405                         exit(1);
1406                 };
1407         }
1408
1409         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1410                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1411                 exit(1);
1412         }
1413         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1414         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1415         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1416         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1417
1418         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1419         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1420         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1421         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1422         SDL_Window *window = SDL_CreateWindow("OpenGL window",
1423                         SDL_WINDOWPOS_UNDEFINED,
1424                         SDL_WINDOWPOS_UNDEFINED,
1425                         64, 64,
1426                         SDL_WINDOW_OPENGL);
1427         SDL_GLContext context = SDL_GL_CreateContext(window);
1428         assert(context != nullptr);
1429
1430         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1431         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1432         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1433
1434         // Load pictures.
1435         unsigned width1, height1, width2, height2;
1436         GLuint tex0 = load_texture(filename0, &width1, &height1);
1437         GLuint tex1 = load_texture(filename1, &width2, &height2);
1438
1439         if (width1 != width2 || height1 != height2) {
1440                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1441                         width1, height1, width2, height2);
1442                 exit(1);
1443         }
1444
1445         // Set up some PBOs to do asynchronous readback.
1446         GLuint pbos[5];
1447         glCreateBuffers(5, pbos);
1448         for (int i = 0; i < 5; ++i) {
1449                 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1450                 spare_pbos.push(pbos[i]);
1451         }
1452
1453         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1454         // before all the render passes).
1455         float vertices[] = {
1456                 0.0f, 1.0f,
1457                 0.0f, 0.0f,
1458                 1.0f, 1.0f,
1459                 1.0f, 0.0f,
1460         };
1461         glCreateBuffers(1, &vertex_vbo);
1462         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1463         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1464
1465         DISComputeFlow compute_flow(width1, height1);
1466         GLuint final_tex = compute_flow.exec(tex0, tex1);
1467
1468         schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1469         compute_flow.release_texture(final_tex);
1470
1471         // See if there are more flows on the command line (ie., more than three arguments),
1472         // and if so, process them.
1473         int num_flows = (argc - optind) / 3;
1474         for (int i = 1; i < num_flows; ++i) {
1475                 const char *filename0 = argv[optind + i * 3 + 0];
1476                 const char *filename1 = argv[optind + i * 3 + 1];
1477                 const char *flow_filename = argv[optind + i * 3 + 2];
1478                 GLuint width, height;
1479                 GLuint tex0 = load_texture(filename0, &width, &height);
1480                 if (width != width1 || height != height1) {
1481                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1482                                 filename0, width, height, width1, height1);
1483                         exit(1);
1484                 }
1485
1486                 GLuint tex1 = load_texture(filename1, &width, &height);
1487                 if (width != width1 || height != height1) {
1488                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1489                                 filename1, width, height, width1, height1);
1490                         exit(1);
1491                 }
1492
1493                 GLuint final_tex = compute_flow.exec(tex0, tex1);
1494                 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1495                 compute_flow.release_texture(final_tex);
1496         }
1497
1498         while (!reads_in_progress.empty()) {
1499                 finish_one_read(width1, height1);
1500         }
1501 }