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