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