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 std::vector<Node *> sorted_effects = topological_sort(effects);
234 for (unsigned i = 0; i < sorted_effects.size(); ++i) {
235 Node *node = sorted_effects[i];
237 if (node->incoming_links.size() == 1) {
238 frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
240 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
242 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
248 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
249 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
250 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
251 frag_shader += "#undef PREFIX\n";
252 frag_shader += "#undef FUNCNAME\n";
253 if (node->incoming_links.size() == 1) {
254 frag_shader += "#undef INPUT\n";
256 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
258 sprintf(buf, "#undef INPUT%d\n", j + 1);
264 input_needs_mipmaps |= node->effect->needs_mipmaps();
266 for (unsigned i = 0; i < sorted_effects.size(); ++i) {
267 Node *node = sorted_effects[i];
268 if (node->effect->num_inputs() == 0) {
269 CHECK(node->effect->set_int("needs_mipmaps", input_needs_mipmaps));
272 frag_shader += std::string("#define INPUT ") + sorted_effects.back()->effect_id + "\n";
273 frag_shader.append(read_file("footer.frag"));
275 if (movit_debug_level == MOVIT_DEBUG_ON) {
276 // Output shader to a temporary file, for easier debugging.
277 static int compiled_shader_num = 0;
279 sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
280 FILE *fp = fopen(filename, "w");
285 fprintf(fp, "%s\n", frag_shader.c_str());
289 GLuint glsl_program_num = glCreateProgram();
290 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
291 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
292 glAttachShader(glsl_program_num, vs_obj);
294 glAttachShader(glsl_program_num, fs_obj);
296 glLinkProgram(glsl_program_num);
299 Phase *phase = new Phase;
300 phase->glsl_program_num = glsl_program_num;
301 phase->vertex_shader = vs_obj;
302 phase->fragment_shader = fs_obj;
303 phase->input_needs_mipmaps = input_needs_mipmaps;
304 phase->inputs = true_inputs;
305 phase->effects = sorted_effects;
310 // Construct GLSL programs, starting at the given effect and following
311 // the chain from there. We end a program every time we come to an effect
312 // marked as "needs texture bounce", one that is used by multiple other
313 // effects, every time an effect wants to change the output size,
314 // and of course at the end.
316 // We follow a quite simple depth-first search from the output, although
317 // without any explicit recursion.
318 void EffectChain::construct_glsl_programs(Node *output)
320 // Which effects have already been completed in this phase?
321 // We need to keep track of it, as an effect with multiple outputs
322 // could otherwise be calculated multiple times.
323 std::set<Node *> completed_effects;
325 // Effects in the current phase, as well as inputs (outputs from other phases
326 // that we depend on). Note that since we start iterating from the end,
327 // the effect list will be in the reverse order.
328 std::vector<Node *> this_phase_inputs;
329 std::vector<Node *> this_phase_effects;
331 // Effects that we have yet to calculate, but that we know should
332 // be in the current phase.
333 std::stack<Node *> effects_todo_this_phase;
335 // Effects that we have yet to calculate, but that come from other phases.
336 // We delay these until we have this phase done in its entirety,
337 // at which point we pick any of them and start a new phase from that.
338 std::stack<Node *> effects_todo_other_phases;
340 effects_todo_this_phase.push(output);
342 for ( ;; ) { // Termination condition within loop.
343 if (!effects_todo_this_phase.empty()) {
344 // OK, we have more to do this phase.
345 Node *node = effects_todo_this_phase.top();
346 effects_todo_this_phase.pop();
348 // This should currently only happen for effects that are inputs
349 // (either true inputs or phase outputs). We special-case inputs,
350 // and then deduplicate phase outputs in compile_glsl_program().
351 if (node->effect->num_inputs() == 0 && completed_effects.count(node)) {
354 assert(completed_effects.count(node) == 0);
356 this_phase_effects.push_back(node);
357 completed_effects.insert(node);
359 // Find all the dependencies of this effect, and add them to the stack.
360 std::vector<Node *> deps = node->incoming_links;
361 assert(node->effect->num_inputs() == deps.size());
362 for (unsigned i = 0; i < deps.size(); ++i) {
363 bool start_new_phase = false;
365 // FIXME: If we sample directly from a texture, we won't need this.
366 if (node->effect->needs_texture_bounce()) {
367 start_new_phase = true;
370 if (deps[i]->outgoing_links.size() > 1) {
371 if (deps[i]->effect->num_inputs() > 0) {
372 // More than one effect uses this as the input,
373 // and it is not a texture itself.
374 // The easiest thing to do (and probably also the safest
375 // performance-wise in most cases) is to bounce it to a texture
376 // and then let the next passes read from that.
377 start_new_phase = true;
379 // For textures, we try to be slightly more clever;
380 // if none of our outputs need a bounce, we don't bounce
381 // but instead simply use the effect many times.
383 // Strictly speaking, we could bounce it for some outputs
384 // and use it directly for others, but the processing becomes
385 // somewhat simpler if the effect is only used in one such way.
386 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
387 Node *rdep = deps[i]->outgoing_links[j];
388 start_new_phase |= rdep->effect->needs_texture_bounce();
393 if (deps[i]->effect->changes_output_size()) {
394 start_new_phase = true;
397 if (start_new_phase) {
398 effects_todo_other_phases.push(deps[i]);
399 this_phase_inputs.push_back(deps[i]);
401 effects_todo_this_phase.push(deps[i]);
407 // No more effects to do this phase. Take all the ones we have,
408 // and create a GLSL program for it.
409 if (!this_phase_effects.empty()) {
410 reverse(this_phase_effects.begin(), this_phase_effects.end());
411 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
412 this_phase_effects.back()->phase = phases.back();
413 this_phase_inputs.clear();
414 this_phase_effects.clear();
416 assert(this_phase_inputs.empty());
417 assert(this_phase_effects.empty());
419 // If we have no effects left, exit.
420 if (effects_todo_other_phases.empty()) {
424 Node *node = effects_todo_other_phases.top();
425 effects_todo_other_phases.pop();
427 if (completed_effects.count(node) == 0) {
428 // Start a new phase, calculating from this effect.
429 effects_todo_this_phase.push(node);
433 // Finally, since the phases are found from the output but must be executed
434 // from the input(s), reverse them, too.
435 std::reverse(phases.begin(), phases.end());
438 void EffectChain::output_dot(const char *filename)
440 if (movit_debug_level != MOVIT_DEBUG_ON) {
444 FILE *fp = fopen(filename, "w");
450 fprintf(fp, "digraph G {\n");
451 for (unsigned i = 0; i < nodes.size(); ++i) {
452 // Find out which phase this event belongs to.
454 for (unsigned j = 0; j < phases.size(); ++j) {
455 const Phase* p = phases[j];
456 if (std::find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
457 assert(in_phase == -1);
462 if (in_phase == -1) {
463 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
465 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
466 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
469 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
470 std::vector<std::string> labels;
472 if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
473 labels.push_back("needs_bounce");
475 if (nodes[i]->effect->changes_output_size()) {
476 labels.push_back("resize");
479 switch (nodes[i]->output_color_space) {
480 case COLORSPACE_INVALID:
481 labels.push_back("spc[invalid]");
483 case COLORSPACE_REC_601_525:
484 labels.push_back("spc[rec601-525]");
486 case COLORSPACE_REC_601_625:
487 labels.push_back("spc[rec601-625]");
493 switch (nodes[i]->output_gamma_curve) {
495 labels.push_back("gamma[invalid]");
498 labels.push_back("gamma[sRGB]");
500 case GAMMA_REC_601: // and GAMMA_REC_709
501 labels.push_back("gamma[rec601/709]");
507 switch (nodes[i]->output_alpha_type) {
509 labels.push_back("alpha[invalid]");
512 labels.push_back("alpha[blank]");
514 case ALPHA_POSTMULTIPLIED:
515 labels.push_back("alpha[postmult]");
521 if (labels.empty()) {
522 fprintf(fp, " n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
524 std::string label = labels[0];
525 for (unsigned k = 1; k < labels.size(); ++k) {
526 label += ", " + labels[k];
528 fprintf(fp, " n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
537 unsigned EffectChain::fit_rectangle_to_aspect(unsigned width, unsigned height)
539 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
540 // Same aspect, or W/H > aspect (image is wider than the frame).
541 // In either case, keep width.
544 // W/H < aspect (image is taller than the frame), so keep height,
545 // and adjust width correspondingly.
546 return lrintf(height * aspect_nom / aspect_denom);
550 // Propagate input texture sizes throughout, and inform effects downstream.
551 // (Like a lot of other code, we depend on effects being in topological order.)
552 void EffectChain::inform_input_sizes(Phase *phase)
554 // All effects that have a defined size (inputs and RTT inputs)
555 // get that. Reset all others.
556 for (unsigned i = 0; i < phase->effects.size(); ++i) {
557 Node *node = phase->effects[i];
558 if (node->effect->num_inputs() == 0) {
559 Input *input = static_cast<Input *>(node->effect);
560 node->output_width = input->get_width();
561 node->output_height = input->get_height();
562 assert(node->output_width != 0);
563 assert(node->output_height != 0);
565 node->output_width = node->output_height = 0;
568 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
569 Node *input = phase->inputs[i];
570 input->output_width = input->phase->output_width;
571 input->output_height = input->phase->output_height;
572 assert(input->output_width != 0);
573 assert(input->output_height != 0);
576 // Now propagate from the inputs towards the end, and inform as we go.
577 // The rules are simple:
579 // 1. Don't touch effects that already have given sizes (ie., inputs).
580 // 2. If all of your inputs have the same size, that will be your output size.
581 // 3. Otherwise, your output size is 0x0.
582 for (unsigned i = 0; i < phase->effects.size(); ++i) {
583 Node *node = phase->effects[i];
584 if (node->effect->num_inputs() == 0) {
587 unsigned this_output_width = 0;
588 unsigned this_output_height = 0;
589 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
590 Node *input = node->incoming_links[j];
591 node->effect->inform_input_size(j, input->output_width, input->output_height);
593 this_output_width = input->output_width;
594 this_output_height = input->output_height;
595 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
597 this_output_width = 0;
598 this_output_height = 0;
601 node->output_width = this_output_width;
602 node->output_height = this_output_height;
606 // Note: You should call inform_input_sizes() before this, as the last effect's
607 // desired output size might change based on the inputs.
608 void EffectChain::find_output_size(Phase *phase)
610 Node *output_node = phase->effects.back();
612 // If the last effect explicitly sets an output size, use that.
613 if (output_node->effect->changes_output_size()) {
614 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
618 // If not, look at the input phases and textures.
619 // We select the largest one (by fit into the current aspect).
620 unsigned best_width = 0;
621 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
622 Node *input = phase->inputs[i];
623 assert(input->phase->output_width != 0);
624 assert(input->phase->output_height != 0);
625 unsigned width = fit_rectangle_to_aspect(input->phase->output_width, input->phase->output_height);
626 if (width > best_width) {
630 for (unsigned i = 0; i < phase->effects.size(); ++i) {
631 Effect *effect = phase->effects[i]->effect;
632 if (effect->num_inputs() != 0) {
636 Input *input = static_cast<Input *>(effect);
637 unsigned width = fit_rectangle_to_aspect(input->get_width(), input->get_height());
638 if (width > best_width) {
642 assert(best_width != 0);
643 phase->output_width = best_width;
644 phase->output_height = best_width * aspect_denom / aspect_nom;
647 void EffectChain::sort_all_nodes_topologically()
649 nodes = topological_sort(nodes);
652 std::vector<Node *> EffectChain::topological_sort(const std::vector<Node *> &nodes)
654 std::set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
655 std::vector<Node *> sorted_list;
656 for (unsigned i = 0; i < nodes.size(); ++i) {
657 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
659 reverse(sorted_list.begin(), sorted_list.end());
663 void EffectChain::topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list)
665 if (nodes_left_to_visit->count(node) == 0) {
668 nodes_left_to_visit->erase(node);
669 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
670 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
672 sorted_list->push_back(node);
675 void EffectChain::find_color_spaces_for_inputs()
677 for (unsigned i = 0; i < nodes.size(); ++i) {
678 Node *node = nodes[i];
679 if (node->disabled) {
682 if (node->incoming_links.size() == 0) {
683 Input *input = static_cast<Input *>(node->effect);
684 node->output_color_space = input->get_color_space();
685 node->output_gamma_curve = input->get_gamma_curve();
687 Effect::AlphaHandling alpha_handling = input->alpha_handling();
688 switch (alpha_handling) {
689 case Effect::OUTPUT_BLANK_ALPHA:
690 node->output_alpha_type = ALPHA_BLANK;
692 case Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED:
693 node->output_alpha_type = ALPHA_PREMULTIPLIED;
695 case Effect::OUTPUT_ALPHA_POSTMULTIPLIED:
696 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
698 case Effect::DONT_CARE_ALPHA_TYPE:
706 // Propagate gamma and color space information as far as we can in the graph.
707 // The rules are simple: Anything where all the inputs agree, get that as
708 // output as well. Anything else keeps having *_INVALID.
709 void EffectChain::propagate_gamma_and_color_space()
711 // We depend on going through the nodes in order.
712 sort_all_nodes_topologically();
714 for (unsigned i = 0; i < nodes.size(); ++i) {
715 Node *node = nodes[i];
716 if (node->disabled) {
719 assert(node->incoming_links.size() == node->effect->num_inputs());
720 if (node->incoming_links.size() == 0) {
721 assert(node->output_color_space != COLORSPACE_INVALID);
722 assert(node->output_gamma_curve != GAMMA_INVALID);
726 Colorspace color_space = node->incoming_links[0]->output_color_space;
727 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
728 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
729 if (node->incoming_links[j]->output_color_space != color_space) {
730 color_space = COLORSPACE_INVALID;
732 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
733 gamma_curve = GAMMA_INVALID;
737 // The conversion effects already have their outputs set correctly,
738 // so leave them alone.
739 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
740 node->output_color_space = color_space;
742 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
743 node->effect->effect_type_id() != "GammaExpansionEffect") {
744 node->output_gamma_curve = gamma_curve;
749 // Propagate alpha information as far as we can in the graph.
750 // Similar to propagate_gamma_and_color_space().
751 void EffectChain::propagate_alpha()
753 // We depend on going through the nodes in order.
754 sort_all_nodes_topologically();
756 for (unsigned i = 0; i < nodes.size(); ++i) {
757 Node *node = nodes[i];
758 if (node->disabled) {
761 assert(node->incoming_links.size() == node->effect->num_inputs());
762 if (node->incoming_links.size() == 0) {
763 assert(node->output_alpha_type != ALPHA_INVALID);
767 // The alpha multiplication/division effects are special cases.
768 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
769 assert(node->incoming_links.size() == 1);
770 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
771 node->output_alpha_type = ALPHA_PREMULTIPLIED;
774 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
775 assert(node->incoming_links.size() == 1);
776 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
777 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
781 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
782 // because they are the only one that _need_ postmultiplied alpha.
783 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
784 node->effect->effect_type_id() == "GammaExpansionEffect") {
785 assert(node->incoming_links.size() == 1);
786 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
787 node->output_alpha_type = ALPHA_BLANK;
788 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
789 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
791 node->output_alpha_type = ALPHA_INVALID;
796 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
797 // or OUTPUT_ALPHA_POSTMULTIPLIED), and they have already been
798 // taken care of above. Rationale: Even if you could imagine
799 // e.g. an effect that took in an image and set alpha=1.0
800 // unconditionally, it wouldn't make any sense to have it as
801 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
802 // got its input pre- or postmultiplied, so it wouldn't know
803 // whether to divide away the old alpha or not.
804 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
805 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED ||
806 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
808 // If the node has multiple inputs, check that they are all valid and
810 bool any_invalid = false;
811 bool any_premultiplied = false;
812 bool any_postmultiplied = false;
814 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
815 switch (node->incoming_links[j]->output_alpha_type) {
820 // Blank is good as both pre- and postmultiplied alpha,
821 // so just ignore it.
823 case ALPHA_PREMULTIPLIED:
824 any_premultiplied = true;
826 case ALPHA_POSTMULTIPLIED:
827 any_postmultiplied = true;
835 node->output_alpha_type = ALPHA_INVALID;
839 // Inputs must be of the same type.
840 if (any_premultiplied && any_postmultiplied) {
841 node->output_alpha_type = ALPHA_INVALID;
845 if (alpha_handling == Effect::INPUT_AND_OUTPUT_ALPHA_PREMULTIPLIED) {
846 // If the effect has asked for premultiplied alpha, check that it has got it.
847 if (any_postmultiplied) {
848 node->output_alpha_type = ALPHA_INVALID;
850 // In some rare cases, it might be advantageous to say
851 // that blank input alpha yields blank output alpha.
852 // However, this would cause a more complex Effect interface
853 // an effect would need to guarantee that it doesn't mess with
854 // blank alpha), so this is the simplest.
855 node->output_alpha_type = ALPHA_PREMULTIPLIED;
858 // OK, all inputs are the same, and this effect is not going
860 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
861 if (any_premultiplied) {
862 node->output_alpha_type = ALPHA_PREMULTIPLIED;
863 } else if (any_postmultiplied) {
864 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
866 node->output_alpha_type = ALPHA_BLANK;
872 bool EffectChain::node_needs_colorspace_fix(Node *node)
874 if (node->disabled) {
877 if (node->effect->num_inputs() == 0) {
881 // propagate_gamma_and_color_space() has already set our output
882 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
883 if (node->output_color_space == COLORSPACE_INVALID) {
886 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
889 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
890 // the graph. Our strategy is not always optimal, but quite simple:
891 // Find an effect that's as early as possible where the inputs are of
892 // unacceptable colorspaces (that is, either different, or, if the effect only
893 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
894 // propagate the information anew, and repeat until there are no more such
896 void EffectChain::fix_internal_color_spaces()
898 unsigned colorspace_propagation_pass = 0;
902 for (unsigned i = 0; i < nodes.size(); ++i) {
903 Node *node = nodes[i];
904 if (!node_needs_colorspace_fix(node)) {
908 // Go through each input that is not sRGB, and insert
909 // a colorspace conversion before it.
910 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
911 Node *input = node->incoming_links[j];
912 assert(input->output_color_space != COLORSPACE_INVALID);
913 if (input->output_color_space == COLORSPACE_sRGB) {
916 Node *conversion = add_node(new ColorspaceConversionEffect());
917 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
918 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
919 conversion->output_color_space = COLORSPACE_sRGB;
920 insert_node_between(input, conversion, node);
923 // Re-sort topologically, and propagate the new information.
924 propagate_gamma_and_color_space();
931 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
932 output_dot(filename);
933 assert(colorspace_propagation_pass < 100);
936 for (unsigned i = 0; i < nodes.size(); ++i) {
937 Node *node = nodes[i];
938 if (node->disabled) {
941 assert(node->output_color_space != COLORSPACE_INVALID);
945 bool EffectChain::node_needs_alpha_fix(Node *node)
947 if (node->disabled) {
951 // propagate_alpha() has already set our output to ALPHA_INVALID if the
952 // inputs differ or we are otherwise in mismatch, so we can rely on that.
953 return (node->output_alpha_type == ALPHA_INVALID);
956 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
957 // the graph. Similar to fix_internal_color_spaces().
958 void EffectChain::fix_internal_alpha(unsigned step)
960 unsigned alpha_propagation_pass = 0;
964 for (unsigned i = 0; i < nodes.size(); ++i) {
965 Node *node = nodes[i];
966 if (!node_needs_alpha_fix(node)) {
970 // If we need to fix up GammaExpansionEffect, then clearly something
971 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
973 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
975 AlphaType desired_type = ALPHA_PREMULTIPLIED;
977 // GammaCompressionEffect is special; it needs postmultiplied alpha.
978 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
979 assert(node->incoming_links.size() == 1);
980 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
981 desired_type = ALPHA_POSTMULTIPLIED;
984 // Go through each input that is not premultiplied alpha, and insert
985 // a conversion before it.
986 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
987 Node *input = node->incoming_links[j];
988 assert(input->output_alpha_type != ALPHA_INVALID);
989 if (input->output_alpha_type == desired_type ||
990 input->output_alpha_type == ALPHA_BLANK) {
994 if (desired_type == ALPHA_PREMULTIPLIED) {
995 conversion = add_node(new AlphaMultiplicationEffect());
997 conversion = add_node(new AlphaDivisionEffect());
999 conversion->output_alpha_type = desired_type;
1000 insert_node_between(input, conversion, node);
1003 // Re-sort topologically, and propagate the new information.
1004 propagate_gamma_and_color_space();
1012 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1013 output_dot(filename);
1014 assert(alpha_propagation_pass < 100);
1015 } while (found_any);
1017 for (unsigned i = 0; i < nodes.size(); ++i) {
1018 Node *node = nodes[i];
1019 if (node->disabled) {
1022 assert(node->output_alpha_type != ALPHA_INVALID);
1026 // Make so that the output is in the desired color space.
1027 void EffectChain::fix_output_color_space()
1029 Node *output = find_output_node();
1030 if (output->output_color_space != output_format.color_space) {
1031 Node *conversion = add_node(new ColorspaceConversionEffect());
1032 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1033 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1034 conversion->output_color_space = output_format.color_space;
1035 connect_nodes(output, conversion);
1037 propagate_gamma_and_color_space();
1041 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1042 void EffectChain::fix_output_alpha()
1044 Node *output = find_output_node();
1045 assert(output->output_alpha_type != ALPHA_INVALID);
1046 if (output->output_alpha_type == ALPHA_BLANK) {
1047 // No alpha output, so we don't care.
1050 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1051 output_alpha_format == OUTPUT_ALPHA_POSTMULTIPLIED) {
1052 Node *conversion = add_node(new AlphaDivisionEffect());
1053 connect_nodes(output, conversion);
1055 propagate_gamma_and_color_space();
1057 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1058 output_alpha_format == OUTPUT_ALPHA_PREMULTIPLIED) {
1059 Node *conversion = add_node(new AlphaMultiplicationEffect());
1060 connect_nodes(output, conversion);
1062 propagate_gamma_and_color_space();
1066 bool EffectChain::node_needs_gamma_fix(Node *node)
1068 if (node->disabled) {
1072 // Small hack since the output is not an explicit node:
1073 // If we are the last node and our output is in the wrong
1074 // space compared to EffectChain's output, we need to fix it.
1075 // This will only take us to linear, but fix_output_gamma()
1076 // will come and take us to the desired output gamma
1079 // This needs to be before everything else, since it could
1080 // even apply to inputs (if they are the only effect).
1081 if (node->outgoing_links.empty() &&
1082 node->output_gamma_curve != output_format.gamma_curve &&
1083 node->output_gamma_curve != GAMMA_LINEAR) {
1087 if (node->effect->num_inputs() == 0) {
1091 // propagate_gamma_and_color_space() has already set our output
1092 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1093 // except for GammaCompressionEffect.
1094 if (node->output_gamma_curve == GAMMA_INVALID) {
1097 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1098 assert(node->incoming_links.size() == 1);
1099 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1102 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1105 // Very similar to fix_internal_color_spaces(), but for gamma.
1106 // There is one difference, though; before we start adding conversion nodes,
1107 // we see if we can get anything out of asking the sources to deliver
1108 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1109 // does that part, while fix_internal_gamma_by_inserting_nodes()
1110 // inserts nodes as needed afterwards.
1111 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1113 unsigned gamma_propagation_pass = 0;
1117 for (unsigned i = 0; i < nodes.size(); ++i) {
1118 Node *node = nodes[i];
1119 if (!node_needs_gamma_fix(node)) {
1123 // See if all inputs can give us linear gamma. If not, leave it.
1124 std::vector<Node *> nonlinear_inputs;
1125 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1126 assert(!nonlinear_inputs.empty());
1129 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1130 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1131 all_ok &= input->can_output_linear_gamma();
1138 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1139 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1140 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1143 // Re-sort topologically, and propagate the new information.
1144 propagate_gamma_and_color_space();
1151 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1152 output_dot(filename);
1153 assert(gamma_propagation_pass < 100);
1154 } while (found_any);
1157 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1159 unsigned gamma_propagation_pass = 0;
1163 for (unsigned i = 0; i < nodes.size(); ++i) {
1164 Node *node = nodes[i];
1165 if (!node_needs_gamma_fix(node)) {
1169 // Special case: We could be an input and still be asked to
1170 // fix our gamma; if so, we should be the only node
1171 // (as node_needs_gamma_fix() would only return true in
1172 // for an input in that case). That means we should insert
1173 // a conversion node _after_ ourselves.
1174 if (node->incoming_links.empty()) {
1175 assert(node->outgoing_links.empty());
1176 Node *conversion = add_node(new GammaExpansionEffect());
1177 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1178 conversion->output_gamma_curve = GAMMA_LINEAR;
1179 connect_nodes(node, conversion);
1182 // If not, go through each input that is not linear gamma,
1183 // and insert a gamma conversion before it.
1184 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1185 Node *input = node->incoming_links[j];
1186 assert(input->output_gamma_curve != GAMMA_INVALID);
1187 if (input->output_gamma_curve == GAMMA_LINEAR) {
1190 Node *conversion = add_node(new GammaExpansionEffect());
1191 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1192 conversion->output_gamma_curve = GAMMA_LINEAR;
1193 insert_node_between(input, conversion, node);
1196 // Re-sort topologically, and propagate the new information.
1198 propagate_gamma_and_color_space();
1205 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1206 output_dot(filename);
1207 assert(gamma_propagation_pass < 100);
1208 } while (found_any);
1210 for (unsigned i = 0; i < nodes.size(); ++i) {
1211 Node *node = nodes[i];
1212 if (node->disabled) {
1215 assert(node->output_gamma_curve != GAMMA_INVALID);
1219 // Make so that the output is in the desired gamma.
1220 // Note that this assumes linear input gamma, so it might create the need
1221 // for another pass of fix_internal_gamma().
1222 void EffectChain::fix_output_gamma()
1224 Node *output = find_output_node();
1225 if (output->output_gamma_curve != output_format.gamma_curve) {
1226 Node *conversion = add_node(new GammaCompressionEffect());
1227 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1228 conversion->output_gamma_curve = output_format.gamma_curve;
1229 connect_nodes(output, conversion);
1233 // If the user has requested dither, add a DitherEffect right at the end
1234 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1235 // since dither is about the only effect that can _not_ be done in linear space.
1236 void EffectChain::add_dither_if_needed()
1238 if (num_dither_bits == 0) {
1241 Node *output = find_output_node();
1242 Node *dither = add_node(new DitherEffect());
1243 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1244 connect_nodes(output, dither);
1246 dither_effect = dither->effect;
1249 // Find the output node. This is, simply, one that has no outgoing links.
1250 // If there are multiple ones, the graph is malformed (we do not support
1251 // multiple outputs right now).
1252 Node *EffectChain::find_output_node()
1254 std::vector<Node *> output_nodes;
1255 for (unsigned i = 0; i < nodes.size(); ++i) {
1256 Node *node = nodes[i];
1257 if (node->disabled) {
1260 if (node->outgoing_links.empty()) {
1261 output_nodes.push_back(node);
1264 assert(output_nodes.size() == 1);
1265 return output_nodes[0];
1268 void EffectChain::finalize()
1270 // Output the graph as it is before we do any conversions on it.
1271 output_dot("step0-start.dot");
1273 // Give each effect in turn a chance to rewrite its own part of the graph.
1274 // Note that if more effects are added as part of this, they will be
1275 // picked up as part of the same for loop, since they are added at the end.
1276 for (unsigned i = 0; i < nodes.size(); ++i) {
1277 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1279 output_dot("step1-rewritten.dot");
1281 find_color_spaces_for_inputs();
1282 output_dot("step2-input-colorspace.dot");
1285 output_dot("step3-propagated-alpha.dot");
1287 propagate_gamma_and_color_space();
1288 output_dot("step4-propagated-all.dot");
1290 fix_internal_color_spaces();
1291 fix_internal_alpha(6);
1292 fix_output_color_space();
1293 output_dot("step7-output-colorspacefix.dot");
1295 output_dot("step8-output-alphafix.dot");
1297 // Note that we need to fix gamma after colorspace conversion,
1298 // because colorspace conversions might create needs for gamma conversions.
1299 // Also, we need to run an extra pass of fix_internal_gamma() after
1300 // fixing the output gamma, as we only have conversions to/from linear,
1301 // and fix_internal_alpha() since GammaCompressionEffect needs
1302 // postmultiplied input.
1303 fix_internal_gamma_by_asking_inputs(9);
1304 fix_internal_gamma_by_inserting_nodes(10);
1306 output_dot("step11-output-gammafix.dot");
1308 output_dot("step12-output-alpha-propagated.dot");
1309 fix_internal_alpha(13);
1310 output_dot("step14-output-alpha-fixed.dot");
1311 fix_internal_gamma_by_asking_inputs(15);
1312 fix_internal_gamma_by_inserting_nodes(16);
1314 output_dot("step17-before-dither.dot");
1316 add_dither_if_needed();
1318 output_dot("step18-final.dot");
1320 // Construct all needed GLSL programs, starting at the output.
1321 construct_glsl_programs(find_output_node());
1323 output_dot("step19-split-to-phases.dot");
1325 // If we have more than one phase, we need intermediate render-to-texture.
1326 // Construct an FBO, and then as many textures as we need.
1327 // We choose the simplest option of having one texture per output,
1328 // since otherwise this turns into an (albeit simple)
1329 // register allocation problem.
1330 if (phases.size() > 1) {
1331 glGenFramebuffers(1, &fbo);
1333 for (unsigned i = 0; i < phases.size() - 1; ++i) {
1334 inform_input_sizes(phases[i]);
1335 find_output_size(phases[i]);
1337 Node *output_node = phases[i]->effects.back();
1338 glGenTextures(1, &output_node->output_texture);
1340 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1342 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1344 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1346 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1349 output_node->output_texture_width = phases[i]->output_width;
1350 output_node->output_texture_height = phases[i]->output_height;
1352 inform_input_sizes(phases.back());
1355 for (unsigned i = 0; i < inputs.size(); ++i) {
1356 inputs[i]->finalize();
1359 assert(phases[0]->inputs.empty());
1364 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1368 // Save original viewport.
1369 GLuint x = 0, y = 0;
1371 if (width == 0 && height == 0) {
1373 glGetIntegerv(GL_VIEWPORT, viewport);
1376 width = viewport[2];
1377 height = viewport[3];
1381 glDisable(GL_BLEND);
1383 glDisable(GL_DEPTH_TEST);
1385 glDepthMask(GL_FALSE);
1388 glMatrixMode(GL_PROJECTION);
1390 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
1392 glMatrixMode(GL_MODELVIEW);
1395 if (phases.size() > 1) {
1396 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1400 std::set<Node *> generated_mipmaps;
1402 for (unsigned phase = 0; phase < phases.size(); ++phase) {
1403 // See if the requested output size has changed. If so, we need to recreate
1404 // the texture (and before we start setting up inputs).
1405 inform_input_sizes(phases[phase]);
1406 if (phase != phases.size() - 1) {
1407 find_output_size(phases[phase]);
1409 Node *output_node = phases[phase]->effects.back();
1411 if (output_node->output_texture_width != phases[phase]->output_width ||
1412 output_node->output_texture_height != phases[phase]->output_height) {
1413 glActiveTexture(GL_TEXTURE0);
1415 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
1417 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1419 glBindTexture(GL_TEXTURE_2D, 0);
1422 output_node->output_texture_width = phases[phase]->output_width;
1423 output_node->output_texture_height = phases[phase]->output_height;
1427 glUseProgram(phases[phase]->glsl_program_num);
1430 // Set up RTT inputs for this phase.
1431 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1432 glActiveTexture(GL_TEXTURE0 + sampler);
1433 Node *input = phases[phase]->inputs[sampler];
1434 glBindTexture(GL_TEXTURE_2D, input->output_texture);
1436 if (phases[phase]->input_needs_mipmaps) {
1437 if (generated_mipmaps.count(input) == 0) {
1438 glGenerateMipmap(GL_TEXTURE_2D);
1440 generated_mipmaps.insert(input);
1442 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1445 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1449 std::string texture_name = std::string("tex_") + input->effect_id;
1450 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
1454 // And now the output.
1455 if (phase == phases.size() - 1) {
1456 // Last phase goes to the output the user specified.
1457 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1459 glViewport(x, y, width, height);
1460 if (dither_effect != NULL) {
1461 CHECK(dither_effect->set_int("output_width", width));
1462 CHECK(dither_effect->set_int("output_height", height));
1465 Node *output_node = phases[phase]->effects.back();
1466 glFramebufferTexture2D(
1468 GL_COLOR_ATTACHMENT0,
1470 output_node->output_texture,
1473 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1476 // Give the required parameters to all the effects.
1477 unsigned sampler_num = phases[phase]->inputs.size();
1478 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1479 Node *node = phases[phase]->effects[i];
1480 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
1487 glTexCoord2f(0.0f, 0.0f);
1488 glVertex2f(0.0f, 0.0f);
1490 glTexCoord2f(1.0f, 0.0f);
1491 glVertex2f(1.0f, 0.0f);
1493 glTexCoord2f(1.0f, 1.0f);
1494 glVertex2f(1.0f, 1.0f);
1496 glTexCoord2f(0.0f, 1.0f);
1497 glVertex2f(0.0f, 1.0f);
1502 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1503 Node *node = phases[phase]->effects[i];
1504 node->effect->clear_gl_state();