]> git.sesse.net Git - nageru/blob - flow.cpp
Split texture pooling out from DISComputeFlow into its own class.
[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;
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         bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
346
347         glViewport(0, 0, level_width, level_height);
348         fbos.render_to(grad0_tex);
349         glBindVertexArray(sobel_vao);
350         glUseProgram(sobel_program);
351         glDisable(GL_BLEND);
352         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
353 }
354
355 // Motion search to find the initial flow. See motion_search.frag for documentation.
356 class MotionSearch {
357 public:
358         MotionSearch();
359         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);
360
361 private:
362         PersistentFBOSet<1> fbos;
363
364         GLuint motion_vs_obj;
365         GLuint motion_fs_obj;
366         GLuint motion_search_program;
367         GLuint motion_search_vao;
368
369         GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
370         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
371 };
372
373 MotionSearch::MotionSearch()
374 {
375         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
376         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
377         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
378
379         // Set up the VAO containing all the required position/texcoord data.
380         glCreateVertexArrays(1, &motion_search_vao);
381         glBindVertexArray(motion_search_vao);
382         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
383
384         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
385         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
386         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
387
388         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
389         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
390         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
391         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
392         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
393         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
394 }
395
396 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)
397 {
398         glUseProgram(motion_search_program);
399
400         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
401         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
402         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
403         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
404
405         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
406         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
407
408         glViewport(0, 0, width_patches, height_patches);
409         fbos.render_to(flow_out_tex);
410         glBindVertexArray(motion_search_vao);
411         glUseProgram(motion_search_program);
412         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
413 }
414
415 // Do “densification”, ie., upsampling of the flow patches to the flow field
416 // (the same size as the image at this level). We draw one quad per patch
417 // over its entire covered area (using instancing in the vertex shader),
418 // and then weight the contributions in the pixel shader by post-warp difference.
419 // This is equation (3) in the paper.
420 //
421 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
422 // weight in the B channel. Dividing R and G by B gives the normalized values.
423 class Densify {
424 public:
425         Densify();
426         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);
427
428 private:
429         PersistentFBOSet<1> fbos;
430
431         GLuint densify_vs_obj;
432         GLuint densify_fs_obj;
433         GLuint densify_program;
434         GLuint densify_vao;
435
436         GLuint uniform_patch_size, uniform_patch_spacing;
437         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
438 };
439
440 Densify::Densify()
441 {
442         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
443         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
444         densify_program = link_program(densify_vs_obj, densify_fs_obj);
445
446         // Set up the VAO containing all the required position/texcoord data.
447         glCreateVertexArrays(1, &densify_vao);
448         glBindVertexArray(densify_vao);
449         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
450
451         GLint position_attrib = glGetAttribLocation(densify_program, "position");
452         glEnableVertexArrayAttrib(densify_vao, position_attrib);
453         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
454
455         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
456         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
457         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
458         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
459         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
460 }
461
462 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)
463 {
464         glUseProgram(densify_program);
465
466         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
467         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
468         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
469
470         glProgramUniform2f(densify_program, uniform_patch_size,
471                 float(patch_size_pixels) / level_width,
472                 float(patch_size_pixels) / level_height);
473
474         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
475         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
476         if (width_patches == 1) patch_spacing_x = 0.0f;  // Avoid infinities.
477         if (height_patches == 1) patch_spacing_y = 0.0f;
478         glProgramUniform2f(densify_program, uniform_patch_spacing,
479                 patch_spacing_x / level_width,
480                 patch_spacing_y / level_height);
481
482         glViewport(0, 0, level_width, level_height);
483         glEnable(GL_BLEND);
484         glBlendFunc(GL_ONE, GL_ONE);
485         glBindVertexArray(densify_vao);
486         fbos.render_to(dense_flow_tex);
487         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
488 }
489
490 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
491 // I_0 and I_w. The prewarping is what enables us to solve the variational
492 // flow for du,dv instead of u,v.
493 //
494 // Also calculates the normalized flow, ie. divides by z (this is needed because
495 // Densify works by additive blending) and multiplies by the image size.
496 //
497 // See variational_refinement.txt for more information.
498 class Prewarp {
499 public:
500         Prewarp();
501         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);
502
503 private:
504         PersistentFBOSet<3> fbos;
505
506         GLuint prewarp_vs_obj;
507         GLuint prewarp_fs_obj;
508         GLuint prewarp_program;
509         GLuint prewarp_vao;
510
511         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
512 };
513
514 Prewarp::Prewarp()
515 {
516         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
517         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
518         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
519
520         // Set up the VAO containing all the required position/texcoord data.
521         glCreateVertexArrays(1, &prewarp_vao);
522         glBindVertexArray(prewarp_vao);
523         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
524
525         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
526         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
527         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
528
529         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
530         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
531         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
532 }
533
534 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)
535 {
536         glUseProgram(prewarp_program);
537
538         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
539         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
540         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
541
542         glViewport(0, 0, level_width, level_height);
543         glDisable(GL_BLEND);
544         glBindVertexArray(prewarp_vao);
545         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
546         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
547 }
548
549 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
550 // central difference filter, since apparently, that's tradition (I haven't
551 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
552 // The coefficients come from
553 //
554 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
555 //
556 // Also computes β_0, since it depends only on I_x and I_y.
557 class Derivatives {
558 public:
559         Derivatives();
560         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
561
562 private:
563         PersistentFBOSet<2> fbos;
564
565         GLuint derivatives_vs_obj;
566         GLuint derivatives_fs_obj;
567         GLuint derivatives_program;
568         GLuint derivatives_vao;
569
570         GLuint uniform_tex;
571 };
572
573 Derivatives::Derivatives()
574 {
575         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
576         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
577         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
578
579         // Set up the VAO containing all the required position/texcoord data.
580         glCreateVertexArrays(1, &derivatives_vao);
581         glBindVertexArray(derivatives_vao);
582         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
583
584         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
585         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
586         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
587
588         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
589 }
590
591 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
592 {
593         glUseProgram(derivatives_program);
594
595         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
596
597         glViewport(0, 0, level_width, level_height);
598         glDisable(GL_BLEND);
599         glBindVertexArray(derivatives_vao);
600         fbos.render_to(I_x_y_tex, beta_0_tex);
601         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
602 }
603
604 // Calculate the smoothness constraints between neighboring pixels;
605 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
606 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
607 // border color (0,0) later, so that there's zero diffusion out of
608 // the border.
609 //
610 // See variational_refinement.txt for more information.
611 class ComputeSmoothness {
612 public:
613         ComputeSmoothness();
614         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
615
616 private:
617         PersistentFBOSet<2> fbos;
618
619         GLuint smoothness_vs_obj;
620         GLuint smoothness_fs_obj;
621         GLuint smoothness_program;
622         GLuint smoothness_vao;
623
624         GLuint uniform_flow_tex, uniform_diff_flow_tex;
625         GLuint uniform_alpha;
626 };
627
628 ComputeSmoothness::ComputeSmoothness()
629 {
630         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
631         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
632         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
633
634         // Set up the VAO containing all the required position/texcoord data.
635         glCreateVertexArrays(1, &smoothness_vao);
636         glBindVertexArray(smoothness_vao);
637         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
638
639         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
640         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
641         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
642
643         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
644         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
645         uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
646 }
647
648 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
649 {
650         glUseProgram(smoothness_program);
651
652         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
653         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
654         glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
655
656         glViewport(0, 0, level_width, level_height);
657
658         glDisable(GL_BLEND);
659         glBindVertexArray(smoothness_vao);
660         fbos.render_to(smoothness_x_tex, smoothness_y_tex);
661         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
662
663         // Make sure the smoothness on the right and upper borders is zero.
664         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
665         // (we're sampling smoothness with all-zero border color), but we'd
666         // have to adjust the sampling coordinates, which is annoying.
667         glClearTexSubImage(smoothness_x_tex, 0,  level_width - 1, 0, 0,   1, level_height, 1,  GL_RED, GL_FLOAT, nullptr);
668         glClearTexSubImage(smoothness_y_tex, 0,  0, level_height - 1, 0,  level_width, 1, 1,   GL_RED, GL_FLOAT, nullptr);
669 }
670
671 // Set up the equations set (two equations in two unknowns, per pixel).
672 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
673 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
674 // floats. (Actually, we store the inverse of the diagonal elements, because
675 // we only ever need to divide by them.) This fits into four u32 values;
676 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
677 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
678 // terms that depend on other pixels, are calculated in one pass.
679 //
680 // See variational_refinement.txt for more information.
681 class SetupEquations {
682 public:
683         SetupEquations();
684         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);
685
686 private:
687         PersistentFBOSet<1> fbos;
688
689         GLuint equations_vs_obj;
690         GLuint equations_fs_obj;
691         GLuint equations_program;
692         GLuint equations_vao;
693
694         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
695         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
696         GLuint uniform_beta_0_tex;
697         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
698         GLuint uniform_gamma, uniform_delta;
699 };
700
701 SetupEquations::SetupEquations()
702 {
703         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
704         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
705         equations_program = link_program(equations_vs_obj, equations_fs_obj);
706
707         // Set up the VAO containing all the required position/texcoord data.
708         glCreateVertexArrays(1, &equations_vao);
709         glBindVertexArray(equations_vao);
710         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
711
712         GLint position_attrib = glGetAttribLocation(equations_program, "position");
713         glEnableVertexArrayAttrib(equations_vao, position_attrib);
714         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
715
716         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
717         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
718         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
719         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
720         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
721         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
722         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
723         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
724         uniform_delta = glGetUniformLocation(equations_program, "delta");
725 }
726
727 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)
728 {
729         glUseProgram(equations_program);
730
731         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
732         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
733         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
734         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
735         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
736         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
737         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
738         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
739         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
740
741         glViewport(0, 0, level_width, level_height);
742         glDisable(GL_BLEND);
743         glBindVertexArray(equations_vao);
744         fbos.render_to(equation_tex);
745         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
746 }
747
748 // Actually solve the equation sets made by SetupEquations, by means of
749 // successive over-relaxation (SOR).
750 //
751 // See variational_refinement.txt for more information.
752 class SOR {
753 public:
754         SOR();
755         void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
756
757 private:
758         PersistentFBOSet<1> fbos;
759
760         GLuint sor_vs_obj;
761         GLuint sor_fs_obj;
762         GLuint sor_program;
763         GLuint sor_vao;
764
765         GLuint uniform_diff_flow_tex;
766         GLuint uniform_equation_tex;
767         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
768         GLuint uniform_phase;
769 };
770
771 SOR::SOR()
772 {
773         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
774         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
775         sor_program = link_program(sor_vs_obj, sor_fs_obj);
776
777         // Set up the VAO containing all the required position/texcoord data.
778         glCreateVertexArrays(1, &sor_vao);
779         glBindVertexArray(sor_vao);
780         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
781
782         GLint position_attrib = glGetAttribLocation(sor_program, "position");
783         glEnableVertexArrayAttrib(sor_vao, position_attrib);
784         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
785
786         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
787         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
788         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
789         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
790         uniform_phase = glGetUniformLocation(sor_program, "phase");
791 }
792
793 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)
794 {
795         glUseProgram(sor_program);
796
797         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
798         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
799         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
800         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
801
802         // NOTE: We bind to the texture we are rendering from, but we never write any value
803         // that we read in the same shader pass (we call discard for red values when we compute
804         // black, and vice versa), and we have barriers between the passes, so we're fine
805         // as per the spec.
806         glViewport(0, 0, level_width, level_height);
807         glDisable(GL_BLEND);
808         glBindVertexArray(sor_vao);
809         fbos.render_to(diff_flow_tex);
810
811         for (int i = 0; i < num_iterations; ++i) {
812                 glProgramUniform1i(sor_program, uniform_phase, 0);
813                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
814                 glTextureBarrier();
815                 glProgramUniform1i(sor_program, uniform_phase, 1);
816                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
817                 if (i != num_iterations - 1) {
818                         glTextureBarrier();
819                 }
820         }
821 }
822
823 // Simply add the differential flow found by the variational refinement to the base flow.
824 // The output is in base_flow_tex; we don't need to make a new texture.
825 class AddBaseFlow {
826 public:
827         AddBaseFlow();
828         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
829
830 private:
831         PersistentFBOSet<1> fbos;
832
833         GLuint add_flow_vs_obj;
834         GLuint add_flow_fs_obj;
835         GLuint add_flow_program;
836         GLuint add_flow_vao;
837
838         GLuint uniform_diff_flow_tex;
839 };
840
841 AddBaseFlow::AddBaseFlow()
842 {
843         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
844         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
845         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
846
847         // Set up the VAO containing all the required position/texcoord data.
848         glCreateVertexArrays(1, &add_flow_vao);
849         glBindVertexArray(add_flow_vao);
850         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
851
852         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
853         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
854         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
855
856         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
857 }
858
859 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
860 {
861         glUseProgram(add_flow_program);
862
863         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
864
865         glViewport(0, 0, level_width, level_height);
866         glEnable(GL_BLEND);
867         glBlendFunc(GL_ONE, GL_ONE);
868         glBindVertexArray(add_flow_vao);
869         fbos.render_to(base_flow_tex);
870
871         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
872 }
873
874 // Take a copy of the flow, bilinearly interpolated and scaled up.
875 class ResizeFlow {
876 public:
877         ResizeFlow();
878         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
879
880 private:
881         PersistentFBOSet<1> fbos;
882
883         GLuint resize_flow_vs_obj;
884         GLuint resize_flow_fs_obj;
885         GLuint resize_flow_program;
886         GLuint resize_flow_vao;
887
888         GLuint uniform_flow_tex;
889         GLuint uniform_scale_factor;
890 };
891
892 ResizeFlow::ResizeFlow()
893 {
894         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
895         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
896         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
897
898         // Set up the VAO containing all the required position/texcoord data.
899         glCreateVertexArrays(1, &resize_flow_vao);
900         glBindVertexArray(resize_flow_vao);
901         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
902
903         GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
904         glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
905         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
906
907         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
908         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
909 }
910
911 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
912 {
913         glUseProgram(resize_flow_program);
914
915         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
916
917         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
918
919         glViewport(0, 0, output_width, output_height);
920         glDisable(GL_BLEND);
921         glBindVertexArray(resize_flow_vao);
922         fbos.render_to(out_tex);
923
924         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
925 }
926
927 class GPUTimers {
928 public:
929         void print();
930         pair<GLuint, GLuint> begin_timer(const string &name, int level);
931
932 private:
933         struct Timer {
934                 string name;
935                 int level;
936                 pair<GLuint, GLuint> query;
937         };
938         vector<Timer> timers;
939 };
940
941 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
942 {
943         if (!enable_timing) {
944                 return make_pair(0, 0);
945         }
946
947         GLuint queries[2];
948         glGenQueries(2, queries);
949         glQueryCounter(queries[0], GL_TIMESTAMP);
950
951         Timer timer;
952         timer.name = name;
953         timer.level = level;
954         timer.query.first = queries[0];
955         timer.query.second = queries[1];
956         timers.push_back(timer);
957         return timer.query;
958 }
959
960 void GPUTimers::print()
961 {
962         for (const Timer &timer : timers) {
963                 // NOTE: This makes the CPU wait for the GPU.
964                 GLuint64 time_start, time_end;
965                 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
966                 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
967                 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
968                 for (int i = 0; i < timer.level * 2; ++i) {
969                         fprintf(stderr, " ");
970                 }
971                 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
972         }
973 }
974
975 // A simple RAII class for timing until the end of the scope.
976 class ScopedTimer {
977 public:
978         ScopedTimer(const string &name, GPUTimers *timers)
979                 : timers(timers), level(0)
980         {
981                 query = timers->begin_timer(name, level);
982         }
983
984         ScopedTimer(const string &name, ScopedTimer *parent_timer)
985                 : timers(parent_timer->timers),
986                   level(parent_timer->level + 1)
987         {
988                 query = timers->begin_timer(name, level);
989         }
990
991         ~ScopedTimer()
992         {
993                 end();
994         }
995
996         void end()
997         {
998                 if (enable_timing && !ended) {
999                         glQueryCounter(query.second, GL_TIMESTAMP);
1000                         ended = true;
1001                 }
1002         }
1003
1004 private:
1005         GPUTimers *timers;
1006         int level;
1007         pair<GLuint, GLuint> query;
1008         bool ended = false;
1009 };
1010
1011 class TexturePool {
1012 public:
1013         GLuint get_texture(GLenum format, GLuint width, GLuint height);
1014         void release_texture(GLuint tex_num);
1015
1016 private:
1017         struct Texture {
1018                 GLuint tex_num;
1019                 GLenum format;
1020                 GLuint width, height;
1021                 bool in_use = false;
1022         };
1023         vector<Texture> textures;
1024 };
1025
1026 class DISComputeFlow {
1027 public:
1028         DISComputeFlow(int width, int height);
1029
1030         // Returns a texture that must be released with release_texture()
1031         // after use.
1032         GLuint exec(GLuint tex0, GLuint tex1);
1033
1034         void release_texture(GLuint tex) {
1035                 pool.release_texture(tex);
1036         }
1037
1038 private:
1039         int width, height;
1040         GLuint initial_flow_tex;
1041         TexturePool pool;
1042
1043         // The various passes.
1044         Sobel sobel;
1045         MotionSearch motion_search;
1046         Densify densify;
1047         Prewarp prewarp;
1048         Derivatives derivatives;
1049         ComputeSmoothness compute_smoothness;
1050         SetupEquations setup_equations;
1051         SOR sor;
1052         AddBaseFlow add_base_flow;
1053         ResizeFlow resize_flow;
1054 };
1055
1056 DISComputeFlow::DISComputeFlow(int width, int height)
1057         : width(width), height(height)
1058 {
1059         // Make some samplers.
1060         glCreateSamplers(1, &nearest_sampler);
1061         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1062         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1063         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1064         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1065
1066         glCreateSamplers(1, &linear_sampler);
1067         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1068         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1069         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1070         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1071
1072         // The smoothness is sampled so that once we get to a smoothness involving
1073         // a value outside the border, the diffusivity between the two becomes zero.
1074         // Similarly, gradients are zero outside the border, since the edge is taken
1075         // to be constant.
1076         glCreateSamplers(1, &zero_border_sampler);
1077         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1078         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1079         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1080         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1081         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1082         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1083
1084         // Initial flow is zero, 1x1.
1085         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1086         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1087         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1088 }
1089
1090 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1)
1091 {
1092         int prev_level_width = 1, prev_level_height = 1;
1093         GLuint prev_level_flow_tex = initial_flow_tex;
1094
1095         GPUTimers timers;
1096
1097         ScopedTimer total_timer("Total", &timers);
1098         for (int level = coarsest_level; level >= int(finest_level); --level) {
1099                 char timer_name[256];
1100                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1101                 ScopedTimer level_timer(timer_name, &total_timer);
1102
1103                 int level_width = width >> level;
1104                 int level_height = height >> level;
1105                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1106
1107                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1108                 // and patch_spacing=3 (the default), we put out patch centers in
1109                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1110                 // lock all the centers to integer coordinates if needed.
1111                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1112                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1113
1114                 // Make sure we always read from the correct level; the chosen
1115                 // mipmapping could otherwise be rather unpredictable, especially
1116                 // during motion search.
1117                 GLuint tex0_view, tex1_view;
1118                 glGenTextures(1, &tex0_view);
1119                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1120                 glGenTextures(1, &tex1_view);
1121                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1122
1123                 // Create a new texture; we could be fancy and render use a multi-level
1124                 // texture, but meh.
1125                 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1126
1127                 // Find the derivative.
1128                 {
1129                         ScopedTimer timer("Sobel", &level_timer);
1130                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1131                 }
1132
1133                 // Motion search to find the initial flow. We use the flow from the previous
1134                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1135
1136                 // Create an output flow texture.
1137                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1138
1139                 // And draw.
1140                 {
1141                         ScopedTimer timer("Motion search", &level_timer);
1142                         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);
1143                 }
1144                 pool.release_texture(grad0_tex);
1145
1146                 // Densification.
1147
1148                 // Set up an output texture (initially zero).
1149                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1150                 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1151
1152                 // And draw.
1153                 {
1154                         ScopedTimer timer("Densification", &level_timer);
1155                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1156                 }
1157                 pool.release_texture(flow_out_tex);
1158
1159                 // Everything below here in the loop belongs to variational refinement.
1160                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1161
1162                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1163                 // have to normalize it over and over again, and also save some bandwidth).
1164                 //
1165                 // During the entire rest of the variational refinement, flow will be measured
1166                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1167                 // This is because variational refinement depends so heavily on derivatives,
1168                 // which are measured in intensity levels per pixel.
1169                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1170                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1171                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1172                 {
1173                         ScopedTimer timer("Prewarping", &varref_timer);
1174                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1175                 }
1176                 pool.release_texture(dense_flow_tex);
1177                 glDeleteTextures(1, &tex0_view);
1178                 glDeleteTextures(1, &tex1_view);
1179
1180                 // Calculate I_x and I_y. We're only calculating first derivatives;
1181                 // the others will be taken on-the-fly in order to sample from fewer
1182                 // textures overall, since sampling from the L1 cache is cheap.
1183                 // (TODO: Verify that this is indeed faster than making separate
1184                 // double-derivative textures.)
1185                 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1186                 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1187                 {
1188                         ScopedTimer timer("First derivatives", &varref_timer);
1189                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1190                 }
1191                 pool.release_texture(I_tex);
1192
1193                 // We need somewhere to store du and dv (the flow increment, relative
1194                 // to the non-refined base flow u0 and v0). It starts at zero.
1195                 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1196                 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1197
1198                 // And for smoothness.
1199                 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1200                 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1201
1202                 // And finally for the equation set. See SetupEquations for
1203                 // the storage format.
1204                 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1205
1206                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1207                         // Calculate the smoothness terms between the neighboring pixels,
1208                         // both in x and y direction.
1209                         {
1210                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1211                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1212                         }
1213
1214                         // Set up the 2x2 equation system for each pixel.
1215                         {
1216                                 ScopedTimer timer("Set up equations", &varref_timer);
1217                                 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);
1218                         }
1219
1220                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1221                         // Note that these are to/from the same texture.
1222                         {
1223                                 ScopedTimer timer("SOR", &varref_timer);
1224                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1225                         }
1226                 }
1227
1228                 pool.release_texture(I_t_tex);
1229                 pool.release_texture(I_x_y_tex);
1230                 pool.release_texture(beta_0_tex);
1231                 pool.release_texture(smoothness_x_tex);
1232                 pool.release_texture(smoothness_y_tex);
1233                 pool.release_texture(equation_tex);
1234
1235                 // Add the differential flow found by the variational refinement to the base flow,
1236                 // giving the final flow estimate for this level.
1237                 // The output is in diff_flow_tex; we don't need to make a new texture.
1238                 //
1239                 // Disabling this doesn't save any time (although we could easily make it so that
1240                 // it is more efficient), but it helps debug the motion search.
1241                 if (enable_variational_refinement) {
1242                         ScopedTimer timer("Add differential flow", &varref_timer);
1243                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1244                 }
1245                 pool.release_texture(du_dv_tex);
1246
1247                 if (prev_level_flow_tex != initial_flow_tex) {
1248                         pool.release_texture(prev_level_flow_tex);
1249                 }
1250                 prev_level_flow_tex = base_flow_tex;
1251                 prev_level_width = level_width;
1252                 prev_level_height = level_height;
1253         }
1254         total_timer.end();
1255
1256         timers.print();
1257
1258         // Scale up the flow to the final size (if needed).
1259         if (finest_level == 0) {
1260                 return prev_level_flow_tex;
1261         } else {
1262                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1263                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1264                 pool.release_texture(prev_level_flow_tex);
1265                 return final_tex;
1266         }
1267 }
1268
1269 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1270 {
1271         for (Texture &tex : textures) {
1272                 if (!tex.in_use && tex.format == format &&
1273                     tex.width == width && tex.height == height) {
1274                         tex.in_use = true;
1275                         return tex.tex_num;
1276                 }
1277         }
1278
1279         Texture tex;
1280         glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1281         glTextureStorage2D(tex.tex_num, 1, format, width, height);
1282         tex.format = format;
1283         tex.width = width;
1284         tex.height = height;
1285         tex.in_use = true;
1286         textures.push_back(tex);
1287         return tex.tex_num;
1288 }
1289
1290 void TexturePool::release_texture(GLuint tex_num)
1291 {
1292         for (Texture &tex : textures) {
1293                 if (tex.tex_num == tex_num) {
1294                         assert(tex.in_use);
1295                         tex.in_use = false;
1296                         return;
1297                 }
1298         }
1299         assert(false);
1300 }
1301
1302 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1303 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1304 {
1305         for (unsigned i = 0; i < width * height; ++i) {
1306                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1307         }
1308 }
1309
1310 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1311 {
1312         FILE *flowfp = fopen(filename, "wb");
1313         fprintf(flowfp, "FEIH");
1314         fwrite(&width, 4, 1, flowfp);
1315         fwrite(&height, 4, 1, flowfp);
1316         for (unsigned y = 0; y < height; ++y) {
1317                 int yy = height - y - 1;
1318                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1319         }
1320         fclose(flowfp);
1321 }
1322
1323 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1324 {
1325         FILE *fp = fopen(filename, "wb");
1326         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1327         for (unsigned y = 0; y < unsigned(height); ++y) {
1328                 int yy = height - y - 1;
1329                 for (unsigned x = 0; x < unsigned(width); ++x) {
1330                         float du = dense_flow[(yy * width + x) * 2 + 0];
1331                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1332
1333                         uint8_t r, g, b;
1334                         flow2rgb(du, dv, &r, &g, &b);
1335                         putc(r, fp);
1336                         putc(g, fp);
1337                         putc(b, fp);
1338                 }
1339         }
1340         fclose(fp);
1341 }
1342
1343 void finish_one_read(GLuint width, GLuint height)
1344 {
1345         assert(!reads_in_progress.empty());
1346         ReadInProgress read = reads_in_progress.front();
1347         reads_in_progress.pop_front();
1348
1349         unique_ptr<float[]> flow(new float[width * height * 2]);
1350         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * 2 * sizeof(float), GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1351         memcpy(flow.get(), buf, width * height * 2 * sizeof(float));
1352         glUnmapNamedBuffer(read.pbo);
1353         spare_pbos.push(read.pbo);
1354
1355         flip_coordinate_system(flow.get(), width, height);
1356         if (!read.flow_filename.empty()) {
1357                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1358                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1359         }
1360         if (!read.ppm_filename.empty()) {
1361                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1362         }
1363 }
1364
1365 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1366 {
1367         if (spare_pbos.empty()) {
1368                 finish_one_read(width, height);
1369         }
1370         assert(!spare_pbos.empty());
1371         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1372         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1373         spare_pbos.pop();
1374         glGetTextureImage(tex, 0, GL_RG, GL_FLOAT, width * height * 2 * sizeof(float), nullptr);
1375         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1376 }
1377
1378 int main(int argc, char **argv)
1379 {
1380         static const option long_options[] = {
1381                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
1382                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
1383                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
1384                 { "disable-timing", no_argument, 0, 1000 },
1385                 { "ignore-variational-refinement", no_argument, 0, 1001 }  // Still calculates it, just doesn't apply it.
1386         };
1387
1388         for ( ;; ) {
1389                 int option_index = 0;
1390                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1391
1392                 if (c == -1) {
1393                         break;
1394                 }
1395                 switch (c) {
1396                 case 's':
1397                         vr_alpha = atof(optarg);
1398                         break;
1399                 case 'i':
1400                         vr_delta = atof(optarg);
1401                         break;
1402                 case 'g':
1403                         vr_gamma = atof(optarg);
1404                         break;
1405                 case 1000:
1406                         enable_timing = false;
1407                         break;
1408                 case 1001:
1409                         enable_variational_refinement = false;
1410                         break;
1411                 default:
1412                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1413                         exit(1);
1414                 };
1415         }
1416
1417         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1418                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1419                 exit(1);
1420         }
1421         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1422         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1423         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1424         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1425
1426         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1427         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1428         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1429         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1430         SDL_Window *window = SDL_CreateWindow("OpenGL window",
1431                 SDL_WINDOWPOS_UNDEFINED,
1432                 SDL_WINDOWPOS_UNDEFINED,
1433                 64, 64,
1434                 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
1435         SDL_GLContext context = SDL_GL_CreateContext(window);
1436         assert(context != nullptr);
1437
1438         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1439         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1440         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1441
1442         // Load pictures.
1443         unsigned width1, height1, width2, height2;
1444         GLuint tex0 = load_texture(filename0, &width1, &height1);
1445         GLuint tex1 = load_texture(filename1, &width2, &height2);
1446
1447         if (width1 != width2 || height1 != height2) {
1448                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1449                         width1, height1, width2, height2);
1450                 exit(1);
1451         }
1452
1453         // Set up some PBOs to do asynchronous readback.
1454         GLuint pbos[5];
1455         glCreateBuffers(5, pbos);
1456         for (int i = 0; i < 5; ++i) {
1457                 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1458                 spare_pbos.push(pbos[i]);
1459         }
1460
1461         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1462         // before all the render passes).
1463         float vertices[] = {
1464                 0.0f, 1.0f,
1465                 0.0f, 0.0f,
1466                 1.0f, 1.0f,
1467                 1.0f, 0.0f,
1468         };
1469         glCreateBuffers(1, &vertex_vbo);
1470         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1471         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1472
1473         DISComputeFlow compute_flow(width1, height1);
1474         GLuint final_tex = compute_flow.exec(tex0, tex1);
1475
1476         schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1477         compute_flow.release_texture(final_tex);
1478
1479         // See if there are more flows on the command line (ie., more than three arguments),
1480         // and if so, process them.
1481         int num_flows = (argc - optind) / 3;
1482         for (int i = 1; i < num_flows; ++i) {
1483                 const char *filename0 = argv[optind + i * 3 + 0];
1484                 const char *filename1 = argv[optind + i * 3 + 1];
1485                 const char *flow_filename = argv[optind + i * 3 + 2];
1486                 GLuint width, height;
1487                 GLuint tex0 = load_texture(filename0, &width, &height);
1488                 if (width != width1 || height != height1) {
1489                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1490                                 filename0, width, height, width1, height1);
1491                         exit(1);
1492                 }
1493
1494                 GLuint tex1 = load_texture(filename1, &width, &height);
1495                 if (width != width1 || height != height1) {
1496                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1497                                 filename1, width, height, width1, height1);
1498                         exit(1);
1499                 }
1500
1501                 GLuint final_tex = compute_flow.exec(tex0, tex1);
1502                 schedule_read(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1503                 compute_flow.release_texture(final_tex);
1504         }
1505
1506         while (!reads_in_progress.empty()) {
1507                 finish_one_read(width1, height1);
1508         }
1509 }