1 #define GL_GLEXT_PROTOTYPES 1
15 #include "effect_chain.h"
16 #include "gamma_expansion_effect.h"
17 #include "gamma_compression_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "alpha_multiplication_effect.h"
20 #include "alpha_division_effect.h"
21 #include "dither_effect.h"
25 EffectChain::EffectChain(float aspect_nom, float aspect_denom)
26 : aspect_nom(aspect_nom),
27 aspect_denom(aspect_denom),
33 EffectChain::~EffectChain()
35 for (unsigned i = 0; i < nodes.size(); ++i) {
36 if (nodes[i]->output_texture != 0) {
37 glDeleteTextures(1, &nodes[i]->output_texture);
39 delete nodes[i]->effect;
42 for (unsigned i = 0; i < phases.size(); ++i) {
43 glDeleteProgram(phases[i]->glsl_program_num);
44 glDeleteShader(phases[i]->vertex_shader);
45 glDeleteShader(phases[i]->fragment_shader);
49 glDeleteFramebuffers(1, &fbo);
53 Input *EffectChain::add_input(Input *input)
55 inputs.push_back(input);
60 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
62 output_format = format;
63 output_alpha_format = alpha_format;
66 Node *EffectChain::add_node(Effect *effect)
69 sprintf(effect_id, "eff%u", (unsigned)nodes.size());
71 Node *node = new Node;
72 node->effect = effect;
73 node->disabled = false;
74 node->effect_id = effect_id;
75 node->output_color_space = COLORSPACE_INVALID;
76 node->output_gamma_curve = GAMMA_INVALID;
77 node->output_alpha_type = ALPHA_INVALID;
78 node->output_texture = 0;
80 nodes.push_back(node);
81 node_map[effect] = node;
85 void EffectChain::connect_nodes(Node *sender, Node *receiver)
87 sender->outgoing_links.push_back(receiver);
88 receiver->incoming_links.push_back(sender);
91 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
93 new_receiver->incoming_links = old_receiver->incoming_links;
94 old_receiver->incoming_links.clear();
96 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
97 Node *sender = new_receiver->incoming_links[i];
98 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
99 if (sender->outgoing_links[j] == old_receiver) {
100 sender->outgoing_links[j] = new_receiver;
106 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
108 new_sender->outgoing_links = old_sender->outgoing_links;
109 old_sender->outgoing_links.clear();
111 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
112 Node *receiver = new_sender->outgoing_links[i];
113 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
114 if (receiver->incoming_links[j] == old_sender) {
115 receiver->incoming_links[j] = new_sender;
121 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
123 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
124 if (sender->outgoing_links[i] == receiver) {
125 sender->outgoing_links[i] = middle;
126 middle->incoming_links.push_back(sender);
129 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
130 if (receiver->incoming_links[i] == sender) {
131 receiver->incoming_links[i] = middle;
132 middle->outgoing_links.push_back(receiver);
136 assert(middle->incoming_links.size() == middle->effect->num_inputs());
139 void EffectChain::find_all_nonlinear_inputs(Node *node, std::vector<Node *> *nonlinear_inputs)
141 if (node->output_gamma_curve == GAMMA_LINEAR &&
142 node->effect->effect_type_id() != "GammaCompressionEffect") {
145 if (node->effect->num_inputs() == 0) {
146 nonlinear_inputs->push_back(node);
148 assert(node->effect->num_inputs() == node->incoming_links.size());
149 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
150 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
155 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
157 assert(inputs.size() == effect->num_inputs());
158 Node *node = add_node(effect);
159 for (unsigned i = 0; i < inputs.size(); ++i) {
160 assert(node_map.count(inputs[i]) != 0);
161 connect_nodes(node_map[inputs[i]], node);
166 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
167 std::string replace_prefix(const std::string &text, const std::string &prefix)
172 while (start < text.size()) {
173 size_t pos = text.find("PREFIX(", start);
174 if (pos == std::string::npos) {
175 output.append(text.substr(start, std::string::npos));
179 output.append(text.substr(start, pos - start));
180 output.append(prefix);
183 pos += strlen("PREFIX(");
185 // Output stuff until we find the matching ), which we then eat.
187 size_t end_arg_pos = pos;
188 while (end_arg_pos < text.size()) {
189 if (text[end_arg_pos] == '(') {
191 } else if (text[end_arg_pos] == ')') {
199 output.append(text.substr(pos, end_arg_pos - pos));
207 Phase *EffectChain::compile_glsl_program(
208 const std::vector<Node *> &inputs,
209 const std::vector<Node *> &effects)
211 assert(!effects.empty());
213 // Deduplicate the inputs.
214 std::vector<Node *> true_inputs = inputs;
215 std::sort(true_inputs.begin(), true_inputs.end());
216 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
218 bool input_needs_mipmaps = false;
219 std::string frag_shader = read_file("header.frag");
221 // Create functions for all the texture inputs that we need.
222 for (unsigned i = 0; i < true_inputs.size(); ++i) {
223 Node *input = true_inputs[i];
225 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
226 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
227 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
228 frag_shader += "}\n";
232 for (unsigned i = 0; i < effects.size(); ++i) {
233 Node *node = effects[i];
235 if (node->incoming_links.size() == 1) {
236 frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
238 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
240 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
246 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
247 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
248 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
249 frag_shader += "#undef PREFIX\n";
250 frag_shader += "#undef FUNCNAME\n";
251 if (node->incoming_links.size() == 1) {
252 frag_shader += "#undef INPUT\n";
254 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
256 sprintf(buf, "#undef INPUT%d\n", j + 1);
262 input_needs_mipmaps |= node->effect->needs_mipmaps();
264 for (unsigned i = 0; i < effects.size(); ++i) {
265 Node *node = effects[i];
266 if (node->effect->num_inputs() == 0) {
267 CHECK(node->effect->set_int("needs_mipmaps", input_needs_mipmaps));
270 frag_shader += std::string("#define INPUT ") + effects.back()->effect_id + "\n";
271 frag_shader.append(read_file("footer.frag"));
273 if (movit_debug_level == MOVIT_DEBUG_ON) {
274 // Output shader to a temporary file, for easier debugging.
275 static int compiled_shader_num = 0;
277 sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
278 FILE *fp = fopen(filename, "w");
283 fprintf(fp, "%s\n", frag_shader.c_str());
287 GLuint glsl_program_num = glCreateProgram();
288 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
289 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
290 glAttachShader(glsl_program_num, vs_obj);
292 glAttachShader(glsl_program_num, fs_obj);
294 glLinkProgram(glsl_program_num);
297 Phase *phase = new Phase;
298 phase->glsl_program_num = glsl_program_num;
299 phase->vertex_shader = vs_obj;
300 phase->fragment_shader = fs_obj;
301 phase->input_needs_mipmaps = input_needs_mipmaps;
302 phase->inputs = true_inputs;
303 phase->effects = effects;
308 // Construct GLSL programs, starting at the given effect and following
309 // the chain from there. We end a program every time we come to an effect
310 // marked as "needs texture bounce", one that is used by multiple other
311 // effects, every time an effect wants to change the output size,
312 // and of course at the end.
314 // We follow a quite simple depth-first search from the output, although
315 // without any explicit recursion.
316 void EffectChain::construct_glsl_programs(Node *output)
318 // Which effects have already been completed in this phase?
319 // We need to keep track of it, as an effect with multiple outputs
320 // could otherwise be calculate multiple times.
321 std::set<Node *> completed_effects;
323 // Effects in the current phase, as well as inputs (outputs from other phases
324 // that we depend on). Note that since we start iterating from the end,
325 // the effect list will be in the reverse order.
326 std::vector<Node *> this_phase_inputs;
327 std::vector<Node *> this_phase_effects;
329 // Effects that we have yet to calculate, but that we know should
330 // be in the current phase.
331 std::stack<Node *> effects_todo_this_phase;
333 // Effects that we have yet to calculate, but that come from other phases.
334 // We delay these until we have this phase done in its entirety,
335 // at which point we pick any of them and start a new phase from that.
336 std::stack<Node *> effects_todo_other_phases;
338 effects_todo_this_phase.push(output);
340 for ( ;; ) { // Termination condition within loop.
341 if (!effects_todo_this_phase.empty()) {
342 // OK, we have more to do this phase.
343 Node *node = effects_todo_this_phase.top();
344 effects_todo_this_phase.pop();
346 // This should currently only happen for effects that are phase outputs,
347 // and we throw those out separately below.
348 assert(completed_effects.count(node) == 0);
350 this_phase_effects.push_back(node);
351 completed_effects.insert(node);
353 // Find all the dependencies of this effect, and add them to the stack.
354 std::vector<Node *> deps = node->incoming_links;
355 assert(node->effect->num_inputs() == deps.size());
356 for (unsigned i = 0; i < deps.size(); ++i) {
357 bool start_new_phase = false;
359 // FIXME: If we sample directly from a texture, we won't need this.
360 if (node->effect->needs_texture_bounce()) {
361 start_new_phase = true;
364 if (deps[i]->outgoing_links.size() > 1) {
365 if (deps[i]->effect->num_inputs() > 0) {
366 // More than one effect uses this as the input,
367 // and it is not a texture itself.
368 // The easiest thing to do (and probably also the safest
369 // performance-wise in most cases) is to bounce it to a texture
370 // and then let the next passes read from that.
371 start_new_phase = true;
373 // For textures, we try to be slightly more clever;
374 // if none of our outputs need a bounce, we don't bounce
375 // but instead simply use the effect many times.
377 // Strictly speaking, we could bounce it for some outputs
378 // and use it directly for others, but the processing becomes
379 // somewhat simpler if the effect is only used in one such way.
380 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
381 Node *rdep = deps[i]->outgoing_links[j];
382 start_new_phase |= rdep->effect->needs_texture_bounce();
387 if (deps[i]->effect->changes_output_size()) {
388 start_new_phase = true;
391 if (start_new_phase) {
392 effects_todo_other_phases.push(deps[i]);
393 this_phase_inputs.push_back(deps[i]);
395 effects_todo_this_phase.push(deps[i]);
401 // No more effects to do this phase. Take all the ones we have,
402 // and create a GLSL program for it.
403 if (!this_phase_effects.empty()) {
404 reverse(this_phase_effects.begin(), this_phase_effects.end());
405 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
406 this_phase_effects.back()->phase = phases.back();
407 this_phase_inputs.clear();
408 this_phase_effects.clear();
410 assert(this_phase_inputs.empty());
411 assert(this_phase_effects.empty());
413 // If we have no effects left, exit.
414 if (effects_todo_other_phases.empty()) {
418 Node *node = effects_todo_other_phases.top();
419 effects_todo_other_phases.pop();
421 if (completed_effects.count(node) == 0) {
422 // Start a new phase, calculating from this effect.
423 effects_todo_this_phase.push(node);
427 // Finally, since the phases are found from the output but must be executed
428 // from the input(s), reverse them, too.
429 std::reverse(phases.begin(), phases.end());
432 void EffectChain::output_dot(const char *filename)
434 if (movit_debug_level != MOVIT_DEBUG_ON) {
438 FILE *fp = fopen(filename, "w");
444 fprintf(fp, "digraph G {\n");
445 for (unsigned i = 0; i < nodes.size(); ++i) {
446 // Find out which phase this event belongs to.
448 for (unsigned j = 0; j < phases.size(); ++j) {
449 const Phase* p = phases[j];
450 if (std::find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
451 assert(in_phase == -1);
456 if (in_phase == -1) {
457 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
459 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
460 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
463 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
464 std::vector<std::string> labels;
466 if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
467 labels.push_back("needs_bounce");
469 if (nodes[i]->effect->changes_output_size()) {
470 labels.push_back("resize");
473 switch (nodes[i]->output_color_space) {
474 case COLORSPACE_INVALID:
475 labels.push_back("spc[invalid]");
477 case COLORSPACE_REC_601_525:
478 labels.push_back("spc[rec601-525]");
480 case COLORSPACE_REC_601_625:
481 labels.push_back("spc[rec601-625]");
487 switch (nodes[i]->output_gamma_curve) {
489 labels.push_back("gamma[invalid]");
492 labels.push_back("gamma[sRGB]");
494 case GAMMA_REC_601: // and GAMMA_REC_709
495 labels.push_back("gamma[rec601/709]");
501 switch (nodes[i]->output_alpha_type) {
503 labels.push_back("alpha[invalid]");
506 labels.push_back("alpha[blank]");
508 case ALPHA_POSTMULTIPLIED:
509 labels.push_back("alpha[postmult]");
515 if (labels.empty()) {
516 fprintf(fp, " n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
518 std::string label = labels[0];
519 for (unsigned k = 1; k < labels.size(); ++k) {
520 label += ", " + labels[k];
522 fprintf(fp, " n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
531 unsigned EffectChain::fit_rectangle_to_aspect(unsigned width, unsigned height)
533 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
534 // Same aspect, or W/H > aspect (image is wider than the frame).
535 // In either case, keep width.
538 // W/H < aspect (image is taller than the frame), so keep height,
539 // and adjust width correspondingly.
540 return lrintf(height * aspect_nom / aspect_denom);
544 // Propagate input texture sizes throughout, and inform effects downstream.
545 // (Like a lot of other code, we depend on effects being in topological order.)
546 void EffectChain::inform_input_sizes(Phase *phase)
548 // All effects that have a defined size (inputs and RTT inputs)
549 // get that. Reset all others.
550 for (unsigned i = 0; i < phase->effects.size(); ++i) {
551 Node *node = phase->effects[i];
552 if (node->effect->num_inputs() == 0) {
553 Input *input = static_cast<Input *>(node->effect);
554 node->output_width = input->get_width();
555 node->output_height = input->get_height();
556 assert(node->output_width != 0);
557 assert(node->output_height != 0);
559 node->output_width = node->output_height = 0;
562 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
563 Node *input = phase->inputs[i];
564 input->output_width = input->phase->output_width;
565 input->output_height = input->phase->output_height;
566 assert(input->output_width != 0);
567 assert(input->output_height != 0);
570 // Now propagate from the inputs towards the end, and inform as we go.
571 // The rules are simple:
573 // 1. Don't touch effects that already have given sizes (ie., inputs).
574 // 2. If all of your inputs have the same size, that will be your output size.
575 // 3. Otherwise, your output size is 0x0.
576 for (unsigned i = 0; i < phase->effects.size(); ++i) {
577 Node *node = phase->effects[i];
578 if (node->effect->num_inputs() == 0) {
581 unsigned this_output_width = 0;
582 unsigned this_output_height = 0;
583 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
584 Node *input = node->incoming_links[j];
585 node->effect->inform_input_size(j, input->output_width, input->output_height);
587 this_output_width = input->output_width;
588 this_output_height = input->output_height;
589 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
591 this_output_width = 0;
592 this_output_height = 0;
595 node->output_width = this_output_width;
596 node->output_height = this_output_height;
600 // Note: You should call inform_input_sizes() before this, as the last effect's
601 // desired output size might change based on the inputs.
602 void EffectChain::find_output_size(Phase *phase)
604 Node *output_node = phase->effects.back();
606 // If the last effect explicitly sets an output size, use that.
607 if (output_node->effect->changes_output_size()) {
608 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
612 // If not, look at the input phases and textures.
613 // We select the largest one (by fit into the current aspect).
614 unsigned best_width = 0;
615 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
616 Node *input = phase->inputs[i];
617 assert(input->phase->output_width != 0);
618 assert(input->phase->output_height != 0);
619 unsigned width = fit_rectangle_to_aspect(input->phase->output_width, input->phase->output_height);
620 if (width > best_width) {
624 for (unsigned i = 0; i < phase->effects.size(); ++i) {
625 Effect *effect = phase->effects[i]->effect;
626 if (effect->num_inputs() != 0) {
630 Input *input = static_cast<Input *>(effect);
631 unsigned width = fit_rectangle_to_aspect(input->get_width(), input->get_height());
632 if (width > best_width) {
636 assert(best_width != 0);
637 phase->output_width = best_width;
638 phase->output_height = best_width * aspect_denom / aspect_nom;
641 void EffectChain::sort_nodes_topologically()
643 std::set<Node *> visited_nodes;
644 std::vector<Node *> sorted_list;
645 for (unsigned i = 0; i < nodes.size(); ++i) {
646 if (nodes[i]->incoming_links.size() == 0) {
647 topological_sort_visit_node(nodes[i], &visited_nodes, &sorted_list);
650 reverse(sorted_list.begin(), sorted_list.end());
654 void EffectChain::topological_sort_visit_node(Node *node, std::set<Node *> *visited_nodes, std::vector<Node *> *sorted_list)
656 if (visited_nodes->count(node) != 0) {
659 visited_nodes->insert(node);
660 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
661 topological_sort_visit_node(node->outgoing_links[i], visited_nodes, sorted_list);
663 sorted_list->push_back(node);
666 void EffectChain::find_color_spaces_for_inputs()
668 for (unsigned i = 0; i < nodes.size(); ++i) {
669 Node *node = nodes[i];
670 if (node->disabled) {
673 if (node->incoming_links.size() == 0) {
674 Input *input = static_cast<Input *>(node->effect);
675 node->output_color_space = input->get_color_space();
676 node->output_gamma_curve = input->get_gamma_curve();
678 Effect::AlphaHandling alpha_handling = input->alpha_handling();
679 switch (alpha_handling) {
680 case Effect::OUTPUT_BLANK_ALPHA:
681 node->output_alpha_type = ALPHA_BLANK;
683 case Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED:
684 node->output_alpha_type = ALPHA_PREMULTIPLIED;
686 case Effect::OUTPUT_ALPHA_POSTMULTIPLIED:
687 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
689 case Effect::DONT_CARE_ALPHA_TYPE:
697 // Propagate gamma and color space information as far as we can in the graph.
698 // The rules are simple: Anything where all the inputs agree, get that as
699 // output as well. Anything else keeps having *_INVALID.
700 void EffectChain::propagate_gamma_and_color_space()
702 // We depend on going through the nodes in order.
703 sort_nodes_topologically();
705 for (unsigned i = 0; i < nodes.size(); ++i) {
706 Node *node = nodes[i];
707 if (node->disabled) {
710 assert(node->incoming_links.size() == node->effect->num_inputs());
711 if (node->incoming_links.size() == 0) {
712 assert(node->output_color_space != COLORSPACE_INVALID);
713 assert(node->output_gamma_curve != GAMMA_INVALID);
717 Colorspace color_space = node->incoming_links[0]->output_color_space;
718 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
719 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
720 if (node->incoming_links[j]->output_color_space != color_space) {
721 color_space = COLORSPACE_INVALID;
723 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
724 gamma_curve = GAMMA_INVALID;
728 // The conversion effects already have their outputs set correctly,
729 // so leave them alone.
730 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
731 node->output_color_space = color_space;
733 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
734 node->effect->effect_type_id() != "GammaExpansionEffect") {
735 node->output_gamma_curve = gamma_curve;
740 // Propagate alpha information as far as we can in the graph.
741 // Similar to propagate_gamma_and_color_space().
742 void EffectChain::propagate_alpha()
744 // We depend on going through the nodes in order.
745 sort_nodes_topologically();
747 for (unsigned i = 0; i < nodes.size(); ++i) {
748 Node *node = nodes[i];
749 if (node->disabled) {
752 assert(node->incoming_links.size() == node->effect->num_inputs());
753 if (node->incoming_links.size() == 0) {
754 assert(node->output_alpha_type != ALPHA_INVALID);
758 // The alpha multiplication/division effects are special cases.
759 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
760 assert(node->incoming_links.size() == 1);
761 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
762 node->output_alpha_type = ALPHA_PREMULTIPLIED;
765 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
766 assert(node->incoming_links.size() == 1);
767 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
768 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
772 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
773 // because they are the only one that _need_ postmultiplied alpha.
774 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
775 node->effect->effect_type_id() == "GammaExpansionEffect") {
776 assert(node->incoming_links.size() == 1);
777 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
778 node->output_alpha_type = ALPHA_BLANK;
779 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
780 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
782 node->output_alpha_type = ALPHA_INVALID;
787 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
788 // or OUTPUT_ALPHA_POSTMULTIPLIED), and they have already been
789 // taken care of above. Rationale: Even if you could imagine
790 // e.g. an effect that took in an image and set alpha=1.0
791 // unconditionally, it wouldn't make any sense to have it as
792 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
793 // got its input pre- or postmultiplied, so it wouldn't know
794 // whether to divide away the old alpha or not.
795 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
796 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED ||
797 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
799 // If the node has multiple inputs, check that they are all valid and
801 bool any_invalid = false;
802 bool any_premultiplied = false;
803 bool any_postmultiplied = false;
805 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
806 switch (node->incoming_links[j]->output_alpha_type) {
811 // Blank is good as both pre- and postmultiplied alpha,
812 // so just ignore it.
814 case ALPHA_PREMULTIPLIED:
815 any_premultiplied = true;
817 case ALPHA_POSTMULTIPLIED:
818 any_postmultiplied = true;
826 node->output_alpha_type = ALPHA_INVALID;
830 // Inputs must be of the same type.
831 if (any_premultiplied && any_postmultiplied) {
832 node->output_alpha_type = ALPHA_INVALID;
836 if (alpha_handling == Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED) {
837 // If the effect has asked for premultiplied alpha, check that it has got it.
838 if (any_postmultiplied) {
839 node->output_alpha_type = ALPHA_INVALID;
841 // In some rare cases, it might be advantageous to say
842 // that blank input alpha yields blank output alpha.
843 // However, this would cause a more complex Effect interface
844 // an effect would need to guarantee that it doesn't mess with
845 // blank alpha), so this is the simplest.
846 node->output_alpha_type = ALPHA_PREMULTIPLIED;
849 // OK, all inputs are the same, and this effect is not going
851 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
852 if (any_premultiplied) {
853 node->output_alpha_type = ALPHA_PREMULTIPLIED;
854 } else if (any_postmultiplied) {
855 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
857 node->output_alpha_type = ALPHA_BLANK;
863 bool EffectChain::node_needs_colorspace_fix(Node *node)
865 if (node->disabled) {
868 if (node->effect->num_inputs() == 0) {
872 // propagate_gamma_and_color_space() has already set our output
873 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
874 if (node->output_color_space == COLORSPACE_INVALID) {
877 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
880 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
881 // the graph. Our strategy is not always optimal, but quite simple:
882 // Find an effect that's as early as possible where the inputs are of
883 // unacceptable colorspaces (that is, either different, or, if the effect only
884 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
885 // propagate the information anew, and repeat until there are no more such
887 void EffectChain::fix_internal_color_spaces()
889 unsigned colorspace_propagation_pass = 0;
893 for (unsigned i = 0; i < nodes.size(); ++i) {
894 Node *node = nodes[i];
895 if (!node_needs_colorspace_fix(node)) {
899 // Go through each input that is not sRGB, and insert
900 // a colorspace conversion before it.
901 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
902 Node *input = node->incoming_links[j];
903 assert(input->output_color_space != COLORSPACE_INVALID);
904 if (input->output_color_space == COLORSPACE_sRGB) {
907 Node *conversion = add_node(new ColorspaceConversionEffect());
908 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
909 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
910 conversion->output_color_space = COLORSPACE_sRGB;
911 insert_node_between(input, conversion, node);
914 // Re-sort topologically, and propagate the new information.
915 propagate_gamma_and_color_space();
922 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
923 output_dot(filename);
924 assert(colorspace_propagation_pass < 100);
927 for (unsigned i = 0; i < nodes.size(); ++i) {
928 Node *node = nodes[i];
929 if (node->disabled) {
932 assert(node->output_color_space != COLORSPACE_INVALID);
936 bool EffectChain::node_needs_alpha_fix(Node *node)
938 if (node->disabled) {
942 // propagate_alpha() has already set our output to ALPHA_INVALID if the
943 // inputs differ or we are otherwise in mismatch, so we can rely on that.
944 return (node->output_alpha_type == ALPHA_INVALID);
947 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
948 // the graph. Similar to fix_internal_color_spaces().
949 void EffectChain::fix_internal_alpha(unsigned step)
951 unsigned alpha_propagation_pass = 0;
955 for (unsigned i = 0; i < nodes.size(); ++i) {
956 Node *node = nodes[i];
957 if (!node_needs_alpha_fix(node)) {
961 // If we need to fix up GammaExpansionEffect, then clearly something
962 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
964 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
966 AlphaType desired_type = ALPHA_PREMULTIPLIED;
968 // GammaCompressionEffect is special; it needs postmultiplied alpha.
969 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
970 assert(node->incoming_links.size() == 1);
971 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
972 desired_type = ALPHA_POSTMULTIPLIED;
975 // Go through each input that is not premultiplied alpha, and insert
976 // a conversion before it.
977 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
978 Node *input = node->incoming_links[j];
979 assert(input->output_alpha_type != ALPHA_INVALID);
980 if (input->output_alpha_type == desired_type ||
981 input->output_alpha_type == ALPHA_BLANK) {
985 if (desired_type == ALPHA_PREMULTIPLIED) {
986 conversion = add_node(new AlphaMultiplicationEffect());
988 conversion = add_node(new AlphaDivisionEffect());
990 conversion->output_alpha_type = desired_type;
991 insert_node_between(input, conversion, node);
994 // Re-sort topologically, and propagate the new information.
995 propagate_gamma_and_color_space();
1003 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1004 output_dot(filename);
1005 assert(alpha_propagation_pass < 100);
1006 } while (found_any);
1008 for (unsigned i = 0; i < nodes.size(); ++i) {
1009 Node *node = nodes[i];
1010 if (node->disabled) {
1013 assert(node->output_alpha_type != ALPHA_INVALID);
1017 // Make so that the output is in the desired color space.
1018 void EffectChain::fix_output_color_space()
1020 Node *output = find_output_node();
1021 if (output->output_color_space != output_format.color_space) {
1022 Node *conversion = add_node(new ColorspaceConversionEffect());
1023 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1024 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1025 conversion->output_color_space = output_format.color_space;
1026 connect_nodes(output, conversion);
1028 propagate_gamma_and_color_space();
1032 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1033 void EffectChain::fix_output_alpha()
1035 Node *output = find_output_node();
1036 assert(output->output_alpha_type != ALPHA_INVALID);
1037 if (output->output_alpha_type == ALPHA_BLANK) {
1038 // No alpha output, so we don't care.
1041 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1042 output_alpha_format == OUTPUT_ALPHA_POSTMULTIPLIED) {
1043 Node *conversion = add_node(new AlphaDivisionEffect());
1044 connect_nodes(output, conversion);
1046 propagate_gamma_and_color_space();
1048 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1049 output_alpha_format == OUTPUT_ALPHA_PREMULTIPLIED) {
1050 Node *conversion = add_node(new AlphaMultiplicationEffect());
1051 connect_nodes(output, conversion);
1053 propagate_gamma_and_color_space();
1057 bool EffectChain::node_needs_gamma_fix(Node *node)
1059 if (node->disabled) {
1063 // Small hack since the output is not an explicit node:
1064 // If we are the last node and our output is in the wrong
1065 // space compared to EffectChain's output, we need to fix it.
1066 // This will only take us to linear, but fix_output_gamma()
1067 // will come and take us to the desired output gamma
1070 // This needs to be before everything else, since it could
1071 // even apply to inputs (if they are the only effect).
1072 if (node->outgoing_links.empty() &&
1073 node->output_gamma_curve != output_format.gamma_curve &&
1074 node->output_gamma_curve != GAMMA_LINEAR) {
1078 if (node->effect->num_inputs() == 0) {
1082 // propagate_gamma_and_color_space() has already set our output
1083 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1084 // except for GammaCompressionEffect.
1085 if (node->output_gamma_curve == GAMMA_INVALID) {
1088 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1089 assert(node->incoming_links.size() == 1);
1090 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1093 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1096 // Very similar to fix_internal_color_spaces(), but for gamma.
1097 // There is one difference, though; before we start adding conversion nodes,
1098 // we see if we can get anything out of asking the sources to deliver
1099 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1100 // does that part, while fix_internal_gamma_by_inserting_nodes()
1101 // inserts nodes as needed afterwards.
1102 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1104 unsigned gamma_propagation_pass = 0;
1108 for (unsigned i = 0; i < nodes.size(); ++i) {
1109 Node *node = nodes[i];
1110 if (!node_needs_gamma_fix(node)) {
1114 // See if all inputs can give us linear gamma. If not, leave it.
1115 std::vector<Node *> nonlinear_inputs;
1116 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1117 assert(!nonlinear_inputs.empty());
1120 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1121 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1122 all_ok &= input->can_output_linear_gamma();
1129 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1130 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1131 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1134 // Re-sort topologically, and propagate the new information.
1135 propagate_gamma_and_color_space();
1142 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1143 output_dot(filename);
1144 assert(gamma_propagation_pass < 100);
1145 } while (found_any);
1148 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1150 unsigned gamma_propagation_pass = 0;
1154 for (unsigned i = 0; i < nodes.size(); ++i) {
1155 Node *node = nodes[i];
1156 if (!node_needs_gamma_fix(node)) {
1160 // Special case: We could be an input and still be asked to
1161 // fix our gamma; if so, we should be the only node
1162 // (as node_needs_gamma_fix() would only return true in
1163 // for an input in that case). That means we should insert
1164 // a conversion node _after_ ourselves.
1165 if (node->incoming_links.empty()) {
1166 assert(node->outgoing_links.empty());
1167 Node *conversion = add_node(new GammaExpansionEffect());
1168 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1169 conversion->output_gamma_curve = GAMMA_LINEAR;
1170 connect_nodes(node, conversion);
1173 // If not, go through each input that is not linear gamma,
1174 // and insert a gamma conversion before it.
1175 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1176 Node *input = node->incoming_links[j];
1177 assert(input->output_gamma_curve != GAMMA_INVALID);
1178 if (input->output_gamma_curve == GAMMA_LINEAR) {
1181 Node *conversion = add_node(new GammaExpansionEffect());
1182 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1183 conversion->output_gamma_curve = GAMMA_LINEAR;
1184 insert_node_between(input, conversion, node);
1187 // Re-sort topologically, and propagate the new information.
1189 propagate_gamma_and_color_space();
1196 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1197 output_dot(filename);
1198 assert(gamma_propagation_pass < 100);
1199 } while (found_any);
1201 for (unsigned i = 0; i < nodes.size(); ++i) {
1202 Node *node = nodes[i];
1203 if (node->disabled) {
1206 assert(node->output_gamma_curve != GAMMA_INVALID);
1210 // Make so that the output is in the desired gamma.
1211 // Note that this assumes linear input gamma, so it might create the need
1212 // for another pass of fix_internal_gamma().
1213 void EffectChain::fix_output_gamma()
1215 Node *output = find_output_node();
1216 if (output->output_gamma_curve != output_format.gamma_curve) {
1217 Node *conversion = add_node(new GammaCompressionEffect());
1218 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1219 conversion->output_gamma_curve = output_format.gamma_curve;
1220 connect_nodes(output, conversion);
1224 // If the user has requested dither, add a DitherEffect right at the end
1225 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1226 // since dither is about the only effect that can _not_ be done in linear space.
1227 void EffectChain::add_dither_if_needed()
1229 if (num_dither_bits == 0) {
1232 Node *output = find_output_node();
1233 Node *dither = add_node(new DitherEffect());
1234 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1235 connect_nodes(output, dither);
1237 dither_effect = dither->effect;
1240 // Find the output node. This is, simply, one that has no outgoing links.
1241 // If there are multiple ones, the graph is malformed (we do not support
1242 // multiple outputs right now).
1243 Node *EffectChain::find_output_node()
1245 std::vector<Node *> output_nodes;
1246 for (unsigned i = 0; i < nodes.size(); ++i) {
1247 Node *node = nodes[i];
1248 if (node->disabled) {
1251 if (node->outgoing_links.empty()) {
1252 output_nodes.push_back(node);
1255 assert(output_nodes.size() == 1);
1256 return output_nodes[0];
1259 void EffectChain::finalize()
1261 // Output the graph as it is before we do any conversions on it.
1262 output_dot("step0-start.dot");
1264 // Give each effect in turn a chance to rewrite its own part of the graph.
1265 // Note that if more effects are added as part of this, they will be
1266 // picked up as part of the same for loop, since they are added at the end.
1267 for (unsigned i = 0; i < nodes.size(); ++i) {
1268 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1270 output_dot("step1-rewritten.dot");
1272 find_color_spaces_for_inputs();
1273 output_dot("step2-input-colorspace.dot");
1276 output_dot("step3-propagated-alpha.dot");
1278 propagate_gamma_and_color_space();
1279 output_dot("step4-propagated-all.dot");
1281 fix_internal_color_spaces();
1282 fix_internal_alpha(6);
1283 fix_output_color_space();
1284 output_dot("step7-output-colorspacefix.dot");
1286 output_dot("step8-output-alphafix.dot");
1288 // Note that we need to fix gamma after colorspace conversion,
1289 // because colorspace conversions might create needs for gamma conversions.
1290 // Also, we need to run an extra pass of fix_internal_gamma() after
1291 // fixing the output gamma, as we only have conversions to/from linear,
1292 // and fix_internal_alpha() since GammaCompressionEffect needs
1293 // postmultiplied input.
1294 fix_internal_gamma_by_asking_inputs(9);
1295 fix_internal_gamma_by_inserting_nodes(10);
1297 output_dot("step11-output-gammafix.dot");
1299 output_dot("step12-output-alpha-propagated.dot");
1300 fix_internal_alpha(13);
1301 output_dot("step14-output-alpha-fixed.dot");
1302 fix_internal_gamma_by_asking_inputs(15);
1303 fix_internal_gamma_by_inserting_nodes(16);
1305 output_dot("step17-before-dither.dot");
1307 add_dither_if_needed();
1309 output_dot("step18-final.dot");
1311 // Construct all needed GLSL programs, starting at the output.
1312 construct_glsl_programs(find_output_node());
1314 output_dot("step19-split-to-phases.dot");
1316 // If we have more than one phase, we need intermediate render-to-texture.
1317 // Construct an FBO, and then as many textures as we need.
1318 // We choose the simplest option of having one texture per output,
1319 // since otherwise this turns into an (albeit simple)
1320 // register allocation problem.
1321 if (phases.size() > 1) {
1322 glGenFramebuffers(1, &fbo);
1324 for (unsigned i = 0; i < phases.size() - 1; ++i) {
1325 inform_input_sizes(phases[i]);
1326 find_output_size(phases[i]);
1328 Node *output_node = phases[i]->effects.back();
1329 glGenTextures(1, &output_node->output_texture);
1331 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1337 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1340 output_node->output_texture_width = phases[i]->output_width;
1341 output_node->output_texture_height = phases[i]->output_height;
1343 inform_input_sizes(phases.back());
1346 for (unsigned i = 0; i < inputs.size(); ++i) {
1347 inputs[i]->finalize();
1350 assert(phases[0]->inputs.empty());
1355 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1359 // Save original viewport.
1360 GLuint x = 0, y = 0;
1362 if (width == 0 && height == 0) {
1364 glGetIntegerv(GL_VIEWPORT, viewport);
1367 width = viewport[2];
1368 height = viewport[3];
1372 glDisable(GL_BLEND);
1374 glDisable(GL_DEPTH_TEST);
1376 glDepthMask(GL_FALSE);
1379 glMatrixMode(GL_PROJECTION);
1381 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
1383 glMatrixMode(GL_MODELVIEW);
1386 if (phases.size() > 1) {
1387 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1391 std::set<Node *> generated_mipmaps;
1393 for (unsigned phase = 0; phase < phases.size(); ++phase) {
1394 // See if the requested output size has changed. If so, we need to recreate
1395 // the texture (and before we start setting up inputs).
1396 inform_input_sizes(phases[phase]);
1397 if (phase != phases.size() - 1) {
1398 find_output_size(phases[phase]);
1400 Node *output_node = phases[phase]->effects.back();
1402 if (output_node->output_texture_width != phases[phase]->output_width ||
1403 output_node->output_texture_height != phases[phase]->output_height) {
1404 glActiveTexture(GL_TEXTURE0);
1406 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1408 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1410 glBindTexture(GL_TEXTURE_2D, 0);
1413 output_node->output_texture_width = phases[phase]->output_width;
1414 output_node->output_texture_height = phases[phase]->output_height;
1418 glUseProgram(phases[phase]->glsl_program_num);
1421 // Set up RTT inputs for this phase.
1422 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1423 glActiveTexture(GL_TEXTURE0 + sampler);
1424 Node *input = phases[phase]->inputs[sampler];
1425 glBindTexture(GL_TEXTURE_2D, input->output_texture);
1427 if (phases[phase]->input_needs_mipmaps) {
1428 if (generated_mipmaps.count(input) == 0) {
1429 glGenerateMipmap(GL_TEXTURE_2D);
1431 generated_mipmaps.insert(input);
1433 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1436 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1440 std::string texture_name = std::string("tex_") + input->effect_id;
1441 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
1445 // And now the output.
1446 if (phase == phases.size() - 1) {
1447 // Last phase goes to the output the user specified.
1448 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1450 glViewport(x, y, width, height);
1451 if (dither_effect != NULL) {
1452 CHECK(dither_effect->set_int("output_width", width));
1453 CHECK(dither_effect->set_int("output_height", height));
1456 Node *output_node = phases[phase]->effects.back();
1457 glFramebufferTexture2D(
1459 GL_COLOR_ATTACHMENT0,
1461 output_node->output_texture,
1464 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1467 // Give the required parameters to all the effects.
1468 unsigned sampler_num = phases[phase]->inputs.size();
1469 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1470 Node *node = phases[phase]->effects[i];
1471 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
1478 glTexCoord2f(0.0f, 0.0f);
1479 glVertex2f(0.0f, 0.0f);
1481 glTexCoord2f(1.0f, 0.0f);
1482 glVertex2f(1.0f, 0.0f);
1484 glTexCoord2f(1.0f, 1.0f);
1485 glVertex2f(1.0f, 1.0f);
1487 glTexCoord2f(0.0f, 1.0f);
1488 glVertex2f(0.0f, 1.0f);
1493 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1494 Node *node = phases[phase]->effects[i];
1495 node->effect->clear_gl_state();