]> git.sesse.net Git - movit/blob - effect_chain.h
Make the error printed on check_error() slightly friendlier: Include the enum if...
[movit] / effect_chain.h
1 #ifndef _MOVIT_EFFECT_CHAIN_H
2 #define _MOVIT_EFFECT_CHAIN_H 1
3
4 // An EffectChain is the largest basic entity in Movit; it contains everything
5 // needed to connects a series of effects, from inputs to outputs, and render
6 // them. Generally you set up your effect chain once and then call its render
7 // functions once per frame; setting one up can be relatively expensive,
8 // but rendering is fast.
9 //
10 // Threading considerations: EffectChain is “thread-compatible”; you can use
11 // different EffectChains in multiple threads at the same time (assuming the
12 // threads do not use the same OpenGL context, but this is a good idea anyway),
13 // but you may not use one EffectChain from multiple threads simultaneously.
14 // You _are_ allowed to use one EffectChain from multiple threads as long as
15 // you only use it from one at a time (possibly by doing your own locking),
16 // but if so, the threads' contexts need to be set up to share resources, since
17 // the EffectChain holds textures and other OpenGL objects that are tied to the
18 // context.
19 //
20 // Memory management (only relevant if you use multiple contexts):
21 // See corresponding comment in resource_pool.h. This holds even if you don't
22 // allocate your own ResourcePool, but let EffectChain hold its own.
23
24 #include <epoxy/gl.h>
25 #include <stdio.h>
26 #include <list>
27 #include <map>
28 #include <set>
29 #include <string>
30 #include <vector>
31 #include <Eigen/Core>
32
33 #include "effect.h"
34 #include "image_format.h"
35 #include "ycbcr.h"
36
37 namespace movit {
38
39 class Effect;
40 class Input;
41 struct Phase;
42 class ResourcePool;
43
44 // For internal use within Node.
45 enum AlphaType {
46         ALPHA_INVALID = -1,
47         ALPHA_BLANK,
48         ALPHA_PREMULTIPLIED,
49         ALPHA_POSTMULTIPLIED,
50 };
51
52 // Whether you want pre- or postmultiplied alpha in the output
53 // (see effect.h for a discussion of pre- versus postmultiplied alpha).
54 enum OutputAlphaFormat {
55         OUTPUT_ALPHA_FORMAT_PREMULTIPLIED,
56         OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED,
57 };
58
59 // RGBA output is nearly always packed; Y'CbCr, however, is often planar
60 // due to chroma subsampling. This enum controls how add_ycbcr_output()
61 // distributes the color channels between the fragment shader outputs.
62 // Obviously, anything except YCBCR_OUTPUT_INTERLEAVED will be meaningless
63 // unless you use render_to_fbo() and have an FBO with multiple render
64 // targets attached (the other outputs will be discarded).
65 enum YCbCrOutputSplitting {
66         // Only one output: Store Y'CbCr into the first three output channels,
67         // respectively, plus alpha. This is also called “chunked” or
68         // ”packed” mode.
69         YCBCR_OUTPUT_INTERLEAVED,
70
71         // Store Y' and alpha into the first output (in the red and alpha
72         // channels; effect to the others is undefined), and Cb and Cr into
73         // the first two channels of the second output. This is particularly
74         // useful if you want to end up in a format like NV12, where all the
75         // Y' samples come first and then Cb and Cr come interlevaed afterwards.
76         // You will still need to do the chroma subsampling yourself to actually
77         // get down to NV12, though.
78         YCBCR_OUTPUT_SPLIT_Y_AND_CBCR,
79
80         // Store Y' and alpha into the first output, Cb into the first channel
81         // of the second output and Cr into the first channel of the third output.
82         // (Effect on the other channels is undefined.) Essentially gives you
83         // 4:4:4 planar, or ”yuv444p”.
84         YCBCR_OUTPUT_PLANAR,
85 };
86
87 // Where (0,0) is taken to be in the output. If you want to render to an
88 // OpenGL screen, you should keep the default of bottom-left, as that is
89 // OpenGL's natural coordinate system. However, there are cases, such as if you
90 // render to an FBO and read the pixels back into some other system, where
91 // you'd want a top-left origin; if so, an additional flip step will be added
92 // at the very end (but done in a vertex shader, so it will have zero extra
93 // cost).
94 //
95 // Note that Movit's coordinate system in general consistently puts (0,0) in
96 // the top left for _input_, no matter what you set as output origin.
97 enum OutputOrigin {
98         OUTPUT_ORIGIN_BOTTOM_LEFT,
99         OUTPUT_ORIGIN_TOP_LEFT,
100 };
101
102 // Transformation to apply (if any) to pixel data in temporary buffers.
103 // See set_intermediate_format() below for more information.
104 enum FramebufferTransformation {
105         // The default; just store the value. This is what you usually want.
106         NO_FRAMEBUFFER_TRANSFORMATION,
107
108         // If the values are in linear light, store sqrt(x) to the framebuffer
109         // instead of x itself, of course undoing it with x² on read. Useful as
110         // a rough approximation to the sRGB curve. (If the values are not in
111         // linear light, just store them as-is.)
112         SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION,
113 };
114
115 // A node in the graph; basically an effect and some associated information.
116 class Node {
117 public:
118         Effect *effect;
119         bool disabled;
120
121         // Edges in the graph (forward and backward).
122         std::vector<Node *> outgoing_links;
123         std::vector<Node *> incoming_links;
124
125         // For unit tests only. Do not use from other code.
126         // Will contain an arbitrary choice if the node is in multiple phases.
127         Phase *containing_phase;
128
129 private:
130         // Logical size of the output of this effect, ie. the resolution
131         // you would get if you sampled it as a texture. If it is undefined
132         // (since the inputs differ in resolution), it will be 0x0.
133         // If both this and output_texture_{width,height} are set,
134         // they will be equal.
135         unsigned output_width, output_height;
136
137         // If the effect has is_single_texture(), or if the output went to RTT
138         // and that texture has been bound to a sampler, the sampler number
139         // will be stored here.
140         //
141         // TODO: Can an RTT texture be used as inputs to multiple effects
142         // within the same phase? If so, we have a problem with modifying
143         // sampler state here.
144         int bound_sampler_num;
145
146         // Used during the building of the effect chain.
147         Colorspace output_color_space;
148         GammaCurve output_gamma_curve;
149         AlphaType output_alpha_type;
150         bool needs_mipmaps;  // Directly or indirectly.
151
152         // Set if this effect, and all effects consuming output from this node
153         // (in the same phase) have one_to_one_sampling() set.
154         bool one_to_one_sampling;
155
156         friend class EffectChain;
157 };
158
159 // A rendering phase; a single GLSL program rendering a single quad.
160 struct Phase {
161         Node *output_node;
162
163         GLuint glsl_program_num;  // Owned by the resource_pool.
164
165         // Position and texcoord attribute indexes, although it doesn't matter
166         // which is which, because they contain the same data.
167         std::set<GLint> attribute_indexes;
168
169         bool input_needs_mipmaps;
170
171         // Inputs are only inputs from other phases (ie., those that come from RTT);
172         // input textures are counted as part of <effects>.
173         std::vector<Phase *> inputs;
174         // Bound sampler numbers for each input. Redundant in a sense
175         // (it always corresponds to the index), but we need somewhere
176         // to hold the value for the uniform.
177         std::vector<int> input_samplers;
178         std::vector<Node *> effects;  // In order.
179         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
180
181         // Identifier used to create unique variables in GLSL.
182         // Unique per-phase to increase cacheability of compiled shaders.
183         std::map<Node *, std::string> effect_ids;
184
185         // Uniforms for this phase; combined from all the effects.
186         std::vector<Uniform<int> > uniforms_sampler2d;
187         std::vector<Uniform<bool> > uniforms_bool;
188         std::vector<Uniform<int> > uniforms_int;
189         std::vector<Uniform<float> > uniforms_float;
190         std::vector<Uniform<float> > uniforms_vec2;
191         std::vector<Uniform<float> > uniforms_vec3;
192         std::vector<Uniform<float> > uniforms_vec4;
193         std::vector<Uniform<Eigen::Matrix3d> > uniforms_mat3;
194
195         // For measurement of GPU time used.
196         std::list<GLuint> timer_query_objects_running;
197         std::list<GLuint> timer_query_objects_free;
198         uint64_t time_elapsed_ns;
199         uint64_t num_measured_iterations;
200 };
201
202 class EffectChain {
203 public:
204         // Aspect: e.g. 16.0f, 9.0f for 16:9.
205         // resource_pool is a pointer to a ResourcePool with which to share shaders
206         // and other resources (see resource_pool.h). If NULL (the default),
207         // will create its own that is not shared with anything else. Does not take
208         // ownership of the passed-in ResourcePool, but will naturally take ownership
209         // of its own internal one if created.
210         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL);
211         ~EffectChain();
212
213         // User API:
214         // input, effects, output, finalize need to come in that specific order.
215
216         // EffectChain takes ownership of the given input.
217         // input is returned back for convenience.
218         Input *add_input(Input *input);
219
220         // EffectChain takes ownership of the given effect.
221         // effect is returned back for convenience.
222         Effect *add_effect(Effect *effect) {
223                 return add_effect(effect, last_added_effect());
224         }
225         Effect *add_effect(Effect *effect, Effect *input) {
226                 std::vector<Effect *> inputs;
227                 inputs.push_back(input);
228                 return add_effect(effect, inputs);
229         }
230         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
231                 std::vector<Effect *> inputs;
232                 inputs.push_back(input1);
233                 inputs.push_back(input2);
234                 return add_effect(effect, inputs);
235         }
236         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3) {
237                 std::vector<Effect *> inputs;
238                 inputs.push_back(input1);
239                 inputs.push_back(input2);
240                 inputs.push_back(input3);
241                 return add_effect(effect, inputs);
242         }
243         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3, Effect *input4) {
244                 std::vector<Effect *> inputs;
245                 inputs.push_back(input1);
246                 inputs.push_back(input2);
247                 inputs.push_back(input3);
248                 inputs.push_back(input4);
249                 return add_effect(effect, inputs);
250         }
251         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3, Effect *input4, Effect *input5) {
252                 std::vector<Effect *> inputs;
253                 inputs.push_back(input1);
254                 inputs.push_back(input2);
255                 inputs.push_back(input3);
256                 inputs.push_back(input4);
257                 inputs.push_back(input5);
258                 return add_effect(effect, inputs);
259         }
260         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
261
262         // Adds an RGBA output. Note that you can have at most one RGBA output and one
263         // Y'CbCr output (see below for details).
264         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
265
266         // Adds an YCbCr output. Note that you can only have one output.
267         // Currently, only chunked packed output is supported, and only 4:4:4
268         // (so chroma_subsampling_x and chroma_subsampling_y must both be 1).
269         //
270         // If you have both RGBA and Y'CbCr output, the RGBA output will come
271         // in the last draw buffer. Also, <format> and <alpha_format> must be
272         // identical between the two.
273         void add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
274                               const YCbCrFormat &ycbcr_format,
275                               YCbCrOutputSplitting output_splitting = YCBCR_OUTPUT_INTERLEAVED);
276
277         // Set number of output bits, to scale the dither.
278         // 8 is the right value for most outputs.
279         // The default, 0, is a special value that means no dither.
280         void set_dither_bits(unsigned num_bits)
281         {
282                 this->num_dither_bits = num_bits;
283         }
284
285         // Set where (0,0) is taken to be in the output. The default is
286         // OUTPUT_ORIGIN_BOTTOM_LEFT, which is usually what you want
287         // (see OutputOrigin above for more details).
288         void set_output_origin(OutputOrigin output_origin)
289         {
290                 this->output_origin = output_origin;
291         }
292
293         // Set intermediate format for framebuffers used when we need to bounce
294         // to a temporary texture. The default, GL_RGBA16F, is good for most uses;
295         // it is precise, has good range, and is relatively efficient. However,
296         // if you need even more speed and your chain can do with some loss of
297         // accuracy, you can change the format here (before calling finalize).
298         // Calculations between bounce buffers are still in 32-bit floating-point
299         // no matter what you specify.
300         //
301         // Of special interest is GL_SRGB8_ALPHA8, which stores sRGB-encoded RGB
302         // and linear alpha; this is half the memory bandwidth og GL_RGBA16F,
303         // while retaining reasonable precision for typical image data. It will,
304         // however, cause some gamut clipping if your colorspace is far from sRGB,
305         // as it cannot represent values outside [0,1]. NOTE: If you construct
306         // a chain where you end up bouncing pixels in non-linear light
307         // (gamma different from GAMMA_LINEAR), this will be the wrong thing.
308         // However, it's hard to see how this could happen in a non-contrived
309         // chain; few effects ever need texture bounce or resizing without also
310         // combining multiple pixels, which really needs linear light and thus
311         // triggers a conversion before the bounce.
312         //
313         // If you don't need alpha (or can do with very little of it), GL_RGB10_A2
314         // is even better, as it has two more bits for each color component. There
315         // is no GL_SRGB10, unfortunately, so on its own, it is somewhat worse than
316         // GL_SRGB8, but you can set <transformation> to SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION,
317         // and sqrt(x) will be stored instead of x. This is a rough approximation to
318         // the sRGB curve, and reduces maximum error (in sRGB distance) by almost an
319         // order of magnitude, well below what you can get from 8-bit true sRGB.
320         // (Note that this strategy avoids the problem with bounced non-linear data
321         // above, since the square root is turned off in that case.) However, texture
322         // filtering will happen on the transformed values, so if you have heavy
323         // downscaling or the likes (e.g. mipmaps), you could get subtly bad results.
324         // You'll need to see which of the two that works the best for you in practice.
325         void set_intermediate_format(
326                 GLenum intermediate_format,
327                 FramebufferTransformation transformation = NO_FRAMEBUFFER_TRANSFORMATION)
328         {
329                 this->intermediate_format = intermediate_format;
330                 this->intermediate_transformation = transformation;
331         }
332
333         void finalize();
334
335         // Measure the GPU time used for each actual phase during rendering.
336         // Note that this is only available if GL_ARB_timer_query
337         // (or, equivalently, OpenGL 3.3) is available. Also note that measurement
338         // will incur a performance cost, as we wait for the measurements to
339         // complete at the end of rendering.
340         void enable_phase_timing(bool enable);
341         void reset_phase_timing();
342         void print_phase_timing();
343
344         void render_to_screen()
345         {
346                 render_to_fbo(0, 0, 0);
347         }
348
349         // Render the effect chain to the given FBO. If width=height=0, keeps
350         // the current viewport.
351         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
352
353         Effect *last_added_effect() {
354                 if (nodes.empty()) {
355                         return NULL;
356                 } else {
357                         return nodes.back()->effect;
358                 }       
359         }
360
361         // API for manipulating the graph directly. Intended to be used from
362         // effects and by EffectChain itself.
363         //
364         // Note that for nodes with multiple inputs, the order of calls to
365         // connect_nodes() will matter.
366         Node *add_node(Effect *effect);
367         void connect_nodes(Node *sender, Node *receiver);
368         void replace_receiver(Node *old_receiver, Node *new_receiver);
369         void replace_sender(Node *new_sender, Node *receiver);
370         void insert_node_between(Node *sender, Node *middle, Node *receiver);
371         Node *find_node_for_effect(Effect *effect) { return node_map[effect]; }
372
373         // Get the OpenGL sampler (GL_TEXTURE0, GL_TEXTURE1, etc.) for the
374         // input of the given node, so that one can modify the sampler state
375         // directly. Only valid to call during set_gl_state().
376         //
377         // Also, for this to be allowed, <node>'s effect must have
378         // needs_texture_bounce() set, so that it samples directly from a
379         // single-sampler input, or from an RTT texture.
380         GLenum get_input_sampler(Node *node, unsigned input_num) const;
381
382         // Whether input <input_num> of <node> corresponds to a single sampler
383         // (see get_input_sampler()). Normally, you should not need to call this;
384         // however, if the input Effect has set override_texture_bounce(),
385         // this will return false, and you could be flexible and check it first
386         // if you want.
387         GLenum has_input_sampler(Node *node, unsigned input_num) const;
388
389         // Get the current resource pool assigned to this EffectChain.
390         // Primarily to let effects allocate textures as needed.
391         // Any resources you get from the pool must be returned to the pool
392         // no later than in the Effect's destructor.
393         ResourcePool *get_resource_pool() { return resource_pool; }
394
395 private:
396         // Make sure the output rectangle is at least large enough to hold
397         // the given input rectangle in both dimensions, and is of the
398         // current aspect ratio (aspect_nom/aspect_denom).
399         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
400
401         // Compute the input sizes for all inputs for all effects in a given phase,
402         // and inform the effects about the results.    
403         void inform_input_sizes(Phase *phase);
404
405         // Determine the preferred output size of a given phase.
406         // Requires that all input phases (if any) already have output sizes set.
407         void find_output_size(Phase *phase);
408
409         // Find all inputs eventually feeding into this effect that have
410         // output gamma different from GAMMA_LINEAR.
411         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
412
413         // Create a GLSL program computing the effects for this phase in order.
414         void compile_glsl_program(Phase *phase);
415
416         // Create all GLSL programs needed to compute the given effect, and all outputs
417         // that depend on it (whenever possible). Returns the phase that has <output>
418         // as the last effect. Also pushes all phases in order onto <phases>.
419         Phase *construct_phase(Node *output, std::map<Node *, Phase *> *completed_effects);
420
421         // Execute one phase, ie. set up all inputs, effects and outputs, and render the quad.
422         void execute_phase(Phase *phase, bool last_phase,
423                            std::set<GLint> *bound__attribute_indices,
424                            std::map<Phase *, GLuint> *output_textures,
425                            std::set<Phase *> *generated_mipmaps);
426
427         // Set up uniforms for one phase. The program must already be bound.
428         void setup_uniforms(Phase *phase);
429
430         // Set up the given sampler number for sampling from an RTT texture.
431         void setup_rtt_sampler(int sampler_num, bool use_mipmaps);
432
433         // Output the current graph to the given file in a Graphviz-compatible format;
434         // only useful for debugging.
435         void output_dot(const char *filename);
436         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
437         void output_dot_edge(FILE *fp,
438                              const std::string &from_node_id,
439                              const std::string &to_node_id,
440                              const std::vector<std::string> &labels);
441
442         // Some of the graph algorithms assume that the nodes array is sorted
443         // topologically (inputs are always before outputs), but some operations
444         // (like graph rewriting) can change that. This function restores that order.
445         void sort_all_nodes_topologically();
446
447         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
448         // links that go to nodes not in the set will be ignored.
449         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
450
451         // Utility function used by topological_sort() to do a depth-first search.
452         // The reason why we store nodes left to visit instead of a more conventional
453         // list of nodes to visit is that we want to be able to limit ourselves to
454         // a subgraph instead of all nodes. The set thus serves a dual purpose.
455         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
456
457         // Used during finalize().
458         void find_color_spaces_for_inputs();
459         void propagate_alpha();
460         void propagate_gamma_and_color_space();
461         Node *find_output_node();
462
463         bool node_needs_colorspace_fix(Node *node);
464         void fix_internal_color_spaces();
465         void fix_output_color_space();
466
467         bool node_needs_alpha_fix(Node *node);
468         void fix_internal_alpha(unsigned step);
469         void fix_output_alpha();
470
471         bool node_needs_gamma_fix(Node *node);
472         void fix_internal_gamma_by_asking_inputs(unsigned step);
473         void fix_internal_gamma_by_inserting_nodes(unsigned step);
474         void fix_output_gamma();
475         void add_ycbcr_conversion_if_needed();
476         void add_dither_if_needed();
477
478         float aspect_nom, aspect_denom;
479         ImageFormat output_format;
480         OutputAlphaFormat output_alpha_format;
481
482         bool output_color_rgba, output_color_ycbcr;
483         YCbCrFormat output_ycbcr_format;              // If output_color_ycbcr is true.
484         YCbCrOutputSplitting output_ycbcr_splitting;  // If output_color_ycbcr is true.
485
486         std::vector<Node *> nodes;
487         std::map<Effect *, Node *> node_map;
488         Effect *dither_effect;
489
490         std::vector<Input *> inputs;  // Also contained in nodes.
491         std::vector<Phase *> phases;
492
493         GLenum intermediate_format;
494         FramebufferTransformation intermediate_transformation;
495         unsigned num_dither_bits;
496         OutputOrigin output_origin;
497         bool finalized;
498         GLuint vbo;  // Contains vertex and texture coordinate data.
499
500         ResourcePool *resource_pool;
501         bool owns_resource_pool;
502
503         bool do_phase_timing;
504 };
505
506 }  // namespace movit
507
508 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)