Add YCbCr input. Required a bit of reworking of the sRGB extension stuff, but seems...
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include <GL/gl.h>
8 #include <GL/glext.h>
9
10 #include <algorithm>
11 #include <set>
12 #include <stack>
13 #include <vector>
14
15 #include "util.h"
16 #include "effect_chain.h"
17 #include "gamma_expansion_effect.h"
18 #include "gamma_compression_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "input.h"
21
22 EffectChain::EffectChain(unsigned width, unsigned height)
23         : width(width),
24           height(height),
25           finalized(false) {}
26
27 Input *EffectChain::add_input(Input *input)
28 {
29         char eff_id[256];
30         sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
31
32         effects.push_back(input);
33         inputs.push_back(input);
34         output_color_space.insert(std::make_pair(input, input->get_color_space()));
35         output_gamma_curve.insert(std::make_pair(input, input->get_gamma_curve()));
36         effect_ids.insert(std::make_pair(input, eff_id));
37         incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
38         return input;
39 }
40
41 void EffectChain::add_output(const ImageFormat &format)
42 {
43         output_format = format;
44 }
45
46 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
47 {
48         char effect_id[256];
49         sprintf(effect_id, "eff%u", (unsigned)effects.size());
50
51         effects.push_back(effect);
52         effect_ids.insert(std::make_pair(effect, effect_id));
53         assert(inputs.size() == effect->num_inputs());
54         for (unsigned i = 0; i < inputs.size(); ++i) {
55                 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
56                 outgoing_links[inputs[i]].push_back(effect);
57         }
58         incoming_links.insert(std::make_pair(effect, inputs));
59         output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
60         output_color_space[effect] = output_color_space[last_added_effect()];
61 }
62
63 void EffectChain::find_all_nonlinear_inputs(Effect *effect,
64                                             std::vector<Input *> *nonlinear_inputs,
65                                             std::vector<Effect *> *intermediates)
66 {
67         assert(output_gamma_curve.count(effect) != 0);
68         if (output_gamma_curve[effect] == GAMMA_LINEAR) {
69                 return;
70         }
71         if (effect->num_inputs() == 0) {
72                 nonlinear_inputs->push_back(static_cast<Input *>(effect));
73         } else {
74                 intermediates->push_back(effect);
75
76                 assert(incoming_links.count(effect) == 1);
77                 std::vector<Effect *> deps = incoming_links[effect];
78                 assert(effect->num_inputs() == deps.size());
79                 for (unsigned i = 0; i < deps.size(); ++i) {
80                         find_all_nonlinear_inputs(deps[i], nonlinear_inputs, intermediates);
81                 }
82         }
83 }
84
85 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
86 {
87         // Find out if all the inputs can be set to deliver sRGB inputs.
88         // If so, we can just ask them to do that instead of inserting a
89         // (possibly expensive) conversion operation.
90         //
91         // NOTE: We assume that effects generally don't mess with the gamma
92         // curve (except GammaCompressionEffect, which should never be
93         // inserted into a chain when this is called), so that we can just
94         // update the output gamma as we go.
95         //
96         // TODO: Setting this flag for one source might confuse a different
97         // part of the pipeline using the same source.
98         std::vector<Input *> nonlinear_inputs;
99         std::vector<Effect *> intermediates;
100         find_all_nonlinear_inputs(input, &nonlinear_inputs, &intermediates);
101
102         bool all_ok = true;
103         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
104                 all_ok &= nonlinear_inputs[i]->can_output_linear_gamma();
105         }
106
107         if (all_ok) {
108                 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
109                         bool ok = nonlinear_inputs[i]->set_int("output_linear_gamma", 1);
110                         assert(ok);
111                         output_gamma_curve[nonlinear_inputs[i]] = GAMMA_LINEAR;
112                 }
113                 for (unsigned i = 0; i < intermediates.size(); ++i) {
114                         output_gamma_curve[intermediates[i]] = GAMMA_LINEAR;
115                 }
116                 return input;
117         }
118
119         // OK, that didn't work. Insert a conversion effect.
120         GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
121         gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
122         std::vector<Effect *> inputs;
123         inputs.push_back(input);
124         gamma_conversion->add_self_to_effect_chain(this, inputs);
125         output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
126         return gamma_conversion;
127 }
128
129 Effect *EffectChain::normalize_to_srgb(Effect *input)
130 {
131         assert(output_gamma_curve.count(input) != 0);
132         assert(output_color_space.count(input) != 0);
133         assert(output_gamma_curve[input] == GAMMA_LINEAR);
134         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
135         colorspace_conversion->set_int("source_space", output_color_space[input]);
136         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
137         std::vector<Effect *> inputs;
138         inputs.push_back(input);
139         colorspace_conversion->add_self_to_effect_chain(this, inputs);
140         output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
141         return colorspace_conversion;
142 }
143
144 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
145 {
146         assert(inputs.size() == effect->num_inputs());
147
148         std::vector<Effect *> normalized_inputs = inputs;
149         for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
150                 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
151                 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
152                         normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
153                 }
154                 assert(output_color_space.count(normalized_inputs[i]) != 0);
155                 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
156                         normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
157                 }
158         }
159
160         effect->add_self_to_effect_chain(this, normalized_inputs);
161         return effect;
162 }
163
164 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
165 std::string replace_prefix(const std::string &text, const std::string &prefix)
166 {
167         std::string output;
168         size_t start = 0;
169
170         while (start < text.size()) {
171                 size_t pos = text.find("PREFIX(", start);
172                 if (pos == std::string::npos) {
173                         output.append(text.substr(start, std::string::npos));
174                         break;
175                 }
176
177                 output.append(text.substr(start, pos - start));
178                 output.append(prefix);
179                 output.append("_");
180
181                 pos += strlen("PREFIX(");
182         
183                 // Output stuff until we find the matching ), which we then eat.
184                 int depth = 1;
185                 size_t end_arg_pos = pos;
186                 while (end_arg_pos < text.size()) {
187                         if (text[end_arg_pos] == '(') {
188                                 ++depth;
189                         } else if (text[end_arg_pos] == ')') {
190                                 --depth;
191                                 if (depth == 0) {
192                                         break;
193                                 }
194                         }
195                         ++end_arg_pos;
196                 }
197                 output.append(text.substr(pos, end_arg_pos - pos));
198                 ++end_arg_pos;
199                 assert(depth == 0);
200                 start = end_arg_pos;
201         }
202         return output;
203 }
204
205 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
206 {
207         assert(!effects.empty());
208
209         // Deduplicate the inputs.
210         std::vector<Effect *> true_inputs = inputs;
211         std::sort(true_inputs.begin(), true_inputs.end());
212         true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
213
214         bool input_needs_mipmaps = false;
215         std::string frag_shader = read_file("header.frag");
216
217         // Create functions for all the texture inputs that we need.
218         for (unsigned i = 0; i < true_inputs.size(); ++i) {
219                 Effect *effect = true_inputs[i];
220                 assert(effect_ids.count(effect) != 0);
221                 std::string effect_id = effect_ids[effect];
222         
223                 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";       
224                 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
225                 if (effect->num_inputs() == 0) {
226                         // OpenGL's origin is bottom-left, but most graphics software assumes
227                         // a top-left origin. Thus, for inputs that come from the user,
228                         // we flip the y coordinate. However, for FBOs, the origin
229                         // is all correct, so don't do anything.
230                         frag_shader += "\ttc.y = 1.0f - tc.y;\n";
231                 }
232                 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
233                 frag_shader += "}\n";
234                 frag_shader += "\n";
235         }
236
237         std::string last_effect_id;
238         for (unsigned i = 0; i < effects.size(); ++i) {
239                 Effect *effect = effects[i];
240                 assert(effect != NULL);
241                 assert(effect_ids.count(effect) != 0);
242                 std::string effect_id = effect_ids[effect];
243                 last_effect_id = effect_id;
244
245                 if (incoming_links[effect].size() == 1) {
246                         frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
247                 } else {
248                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
249                                 char buf[256];
250                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
251                                 frag_shader += buf;
252                         }
253                 }
254         
255                 frag_shader += "\n";
256                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
257                 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
258                 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
259                 frag_shader += "#undef PREFIX\n";
260                 frag_shader += "#undef FUNCNAME\n";
261                 if (incoming_links[effect].size() == 1) {
262                         frag_shader += "#undef INPUT\n";
263                 } else {
264                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
265                                 char buf[256];
266                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
267                                 frag_shader += buf;
268                         }
269                 }
270                 frag_shader += "\n";
271
272                 input_needs_mipmaps |= effect->needs_mipmaps();
273         }
274         for (unsigned i = 0; i < effects.size(); ++i) {
275                 Effect *effect = effects[i];
276                 if (effect->num_inputs() == 0) {
277                         effect->set_int("needs_mipmaps", input_needs_mipmaps);
278                 }
279         }
280         assert(!last_effect_id.empty());
281         frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
282         frag_shader.append(read_file("footer.frag"));
283         printf("%s\n", frag_shader.c_str());
284         
285         GLuint glsl_program_num = glCreateProgram();
286         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
287         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
288         glAttachShader(glsl_program_num, vs_obj);
289         check_error();
290         glAttachShader(glsl_program_num, fs_obj);
291         check_error();
292         glLinkProgram(glsl_program_num);
293         check_error();
294
295         Phase phase;
296         phase.glsl_program_num = glsl_program_num;
297         phase.input_needs_mipmaps = input_needs_mipmaps;
298         phase.inputs = true_inputs;
299         phase.effects = effects;
300
301         return phase;
302 }
303
304 // Construct GLSL programs, starting at the given effect and following
305 // the chain from there. We end a program every time we come to an effect
306 // marked as "needs texture bounce", one that is used by multiple other
307 // effects, and of course at the end.
308 //
309 // We follow a quite simple depth-first search from the output, although
310 // without any explicit recursion.
311 void EffectChain::construct_glsl_programs(Effect *output)
312 {
313         // Which effects have already been completed in this phase?
314         // We need to keep track of it, as an effect with multiple outputs
315         // could otherwise be calculate multiple times.
316         std::set<Effect *> completed_effects;
317
318         // Effects in the current phase, as well as inputs (outputs from other phases
319         // that we depend on). Note that since we start iterating from the end,
320         // the effect list will be in the reverse order.
321         std::vector<Effect *> this_phase_inputs;
322         std::vector<Effect *> this_phase_effects;
323
324         // Effects that we have yet to calculate, but that we know should
325         // be in the current phase.
326         std::stack<Effect *> effects_todo_this_phase;
327
328         // Effects that we have yet to calculate, but that come from other phases.
329         // We delay these until we have this phase done in its entirety,
330         // at which point we pick any of them and start a new phase from that.
331         std::stack<Effect *> effects_todo_other_phases;
332
333         effects_todo_this_phase.push(output);
334
335         for ( ;; ) {  // Termination condition within loop.
336                 if (!effects_todo_this_phase.empty()) {
337                         // OK, we have more to do this phase.
338                         Effect *effect = effects_todo_this_phase.top();
339                         effects_todo_this_phase.pop();
340
341                         // This should currently only happen for effects that are phase outputs,
342                         // and we throw those out separately below.
343                         assert(completed_effects.count(effect) == 0);
344
345                         this_phase_effects.push_back(effect);
346                         completed_effects.insert(effect);
347
348                         // Find all the dependencies of this effect, and add them to the stack.
349                         assert(incoming_links.count(effect) == 1);
350                         std::vector<Effect *> deps = incoming_links[effect];
351                         assert(effect->num_inputs() == deps.size());
352                         for (unsigned i = 0; i < deps.size(); ++i) {
353                                 bool start_new_phase = false;
354
355                                 if (effect->needs_texture_bounce()) {
356                                         start_new_phase = true;
357                                 }
358
359                                 assert(outgoing_links.count(deps[i]) == 1);
360                                 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
361                                         // More than one effect uses this as the input,
362                                         // and it is not a texture itself.
363                                         // The easiest thing to do (and probably also the safest
364                                         // performance-wise in most cases) is to bounce it to a texture
365                                         // and then let the next passes read from that.
366                                         start_new_phase = true;
367                                 }
368
369                                 if (start_new_phase) {
370                                         effects_todo_other_phases.push(deps[i]);
371                                         this_phase_inputs.push_back(deps[i]);
372                                 } else {
373                                         effects_todo_this_phase.push(deps[i]);
374                                 }
375                         }
376                         continue;
377                 }
378
379                 // No more effects to do this phase. Take all the ones we have,
380                 // and create a GLSL program for it.
381                 if (!this_phase_effects.empty()) {
382                         reverse(this_phase_effects.begin(), this_phase_effects.end());
383                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
384                         this_phase_inputs.clear();
385                         this_phase_effects.clear();
386                 }
387                 assert(this_phase_inputs.empty());
388                 assert(this_phase_effects.empty());
389
390                 // If we have no effects left, exit.
391                 if (effects_todo_other_phases.empty()) {
392                         break;
393                 }
394
395                 Effect *effect = effects_todo_other_phases.top();
396                 effects_todo_other_phases.pop();
397
398                 if (completed_effects.count(effect) == 0) {
399                         // Start a new phase, calculating from this effect.
400                         effects_todo_this_phase.push(effect);
401                 }
402         }
403
404         // Finally, since the phases are found from the output but must be executed
405         // from the input(s), reverse them, too.
406         std::reverse(phases.begin(), phases.end());
407 }
408
409 void EffectChain::finalize()
410 {
411         // Find the output effect. This is, simply, one that has no outgoing links.
412         // If there are multiple ones, the graph is malformed (we do not support
413         // multiple outputs right now).
414         std::vector<Effect *> output_effects;
415         for (unsigned i = 0; i < effects.size(); ++i) {
416                 Effect *effect = effects[i];
417                 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
418                         output_effects.push_back(effect);
419                 }
420         }
421         assert(output_effects.size() == 1);
422         Effect *output_effect = output_effects[0];
423
424         // Add normalizers to get the output format right.
425         assert(output_gamma_curve.count(output_effect) != 0);
426         assert(output_color_space.count(output_effect) != 0);
427         ColorSpace current_color_space = output_color_space[output_effect];
428         if (current_color_space != output_format.color_space) {
429                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
430                 colorspace_conversion->set_int("source_space", current_color_space);
431                 colorspace_conversion->set_int("destination_space", output_format.color_space);
432                 std::vector<Effect *> inputs;
433                 inputs.push_back(output_effect);
434                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
435                 output_color_space[colorspace_conversion] = output_format.color_space;
436                 output_effect = colorspace_conversion;
437         }
438         GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
439         if (current_gamma_curve != output_format.gamma_curve) {
440                 if (current_gamma_curve != GAMMA_LINEAR) {
441                         output_effect = normalize_to_linear_gamma(output_effect);
442                         current_gamma_curve = GAMMA_LINEAR;
443                 }
444                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
445                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
446                 std::vector<Effect *> inputs;
447                 inputs.push_back(output_effect);
448                 gamma_conversion->add_self_to_effect_chain(this, inputs);
449                 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
450                 output_effect = gamma_conversion;
451         }
452
453         // Construct all needed GLSL programs, starting at the output.
454         construct_glsl_programs(output_effect);
455
456         // If we have more than one phase, we need intermediate render-to-texture.
457         // Construct an FBO, and then as many textures as we need.
458         // We choose the simplest option of having one texture per output,
459         // since otherwise this turns into an (albeit simple)
460         // register allocation problem.
461         if (phases.size() > 1) {
462                 glGenFramebuffers(1, &fbo);
463
464                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
465                         Effect *output_effect = phases[i].effects.back();
466                         GLuint temp_texture;
467                         glGenTextures(1, &temp_texture);
468                         check_error();
469                         glBindTexture(GL_TEXTURE_2D, temp_texture);
470                         check_error();
471                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
472                         check_error();
473                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
474                         check_error();
475                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
476                         check_error();
477                         effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
478                 }
479         }
480                 
481         for (unsigned i = 0; i < inputs.size(); ++i) {
482                 inputs[i]->finalize();
483         }
484         
485         finalized = true;
486 }
487
488 void EffectChain::render_to_screen()
489 {
490         assert(finalized);
491
492         // Basic state.
493         glDisable(GL_BLEND);
494         check_error();
495         glDisable(GL_DEPTH_TEST);
496         check_error();
497         glDepthMask(GL_FALSE);
498         check_error();
499
500         glMatrixMode(GL_PROJECTION);
501         glLoadIdentity();
502         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
503
504         glMatrixMode(GL_MODELVIEW);
505         glLoadIdentity();
506
507         if (phases.size() > 1) {
508                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
509                 check_error();
510         }
511
512         std::set<Effect *> generated_mipmaps;
513         for (unsigned i = 0; i < inputs.size(); ++i) {
514                 // Inputs generate their own mipmaps if they need to
515                 // (see input.cpp).
516                 generated_mipmaps.insert(inputs[i]);
517         }
518
519         for (unsigned phase = 0; phase < phases.size(); ++phase) {
520                 glUseProgram(phases[phase].glsl_program_num);
521                 check_error();
522
523                 // Set up RTT inputs for this phase.
524                 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
525                         glActiveTexture(GL_TEXTURE0 + sampler);
526                         Effect *input = phases[phase].inputs[sampler];
527                         assert(effect_output_textures.count(input) != 0);
528                         glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
529                         check_error();
530                         if (phases[phase].input_needs_mipmaps) {
531                                 if (generated_mipmaps.count(input) == 0) {
532                                         glGenerateMipmap(GL_TEXTURE_2D);
533                                         check_error();
534                                         generated_mipmaps.insert(input);
535                                 }
536                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
537                                 check_error();
538                         } else {
539                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
540                                 check_error();
541                         }
542
543                         assert(effect_ids.count(input));
544                         std::string texture_name = std::string("tex_") + effect_ids[input];
545                         glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
546                         check_error();
547                 }
548
549                 // And now the output.
550                 if (phase == phases.size() - 1) {
551                         // Last phase goes directly to the screen.
552                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
553                         check_error();
554                 } else {
555                         Effect *last_effect = phases[phase].effects.back();
556                         assert(effect_output_textures.count(last_effect) != 0);
557                         glFramebufferTexture2D(
558                                 GL_FRAMEBUFFER,
559                                 GL_COLOR_ATTACHMENT0,
560                                 GL_TEXTURE_2D,
561                                 effect_output_textures[last_effect],
562                                 0);
563                         check_error();
564                 }
565
566                 // Give the required parameters to all the effects.
567                 unsigned sampler_num = phases[phase].inputs.size();
568                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
569                         Effect *effect = phases[phase].effects[i];
570                         effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
571                 }
572
573                 // Now draw!
574                 glBegin(GL_QUADS);
575
576                 glTexCoord2f(0.0f, 0.0f);
577                 glVertex2f(0.0f, 0.0f);
578
579                 glTexCoord2f(1.0f, 0.0f);
580                 glVertex2f(1.0f, 0.0f);
581
582                 glTexCoord2f(1.0f, 1.0f);
583                 glVertex2f(1.0f, 1.0f);
584
585                 glTexCoord2f(0.0f, 1.0f);
586                 glVertex2f(0.0f, 1.0f);
587
588                 glEnd();
589                 check_error();
590
591                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
592                         Effect *effect = phases[phase].effects[i];
593                         effect->clear_gl_state();
594                 }
595         }
596 }