]> git.sesse.net Git - nageru/blob - futatabi/flow.h
Set CEF autoplay policy to be more lenient.
[nageru] / futatabi / flow.h
1 #ifndef _FLOW_H
2 #define _FLOW_H 1
3
4 // Code for computing optical flow between two images, and using it to interpolate
5 // in-between frames. The main user interface is the DISComputeFlow and Interpolate
6 // classes (also GrayscaleConversion can be useful).
7
8 #include <array>
9 #include <epoxy/gl.h>
10 #include <map>
11 #include <mutex>
12 #include <stdint.h>
13 #include <utility>
14 #include <vector>
15
16 class ScopedTimer;
17
18 // Predefined operating points from the paper.
19 struct OperatingPoint {
20         unsigned coarsest_level;  // TODO: Adjust dynamically based on the resolution?
21         unsigned finest_level;
22         unsigned search_iterations;  // Halved from the paper.
23         unsigned patch_size_pixels;
24         float patch_overlap_ratio;
25         bool variational_refinement;
26
27         // Not part of the original paper; used for interpolation.
28         // NOTE: Values much larger than 1.0 seems to trigger Haswell's “PMA stall”;
29         // the problem is not present on Broadwell and higher (there's a mitigation
30         // in the hardware, but Mesa doesn't enable it at the time of writing).
31         // Since we have hole filling, the holes from 1.0 are not critical,
32         // but larger values seem to do better than hole filling for large
33         // motion, blurs etc. since we have more candidates.
34         float splat_size;
35 };
36
37 // Operating point 1 (600 Hz on CPU, excluding preprocessing).
38 static constexpr OperatingPoint operating_point1 = {
39         5,      // Coarsest level.
40         3,      // Finest level.
41         8,      // Search iterations.
42         8,      // Patch size (pixels).
43         0.30f,  // Overlap ratio.
44         false,  // Variational refinement.
45         1.0f    // Splat size (pixels).
46 };
47
48 // Operating point 2 (300 Hz on CPU, excluding preprocessing).
49 static constexpr OperatingPoint operating_point2 = {
50         5,      // Coarsest level.
51         3,      // Finest level.
52         6,      // Search iterations.
53         8,      // Patch size (pixels).
54         0.40f,  // Overlap ratio.
55         true,   // Variational refinement.
56         1.0f    // Splat size (pixels).
57 };
58
59 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
60 // This is the only one that has been thorougly tested.
61 static constexpr OperatingPoint operating_point3 = {
62         5,      // Coarsest level.
63         1,      // Finest level.
64         8,      // Search iterations.
65         12,     // Patch size (pixels).
66         0.75f,  // Overlap ratio.
67         true,   // Variational refinement.
68         4.0f    // Splat size (pixels).
69 };
70
71 // Operating point 4 (0.5 Hz on CPU, excluding preprocessing).
72 static constexpr OperatingPoint operating_point4 = {
73         5,      // Coarsest level.
74         0,      // Finest level.
75         128,    // Search iterations.
76         12,     // Patch size (pixels).
77         0.75f,  // Overlap ratio.
78         true,   // Variational refinement.
79         8.0f    // Splat size (pixels).
80 };
81
82 int find_num_levels(int width, int height);
83
84 // A class that caches FBOs that render to a given set of textures.
85 // It never frees anything, so it is only suitable for rendering to
86 // the same (small) set of textures over and over again.
87 template<size_t num_elements>
88 class PersistentFBOSet {
89 public:
90         void render_to(const std::array<GLuint, num_elements> &textures);
91
92         // Convenience wrappers.
93         void render_to(GLuint texture0)
94         {
95                 render_to({ { texture0 } });
96         }
97
98         void render_to(GLuint texture0, GLuint texture1)
99         {
100                 render_to({ { texture0, texture1 } });
101         }
102
103         void render_to(GLuint texture0, GLuint texture1, GLuint texture2)
104         {
105                 render_to({ { texture0, texture1, texture2 } });
106         }
107
108         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3)
109         {
110                 render_to({ { texture0, texture1, texture2, texture3 } });
111         }
112
113 private:
114         // TODO: Delete these on destruction.
115         std::map<std::array<GLuint, num_elements>, GLuint> fbos;
116 };
117
118 // Same, but with a depth texture.
119 template<size_t num_elements>
120 class PersistentFBOSetWithDepth {
121 public:
122         void render_to(GLuint depth_rb, const std::array<GLuint, num_elements> &textures);
123
124         // Convenience wrappers.
125         void render_to(GLuint depth_rb, GLuint texture0)
126         {
127                 render_to(depth_rb, { { texture0 } });
128         }
129
130         void render_to(GLuint depth_rb, GLuint texture0, GLuint texture1)
131         {
132                 render_to(depth_rb, { { texture0, texture1 } });
133         }
134
135         void render_to(GLuint depth_rb, GLuint texture0, GLuint texture1, GLuint texture2)
136         {
137                 render_to(depth_rb, { { texture0, texture1, texture2 } });
138         }
139
140         void render_to(GLuint depth_rb, GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3)
141         {
142                 render_to(depth_rb, { { texture0, texture1, texture2, texture3 } });
143         }
144
145 private:
146         // TODO: Delete these on destruction.
147         std::map<std::pair<GLuint, std::array<GLuint, num_elements>>, GLuint> fbos;
148 };
149
150 // Convert RGB to grayscale, using Rec. 709 coefficients.
151 class GrayscaleConversion {
152 public:
153         GrayscaleConversion();
154         void exec(GLint tex, GLint gray_tex, int width, int height, int num_layers);
155
156 private:
157         PersistentFBOSet<1> fbos;
158         GLuint gray_vs_obj;
159         GLuint gray_fs_obj;
160         GLuint gray_program;
161         GLuint gray_vao;
162
163         GLuint uniform_tex;
164 };
165
166 // Compute gradients in every point, used for the motion search.
167 // The DIS paper doesn't actually mention how these are computed,
168 // but seemingly, a 3x3 Sobel operator is used here (at least in
169 // later versions of the code), while a [1 -8 0 8 -1] kernel is
170 // used for all the derivatives in the variational refinement part
171 // (which borrows code from DeepFlow). This is inconsistent,
172 // but I guess we're better off with staying with the original
173 // decisions until we actually know having different ones would be better.
174 class Sobel {
175 public:
176         Sobel();
177         void exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers);
178
179 private:
180         PersistentFBOSet<1> fbos;
181         GLuint sobel_vs_obj;
182         GLuint sobel_fs_obj;
183         GLuint sobel_program;
184
185         GLuint uniform_tex;
186 };
187
188 // Motion search to find the initial flow. See motion_search.frag for documentation.
189 class MotionSearch {
190 public:
191         MotionSearch(const OperatingPoint &op);
192         void exec(GLuint tex_view, GLuint grad_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, int num_layers);
193
194 private:
195         const OperatingPoint op;
196         PersistentFBOSet<1> fbos;
197
198         GLuint motion_vs_obj;
199         GLuint motion_fs_obj;
200         GLuint motion_search_program;
201
202         GLuint uniform_inv_image_size, uniform_inv_prev_level_size, uniform_out_flow_size;
203         GLuint uniform_image_tex, uniform_grad_tex, uniform_flow_tex;
204         GLuint uniform_patch_size, uniform_num_iterations;
205 };
206
207 // Do “densification”, ie., upsampling of the flow patches to the flow field
208 // (the same size as the image at this level). We draw one quad per patch
209 // over its entire covered area (using instancing in the vertex shader),
210 // and then weight the contributions in the pixel shader by post-warp difference.
211 // This is equation (3) in the paper.
212 //
213 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
214 // weight in the B channel. Dividing R and G by B gives the normalized values.
215 class Densify {
216 public:
217         Densify(const OperatingPoint &op);
218         void exec(GLuint tex_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches, int num_layers);
219
220 private:
221         OperatingPoint op;
222         PersistentFBOSet<1> fbos;
223
224         GLuint densify_vs_obj;
225         GLuint densify_fs_obj;
226         GLuint densify_program;
227
228         GLuint uniform_patch_size;
229         GLuint uniform_image_tex, uniform_flow_tex;
230 };
231
232 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
233 // I_0 and I_w. The prewarping is what enables us to solve the variational
234 // flow for du,dv instead of u,v.
235 //
236 // Also calculates the normalized flow, ie. divides by z (this is needed because
237 // Densify works by additive blending) and multiplies by the image size.
238 //
239 // See variational_refinement.txt for more information.
240 class Prewarp {
241 public:
242         Prewarp();
243         void exec(GLuint tex_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height, int num_layers);
244
245 private:
246         PersistentFBOSet<3> fbos;
247
248         GLuint prewarp_vs_obj;
249         GLuint prewarp_fs_obj;
250         GLuint prewarp_program;
251
252         GLuint uniform_image_tex, uniform_flow_tex;
253 };
254
255 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
256 // central difference filter, since apparently, that's tradition (I haven't
257 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
258 // The coefficients come from
259 //
260 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
261 //
262 // Also computes β_0, since it depends only on I_x and I_y.
263 class Derivatives {
264 public:
265         Derivatives();
266         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height, int num_layers);
267
268 private:
269         PersistentFBOSet<2> fbos;
270
271         GLuint derivatives_vs_obj;
272         GLuint derivatives_fs_obj;
273         GLuint derivatives_program;
274
275         GLuint uniform_tex;
276 };
277
278 // Calculate the diffusivity for each pixels, g(x,y). Smoothness (s) will
279 // be calculated in the shaders on-the-fly by sampling in-between two
280 // neighboring g(x,y) pixels, plus a border tweak to make sure we get
281 // zero smoothness at the border.
282 //
283 // See variational_refinement.txt for more information.
284 class ComputeDiffusivity {
285 public:
286         ComputeDiffusivity();
287         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers);
288
289 private:
290         PersistentFBOSet<1> fbos;
291
292         GLuint diffusivity_vs_obj;
293         GLuint diffusivity_fs_obj;
294         GLuint diffusivity_program;
295
296         GLuint uniform_flow_tex, uniform_diff_flow_tex;
297         GLuint uniform_alpha, uniform_zero_diff_flow;
298 };
299
300 // Set up the equations set (two equations in two unknowns, per pixel).
301 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
302 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
303 // floats. (Actually, we store the inverse of the diagonal elements, because
304 // we only ever need to divide by them.) This fits into four u32 values;
305 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
306 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
307 // terms that depend on other pixels, are calculated in one pass.
308 //
309 // The equation set is split in two; one contains only the pixels needed for
310 // the red pass, and one only for the black pass (see sor.frag). This reduces
311 // the amount of data the SOR shader has to pull in, at the cost of some
312 // complexity when the equation texture ends up with half the size and we need
313 // to adjust texture coordinates.  The contraction is done along the horizontal
314 // axis, so that on even rows (0, 2, 4, ...), the “red” texture will contain
315 // pixels 0, 2, 4, 6, etc., and on odd rows 1, 3, 5, etc..
316 //
317 // See variational_refinement.txt for more information about the actual
318 // equations in use.
319 class SetupEquations {
320 public:
321         SetupEquations();
322         void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers);
323
324 private:
325         PersistentFBOSet<2> fbos;
326
327         GLuint equations_vs_obj;
328         GLuint equations_fs_obj;
329         GLuint equations_program;
330
331         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
332         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
333         GLuint uniform_beta_0_tex;
334         GLuint uniform_diffusivity_tex;
335         GLuint uniform_gamma, uniform_delta, uniform_zero_diff_flow;
336 };
337
338 // Actually solve the equation sets made by SetupEquations, by means of
339 // successive over-relaxation (SOR).
340 //
341 // See variational_refinement.txt for more information.
342 class SOR {
343 public:
344         SOR();
345         void exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, int num_layers, ScopedTimer *sor_timer);
346
347 private:
348         PersistentFBOSet<1> fbos;
349
350         GLuint sor_vs_obj;
351         GLuint sor_fs_obj;
352         GLuint sor_program;
353
354         GLuint uniform_diff_flow_tex;
355         GLuint uniform_equation_red_tex, uniform_equation_black_tex;
356         GLuint uniform_diffusivity_tex;
357         GLuint uniform_phase, uniform_num_nonzero_phases;
358 };
359
360 // Simply add the differential flow found by the variational refinement to the base flow.
361 // The output is in base_flow_tex; we don't need to make a new texture.
362 class AddBaseFlow {
363 public:
364         AddBaseFlow();
365         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers);
366
367 private:
368         PersistentFBOSet<1> fbos;
369
370         GLuint add_flow_vs_obj;
371         GLuint add_flow_fs_obj;
372         GLuint add_flow_program;
373
374         GLuint uniform_diff_flow_tex;
375 };
376
377 // Take a copy of the flow, bilinearly interpolated and scaled up.
378 class ResizeFlow {
379 public:
380         ResizeFlow();
381         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height, int num_layers);
382
383 private:
384         PersistentFBOSet<1> fbos;
385
386         GLuint resize_flow_vs_obj;
387         GLuint resize_flow_fs_obj;
388         GLuint resize_flow_program;
389
390         GLuint uniform_flow_tex;
391         GLuint uniform_scale_factor;
392 };
393
394 // All operations, except construction and destruction, are thread-safe.
395 class TexturePool {
396 public:
397         GLuint get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers = 0);
398         void release_texture(GLuint tex_num);
399         GLuint get_renderbuffer(GLenum format, GLuint width, GLuint height);
400         void release_renderbuffer(GLuint tex_num);
401
402 private:
403         struct Texture {
404                 GLuint tex_num;
405                 GLenum format;
406                 GLuint width, height, num_layers;
407                 bool in_use = false;
408                 bool is_renderbuffer = false;
409         };
410         std::mutex mu;
411         std::vector<Texture> textures;  // Under mu.
412 };
413
414 class DISComputeFlow {
415 public:
416         DISComputeFlow(int width, int height, const OperatingPoint &op);
417
418         enum FlowDirection {
419                 FORWARD,
420                 FORWARD_AND_BACKWARD
421         };
422         enum ResizeStrategy {
423                 DO_NOT_RESIZE_FLOW,
424                 RESIZE_FLOW_TO_FULL_SIZE
425         };
426
427         // The texture must have two layers (first and second frame).
428         // Returns a texture that must be released with release_texture()
429         // after use.
430         GLuint exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy);
431
432         void release_texture(GLuint tex)
433         {
434                 pool.release_texture(tex);
435         }
436
437 private:
438         int width, height;
439         GLuint initial_flow_tex;
440         GLuint vertex_vbo, vao;
441         TexturePool pool;
442         const OperatingPoint op;
443
444         // The various passes.
445         Sobel sobel;
446         MotionSearch motion_search;
447         Densify densify;
448         Prewarp prewarp;
449         Derivatives derivatives;
450         ComputeDiffusivity compute_diffusivity;
451         SetupEquations setup_equations;
452         SOR sor;
453         AddBaseFlow add_base_flow;
454         ResizeFlow resize_flow;
455 };
456
457 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
458 // radius fills most of the holes.
459 class Splat {
460 public:
461         Splat(const OperatingPoint &op);
462
463         // alpha is the time of the interpolated frame (0..1).
464         void exec(GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha);
465
466 private:
467         const OperatingPoint op;
468         PersistentFBOSetWithDepth<1> fbos;
469
470         GLuint splat_vs_obj;
471         GLuint splat_fs_obj;
472         GLuint splat_program;
473
474         GLuint uniform_splat_size, uniform_alpha;
475         GLuint uniform_gray_tex, uniform_flow_tex;
476         GLuint uniform_inv_flow_size;
477 };
478
479 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
480 // that's fairly simple (given that most holes are really small) and also hopefully
481 // cheap should the holes not be so small. Conceptually, we look for the first
482 // non-hole to the left of us (ie., shoot a ray until we hit something), then
483 // the first non-hole to the right of us, then up and down, and then average them
484 // all together. It's going to create “stars” if the holes are big, but OK, that's
485 // a tradeoff.
486 //
487 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
488 // on even for shaders that do discard (this typically kills early Z, but hopefully
489 // not hierarchical Z); we set up Z so that only holes are written to, which means
490 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
491 // fullscreen quads should just be discarded outright, really.
492 class HoleFill {
493 public:
494         HoleFill();
495
496         // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
497         // from the down, left, right and up, respectively. Use HoleBlend to merge
498         // them into one.
499         void exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height);
500
501 private:
502         PersistentFBOSetWithDepth<1> fbos;
503
504         GLuint fill_vs_obj;
505         GLuint fill_fs_obj;
506         GLuint fill_program;
507
508         GLuint uniform_tex;
509         GLuint uniform_z, uniform_sample_offset;
510 };
511
512 // Blend the four directions from HoleFill into one pixel, so that single-pixel
513 // holes become the average of their four neighbors.
514 class HoleBlend {
515 public:
516         HoleBlend();
517
518         void exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height);
519
520 private:
521         PersistentFBOSetWithDepth<1> fbos;
522
523         GLuint blend_vs_obj;
524         GLuint blend_fs_obj;
525         GLuint blend_program;
526
527         GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
528         GLuint uniform_z, uniform_sample_offset;
529 };
530
531 class Blend {
532 public:
533         Blend(bool split_ycbcr_output);
534
535         // output2_tex is only used if split_ycbcr_output was true.
536         void exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, GLuint output2_tex, int width, int height, float alpha);
537
538 private:
539         bool split_ycbcr_output;
540         PersistentFBOSet<1> fbos;
541         PersistentFBOSet<2> fbos_split;
542         GLuint blend_vs_obj;
543         GLuint blend_fs_obj;
544         GLuint blend_program;
545
546         GLuint uniform_image_tex, uniform_flow_tex;
547         GLuint uniform_alpha, uniform_flow_consistency_tolerance;
548 };
549
550 class Interpolate {
551 public:
552         Interpolate(const OperatingPoint &op, bool split_ycbcr_output);
553
554         // Returns a texture (or two, if split_ycbcr_output is true) that must
555         // be released with release_texture() after use. image_tex must be a
556         // two-layer RGBA8 texture with mipmaps (unless flow_level == 0).
557         std::pair<GLuint, GLuint> exec(GLuint image_tex, GLuint gray_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha);
558
559         void release_texture(GLuint tex)
560         {
561                 pool.release_texture(tex);
562         }
563
564 private:
565         int flow_level;
566         GLuint vertex_vbo, vao;
567         TexturePool pool;
568         const bool split_ycbcr_output;
569
570         Splat splat;
571         HoleFill hole_fill;
572         HoleBlend hole_blend;
573         Blend blend;
574 };
575
576 #endif  // !defined(_FLOW_H)