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