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