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