1 #define GL_GLEXT_PROTOTYPES 1
16 #include "alpha_division_effect.h"
17 #include "alpha_multiplication_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "dither_effect.h"
21 #include "effect_chain.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
26 #include "resource_pool.h"
28 #include "ycbcr_conversion_effect.h"
34 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
35 : aspect_nom(aspect_nom),
36 aspect_denom(aspect_denom),
40 resource_pool(resource_pool),
41 do_phase_timing(false) {
42 if (resource_pool == NULL) {
43 this->resource_pool = new ResourcePool();
44 owns_resource_pool = true;
46 owns_resource_pool = false;
50 EffectChain::~EffectChain()
52 for (unsigned i = 0; i < nodes.size(); ++i) {
53 delete nodes[i]->effect;
56 for (unsigned i = 0; i < phases.size(); ++i) {
57 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
60 if (owns_resource_pool) {
65 Input *EffectChain::add_input(Input *input)
68 inputs.push_back(input);
73 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
76 output_format = format;
77 output_alpha_format = alpha_format;
78 output_color_type = OUTPUT_COLOR_RGB;
81 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
82 const YCbCrFormat &ycbcr_format)
85 output_format = format;
86 output_alpha_format = alpha_format;
87 output_color_type = OUTPUT_COLOR_YCBCR;
88 output_ycbcr_format = ycbcr_format;
90 assert(ycbcr_format.chroma_subsampling_x == 1);
91 assert(ycbcr_format.chroma_subsampling_y == 1);
94 Node *EffectChain::add_node(Effect *effect)
96 for (unsigned i = 0; i < nodes.size(); ++i) {
97 assert(nodes[i]->effect != effect);
100 Node *node = new Node;
101 node->effect = effect;
102 node->disabled = false;
103 node->output_color_space = COLORSPACE_INVALID;
104 node->output_gamma_curve = GAMMA_INVALID;
105 node->output_alpha_type = ALPHA_INVALID;
106 node->needs_mipmaps = false;
107 node->one_to_one_sampling = false;
109 nodes.push_back(node);
110 node_map[effect] = node;
111 effect->inform_added(this);
115 void EffectChain::connect_nodes(Node *sender, Node *receiver)
117 sender->outgoing_links.push_back(receiver);
118 receiver->incoming_links.push_back(sender);
121 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
123 new_receiver->incoming_links = old_receiver->incoming_links;
124 old_receiver->incoming_links.clear();
126 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
127 Node *sender = new_receiver->incoming_links[i];
128 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
129 if (sender->outgoing_links[j] == old_receiver) {
130 sender->outgoing_links[j] = new_receiver;
136 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
138 new_sender->outgoing_links = old_sender->outgoing_links;
139 old_sender->outgoing_links.clear();
141 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
142 Node *receiver = new_sender->outgoing_links[i];
143 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
144 if (receiver->incoming_links[j] == old_sender) {
145 receiver->incoming_links[j] = new_sender;
151 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
153 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
154 if (sender->outgoing_links[i] == receiver) {
155 sender->outgoing_links[i] = middle;
156 middle->incoming_links.push_back(sender);
159 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
160 if (receiver->incoming_links[i] == sender) {
161 receiver->incoming_links[i] = middle;
162 middle->outgoing_links.push_back(receiver);
166 assert(middle->incoming_links.size() == middle->effect->num_inputs());
169 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
171 assert(node->effect->needs_texture_bounce());
172 assert(input_num < node->incoming_links.size());
173 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
174 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
175 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
178 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
180 if (node->output_gamma_curve == GAMMA_LINEAR &&
181 node->effect->effect_type_id() != "GammaCompressionEffect") {
184 if (node->effect->num_inputs() == 0) {
185 nonlinear_inputs->push_back(node);
187 assert(node->effect->num_inputs() == node->incoming_links.size());
188 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
189 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
194 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
197 assert(inputs.size() == effect->num_inputs());
198 Node *node = add_node(effect);
199 for (unsigned i = 0; i < inputs.size(); ++i) {
200 assert(node_map.count(inputs[i]) != 0);
201 connect_nodes(node_map[inputs[i]], node);
206 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
207 string replace_prefix(const string &text, const string &prefix)
212 while (start < text.size()) {
213 size_t pos = text.find("PREFIX(", start);
214 if (pos == string::npos) {
215 output.append(text.substr(start, string::npos));
219 output.append(text.substr(start, pos - start));
220 output.append(prefix);
223 pos += strlen("PREFIX(");
225 // Output stuff until we find the matching ), which we then eat.
227 size_t end_arg_pos = pos;
228 while (end_arg_pos < text.size()) {
229 if (text[end_arg_pos] == '(') {
231 } else if (text[end_arg_pos] == ')') {
239 output.append(text.substr(pos, end_arg_pos - pos));
247 void EffectChain::compile_glsl_program(Phase *phase)
249 string frag_shader = read_version_dependent_file("header", "frag");
251 // Create functions for all the texture inputs that we need.
252 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
253 Node *input = phase->inputs[i]->output_node;
255 sprintf(effect_id, "in%u", i);
256 phase->effect_ids.insert(make_pair(input, effect_id));
258 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
259 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
260 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
261 frag_shader += "}\n";
265 for (unsigned i = 0; i < phase->effects.size(); ++i) {
266 Node *node = phase->effects[i];
268 sprintf(effect_id, "eff%u", i);
269 phase->effect_ids.insert(make_pair(node, effect_id));
271 if (node->incoming_links.size() == 1) {
272 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
274 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
276 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
282 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
283 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
284 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
285 frag_shader += "#undef PREFIX\n";
286 frag_shader += "#undef FUNCNAME\n";
287 if (node->incoming_links.size() == 1) {
288 frag_shader += "#undef INPUT\n";
290 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
292 sprintf(buf, "#undef INPUT%d\n", j + 1);
298 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
299 frag_shader.append(read_version_dependent_file("footer", "frag"));
301 string vert_shader = read_version_dependent_file("vs", "vert");
302 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
305 // Construct GLSL programs, starting at the given effect and following
306 // the chain from there. We end a program every time we come to an effect
307 // marked as "needs texture bounce", one that is used by multiple other
308 // effects, every time we need to bounce due to output size change
309 // (not all size changes require ending), and of course at the end.
311 // We follow a quite simple depth-first search from the output, although
312 // without recursing explicitly within each phase.
313 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
315 if (completed_effects->count(output)) {
316 return (*completed_effects)[output];
319 Phase *phase = new Phase;
320 phase->output_node = output;
322 // If the output effect has one-to-one sampling, we try to trace this
323 // status down through the dependency chain. This is important in case
324 // we hit an effect that changes output size (and not sets a virtual
325 // output size); if we have one-to-one sampling, we don't have to break
327 output->one_to_one_sampling = output->effect->one_to_one_sampling();
329 // Effects that we have yet to calculate, but that we know should
330 // be in the current phase.
331 stack<Node *> effects_todo_this_phase;
332 effects_todo_this_phase.push(output);
334 while (!effects_todo_this_phase.empty()) {
335 Node *node = effects_todo_this_phase.top();
336 effects_todo_this_phase.pop();
338 if (node->effect->needs_mipmaps()) {
339 node->needs_mipmaps = true;
342 // This should currently only happen for effects that are inputs
343 // (either true inputs or phase outputs). We special-case inputs,
344 // and then deduplicate phase outputs below.
345 if (node->effect->num_inputs() == 0) {
346 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
350 assert(completed_effects->count(node) == 0);
353 phase->effects.push_back(node);
355 // Find all the dependencies of this effect, and add them to the stack.
356 vector<Node *> deps = node->incoming_links;
357 assert(node->effect->num_inputs() == deps.size());
358 for (unsigned i = 0; i < deps.size(); ++i) {
359 bool start_new_phase = false;
361 if (node->effect->needs_texture_bounce() &&
362 !deps[i]->effect->is_single_texture()) {
363 start_new_phase = true;
366 // Propagate information about needing mipmaps down the chain,
367 // breaking the phase if we notice an incompatibility.
369 // Note that we cannot do this propagation as a normal pass,
370 // because it needs information about where the phases end
371 // (we should not propagate the flag across phases).
372 if (node->needs_mipmaps) {
373 if (deps[i]->effect->num_inputs() == 0) {
374 Input *input = static_cast<Input *>(deps[i]->effect);
375 start_new_phase |= !input->can_supply_mipmaps();
377 deps[i]->needs_mipmaps = true;
381 if (deps[i]->outgoing_links.size() > 1) {
382 if (!deps[i]->effect->is_single_texture()) {
383 // More than one effect uses this as the input,
384 // and it is not a texture itself.
385 // The easiest thing to do (and probably also the safest
386 // performance-wise in most cases) is to bounce it to a texture
387 // and then let the next passes read from that.
388 start_new_phase = true;
390 assert(deps[i]->effect->num_inputs() == 0);
392 // For textures, we try to be slightly more clever;
393 // if none of our outputs need a bounce, we don't bounce
394 // but instead simply use the effect many times.
396 // Strictly speaking, we could bounce it for some outputs
397 // and use it directly for others, but the processing becomes
398 // somewhat simpler if the effect is only used in one such way.
399 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
400 Node *rdep = deps[i]->outgoing_links[j];
401 start_new_phase |= rdep->effect->needs_texture_bounce();
406 if (deps[i]->effect->sets_virtual_output_size()) {
407 assert(deps[i]->effect->changes_output_size());
408 // If the next effect sets a virtual size to rely on OpenGL's
409 // bilinear sampling, we'll really need to break the phase here.
410 start_new_phase = true;
411 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
412 // If the next effect changes size and we don't have one-to-one sampling,
413 // we also need to break here.
414 start_new_phase = true;
417 if (start_new_phase) {
418 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
420 effects_todo_this_phase.push(deps[i]);
422 // Propagate the one-to-one status down through the dependency.
423 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
424 deps[i]->effect->one_to_one_sampling();
429 // No more effects to do this phase. Take all the ones we have,
430 // and create a GLSL program for it.
431 assert(!phase->effects.empty());
433 // Deduplicate the inputs.
434 sort(phase->inputs.begin(), phase->inputs.end());
435 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
437 // We added the effects from the output and back, but we need to output
438 // them in topological sort order in the shader.
439 phase->effects = topological_sort(phase->effects);
441 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
442 phase->input_needs_mipmaps = false;
443 for (unsigned i = 0; i < phase->effects.size(); ++i) {
444 Node *node = phase->effects[i];
445 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
447 for (unsigned i = 0; i < phase->effects.size(); ++i) {
448 Node *node = phase->effects[i];
449 if (node->effect->num_inputs() == 0) {
450 Input *input = static_cast<Input *>(node->effect);
451 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
452 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
456 // Tell each node which phase it ended up in, so that the unit test
457 // can check that the phases were split in the right place.
458 // Note that this ignores that effects may be part of multiple phases;
459 // if the unit tests need to test such cases, we'll reconsider.
460 for (unsigned i = 0; i < phase->effects.size(); ++i) {
461 phase->effects[i]->containing_phase = phase;
464 // Actually make the shader for this phase.
465 compile_glsl_program(phase);
467 // Initialize timer objects.
468 if (movit_timer_queries_supported) {
469 glGenQueries(1, &phase->timer_query_object);
470 phase->time_elapsed_ns = 0;
471 phase->num_measured_iterations = 0;
474 assert(completed_effects->count(output) == 0);
475 completed_effects->insert(make_pair(output, phase));
476 phases.push_back(phase);
480 void EffectChain::output_dot(const char *filename)
482 if (movit_debug_level != MOVIT_DEBUG_ON) {
486 FILE *fp = fopen(filename, "w");
492 fprintf(fp, "digraph G {\n");
493 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
494 for (unsigned i = 0; i < nodes.size(); ++i) {
495 // Find out which phase this event belongs to.
496 vector<int> in_phases;
497 for (unsigned j = 0; j < phases.size(); ++j) {
498 const Phase* p = phases[j];
499 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
500 in_phases.push_back(j);
504 if (in_phases.empty()) {
505 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
506 } else if (in_phases.size() == 1) {
507 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
508 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
509 (in_phases[0] % 8) + 1);
511 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
513 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
514 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
515 (in_phases[0] % 8) + 1);
518 char from_node_id[256];
519 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
521 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
522 char to_node_id[256];
523 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
525 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
526 output_dot_edge(fp, from_node_id, to_node_id, labels);
529 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
531 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
532 output_dot_edge(fp, from_node_id, "output", labels);
540 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
542 vector<string> labels;
544 if (to != NULL && to->effect->needs_texture_bounce()) {
545 labels.push_back("needs_bounce");
547 if (from->effect->changes_output_size()) {
548 labels.push_back("resize");
551 switch (from->output_color_space) {
552 case COLORSPACE_INVALID:
553 labels.push_back("spc[invalid]");
555 case COLORSPACE_REC_601_525:
556 labels.push_back("spc[rec601-525]");
558 case COLORSPACE_REC_601_625:
559 labels.push_back("spc[rec601-625]");
565 switch (from->output_gamma_curve) {
567 labels.push_back("gamma[invalid]");
570 labels.push_back("gamma[sRGB]");
572 case GAMMA_REC_601: // and GAMMA_REC_709
573 labels.push_back("gamma[rec601/709]");
579 switch (from->output_alpha_type) {
581 labels.push_back("alpha[invalid]");
584 labels.push_back("alpha[blank]");
586 case ALPHA_POSTMULTIPLIED:
587 labels.push_back("alpha[postmult]");
596 void EffectChain::output_dot_edge(FILE *fp,
597 const string &from_node_id,
598 const string &to_node_id,
599 const vector<string> &labels)
601 if (labels.empty()) {
602 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
604 string label = labels[0];
605 for (unsigned k = 1; k < labels.size(); ++k) {
606 label += ", " + labels[k];
608 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
612 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
614 unsigned scaled_width, scaled_height;
616 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
617 // Same aspect, or W/H > aspect (image is wider than the frame).
618 // In either case, keep width, and adjust height.
619 scaled_width = width;
620 scaled_height = lrintf(width * aspect_denom / aspect_nom);
622 // W/H < aspect (image is taller than the frame), so keep height,
624 scaled_width = lrintf(height * aspect_nom / aspect_denom);
625 scaled_height = height;
628 // We should be consistently larger or smaller then the existing choice,
629 // since we have the same aspect.
630 assert(!(scaled_width < *output_width && scaled_height > *output_height));
631 assert(!(scaled_height < *output_height && scaled_width > *output_width));
633 if (scaled_width >= *output_width && scaled_height >= *output_height) {
634 *output_width = scaled_width;
635 *output_height = scaled_height;
639 // Propagate input texture sizes throughout, and inform effects downstream.
640 // (Like a lot of other code, we depend on effects being in topological order.)
641 void EffectChain::inform_input_sizes(Phase *phase)
643 // All effects that have a defined size (inputs and RTT inputs)
644 // get that. Reset all others.
645 for (unsigned i = 0; i < phase->effects.size(); ++i) {
646 Node *node = phase->effects[i];
647 if (node->effect->num_inputs() == 0) {
648 Input *input = static_cast<Input *>(node->effect);
649 node->output_width = input->get_width();
650 node->output_height = input->get_height();
651 assert(node->output_width != 0);
652 assert(node->output_height != 0);
654 node->output_width = node->output_height = 0;
657 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
658 Phase *input = phase->inputs[i];
659 input->output_node->output_width = input->virtual_output_width;
660 input->output_node->output_height = input->virtual_output_height;
661 assert(input->output_node->output_width != 0);
662 assert(input->output_node->output_height != 0);
665 // Now propagate from the inputs towards the end, and inform as we go.
666 // The rules are simple:
668 // 1. Don't touch effects that already have given sizes (ie., inputs
669 // or effects that change the output size).
670 // 2. If all of your inputs have the same size, that will be your output size.
671 // 3. Otherwise, your output size is 0x0.
672 for (unsigned i = 0; i < phase->effects.size(); ++i) {
673 Node *node = phase->effects[i];
674 if (node->effect->num_inputs() == 0) {
677 unsigned this_output_width = 0;
678 unsigned this_output_height = 0;
679 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
680 Node *input = node->incoming_links[j];
681 node->effect->inform_input_size(j, input->output_width, input->output_height);
683 this_output_width = input->output_width;
684 this_output_height = input->output_height;
685 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
687 this_output_width = 0;
688 this_output_height = 0;
691 if (node->effect->changes_output_size()) {
692 // We cannot call get_output_size() before we've done inform_input_size()
694 unsigned real_width, real_height;
695 node->effect->get_output_size(&real_width, &real_height,
696 &node->output_width, &node->output_height);
697 assert(node->effect->sets_virtual_output_size() ||
698 (real_width == node->output_width &&
699 real_height == node->output_height));
701 node->output_width = this_output_width;
702 node->output_height = this_output_height;
707 // Note: You should call inform_input_sizes() before this, as the last effect's
708 // desired output size might change based on the inputs.
709 void EffectChain::find_output_size(Phase *phase)
711 Node *output_node = phase->effects.back();
713 // If the last effect explicitly sets an output size, use that.
714 if (output_node->effect->changes_output_size()) {
715 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
716 &phase->virtual_output_width, &phase->virtual_output_height);
717 assert(output_node->effect->sets_virtual_output_size() ||
718 (phase->output_width == phase->virtual_output_width &&
719 phase->output_height == phase->virtual_output_height));
723 // If all effects have the same size, use that.
724 unsigned output_width = 0, output_height = 0;
725 bool all_inputs_same_size = true;
727 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
728 Phase *input = phase->inputs[i];
729 assert(input->output_width != 0);
730 assert(input->output_height != 0);
731 if (output_width == 0 && output_height == 0) {
732 output_width = input->virtual_output_width;
733 output_height = input->virtual_output_height;
734 } else if (output_width != input->virtual_output_width ||
735 output_height != input->virtual_output_height) {
736 all_inputs_same_size = false;
739 for (unsigned i = 0; i < phase->effects.size(); ++i) {
740 Effect *effect = phase->effects[i]->effect;
741 if (effect->num_inputs() != 0) {
745 Input *input = static_cast<Input *>(effect);
746 if (output_width == 0 && output_height == 0) {
747 output_width = input->get_width();
748 output_height = input->get_height();
749 } else if (output_width != input->get_width() ||
750 output_height != input->get_height()) {
751 all_inputs_same_size = false;
755 if (all_inputs_same_size) {
756 assert(output_width != 0);
757 assert(output_height != 0);
758 phase->virtual_output_width = phase->output_width = output_width;
759 phase->virtual_output_height = phase->output_height = output_height;
763 // If not, fit all the inputs into the current aspect, and select the largest one.
766 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
767 Phase *input = phase->inputs[i];
768 assert(input->output_width != 0);
769 assert(input->output_height != 0);
770 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
772 for (unsigned i = 0; i < phase->effects.size(); ++i) {
773 Effect *effect = phase->effects[i]->effect;
774 if (effect->num_inputs() != 0) {
778 Input *input = static_cast<Input *>(effect);
779 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
781 assert(output_width != 0);
782 assert(output_height != 0);
783 phase->virtual_output_width = phase->output_width = output_width;
784 phase->virtual_output_height = phase->output_height = output_height;
787 void EffectChain::sort_all_nodes_topologically()
789 nodes = topological_sort(nodes);
792 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
794 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
795 vector<Node *> sorted_list;
796 for (unsigned i = 0; i < nodes.size(); ++i) {
797 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
799 reverse(sorted_list.begin(), sorted_list.end());
803 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
805 if (nodes_left_to_visit->count(node) == 0) {
808 nodes_left_to_visit->erase(node);
809 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
810 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
812 sorted_list->push_back(node);
815 void EffectChain::find_color_spaces_for_inputs()
817 for (unsigned i = 0; i < nodes.size(); ++i) {
818 Node *node = nodes[i];
819 if (node->disabled) {
822 if (node->incoming_links.size() == 0) {
823 Input *input = static_cast<Input *>(node->effect);
824 node->output_color_space = input->get_color_space();
825 node->output_gamma_curve = input->get_gamma_curve();
827 Effect::AlphaHandling alpha_handling = input->alpha_handling();
828 switch (alpha_handling) {
829 case Effect::OUTPUT_BLANK_ALPHA:
830 node->output_alpha_type = ALPHA_BLANK;
832 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
833 node->output_alpha_type = ALPHA_PREMULTIPLIED;
835 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
836 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
838 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
839 case Effect::DONT_CARE_ALPHA_TYPE:
844 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
845 assert(node->output_gamma_curve == GAMMA_LINEAR);
851 // Propagate gamma and color space information as far as we can in the graph.
852 // The rules are simple: Anything where all the inputs agree, get that as
853 // output as well. Anything else keeps having *_INVALID.
854 void EffectChain::propagate_gamma_and_color_space()
856 // We depend on going through the nodes in order.
857 sort_all_nodes_topologically();
859 for (unsigned i = 0; i < nodes.size(); ++i) {
860 Node *node = nodes[i];
861 if (node->disabled) {
864 assert(node->incoming_links.size() == node->effect->num_inputs());
865 if (node->incoming_links.size() == 0) {
866 assert(node->output_color_space != COLORSPACE_INVALID);
867 assert(node->output_gamma_curve != GAMMA_INVALID);
871 Colorspace color_space = node->incoming_links[0]->output_color_space;
872 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
873 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
874 if (node->incoming_links[j]->output_color_space != color_space) {
875 color_space = COLORSPACE_INVALID;
877 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
878 gamma_curve = GAMMA_INVALID;
882 // The conversion effects already have their outputs set correctly,
883 // so leave them alone.
884 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
885 node->output_color_space = color_space;
887 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
888 node->effect->effect_type_id() != "GammaExpansionEffect") {
889 node->output_gamma_curve = gamma_curve;
894 // Propagate alpha information as far as we can in the graph.
895 // Similar to propagate_gamma_and_color_space().
896 void EffectChain::propagate_alpha()
898 // We depend on going through the nodes in order.
899 sort_all_nodes_topologically();
901 for (unsigned i = 0; i < nodes.size(); ++i) {
902 Node *node = nodes[i];
903 if (node->disabled) {
906 assert(node->incoming_links.size() == node->effect->num_inputs());
907 if (node->incoming_links.size() == 0) {
908 assert(node->output_alpha_type != ALPHA_INVALID);
912 // The alpha multiplication/division effects are special cases.
913 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
914 assert(node->incoming_links.size() == 1);
915 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
916 node->output_alpha_type = ALPHA_PREMULTIPLIED;
919 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
920 assert(node->incoming_links.size() == 1);
921 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
922 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
926 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
927 // because they are the only one that _need_ postmultiplied alpha.
928 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
929 node->effect->effect_type_id() == "GammaExpansionEffect") {
930 assert(node->incoming_links.size() == 1);
931 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
932 node->output_alpha_type = ALPHA_BLANK;
933 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
934 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
936 node->output_alpha_type = ALPHA_INVALID;
941 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
942 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
943 // taken care of above. Rationale: Even if you could imagine
944 // e.g. an effect that took in an image and set alpha=1.0
945 // unconditionally, it wouldn't make any sense to have it as
946 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
947 // got its input pre- or postmultiplied, so it wouldn't know
948 // whether to divide away the old alpha or not.
949 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
950 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
951 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
952 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
954 // If the node has multiple inputs, check that they are all valid and
956 bool any_invalid = false;
957 bool any_premultiplied = false;
958 bool any_postmultiplied = false;
960 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
961 switch (node->incoming_links[j]->output_alpha_type) {
966 // Blank is good as both pre- and postmultiplied alpha,
967 // so just ignore it.
969 case ALPHA_PREMULTIPLIED:
970 any_premultiplied = true;
972 case ALPHA_POSTMULTIPLIED:
973 any_postmultiplied = true;
981 node->output_alpha_type = ALPHA_INVALID;
985 // Inputs must be of the same type.
986 if (any_premultiplied && any_postmultiplied) {
987 node->output_alpha_type = ALPHA_INVALID;
991 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
992 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
993 // If the effect has asked for premultiplied alpha, check that it has got it.
994 if (any_postmultiplied) {
995 node->output_alpha_type = ALPHA_INVALID;
996 } else if (!any_premultiplied &&
997 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
998 // Blank input alpha, and the effect preserves blank alpha.
999 node->output_alpha_type = ALPHA_BLANK;
1001 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1004 // OK, all inputs are the same, and this effect is not going
1006 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1007 if (any_premultiplied) {
1008 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1009 } else if (any_postmultiplied) {
1010 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1012 node->output_alpha_type = ALPHA_BLANK;
1018 bool EffectChain::node_needs_colorspace_fix(Node *node)
1020 if (node->disabled) {
1023 if (node->effect->num_inputs() == 0) {
1027 // propagate_gamma_and_color_space() has already set our output
1028 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1029 if (node->output_color_space == COLORSPACE_INVALID) {
1032 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1035 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1036 // the graph. Our strategy is not always optimal, but quite simple:
1037 // Find an effect that's as early as possible where the inputs are of
1038 // unacceptable colorspaces (that is, either different, or, if the effect only
1039 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1040 // propagate the information anew, and repeat until there are no more such
1042 void EffectChain::fix_internal_color_spaces()
1044 unsigned colorspace_propagation_pass = 0;
1048 for (unsigned i = 0; i < nodes.size(); ++i) {
1049 Node *node = nodes[i];
1050 if (!node_needs_colorspace_fix(node)) {
1054 // Go through each input that is not sRGB, and insert
1055 // a colorspace conversion after it.
1056 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1057 Node *input = node->incoming_links[j];
1058 assert(input->output_color_space != COLORSPACE_INVALID);
1059 if (input->output_color_space == COLORSPACE_sRGB) {
1062 Node *conversion = add_node(new ColorspaceConversionEffect());
1063 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1064 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1065 conversion->output_color_space = COLORSPACE_sRGB;
1066 replace_sender(input, conversion);
1067 connect_nodes(input, conversion);
1070 // Re-sort topologically, and propagate the new information.
1071 propagate_gamma_and_color_space();
1078 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1079 output_dot(filename);
1080 assert(colorspace_propagation_pass < 100);
1081 } while (found_any);
1083 for (unsigned i = 0; i < nodes.size(); ++i) {
1084 Node *node = nodes[i];
1085 if (node->disabled) {
1088 assert(node->output_color_space != COLORSPACE_INVALID);
1092 bool EffectChain::node_needs_alpha_fix(Node *node)
1094 if (node->disabled) {
1098 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1099 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1100 return (node->output_alpha_type == ALPHA_INVALID);
1103 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1104 // the graph. Similar to fix_internal_color_spaces().
1105 void EffectChain::fix_internal_alpha(unsigned step)
1107 unsigned alpha_propagation_pass = 0;
1111 for (unsigned i = 0; i < nodes.size(); ++i) {
1112 Node *node = nodes[i];
1113 if (!node_needs_alpha_fix(node)) {
1117 // If we need to fix up GammaExpansionEffect, then clearly something
1118 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1120 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1122 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1124 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1125 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1126 assert(node->incoming_links.size() == 1);
1127 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1128 desired_type = ALPHA_POSTMULTIPLIED;
1131 // Go through each input that is not premultiplied alpha, and insert
1132 // a conversion before it.
1133 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1134 Node *input = node->incoming_links[j];
1135 assert(input->output_alpha_type != ALPHA_INVALID);
1136 if (input->output_alpha_type == desired_type ||
1137 input->output_alpha_type == ALPHA_BLANK) {
1141 if (desired_type == ALPHA_PREMULTIPLIED) {
1142 conversion = add_node(new AlphaMultiplicationEffect());
1144 conversion = add_node(new AlphaDivisionEffect());
1146 conversion->output_alpha_type = desired_type;
1147 replace_sender(input, conversion);
1148 connect_nodes(input, conversion);
1151 // Re-sort topologically, and propagate the new information.
1152 propagate_gamma_and_color_space();
1160 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1161 output_dot(filename);
1162 assert(alpha_propagation_pass < 100);
1163 } while (found_any);
1165 for (unsigned i = 0; i < nodes.size(); ++i) {
1166 Node *node = nodes[i];
1167 if (node->disabled) {
1170 assert(node->output_alpha_type != ALPHA_INVALID);
1174 // Make so that the output is in the desired color space.
1175 void EffectChain::fix_output_color_space()
1177 Node *output = find_output_node();
1178 if (output->output_color_space != output_format.color_space) {
1179 Node *conversion = add_node(new ColorspaceConversionEffect());
1180 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1181 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1182 conversion->output_color_space = output_format.color_space;
1183 connect_nodes(output, conversion);
1185 propagate_gamma_and_color_space();
1189 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1190 void EffectChain::fix_output_alpha()
1192 Node *output = find_output_node();
1193 assert(output->output_alpha_type != ALPHA_INVALID);
1194 if (output->output_alpha_type == ALPHA_BLANK) {
1195 // No alpha output, so we don't care.
1198 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1199 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1200 Node *conversion = add_node(new AlphaDivisionEffect());
1201 connect_nodes(output, conversion);
1203 propagate_gamma_and_color_space();
1205 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1206 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1207 Node *conversion = add_node(new AlphaMultiplicationEffect());
1208 connect_nodes(output, conversion);
1210 propagate_gamma_and_color_space();
1214 bool EffectChain::node_needs_gamma_fix(Node *node)
1216 if (node->disabled) {
1220 // Small hack since the output is not an explicit node:
1221 // If we are the last node and our output is in the wrong
1222 // space compared to EffectChain's output, we need to fix it.
1223 // This will only take us to linear, but fix_output_gamma()
1224 // will come and take us to the desired output gamma
1227 // This needs to be before everything else, since it could
1228 // even apply to inputs (if they are the only effect).
1229 if (node->outgoing_links.empty() &&
1230 node->output_gamma_curve != output_format.gamma_curve &&
1231 node->output_gamma_curve != GAMMA_LINEAR) {
1235 if (node->effect->num_inputs() == 0) {
1239 // propagate_gamma_and_color_space() has already set our output
1240 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1241 // except for GammaCompressionEffect.
1242 if (node->output_gamma_curve == GAMMA_INVALID) {
1245 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1246 assert(node->incoming_links.size() == 1);
1247 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1250 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1253 // Very similar to fix_internal_color_spaces(), but for gamma.
1254 // There is one difference, though; before we start adding conversion nodes,
1255 // we see if we can get anything out of asking the sources to deliver
1256 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1257 // does that part, while fix_internal_gamma_by_inserting_nodes()
1258 // inserts nodes as needed afterwards.
1259 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1261 unsigned gamma_propagation_pass = 0;
1265 for (unsigned i = 0; i < nodes.size(); ++i) {
1266 Node *node = nodes[i];
1267 if (!node_needs_gamma_fix(node)) {
1271 // See if all inputs can give us linear gamma. If not, leave it.
1272 vector<Node *> nonlinear_inputs;
1273 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1274 assert(!nonlinear_inputs.empty());
1277 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1278 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1279 all_ok &= input->can_output_linear_gamma();
1286 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1287 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1288 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1291 // Re-sort topologically, and propagate the new information.
1292 propagate_gamma_and_color_space();
1299 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1300 output_dot(filename);
1301 assert(gamma_propagation_pass < 100);
1302 } while (found_any);
1305 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1307 unsigned gamma_propagation_pass = 0;
1311 for (unsigned i = 0; i < nodes.size(); ++i) {
1312 Node *node = nodes[i];
1313 if (!node_needs_gamma_fix(node)) {
1317 // Special case: We could be an input and still be asked to
1318 // fix our gamma; if so, we should be the only node
1319 // (as node_needs_gamma_fix() would only return true in
1320 // for an input in that case). That means we should insert
1321 // a conversion node _after_ ourselves.
1322 if (node->incoming_links.empty()) {
1323 assert(node->outgoing_links.empty());
1324 Node *conversion = add_node(new GammaExpansionEffect());
1325 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1326 conversion->output_gamma_curve = GAMMA_LINEAR;
1327 connect_nodes(node, conversion);
1330 // If not, go through each input that is not linear gamma,
1331 // and insert a gamma conversion after it.
1332 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1333 Node *input = node->incoming_links[j];
1334 assert(input->output_gamma_curve != GAMMA_INVALID);
1335 if (input->output_gamma_curve == GAMMA_LINEAR) {
1338 Node *conversion = add_node(new GammaExpansionEffect());
1339 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1340 conversion->output_gamma_curve = GAMMA_LINEAR;
1341 replace_sender(input, conversion);
1342 connect_nodes(input, conversion);
1345 // Re-sort topologically, and propagate the new information.
1347 propagate_gamma_and_color_space();
1354 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1355 output_dot(filename);
1356 assert(gamma_propagation_pass < 100);
1357 } while (found_any);
1359 for (unsigned i = 0; i < nodes.size(); ++i) {
1360 Node *node = nodes[i];
1361 if (node->disabled) {
1364 assert(node->output_gamma_curve != GAMMA_INVALID);
1368 // Make so that the output is in the desired gamma.
1369 // Note that this assumes linear input gamma, so it might create the need
1370 // for another pass of fix_internal_gamma().
1371 void EffectChain::fix_output_gamma()
1373 Node *output = find_output_node();
1374 if (output->output_gamma_curve != output_format.gamma_curve) {
1375 Node *conversion = add_node(new GammaCompressionEffect());
1376 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1377 conversion->output_gamma_curve = output_format.gamma_curve;
1378 connect_nodes(output, conversion);
1382 // If the user has requested Y'CbCr output, we need to do this conversion
1383 // _after_ GammaCompressionEffect etc., but before dither (see below).
1384 // This is because Y'CbCr, with the exception of a special optional mode
1385 // in Rec. 2020 (which we currently don't support), is defined to work on
1386 // gamma-encoded data.
1387 void EffectChain::add_ycbcr_conversion_if_needed()
1389 assert(output_color_type == OUTPUT_COLOR_RGB || output_color_type == OUTPUT_COLOR_YCBCR);
1390 if (output_color_type != OUTPUT_COLOR_YCBCR) {
1393 Node *output = find_output_node();
1394 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1395 connect_nodes(output, ycbcr);
1398 // If the user has requested dither, add a DitherEffect right at the end
1399 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1400 // since dither is about the only effect that can _not_ be done in linear space.
1401 void EffectChain::add_dither_if_needed()
1403 if (num_dither_bits == 0) {
1406 Node *output = find_output_node();
1407 Node *dither = add_node(new DitherEffect());
1408 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1409 connect_nodes(output, dither);
1411 dither_effect = dither->effect;
1414 // Find the output node. This is, simply, one that has no outgoing links.
1415 // If there are multiple ones, the graph is malformed (we do not support
1416 // multiple outputs right now).
1417 Node *EffectChain::find_output_node()
1419 vector<Node *> output_nodes;
1420 for (unsigned i = 0; i < nodes.size(); ++i) {
1421 Node *node = nodes[i];
1422 if (node->disabled) {
1425 if (node->outgoing_links.empty()) {
1426 output_nodes.push_back(node);
1429 assert(output_nodes.size() == 1);
1430 return output_nodes[0];
1433 void EffectChain::finalize()
1435 // Output the graph as it is before we do any conversions on it.
1436 output_dot("step0-start.dot");
1438 // Give each effect in turn a chance to rewrite its own part of the graph.
1439 // Note that if more effects are added as part of this, they will be
1440 // picked up as part of the same for loop, since they are added at the end.
1441 for (unsigned i = 0; i < nodes.size(); ++i) {
1442 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1444 output_dot("step1-rewritten.dot");
1446 find_color_spaces_for_inputs();
1447 output_dot("step2-input-colorspace.dot");
1450 output_dot("step3-propagated-alpha.dot");
1452 propagate_gamma_and_color_space();
1453 output_dot("step4-propagated-all.dot");
1455 fix_internal_color_spaces();
1456 fix_internal_alpha(6);
1457 fix_output_color_space();
1458 output_dot("step7-output-colorspacefix.dot");
1460 output_dot("step8-output-alphafix.dot");
1462 // Note that we need to fix gamma after colorspace conversion,
1463 // because colorspace conversions might create needs for gamma conversions.
1464 // Also, we need to run an extra pass of fix_internal_gamma() after
1465 // fixing the output gamma, as we only have conversions to/from linear,
1466 // and fix_internal_alpha() since GammaCompressionEffect needs
1467 // postmultiplied input.
1468 fix_internal_gamma_by_asking_inputs(9);
1469 fix_internal_gamma_by_inserting_nodes(10);
1471 output_dot("step11-output-gammafix.dot");
1473 output_dot("step12-output-alpha-propagated.dot");
1474 fix_internal_alpha(13);
1475 output_dot("step14-output-alpha-fixed.dot");
1476 fix_internal_gamma_by_asking_inputs(15);
1477 fix_internal_gamma_by_inserting_nodes(16);
1479 output_dot("step17-before-ycbcr.dot");
1480 add_ycbcr_conversion_if_needed();
1482 output_dot("step18-before-dither.dot");
1483 add_dither_if_needed();
1485 output_dot("step19-final.dot");
1487 // Construct all needed GLSL programs, starting at the output.
1488 // We need to keep track of which effects have already been computed,
1489 // as an effect with multiple users could otherwise be calculated
1491 map<Node *, Phase *> completed_effects;
1492 construct_phase(find_output_node(), &completed_effects);
1494 output_dot("step20-split-to-phases.dot");
1496 assert(phases[0]->inputs.empty());
1501 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1505 // Save original viewport.
1506 GLuint x = 0, y = 0;
1508 if (width == 0 && height == 0) {
1510 glGetIntegerv(GL_VIEWPORT, viewport);
1513 width = viewport[2];
1514 height = viewport[3];
1518 glDisable(GL_BLEND);
1520 glDisable(GL_DEPTH_TEST);
1522 glDepthMask(GL_FALSE);
1525 set<Phase *> generated_mipmaps;
1527 // We choose the simplest option of having one texture per output,
1528 // since otherwise this turns into an (albeit simple) register allocation problem.
1529 map<Phase *, GLuint> output_textures;
1531 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1532 Phase *phase = phases[phase_num];
1534 if (do_phase_timing) {
1535 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1537 if (phase_num == phases.size() - 1) {
1538 // Last phase goes to the output the user specified.
1539 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1541 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1542 assert(status == GL_FRAMEBUFFER_COMPLETE);
1543 glViewport(x, y, width, height);
1544 if (dither_effect != NULL) {
1545 CHECK(dither_effect->set_int("output_width", width));
1546 CHECK(dither_effect->set_int("output_height", height));
1549 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1550 if (do_phase_timing) {
1551 glEndQuery(GL_TIME_ELAPSED);
1555 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1556 texture_it != output_textures.end();
1558 resource_pool->release_2d_texture(texture_it->second);
1561 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1566 if (do_phase_timing) {
1567 // Get back the timer queries.
1568 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1569 Phase *phase = phases[phase_num];
1570 GLint available = 0;
1571 while (!available) {
1572 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1574 GLuint64 time_elapsed;
1575 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1576 phase->time_elapsed_ns += time_elapsed;
1577 ++phase->num_measured_iterations;
1582 void EffectChain::enable_phase_timing(bool enable)
1585 assert(movit_timer_queries_supported);
1587 this->do_phase_timing = enable;
1590 void EffectChain::reset_phase_timing()
1592 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1593 Phase *phase = phases[phase_num];
1594 phase->time_elapsed_ns = 0;
1595 phase->num_measured_iterations = 0;
1599 void EffectChain::print_phase_timing()
1601 double total_time_ms = 0.0;
1602 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1603 Phase *phase = phases[phase_num];
1604 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1605 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1606 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1607 if (effect_num != 0) {
1610 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1613 total_time_ms += avg_time_ms;
1615 printf("Total: %5.1f ms\n", total_time_ms);
1618 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1622 // Find a texture for this phase.
1623 inform_input_sizes(phase);
1625 find_output_size(phase);
1627 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1628 output_textures->insert(make_pair(phase, tex_num));
1631 const GLuint glsl_program_num = phase->glsl_program_num;
1633 glUseProgram(glsl_program_num);
1636 // Set up RTT inputs for this phase.
1637 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1638 glActiveTexture(GL_TEXTURE0 + sampler);
1639 Phase *input = phase->inputs[sampler];
1640 input->output_node->bound_sampler_num = sampler;
1641 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1643 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1644 glGenerateMipmap(GL_TEXTURE_2D);
1646 generated_mipmaps->insert(input);
1648 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1651 // And now the output. (Already set up for us if it is the last phase.)
1653 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1654 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1655 glViewport(0, 0, phase->output_width, phase->output_height);
1658 // Give the required parameters to all the effects.
1659 unsigned sampler_num = phase->inputs.size();
1660 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1661 Node *node = phase->effects[i];
1662 unsigned old_sampler_num = sampler_num;
1663 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1666 if (node->effect->is_single_texture()) {
1667 assert(sampler_num - old_sampler_num == 1);
1668 node->bound_sampler_num = old_sampler_num;
1670 node->bound_sampler_num = -1;
1675 float vertices[] = {
1682 glGenVertexArrays(1, &vao);
1684 glBindVertexArray(vao);
1687 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1688 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1690 glDrawArrays(GL_TRIANGLES, 0, 3);
1693 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1694 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1699 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1700 Node *node = phase->effects[i];
1701 node->effect->clear_gl_state();
1705 resource_pool->release_fbo(fbo);
1708 glDeleteVertexArrays(1, &vao);
1712 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1714 glActiveTexture(GL_TEXTURE0 + sampler_num);
1717 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1720 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1723 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1725 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1728 string texture_name = string("tex_") + effect_id;
1729 glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1733 } // namespace movit