In overlay matte, use the luminance as a matte instead of each individual color compo...
[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
13 #include "util.h"
14 #include "effect_chain.h"
15 #include "gamma_expansion_effect.h"
16 #include "gamma_compression_effect.h"
17 #include "lift_gamma_gain_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "sandbox_effect.h"
20 #include "saturation_effect.h"
21 #include "mirror_effect.h"
22 #include "vignette_effect.h"
23 #include "blur_effect.h"
24 #include "diffusion_effect.h"
25 #include "input.h"
26
27 EffectChain::EffectChain(unsigned width, unsigned height)
28         : width(width),
29           height(height),
30           finalized(false) {}
31
32 Input *EffectChain::add_input(const ImageFormat &format)
33 {
34         Input *input = new Input(format, width, height);
35         effects.push_back(input);
36         output_color_space.insert(std::make_pair(input, format.color_space));
37         output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
38         effect_ids.insert(std::make_pair(input, "src_image"));
39         incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
40         return input;
41 }
42
43 void EffectChain::add_output(const ImageFormat &format)
44 {
45         output_format = format;
46 }
47
48 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
49 {
50         char effect_id[256];
51         sprintf(effect_id, "eff%u", (unsigned)effects.size());
52
53         effects.push_back(effect);
54         effect_ids.insert(std::make_pair(effect, effect_id));
55         assert(inputs.size() == effect->num_inputs());
56         for (unsigned i = 0; i < inputs.size(); ++i) {
57                 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
58                 outgoing_links[inputs[i]].push_back(effect);
59         }
60         incoming_links.insert(std::make_pair(effect, inputs));
61         output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
62         output_color_space[effect] = output_color_space[last_added_effect()];
63 }
64
65 Effect *instantiate_effect(EffectId effect)
66 {
67         switch (effect) {
68         case EFFECT_GAMMA_EXPANSION:
69                 return new GammaExpansionEffect();
70         case EFFECT_GAMMA_COMPRESSION:
71                 return new GammaCompressionEffect();
72         case EFFECT_COLOR_SPACE_CONVERSION:
73                 return new ColorSpaceConversionEffect();
74         case EFFECT_SANDBOX:
75                 return new SandboxEffect();
76         case EFFECT_LIFT_GAMMA_GAIN:
77                 return new LiftGammaGainEffect();
78         case EFFECT_SATURATION:
79                 return new SaturationEffect();
80         case EFFECT_MIRROR:
81                 return new MirrorEffect();
82         case EFFECT_VIGNETTE:
83                 return new VignetteEffect();
84         case EFFECT_BLUR:
85                 return new BlurEffect();
86         case EFFECT_DIFFUSION:
87                 return new DiffusionEffect();
88         }
89         assert(false);
90 }
91
92 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
93 {
94         assert(output_gamma_curve.count(input) != 0);
95         if (output_gamma_curve[input] == GAMMA_sRGB) {
96                 // TODO: check if the extension exists
97                 effects[0]->set_int("use_srgb_texture_format", 1);
98                 output_gamma_curve[input] = GAMMA_LINEAR;
99                 return input;
100         } else {
101                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
102                 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
103                 std::vector<Effect *> inputs;
104                 inputs.push_back(input);
105                 gamma_conversion->add_self_to_effect_chain(this, inputs);
106                 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
107                 return gamma_conversion;
108         }
109 }
110
111 Effect *EffectChain::normalize_to_srgb(Effect *input)
112 {
113         assert(output_gamma_curve.count(input) != 0);
114         assert(output_color_space.count(input) != 0);
115         assert(output_gamma_curve[input] == GAMMA_LINEAR);
116         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
117         colorspace_conversion->set_int("source_space", output_color_space[input]);
118         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
119         std::vector<Effect *> inputs;
120         inputs.push_back(input);
121         colorspace_conversion->add_self_to_effect_chain(this, inputs);
122         output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
123         return colorspace_conversion;
124 }
125
126 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
127 {
128         Effect *effect = instantiate_effect(effect_id);
129
130         assert(inputs.size() == effect->num_inputs());
131
132         std::vector<Effect *> normalized_inputs = inputs;
133         for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
134                 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
135                 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
136                         normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
137                 }
138                 assert(output_color_space.count(normalized_inputs[i]) != 0);
139                 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
140                         normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
141                 }
142         }
143
144         effect->add_self_to_effect_chain(this, normalized_inputs);
145         return effect;
146 }
147
148 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
149 std::string replace_prefix(const std::string &text, const std::string &prefix)
150 {
151         std::string output;
152         size_t start = 0;
153
154         while (start < text.size()) {
155                 size_t pos = text.find("PREFIX(", start);
156                 if (pos == std::string::npos) {
157                         output.append(text.substr(start, std::string::npos));
158                         break;
159                 }
160
161                 output.append(text.substr(start, pos - start));
162                 output.append(prefix);
163                 output.append("_");
164
165                 pos += strlen("PREFIX(");
166         
167                 // Output stuff until we find the matching ), which we then eat.
168                 int depth = 1;
169                 size_t end_arg_pos = pos;
170                 while (end_arg_pos < text.size()) {
171                         if (text[end_arg_pos] == '(') {
172                                 ++depth;
173                         } else if (text[end_arg_pos] == ')') {
174                                 --depth;
175                                 if (depth == 0) {
176                                         break;
177                                 }
178                         }
179                         ++end_arg_pos;
180                 }
181                 output.append(text.substr(pos, end_arg_pos - pos));
182                 ++end_arg_pos;
183                 assert(depth == 0);
184                 start = end_arg_pos;
185         }
186         return output;
187 }
188
189 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
190 {
191         assert(!inputs.empty());
192         assert(!effects.empty());
193
194         // Figure out the true set of inputs to this phase. These are the ones
195         // that we need somehow but don't calculate ourselves.
196         std::set<Effect *> effect_set(effects.begin(), effects.end());
197         std::set<Effect *> input_set(inputs.begin(), inputs.end());
198         std::vector<Effect *> true_inputs;
199         std::set_difference(input_set.begin(), input_set.end(),
200                 effect_set.begin(), effect_set.end(),
201                 std::back_inserter(true_inputs));
202
203         bool input_needs_mipmaps = false;
204         std::string frag_shader = read_file("header.frag");
205
206         // Create functions for all the texture inputs that we need.
207         for (unsigned i = 0; i < true_inputs.size(); ++i) {
208                 Effect *effect = true_inputs[i];
209                 assert(effect_ids.count(effect) != 0);
210                 std::string effect_id = effect_ids[effect];
211         
212                 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";       
213                 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
214                 if (effect->num_inputs() == 0) {
215                         // OpenGL's origin is bottom-left, but most graphics software assumes
216                         // a top-left origin. Thus, for inputs that come from the user,
217                         // we flip the y coordinate. However, for FBOs, the origin
218                         // is all correct, so don't do anything.
219                         frag_shader += "\ttc.y = 1.0f - tc.y;\n";
220                 }
221                 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
222                 frag_shader += "}\n";
223                 frag_shader += "\n";
224         }
225
226         std::string last_effect_id;
227         for (unsigned i = 0; i < effects.size(); ++i) {
228                 Effect *effect = effects[i];
229                 assert(effect != NULL);
230                 assert(effect_ids.count(effect) != 0);
231                 std::string effect_id = effect_ids[effect];
232                 last_effect_id = effect_id;
233
234                 if (incoming_links[effect].size() == 1) {
235                         frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
236                 } else {
237                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
238                                 char buf[256];
239                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
240                                 frag_shader += buf;
241                         }
242                 }
243         
244                 frag_shader += "\n";
245                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
246                 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
247                 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
248                 frag_shader += "#undef PREFIX\n";
249                 frag_shader += "#undef FUNCNAME\n";
250                 if (incoming_links[effect].size() == 1) {
251                         frag_shader += "#undef INPUT\n";
252                 } else {
253                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
254                                 char buf[256];
255                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
256                                 frag_shader += buf;
257                         }
258                 }
259                 frag_shader += "\n";
260
261                 input_needs_mipmaps |= effect->needs_mipmaps();
262         }
263         for (unsigned i = 0; i < effects.size(); ++i) {
264                 Effect *effect = effects[i];
265                 if (effect->num_inputs() == 0) {
266                         effect->set_int("needs_mipmaps", input_needs_mipmaps);
267                 }
268         }
269         assert(!last_effect_id.empty());
270         frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
271         frag_shader.append(read_file("footer.frag"));
272         printf("%s\n", frag_shader.c_str());
273         
274         GLuint glsl_program_num = glCreateProgram();
275         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
276         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
277         glAttachShader(glsl_program_num, vs_obj);
278         check_error();
279         glAttachShader(glsl_program_num, fs_obj);
280         check_error();
281         glLinkProgram(glsl_program_num);
282         check_error();
283
284         Phase phase;
285         phase.glsl_program_num = glsl_program_num;
286         phase.input_needs_mipmaps = input_needs_mipmaps;
287         phase.inputs = true_inputs;
288         phase.effects = effects;
289
290         return phase;
291 }
292
293 // Construct GLSL programs, starting at the given effect and following
294 // the chain from there. We end a program every time we come to an effect
295 // marked as "needs texture bounce", one that is used by multiple other
296 // effects, and of course at the end.
297 void EffectChain::construct_glsl_programs(Effect *start, std::set<Effect *> *completed_effects)
298 {
299         assert(start != NULL);
300         if (completed_effects->count(start) != 0) {
301                 // This has already been done for us.
302                 return;
303         }
304
305         std::vector<Effect *> this_phase_inputs;  // Also includes all intermediates; these will be filtered away later.
306         std::vector<Effect *> this_phase_effects;
307         Effect *node = start;
308         for ( ;; ) {  // Termination condition within loop.
309                 assert(node != NULL);
310
311                 // Check that we have all the inputs we need for this effect.
312                 // If not, we end the phase here right away; the other side
313                 // of the input chain will eventually come and pick the effect up.
314                 assert(incoming_links.count(node) == 1);
315                 std::vector<Effect *> deps = incoming_links[node];
316                 assert(node->num_inputs() == deps.size());
317                 if (!deps.empty()) {
318                         bool have_all_deps = true;
319                         for (unsigned i = 0; i < deps.size(); ++i) {
320                                 if (completed_effects->count(deps[i]) == 0) {
321                                         have_all_deps = false;
322                                         break;
323                                 }
324                         }
325                 
326                         if (!have_all_deps) {
327                                 if (!this_phase_effects.empty()) {
328                                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
329                                 }
330                                 return;
331                         }
332                         this_phase_inputs.insert(this_phase_inputs.end(), deps.begin(), deps.end());    
333                 }
334                 this_phase_effects.push_back(node);
335                 completed_effects->insert(node);        
336
337                 // Find all the effects that use this one as a direct input.
338                 if (outgoing_links.count(node) == 0) {
339                         // End of the line; output.
340                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
341                         return;
342                 }
343
344                 std::vector<Effect *> next = outgoing_links[node];
345                 assert(!next.empty());
346                 if (next.size() > 1) {
347                         if (node->num_inputs() != 0) {
348                                 // More than one effect uses this as the input, and it is not a texture itself.
349                                 // The easiest thing to do (and probably also the safest
350                                 // performance-wise in most cases) is to bounce it to a texture
351                                 // and then let the next passes read from that.
352                                 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
353                         }
354
355                         // Start phases for all the effects that need us (in arbitrary order).
356                         for (unsigned i = 0; i < next.size(); ++i) {
357                                 construct_glsl_programs(next[i], completed_effects);
358                         }
359                         return;
360                 }
361         
362                 // OK, only one effect uses this as the input. Keep iterating,
363                 // but first see if it requires a texture bounce; if so, give it
364                 // one by starting a new phase.
365                 node = next[0];
366                 if (node->needs_texture_bounce()) {
367                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
368                         this_phase_inputs.clear();
369                         this_phase_effects.clear();
370                 }
371         }
372 }
373
374 void EffectChain::finalize()
375 {
376         // Add normalizers to get the output format right.
377         assert(output_gamma_curve.count(last_added_effect()) != 0);
378         assert(output_color_space.count(last_added_effect()) != 0);
379         ColorSpace current_color_space = output_color_space[last_added_effect()];  // FIXME
380         if (current_color_space != output_format.color_space) {
381                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
382                 colorspace_conversion->set_int("source_space", current_color_space);
383                 colorspace_conversion->set_int("destination_space", output_format.color_space);
384                 std::vector<Effect *> inputs;
385                 inputs.push_back(last_added_effect());
386                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
387                 output_color_space[colorspace_conversion] = output_format.color_space;
388         }
389         GammaCurve current_gamma_curve = output_gamma_curve[last_added_effect()];  // FIXME
390         if (current_gamma_curve != output_format.gamma_curve) {
391                 if (current_gamma_curve != GAMMA_LINEAR) {
392                         normalize_to_linear_gamma(last_added_effect());  // FIXME
393                 }
394                 assert(current_gamma_curve == GAMMA_LINEAR);
395                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
396                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
397                 std::vector<Effect *> inputs;
398                 inputs.push_back(last_added_effect());
399                 gamma_conversion->add_self_to_effect_chain(this, inputs);
400                 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
401         }
402
403         // Construct all needed GLSL programs, starting at the input.
404         std::set<Effect *> completed_effects;
405         construct_glsl_programs(effects[0], &completed_effects);
406
407         // If we have more than one phase, we need intermediate render-to-texture.
408         // Construct an FBO, and then as many textures as we need.
409         // We choose the simplest option of having one texture per output,
410         // since otherwise this turns into an (albeit simple)
411         // register allocation problem.
412         if (phases.size() > 1) {
413                 glGenFramebuffers(1, &fbo);
414
415                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
416                         Effect *output_effect = phases[i].effects.back();
417                         GLuint temp_texture;
418                         glGenTextures(1, &temp_texture);
419                         check_error();
420                         glBindTexture(GL_TEXTURE_2D, temp_texture);
421                         check_error();
422                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
423                         check_error();
424                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
425                         check_error();
426                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
427                         check_error();
428                         effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
429                 }
430         }
431                 
432         (static_cast<Input *>(effects[0]))->finalize();
433         
434         finalized = true;
435 }
436
437 void EffectChain::render_to_screen()
438 {
439         assert(finalized);
440
441         // Basic state.
442         glDisable(GL_BLEND);
443         check_error();
444         glDisable(GL_DEPTH_TEST);
445         check_error();
446         glDepthMask(GL_FALSE);
447         check_error();
448
449         glMatrixMode(GL_PROJECTION);
450         glLoadIdentity();
451         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
452
453         glMatrixMode(GL_MODELVIEW);
454         glLoadIdentity();
455
456         if (phases.size() > 1) {
457                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
458                 check_error();
459         }
460
461         std::set<Effect *> generated_mipmaps;
462         generated_mipmaps.insert(effects[0]);  // Already done further up.
463
464         for (unsigned phase = 0; phase < phases.size(); ++phase) {
465                 glUseProgram(phases[phase].glsl_program_num);
466                 check_error();
467
468                 // Set up RTT inputs for this phase.
469                 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
470                         glActiveTexture(GL_TEXTURE0 + sampler);
471                         Effect *input = phases[phase].inputs[sampler];
472                         assert(effect_output_textures.count(input) != 0);
473                         glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
474                         check_error();
475                         if (phases[phase].input_needs_mipmaps) {
476                                 if (generated_mipmaps.count(input) == 0) {
477                                         glGenerateMipmap(GL_TEXTURE_2D);
478                                         check_error();
479                                         generated_mipmaps.insert(input);
480                                 }
481                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
482                                 check_error();
483                         } else {
484                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
485                                 check_error();
486                         }
487
488                         assert(effect_ids.count(input));
489                         std::string texture_name = std::string("tex_") + effect_ids[input];
490                         glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
491                         check_error();
492                 }
493
494                 // And now the output.
495                 if (phase == phases.size() - 1) {
496                         // Last phase goes directly to the screen.
497                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
498                         check_error();
499                 } else {
500                         Effect *last_effect = phases[phase].effects.back();
501                         assert(effect_output_textures.count(last_effect) != 0);
502                         glFramebufferTexture2D(
503                                 GL_FRAMEBUFFER,
504                                 GL_COLOR_ATTACHMENT0,
505                                 GL_TEXTURE_2D,
506                                 effect_output_textures[last_effect],
507                                 0);
508                         check_error();
509                 }
510
511                 // Give the required parameters to all the effects.
512                 unsigned sampler_num = phases[phase].inputs.size();
513                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
514                         Effect *effect = phases[phase].effects[i];
515                         effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
516                 }
517
518                 // Now draw!
519                 glBegin(GL_QUADS);
520
521                 glTexCoord2f(0.0f, 0.0f);
522                 glVertex2f(0.0f, 0.0f);
523
524                 glTexCoord2f(1.0f, 0.0f);
525                 glVertex2f(1.0f, 0.0f);
526
527                 glTexCoord2f(1.0f, 1.0f);
528                 glVertex2f(1.0f, 1.0f);
529
530                 glTexCoord2f(0.0f, 1.0f);
531                 glVertex2f(0.0f, 1.0f);
532
533                 glEnd();
534                 check_error();
535
536                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
537                         Effect *effect = phases[phase].effects[i];
538                         effect->clear_gl_state();
539                 }
540         }
541 }