]> git.sesse.net Git - movit/blob - effect_chain.h
Reduce the amount of computation in combine_two_samples().
[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 <map>
27 #include <set>
28 #include <string>
29 #include <vector>
30 #include <Eigen/Core>
31
32 #include "effect.h"
33 #include "image_format.h"
34 #include "ycbcr.h"
35
36 namespace movit {
37
38 class Effect;
39 class Input;
40 struct Phase;
41 class ResourcePool;
42
43 // For internal use within Node.
44 enum AlphaType {
45         ALPHA_INVALID = -1,
46         ALPHA_BLANK,
47         ALPHA_PREMULTIPLIED,
48         ALPHA_POSTMULTIPLIED,
49 };
50
51 // Whether you want pre- or postmultiplied alpha in the output
52 // (see effect.h for a discussion of pre- versus postmultiplied alpha).
53 enum OutputAlphaFormat {
54         OUTPUT_ALPHA_FORMAT_PREMULTIPLIED,
55         OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED,
56 };
57
58 // RGBA output is nearly always packed; Y'CbCr, however, is often planar
59 // due to chroma subsampling. This enum controls how add_ycbcr_output()
60 // distributes the color channels between the fragment shader outputs.
61 // Obviously, anything except YCBCR_OUTPUT_INTERLEAVED will be meaningless
62 // unless you use render_to_fbo() and have an FBO with multiple render
63 // targets attached (the other outputs will be discarded).
64 enum YCbCrOutputSplitting {
65         // Only one output: Store Y'CbCr into the first three output channels,
66         // respectively, plus alpha. This is also called “chunked” or
67         // ”packed” mode.
68         YCBCR_OUTPUT_INTERLEAVED,
69
70         // Store Y' and alpha into the first output (in the red and alpha
71         // channels; effect to the others is undefined), and Cb and Cr into
72         // the first two channels of the second output. This is particularly
73         // useful if you want to end up in a format like NV12, where all the
74         // Y' samples come first and then Cb and Cr come interlevaed afterwards.
75         // You will still need to do the chroma subsampling yourself to actually
76         // get down to NV12, though.
77         YCBCR_OUTPUT_SPLIT_Y_AND_CBCR,
78
79         // Store Y' and alpha into the first output, Cb into the first channel
80         // of the second output and Cr into the first channel of the third output.
81         // (Effect on the other channels is undefined.) Essentially gives you
82         // 4:4:4 planar, or ”yuv444p”.
83         YCBCR_OUTPUT_PLANAR,
84 };
85
86 // Where (0,0) is taken to be in the output. If you want to render to an
87 // OpenGL screen, you should keep the default of bottom-left, as that is
88 // OpenGL's natural coordinate system. However, there are cases, such as if you
89 // render to an FBO and read the pixels back into some other system, where
90 // you'd want a top-left origin; if so, an additional flip step will be added
91 // at the very end (but done in a vertex shader, so it will have zero extra
92 // cost).
93 //
94 // Note that Movit's coordinate system in general consistently puts (0,0) in
95 // the top left for _input_, no matter what you set as output origin.
96 enum OutputOrigin {
97         OUTPUT_ORIGIN_BOTTOM_LEFT,
98         OUTPUT_ORIGIN_TOP_LEFT,
99 };
100
101 // A node in the graph; basically an effect and some associated information.
102 class Node {
103 public:
104         Effect *effect;
105         bool disabled;
106
107         // Edges in the graph (forward and backward).
108         std::vector<Node *> outgoing_links;
109         std::vector<Node *> incoming_links;
110
111         // For unit tests only. Do not use from other code.
112         // Will contain an arbitrary choice if the node is in multiple phases.
113         Phase *containing_phase;
114
115 private:
116         // Logical size of the output of this effect, ie. the resolution
117         // you would get if you sampled it as a texture. If it is undefined
118         // (since the inputs differ in resolution), it will be 0x0.
119         // If both this and output_texture_{width,height} are set,
120         // they will be equal.
121         unsigned output_width, output_height;
122
123         // If the effect has is_single_texture(), or if the output went to RTT
124         // and that texture has been bound to a sampler, the sampler number
125         // will be stored here.
126         //
127         // TODO: Can an RTT texture be used as inputs to multiple effects
128         // within the same phase? If so, we have a problem with modifying
129         // sampler state here.
130         int bound_sampler_num;
131
132         // Used during the building of the effect chain.
133         Colorspace output_color_space;
134         GammaCurve output_gamma_curve;
135         AlphaType output_alpha_type;
136         bool needs_mipmaps;  // Directly or indirectly.
137
138         // Set if this effect, and all effects consuming output from this node
139         // (in the same phase) have one_to_one_sampling() set.
140         bool one_to_one_sampling;
141
142         friend class EffectChain;
143 };
144
145 // A rendering phase; a single GLSL program rendering a single quad.
146 struct Phase {
147         Node *output_node;
148
149         GLuint glsl_program_num;  // Owned by the resource_pool.
150         bool input_needs_mipmaps;
151
152         // Inputs are only inputs from other phases (ie., those that come from RTT);
153         // input textures are counted as part of <effects>.
154         std::vector<Phase *> inputs;
155         // Bound sampler numbers for each input. Redundant in a sense
156         // (it always corresponds to the index), but we need somewhere
157         // to hold the value for the uniform.
158         std::vector<int> input_samplers;
159         std::vector<Node *> effects;  // In order.
160         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
161
162         // Identifier used to create unique variables in GLSL.
163         // Unique per-phase to increase cacheability of compiled shaders.
164         std::map<Node *, std::string> effect_ids;
165
166         // Uniforms for this phase; combined from all the effects.
167         std::vector<Uniform<int> > uniforms_sampler2d;
168         std::vector<Uniform<bool> > uniforms_bool;
169         std::vector<Uniform<int> > uniforms_int;
170         std::vector<Uniform<float> > uniforms_float;
171         std::vector<Uniform<float> > uniforms_vec2;
172         std::vector<Uniform<float> > uniforms_vec3;
173         std::vector<Uniform<float> > uniforms_vec4;
174         std::vector<Uniform<Eigen::Matrix3d> > uniforms_mat3;
175
176         // For measurement of GPU time used.
177         GLuint timer_query_object;
178         uint64_t time_elapsed_ns;
179         uint64_t num_measured_iterations;
180 };
181
182 class EffectChain {
183 public:
184         // Aspect: e.g. 16.0f, 9.0f for 16:9.
185         // resource_pool is a pointer to a ResourcePool with which to share shaders
186         // and other resources (see resource_pool.h). If NULL (the default),
187         // will create its own that is not shared with anything else. Does not take
188         // ownership of the passed-in ResourcePool, but will naturally take ownership
189         // of its own internal one if created.
190         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL);
191         ~EffectChain();
192
193         // User API:
194         // input, effects, output, finalize need to come in that specific order.
195
196         // EffectChain takes ownership of the given input.
197         // input is returned back for convenience.
198         Input *add_input(Input *input);
199
200         // EffectChain takes ownership of the given effect.
201         // effect is returned back for convenience.
202         Effect *add_effect(Effect *effect) {
203                 return add_effect(effect, last_added_effect());
204         }
205         Effect *add_effect(Effect *effect, Effect *input) {
206                 std::vector<Effect *> inputs;
207                 inputs.push_back(input);
208                 return add_effect(effect, inputs);
209         }
210         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
211                 std::vector<Effect *> inputs;
212                 inputs.push_back(input1);
213                 inputs.push_back(input2);
214                 return add_effect(effect, inputs);
215         }
216         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3) {
217                 std::vector<Effect *> inputs;
218                 inputs.push_back(input1);
219                 inputs.push_back(input2);
220                 inputs.push_back(input3);
221                 return add_effect(effect, inputs);
222         }
223         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
224
225         // Adds an RGB output. Note that you can only have one output.
226         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
227
228         // Adds an YCbCr output. Note that you can only have one output.
229         // Currently, only chunked packed output is supported, and only 4:4:4
230         // (so chroma_subsampling_x and chroma_subsampling_y must both be 1).
231         void add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
232                               const YCbCrFormat &ycbcr_format,
233                               YCbCrOutputSplitting output_splitting = YCBCR_OUTPUT_INTERLEAVED);
234
235         // Set number of output bits, to scale the dither.
236         // 8 is the right value for most outputs.
237         // The default, 0, is a special value that means no dither.
238         void set_dither_bits(unsigned num_bits)
239         {
240                 this->num_dither_bits = num_bits;
241         }
242
243         // Set where (0,0) is taken to be in the output. The default is
244         // OUTPUT_ORIGIN_BOTTOM_LEFT, which is usually what you want
245         // (see OutputOrigin above for more details).
246         void set_output_origin(OutputOrigin output_origin)
247         {
248                 this->output_origin = output_origin;
249         }
250
251         void finalize();
252
253         // Measure the GPU time used for each actual phase during rendering.
254         // Note that this is only available if GL_ARB_timer_query
255         // (or, equivalently, OpenGL 3.3) is available. Also note that measurement
256         // will incur a performance cost, as we wait for the measurements to
257         // complete at the end of rendering.
258         void enable_phase_timing(bool enable);
259         void reset_phase_timing();
260         void print_phase_timing();
261
262         //void render(unsigned char *src, unsigned char *dst);
263         void render_to_screen()
264         {
265                 render_to_fbo(0, 0, 0);
266         }
267
268         // Render the effect chain to the given FBO. If width=height=0, keeps
269         // the current viewport.
270         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
271
272         Effect *last_added_effect() {
273                 if (nodes.empty()) {
274                         return NULL;
275                 } else {
276                         return nodes.back()->effect;
277                 }       
278         }
279
280         // API for manipulating the graph directly. Intended to be used from
281         // effects and by EffectChain itself.
282         //
283         // Note that for nodes with multiple inputs, the order of calls to
284         // connect_nodes() will matter.
285         Node *add_node(Effect *effect);
286         void connect_nodes(Node *sender, Node *receiver);
287         void replace_receiver(Node *old_receiver, Node *new_receiver);
288         void replace_sender(Node *new_sender, Node *receiver);
289         void insert_node_between(Node *sender, Node *middle, Node *receiver);
290         Node *find_node_for_effect(Effect *effect) { return node_map[effect]; }
291
292         // Get the OpenGL sampler (GL_TEXTURE0, GL_TEXTURE1, etc.) for the
293         // input of the given node, so that one can modify the sampler state
294         // directly. Only valid to call during set_gl_state().
295         //
296         // Also, for this to be allowed, <node>'s effect must have
297         // needs_texture_bounce() set, so that it samples directly from a
298         // single-sampler input, or from an RTT texture.
299         GLenum get_input_sampler(Node *node, unsigned input_num) const;
300
301         // Get the current resource pool assigned to this EffectChain.
302         // Primarily to let effects allocate textures as needed.
303         // Any resources you get from the pool must be returned to the pool
304         // no later than in the Effect's destructor.
305         ResourcePool *get_resource_pool() { return resource_pool; }
306
307 private:
308         // Make sure the output rectangle is at least large enough to hold
309         // the given input rectangle in both dimensions, and is of the
310         // current aspect ratio (aspect_nom/aspect_denom).
311         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
312
313         // Compute the input sizes for all inputs for all effects in a given phase,
314         // and inform the effects about the results.    
315         void inform_input_sizes(Phase *phase);
316
317         // Determine the preferred output size of a given phase.
318         // Requires that all input phases (if any) already have output sizes set.
319         void find_output_size(Phase *phase);
320
321         // Find all inputs eventually feeding into this effect that have
322         // output gamma different from GAMMA_LINEAR.
323         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
324
325         // Create a GLSL program computing the effects for this phase in order.
326         void compile_glsl_program(Phase *phase);
327
328         // Create all GLSL programs needed to compute the given effect, and all outputs
329         // that depend on it (whenever possible). Returns the phase that has <output>
330         // as the last effect. Also pushes all phases in order onto <phases>.
331         Phase *construct_phase(Node *output, std::map<Node *, Phase *> *completed_effects);
332
333         // Execute one phase, ie. set up all inputs, effects and outputs, and render the quad.
334         void execute_phase(Phase *phase, bool last_phase, std::map<Phase *, GLuint> *output_textures, std::set<Phase *> *generated_mipmaps);
335
336         // Set up uniforms for one phase. The program must already be bound.
337         void setup_uniforms(Phase *phase);
338
339         // Set up the given sampler number for sampling from an RTT texture.
340         void setup_rtt_sampler(int sampler_num, bool use_mipmaps);
341
342         // Output the current graph to the given file in a Graphviz-compatible format;
343         // only useful for debugging.
344         void output_dot(const char *filename);
345         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
346         void output_dot_edge(FILE *fp,
347                              const std::string &from_node_id,
348                              const std::string &to_node_id,
349                              const std::vector<std::string> &labels);
350
351         // Some of the graph algorithms assume that the nodes array is sorted
352         // topologically (inputs are always before outputs), but some operations
353         // (like graph rewriting) can change that. This function restores that order.
354         void sort_all_nodes_topologically();
355
356         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
357         // links that go to nodes not in the set will be ignored.
358         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
359
360         // Utility function used by topological_sort() to do a depth-first search.
361         // The reason why we store nodes left to visit instead of a more conventional
362         // list of nodes to visit is that we want to be able to limit ourselves to
363         // a subgraph instead of all nodes. The set thus serves a dual purpose.
364         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
365
366         // Used during finalize().
367         void find_color_spaces_for_inputs();
368         void propagate_alpha();
369         void propagate_gamma_and_color_space();
370         Node *find_output_node();
371
372         bool node_needs_colorspace_fix(Node *node);
373         void fix_internal_color_spaces();
374         void fix_output_color_space();
375
376         bool node_needs_alpha_fix(Node *node);
377         void fix_internal_alpha(unsigned step);
378         void fix_output_alpha();
379
380         bool node_needs_gamma_fix(Node *node);
381         void fix_internal_gamma_by_asking_inputs(unsigned step);
382         void fix_internal_gamma_by_inserting_nodes(unsigned step);
383         void fix_output_gamma();
384         void add_ycbcr_conversion_if_needed();
385         void add_dither_if_needed();
386
387         float aspect_nom, aspect_denom;
388         ImageFormat output_format;
389         OutputAlphaFormat output_alpha_format;
390
391         enum OutputColorType { OUTPUT_COLOR_RGB, OUTPUT_COLOR_YCBCR };
392         OutputColorType output_color_type;
393         YCbCrFormat output_ycbcr_format;              // If output_color_type == OUTPUT_COLOR_YCBCR.
394         YCbCrOutputSplitting output_ycbcr_splitting;  // If output_color_type == OUTPUT_COLOR_YCBCR.
395
396         std::vector<Node *> nodes;
397         std::map<Effect *, Node *> node_map;
398         Effect *dither_effect;
399
400         std::vector<Input *> inputs;  // Also contained in nodes.
401         std::vector<Phase *> phases;
402
403         unsigned num_dither_bits;
404         OutputOrigin output_origin;
405         bool finalized;
406
407         ResourcePool *resource_pool;
408         bool owns_resource_pool;
409
410         bool do_phase_timing;
411 };
412
413 }  // namespace movit
414
415 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)