]> git.sesse.net Git - movit/blob - effect_chain.h
Use UBOs instead of glUniform. Work in progress; no clear wins seen yet.
[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 // A node in the graph; basically an effect and some associated information.
103 class Node {
104 public:
105         Effect *effect;
106         bool disabled;
107
108         // Edges in the graph (forward and backward).
109         std::vector<Node *> outgoing_links;
110         std::vector<Node *> incoming_links;
111
112         // For unit tests only. Do not use from other code.
113         // Will contain an arbitrary choice if the node is in multiple phases.
114         Phase *containing_phase;
115
116 private:
117         // Logical size of the output of this effect, ie. the resolution
118         // you would get if you sampled it as a texture. If it is undefined
119         // (since the inputs differ in resolution), it will be 0x0.
120         // If both this and output_texture_{width,height} are set,
121         // they will be equal.
122         unsigned output_width, output_height;
123
124         // If the effect has is_single_texture(), or if the output went to RTT
125         // and that texture has been bound to a sampler, the sampler number
126         // will be stored here.
127         //
128         // TODO: Can an RTT texture be used as inputs to multiple effects
129         // within the same phase? If so, we have a problem with modifying
130         // sampler state here.
131         int bound_sampler_num;
132
133         // Used during the building of the effect chain.
134         Colorspace output_color_space;
135         GammaCurve output_gamma_curve;
136         AlphaType output_alpha_type;
137         bool needs_mipmaps;  // Directly or indirectly.
138
139         // Set if this effect, and all effects consuming output from this node
140         // (in the same phase) have one_to_one_sampling() set.
141         bool one_to_one_sampling;
142
143         friend class EffectChain;
144 };
145
146 // A rendering phase; a single GLSL program rendering a single quad.
147 struct Phase {
148         Node *output_node;
149
150         GLuint glsl_program_num;  // Owned by the resource_pool.
151
152         // Position and texcoord attribute indexes, although it doesn't matter
153         // which is which, because they contain the same data.
154         std::set<GLint> attribute_indexes;
155
156         bool input_needs_mipmaps;
157
158         // Inputs are only inputs from other phases (ie., those that come from RTT);
159         // input textures are counted as part of <effects>.
160         std::vector<Phase *> inputs;
161         // Bound sampler numbers for each input. Redundant in a sense
162         // (it always corresponds to the index), but we need somewhere
163         // to hold the value for the uniform.
164         std::vector<int> input_samplers;
165         std::vector<Node *> effects;  // In order.
166         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
167
168         // Identifier used to create unique variables in GLSL.
169         // Unique per-phase to increase cacheability of compiled shaders.
170         std::map<Node *, std::string> effect_ids;
171
172         // Uniforms for this phase; combined from all the effects.
173         std::vector<Uniform<int> > uniforms_sampler2d;
174         std::vector<Uniform<bool> > uniforms_bool;
175         std::vector<Uniform<int> > uniforms_int;
176         std::vector<Uniform<float> > uniforms_float;
177         std::vector<Uniform<float> > uniforms_vec2;
178         std::vector<Uniform<float> > uniforms_vec3;
179         std::vector<Uniform<float> > uniforms_vec4;
180         std::vector<Uniform<Eigen::Matrix3d> > uniforms_mat3;
181
182         GLuint ubo;  // GL_INVALID_INDEX if not using UBOs.
183         GLuint uniform_block_index;
184         std::vector<char> ubo_data;
185
186         // For measurement of GPU time used.
187         std::list<GLuint> timer_query_objects_running;
188         std::list<GLuint> timer_query_objects_free;
189         uint64_t time_elapsed_ns;
190         uint64_t num_measured_iterations;
191 };
192
193 class EffectChain {
194 public:
195         // Aspect: e.g. 16.0f, 9.0f for 16:9.
196         // resource_pool is a pointer to a ResourcePool with which to share shaders
197         // and other resources (see resource_pool.h). If NULL (the default),
198         // will create its own that is not shared with anything else. Does not take
199         // ownership of the passed-in ResourcePool, but will naturally take ownership
200         // of its own internal one if created.
201         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL, GLenum intermediate_format = GL_RGBA16F);
202         ~EffectChain();
203
204         // User API:
205         // input, effects, output, finalize need to come in that specific order.
206
207         // EffectChain takes ownership of the given input.
208         // input is returned back for convenience.
209         Input *add_input(Input *input);
210
211         // EffectChain takes ownership of the given effect.
212         // effect is returned back for convenience.
213         Effect *add_effect(Effect *effect) {
214                 return add_effect(effect, last_added_effect());
215         }
216         Effect *add_effect(Effect *effect, Effect *input) {
217                 std::vector<Effect *> inputs;
218                 inputs.push_back(input);
219                 return add_effect(effect, inputs);
220         }
221         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
222                 std::vector<Effect *> inputs;
223                 inputs.push_back(input1);
224                 inputs.push_back(input2);
225                 return add_effect(effect, inputs);
226         }
227         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3) {
228                 std::vector<Effect *> inputs;
229                 inputs.push_back(input1);
230                 inputs.push_back(input2);
231                 inputs.push_back(input3);
232                 return add_effect(effect, inputs);
233         }
234         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3, Effect *input4) {
235                 std::vector<Effect *> inputs;
236                 inputs.push_back(input1);
237                 inputs.push_back(input2);
238                 inputs.push_back(input3);
239                 inputs.push_back(input4);
240                 return add_effect(effect, inputs);
241         }
242         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3, Effect *input4, Effect *input5) {
243                 std::vector<Effect *> inputs;
244                 inputs.push_back(input1);
245                 inputs.push_back(input2);
246                 inputs.push_back(input3);
247                 inputs.push_back(input4);
248                 inputs.push_back(input5);
249                 return add_effect(effect, inputs);
250         }
251         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
252
253         // Adds an RGBA output. Note that you can have at most one RGBA output and one
254         // Y'CbCr output (see below for details).
255         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
256
257         // Adds an YCbCr output. Note that you can only have one output.
258         // Currently, only chunked packed output is supported, and only 4:4:4
259         // (so chroma_subsampling_x and chroma_subsampling_y must both be 1).
260         //
261         // If you have both RGBA and Y'CbCr output, the RGBA output will come
262         // in the last draw buffer. Also, <format> and <alpha_format> must be
263         // identical between the two.
264         void add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
265                               const YCbCrFormat &ycbcr_format,
266                               YCbCrOutputSplitting output_splitting = YCBCR_OUTPUT_INTERLEAVED);
267
268         // Set number of output bits, to scale the dither.
269         // 8 is the right value for most outputs.
270         // The default, 0, is a special value that means no dither.
271         void set_dither_bits(unsigned num_bits)
272         {
273                 this->num_dither_bits = num_bits;
274         }
275
276         // Set where (0,0) is taken to be in the output. The default is
277         // OUTPUT_ORIGIN_BOTTOM_LEFT, which is usually what you want
278         // (see OutputOrigin above for more details).
279         void set_output_origin(OutputOrigin output_origin)
280         {
281                 this->output_origin = output_origin;
282         }
283
284         void finalize();
285
286         // Measure the GPU time used for each actual phase during rendering.
287         // Note that this is only available if GL_ARB_timer_query
288         // (or, equivalently, OpenGL 3.3) is available. Also note that measurement
289         // will incur a performance cost, as we wait for the measurements to
290         // complete at the end of rendering.
291         void enable_phase_timing(bool enable);
292         void reset_phase_timing();
293         void print_phase_timing();
294
295         //void render(unsigned char *src, unsigned char *dst);
296         void render_to_screen()
297         {
298                 render_to_fbo(0, 0, 0);
299         }
300
301         // Render the effect chain to the given FBO. If width=height=0, keeps
302         // the current viewport.
303         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
304
305         Effect *last_added_effect() {
306                 if (nodes.empty()) {
307                         return NULL;
308                 } else {
309                         return nodes.back()->effect;
310                 }       
311         }
312
313         // API for manipulating the graph directly. Intended to be used from
314         // effects and by EffectChain itself.
315         //
316         // Note that for nodes with multiple inputs, the order of calls to
317         // connect_nodes() will matter.
318         Node *add_node(Effect *effect);
319         void connect_nodes(Node *sender, Node *receiver);
320         void replace_receiver(Node *old_receiver, Node *new_receiver);
321         void replace_sender(Node *new_sender, Node *receiver);
322         void insert_node_between(Node *sender, Node *middle, Node *receiver);
323         Node *find_node_for_effect(Effect *effect) { return node_map[effect]; }
324
325         // Get the OpenGL sampler (GL_TEXTURE0, GL_TEXTURE1, etc.) for the
326         // input of the given node, so that one can modify the sampler state
327         // directly. Only valid to call during set_gl_state().
328         //
329         // Also, for this to be allowed, <node>'s effect must have
330         // needs_texture_bounce() set, so that it samples directly from a
331         // single-sampler input, or from an RTT texture.
332         GLenum get_input_sampler(Node *node, unsigned input_num) const;
333
334         // Whether input <input_num> of <node> corresponds to a single sampler
335         // (see get_input_sampler()). Normally, you should not need to call this;
336         // however, if the input Effect has set override_texture_bounce(),
337         // this will return false, and you could be flexible and check it first
338         // if you want.
339         GLenum has_input_sampler(Node *node, unsigned input_num) const;
340
341         // Get the current resource pool assigned to this EffectChain.
342         // Primarily to let effects allocate textures as needed.
343         // Any resources you get from the pool must be returned to the pool
344         // no later than in the Effect's destructor.
345         ResourcePool *get_resource_pool() { return resource_pool; }
346
347 private:
348         // Make sure the output rectangle is at least large enough to hold
349         // the given input rectangle in both dimensions, and is of the
350         // current aspect ratio (aspect_nom/aspect_denom).
351         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
352
353         // Compute the input sizes for all inputs for all effects in a given phase,
354         // and inform the effects about the results.    
355         void inform_input_sizes(Phase *phase);
356
357         // Determine the preferred output size of a given phase.
358         // Requires that all input phases (if any) already have output sizes set.
359         void find_output_size(Phase *phase);
360
361         // Find all inputs eventually feeding into this effect that have
362         // output gamma different from GAMMA_LINEAR.
363         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
364
365         // Create a GLSL program computing the effects for this phase in order.
366         void compile_glsl_program(Phase *phase);
367
368         // Create all GLSL programs needed to compute the given effect, and all outputs
369         // that depend on it (whenever possible). Returns the phase that has <output>
370         // as the last effect. Also pushes all phases in order onto <phases>.
371         Phase *construct_phase(Node *output, std::map<Node *, Phase *> *completed_effects);
372
373         // Execute one phase, ie. set up all inputs, effects and outputs, and render the quad.
374         void execute_phase(Phase *phase, bool last_phase,
375                            std::set<GLint> *bound__attribute_indices,
376                            std::map<Phase *, GLuint> *output_textures,
377                            std::set<Phase *> *generated_mipmaps);
378
379         // Set up uniforms for one phase. The program must already be bound.
380         void setup_uniforms(Phase *phase);
381
382         // Set up the given sampler number for sampling from an RTT texture.
383         void setup_rtt_sampler(int sampler_num, bool use_mipmaps);
384
385         // Output the current graph to the given file in a Graphviz-compatible format;
386         // only useful for debugging.
387         void output_dot(const char *filename);
388         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
389         void output_dot_edge(FILE *fp,
390                              const std::string &from_node_id,
391                              const std::string &to_node_id,
392                              const std::vector<std::string> &labels);
393
394         // Some of the graph algorithms assume that the nodes array is sorted
395         // topologically (inputs are always before outputs), but some operations
396         // (like graph rewriting) can change that. This function restores that order.
397         void sort_all_nodes_topologically();
398
399         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
400         // links that go to nodes not in the set will be ignored.
401         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
402
403         // Utility function used by topological_sort() to do a depth-first search.
404         // The reason why we store nodes left to visit instead of a more conventional
405         // list of nodes to visit is that we want to be able to limit ourselves to
406         // a subgraph instead of all nodes. The set thus serves a dual purpose.
407         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
408
409         // Used during finalize().
410         void find_color_spaces_for_inputs();
411         void propagate_alpha();
412         void propagate_gamma_and_color_space();
413         Node *find_output_node();
414
415         bool node_needs_colorspace_fix(Node *node);
416         void fix_internal_color_spaces();
417         void fix_output_color_space();
418
419         bool node_needs_alpha_fix(Node *node);
420         void fix_internal_alpha(unsigned step);
421         void fix_output_alpha();
422
423         bool node_needs_gamma_fix(Node *node);
424         void fix_internal_gamma_by_asking_inputs(unsigned step);
425         void fix_internal_gamma_by_inserting_nodes(unsigned step);
426         void fix_output_gamma();
427         void add_ycbcr_conversion_if_needed();
428         void add_dither_if_needed();
429
430         float aspect_nom, aspect_denom;
431         ImageFormat output_format;
432         OutputAlphaFormat output_alpha_format;
433
434         bool output_color_rgba, output_color_ycbcr;
435         YCbCrFormat output_ycbcr_format;              // If output_color_ycbcr is true.
436         YCbCrOutputSplitting output_ycbcr_splitting;  // If output_color_ycbcr is true.
437
438         std::vector<Node *> nodes;
439         std::map<Effect *, Node *> node_map;
440         Effect *dither_effect;
441
442         std::vector<Input *> inputs;  // Also contained in nodes.
443         std::vector<Phase *> phases;
444
445         GLenum intermediate_format;
446         unsigned num_dither_bits;
447         OutputOrigin output_origin;
448         bool finalized;
449         GLuint vbo;  // Contains vertex and texture coordinate data.
450
451         ResourcePool *resource_pool;
452         bool owns_resource_pool;
453
454         bool do_phase_timing;
455 };
456
457 }  // namespace movit
458
459 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)