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