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