]> git.sesse.net Git - movit/blob - effect_chain.h
2f088b607feeec92fd3bb98c69be5cafde2329dd
[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
31 #include "image_format.h"
32
33 namespace movit {
34
35 class Effect;
36 class Input;
37 struct Phase;
38 class ResourcePool;
39
40 // For internal use within Node.
41 enum AlphaType {
42         ALPHA_INVALID = -1,
43         ALPHA_BLANK,
44         ALPHA_PREMULTIPLIED,
45         ALPHA_POSTMULTIPLIED,
46 };
47
48 // Whether you want pre- or postmultiplied alpha in the output
49 // (see effect.h for a discussion of pre- versus postmultiplied alpha).
50 enum OutputAlphaFormat {
51         OUTPUT_ALPHA_FORMAT_PREMULTIPLIED,
52         OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED,
53 };
54
55 // A node in the graph; basically an effect and some associated information.
56 class Node {
57 public:
58         Effect *effect;
59         bool disabled;
60
61         // Edges in the graph (forward and backward).
62         std::vector<Node *> outgoing_links;
63         std::vector<Node *> incoming_links;
64
65         // For unit tests only. Do not use from other code.
66         // Will contain an arbitrary choice if the node is in multiple phases.
67         Phase *containing_phase;
68
69 private:
70         // Logical size of the output of this effect, ie. the resolution
71         // you would get if you sampled it as a texture. If it is undefined
72         // (since the inputs differ in resolution), it will be 0x0.
73         // If both this and output_texture_{width,height} are set,
74         // they will be equal.
75         unsigned output_width, output_height;
76
77         // If the effect has is_single_texture(), or if the output went to RTT
78         // and that texture has been bound to a sampler, the sampler number
79         // will be stored here.
80         //
81         // TODO: Can an RTT texture be used as inputs to multiple effects
82         // within the same phase? If so, we have a problem with modifying
83         // sampler state here.
84         int bound_sampler_num;
85
86         // Used during the building of the effect chain.
87         Colorspace output_color_space;
88         GammaCurve output_gamma_curve;
89         AlphaType output_alpha_type;
90         bool needs_mipmaps;  // Directly or indirectly.
91
92         // Set if this effect, and all effects consuming output from this node
93         // (in the same phase) have one_to_one_sampling() set.
94         bool one_to_one_sampling;
95
96         friend class EffectChain;
97 };
98
99 // A rendering phase; a single GLSL program rendering a single quad.
100 struct Phase {
101         Node *output_node;
102
103         GLuint glsl_program_num;  // Owned by the resource_pool.
104         bool input_needs_mipmaps;
105
106         // Inputs are only inputs from other phases (ie., those that come from RTT);
107         // input textures are counted as part of <effects>.
108         std::vector<Phase *> inputs;
109         std::vector<Node *> effects;  // In order.
110         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
111
112         // Identifier used to create unique variables in GLSL.
113         // Unique per-phase to increase cacheability of compiled shaders.
114         std::map<Node *, std::string> effect_ids;
115
116         // For measurement of GPU time used.
117         GLuint timer_query_object;
118         uint64_t time_elapsed_ns;
119         uint64_t num_measured_iterations;
120 };
121
122 class EffectChain {
123 public:
124         // Aspect: e.g. 16.0f, 9.0f for 16:9.
125         // resource_pool is a pointer to a ResourcePool with which to share shaders
126         // and other resources (see resource_pool.h). If NULL (the default),
127         // will create its own that is not shared with anything else. Does not take
128         // ownership of the passed-in ResourcePool, but will naturally take ownership
129         // of its own internal one if created.
130         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL);
131         ~EffectChain();
132
133         // User API:
134         // input, effects, output, finalize need to come in that specific order.
135
136         // EffectChain takes ownership of the given input.
137         // input is returned back for convenience.
138         Input *add_input(Input *input);
139
140         // EffectChain takes ownership of the given effect.
141         // effect is returned back for convenience.
142         Effect *add_effect(Effect *effect) {
143                 return add_effect(effect, last_added_effect());
144         }
145         Effect *add_effect(Effect *effect, Effect *input) {
146                 std::vector<Effect *> inputs;
147                 inputs.push_back(input);
148                 return add_effect(effect, inputs);
149         }
150         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
151                 std::vector<Effect *> inputs;
152                 inputs.push_back(input1);
153                 inputs.push_back(input2);
154                 return add_effect(effect, inputs);
155         }
156         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3) {
157                 std::vector<Effect *> inputs;
158                 inputs.push_back(input1);
159                 inputs.push_back(input2);
160                 inputs.push_back(input3);
161                 return add_effect(effect, inputs);
162         }
163         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
164
165         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
166
167         // Set number of output bits, to scale the dither.
168         // 8 is the right value for most outputs.
169         // The default, 0, is a special value that means no dither.
170         void set_dither_bits(unsigned num_bits)
171         {
172                 this->num_dither_bits = num_bits;
173         }
174
175         void finalize();
176
177         // Measure the GPU time used for each actual phase during rendering.
178         // Note that this is only available if GL_ARB_timer_query
179         // (or, equivalently, OpenGL 3.3) is available. Also note that measurement
180         // will incur a performance cost, as we wait for the measurements to
181         // complete at the end of rendering.
182         void enable_phase_timing(bool enable);
183         void reset_phase_timing();
184         void print_phase_timing();
185
186         //void render(unsigned char *src, unsigned char *dst);
187         void render_to_screen()
188         {
189                 render_to_fbo(0, 0, 0);
190         }
191
192         // Render the effect chain to the given FBO. If width=height=0, keeps
193         // the current viewport.
194         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
195
196         Effect *last_added_effect() {
197                 if (nodes.empty()) {
198                         return NULL;
199                 } else {
200                         return nodes.back()->effect;
201                 }       
202         }
203
204         // API for manipulating the graph directly. Intended to be used from
205         // effects and by EffectChain itself.
206         //
207         // Note that for nodes with multiple inputs, the order of calls to
208         // connect_nodes() will matter.
209         Node *add_node(Effect *effect);
210         void connect_nodes(Node *sender, Node *receiver);
211         void replace_receiver(Node *old_receiver, Node *new_receiver);
212         void replace_sender(Node *new_sender, Node *receiver);
213         void insert_node_between(Node *sender, Node *middle, Node *receiver);
214         Node *find_node_for_effect(Effect *effect) { return node_map[effect]; }
215
216         // Get the OpenGL sampler (GL_TEXTURE0, GL_TEXTURE1, etc.) for the
217         // input of the given node, so that one can modify the sampler state
218         // directly. Only valid to call during set_gl_state().
219         //
220         // Also, for this to be allowed, <node>'s effect must have
221         // needs_texture_bounce() set, so that it samples directly from a
222         // single-sampler input, or from an RTT texture.
223         GLenum get_input_sampler(Node *node, unsigned input_num) const;
224
225         // Get the current resource pool assigned to this EffectChain.
226         // Primarily to let effects allocate textures as needed.
227         // Any resources you get from the pool must be returned to the pool
228         // no later than in the Effect's destructor.
229         ResourcePool *get_resource_pool() { return resource_pool; }
230
231 private:
232         // Make sure the output rectangle is at least large enough to hold
233         // the given input rectangle in both dimensions, and is of the
234         // current aspect ratio (aspect_nom/aspect_denom).
235         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
236
237         // Compute the input sizes for all inputs for all effects in a given phase,
238         // and inform the effects about the results.    
239         void inform_input_sizes(Phase *phase);
240
241         // Determine the preferred output size of a given phase.
242         // Requires that all input phases (if any) already have output sizes set.
243         void find_output_size(Phase *phase);
244
245         // Find all inputs eventually feeding into this effect that have
246         // output gamma different from GAMMA_LINEAR.
247         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
248
249         // Create a GLSL program computing the effects for this phase in order.
250         void compile_glsl_program(Phase *phase);
251
252         // Create all GLSL programs needed to compute the given effect, and all outputs
253         // that depend on it (whenever possible). Returns the phase that has <output>
254         // as the last effect. Also pushes all phases in order onto <phases>.
255         Phase *construct_phase(Node *output, std::map<Node *, Phase *> *completed_effects);
256
257         // Execute one phase, ie. set up all inputs, effects and outputs, and render the quad.
258         void execute_phase(Phase *phase, bool last_phase, std::map<Phase *, GLuint> *output_textures, std::set<Phase *> *generated_mipmaps);
259
260         // Set up the given sampler number for sampling from an RTT texture,
261         // and bind it to "tex_" plus the given GLSL variable.
262         void setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const std::string &effect_id, bool use_mipmaps);
263
264         // Output the current graph to the given file in a Graphviz-compatible format;
265         // only useful for debugging.
266         void output_dot(const char *filename);
267         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
268         void output_dot_edge(FILE *fp,
269                              const std::string &from_node_id,
270                              const std::string &to_node_id,
271                              const std::vector<std::string> &labels);
272
273         // Some of the graph algorithms assume that the nodes array is sorted
274         // topologically (inputs are always before outputs), but some operations
275         // (like graph rewriting) can change that. This function restores that order.
276         void sort_all_nodes_topologically();
277
278         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
279         // links that go to nodes not in the set will be ignored.
280         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
281
282         // Utility function used by topological_sort() to do a depth-first search.
283         // The reason why we store nodes left to visit instead of a more conventional
284         // list of nodes to visit is that we want to be able to limit ourselves to
285         // a subgraph instead of all nodes. The set thus serves a dual purpose.
286         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
287
288         // Used during finalize().
289         void find_color_spaces_for_inputs();
290         void propagate_alpha();
291         void propagate_gamma_and_color_space();
292         Node *find_output_node();
293
294         bool node_needs_colorspace_fix(Node *node);
295         void fix_internal_color_spaces();
296         void fix_output_color_space();
297
298         bool node_needs_alpha_fix(Node *node);
299         void fix_internal_alpha(unsigned step);
300         void fix_output_alpha();
301
302         bool node_needs_gamma_fix(Node *node);
303         void fix_internal_gamma_by_asking_inputs(unsigned step);
304         void fix_internal_gamma_by_inserting_nodes(unsigned step);
305         void fix_output_gamma();
306         void add_dither_if_needed();
307
308         float aspect_nom, aspect_denom;
309         ImageFormat output_format;
310         OutputAlphaFormat output_alpha_format;
311
312         std::vector<Node *> nodes;
313         std::map<Effect *, Node *> node_map;
314         Effect *dither_effect;
315
316         std::vector<Input *> inputs;  // Also contained in nodes.
317         std::vector<Phase *> phases;
318
319         unsigned num_dither_bits;
320         bool finalized;
321
322         ResourcePool *resource_pool;
323         bool owns_resource_pool;
324
325         bool do_phase_timing;
326 };
327
328 }  // namespace movit
329
330 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)