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"
33 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
34 : aspect_nom(aspect_nom),
35 aspect_denom(aspect_denom),
39 resource_pool(resource_pool),
40 do_phase_timing(false) {
41 if (resource_pool == NULL) {
42 this->resource_pool = new ResourcePool();
43 owns_resource_pool = true;
45 owns_resource_pool = false;
49 EffectChain::~EffectChain()
51 for (unsigned i = 0; i < nodes.size(); ++i) {
52 delete nodes[i]->effect;
55 for (unsigned i = 0; i < phases.size(); ++i) {
56 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
59 if (owns_resource_pool) {
64 Input *EffectChain::add_input(Input *input)
67 inputs.push_back(input);
72 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
75 output_format = format;
76 output_alpha_format = alpha_format;
79 Node *EffectChain::add_node(Effect *effect)
81 for (unsigned i = 0; i < nodes.size(); ++i) {
82 assert(nodes[i]->effect != effect);
85 Node *node = new Node;
86 node->effect = effect;
87 node->disabled = false;
88 node->output_color_space = COLORSPACE_INVALID;
89 node->output_gamma_curve = GAMMA_INVALID;
90 node->output_alpha_type = ALPHA_INVALID;
91 node->needs_mipmaps = false;
92 node->one_to_one_sampling = false;
94 nodes.push_back(node);
95 node_map[effect] = node;
96 effect->inform_added(this);
100 void EffectChain::connect_nodes(Node *sender, Node *receiver)
102 sender->outgoing_links.push_back(receiver);
103 receiver->incoming_links.push_back(sender);
106 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
108 new_receiver->incoming_links = old_receiver->incoming_links;
109 old_receiver->incoming_links.clear();
111 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
112 Node *sender = new_receiver->incoming_links[i];
113 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
114 if (sender->outgoing_links[j] == old_receiver) {
115 sender->outgoing_links[j] = new_receiver;
121 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
123 new_sender->outgoing_links = old_sender->outgoing_links;
124 old_sender->outgoing_links.clear();
126 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
127 Node *receiver = new_sender->outgoing_links[i];
128 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
129 if (receiver->incoming_links[j] == old_sender) {
130 receiver->incoming_links[j] = new_sender;
136 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
138 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
139 if (sender->outgoing_links[i] == receiver) {
140 sender->outgoing_links[i] = middle;
141 middle->incoming_links.push_back(sender);
144 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
145 if (receiver->incoming_links[i] == sender) {
146 receiver->incoming_links[i] = middle;
147 middle->outgoing_links.push_back(receiver);
151 assert(middle->incoming_links.size() == middle->effect->num_inputs());
154 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
156 assert(node->effect->needs_texture_bounce());
157 assert(input_num < node->incoming_links.size());
158 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
159 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
160 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
163 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
165 if (node->output_gamma_curve == GAMMA_LINEAR &&
166 node->effect->effect_type_id() != "GammaCompressionEffect") {
169 if (node->effect->num_inputs() == 0) {
170 nonlinear_inputs->push_back(node);
172 assert(node->effect->num_inputs() == node->incoming_links.size());
173 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
174 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
179 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
182 assert(inputs.size() == effect->num_inputs());
183 Node *node = add_node(effect);
184 for (unsigned i = 0; i < inputs.size(); ++i) {
185 assert(node_map.count(inputs[i]) != 0);
186 connect_nodes(node_map[inputs[i]], node);
191 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
192 string replace_prefix(const string &text, const string &prefix)
197 while (start < text.size()) {
198 size_t pos = text.find("PREFIX(", start);
199 if (pos == string::npos) {
200 output.append(text.substr(start, string::npos));
204 output.append(text.substr(start, pos - start));
205 output.append(prefix);
208 pos += strlen("PREFIX(");
210 // Output stuff until we find the matching ), which we then eat.
212 size_t end_arg_pos = pos;
213 while (end_arg_pos < text.size()) {
214 if (text[end_arg_pos] == '(') {
216 } else if (text[end_arg_pos] == ')') {
224 output.append(text.substr(pos, end_arg_pos - pos));
232 void EffectChain::compile_glsl_program(Phase *phase)
234 string frag_shader = read_version_dependent_file("header", "frag");
236 // Create functions for all the texture inputs that we need.
237 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
238 Node *input = phase->inputs[i]->output_node;
240 sprintf(effect_id, "in%u", i);
241 phase->effect_ids.insert(make_pair(input, effect_id));
243 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
244 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
245 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
246 frag_shader += "}\n";
250 for (unsigned i = 0; i < phase->effects.size(); ++i) {
251 Node *node = phase->effects[i];
253 sprintf(effect_id, "eff%u", i);
254 phase->effect_ids.insert(make_pair(node, effect_id));
256 if (node->incoming_links.size() == 1) {
257 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
259 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
261 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
267 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
268 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
269 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
270 frag_shader += "#undef PREFIX\n";
271 frag_shader += "#undef FUNCNAME\n";
272 if (node->incoming_links.size() == 1) {
273 frag_shader += "#undef INPUT\n";
275 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
277 sprintf(buf, "#undef INPUT%d\n", j + 1);
283 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
284 frag_shader.append(read_version_dependent_file("footer", "frag"));
286 string vert_shader = read_version_dependent_file("vs", "vert");
287 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
290 // Construct GLSL programs, starting at the given effect and following
291 // the chain from there. We end a program every time we come to an effect
292 // marked as "needs texture bounce", one that is used by multiple other
293 // effects, every time we need to bounce due to output size change
294 // (not all size changes require ending), and of course at the end.
296 // We follow a quite simple depth-first search from the output, although
297 // without recursing explicitly within each phase.
298 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
300 if (completed_effects->count(output)) {
301 return (*completed_effects)[output];
304 Phase *phase = new Phase;
305 phase->output_node = output;
307 // If the output effect has one-to-one sampling, we try to trace this
308 // status down through the dependency chain. This is important in case
309 // we hit an effect that changes output size (and not sets a virtual
310 // output size); if we have one-to-one sampling, we don't have to break
312 output->one_to_one_sampling = output->effect->one_to_one_sampling();
314 // Effects that we have yet to calculate, but that we know should
315 // be in the current phase.
316 stack<Node *> effects_todo_this_phase;
317 effects_todo_this_phase.push(output);
319 while (!effects_todo_this_phase.empty()) {
320 Node *node = effects_todo_this_phase.top();
321 effects_todo_this_phase.pop();
323 if (node->effect->needs_mipmaps()) {
324 node->needs_mipmaps = true;
327 // This should currently only happen for effects that are inputs
328 // (either true inputs or phase outputs). We special-case inputs,
329 // and then deduplicate phase outputs below.
330 if (node->effect->num_inputs() == 0) {
331 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
335 assert(completed_effects->count(node) == 0);
338 phase->effects.push_back(node);
340 // Find all the dependencies of this effect, and add them to the stack.
341 vector<Node *> deps = node->incoming_links;
342 assert(node->effect->num_inputs() == deps.size());
343 for (unsigned i = 0; i < deps.size(); ++i) {
344 bool start_new_phase = false;
346 if (node->effect->needs_texture_bounce() &&
347 !deps[i]->effect->is_single_texture()) {
348 start_new_phase = true;
351 // Propagate information about needing mipmaps down the chain,
352 // breaking the phase if we notice an incompatibility.
354 // Note that we cannot do this propagation as a normal pass,
355 // because it needs information about where the phases end
356 // (we should not propagate the flag across phases).
357 if (node->needs_mipmaps) {
358 if (deps[i]->effect->num_inputs() == 0) {
359 Input *input = static_cast<Input *>(deps[i]->effect);
360 start_new_phase |= !input->can_supply_mipmaps();
362 deps[i]->needs_mipmaps = true;
366 if (deps[i]->outgoing_links.size() > 1) {
367 if (!deps[i]->effect->is_single_texture()) {
368 // More than one effect uses this as the input,
369 // and it is not a texture itself.
370 // The easiest thing to do (and probably also the safest
371 // performance-wise in most cases) is to bounce it to a texture
372 // and then let the next passes read from that.
373 start_new_phase = true;
375 assert(deps[i]->effect->num_inputs() == 0);
377 // For textures, we try to be slightly more clever;
378 // if none of our outputs need a bounce, we don't bounce
379 // but instead simply use the effect many times.
381 // Strictly speaking, we could bounce it for some outputs
382 // and use it directly for others, but the processing becomes
383 // somewhat simpler if the effect is only used in one such way.
384 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
385 Node *rdep = deps[i]->outgoing_links[j];
386 start_new_phase |= rdep->effect->needs_texture_bounce();
391 if (deps[i]->effect->sets_virtual_output_size()) {
392 assert(deps[i]->effect->changes_output_size());
393 // If the next effect sets a virtual size to rely on OpenGL's
394 // bilinear sampling, we'll really need to break the phase here.
395 start_new_phase = true;
396 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
397 // If the next effect changes size and we don't have one-to-one sampling,
398 // we also need to break here.
399 start_new_phase = true;
402 if (start_new_phase) {
403 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
405 effects_todo_this_phase.push(deps[i]);
407 // Propagate the one-to-one status down through the dependency.
408 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
409 deps[i]->effect->one_to_one_sampling();
414 // No more effects to do this phase. Take all the ones we have,
415 // and create a GLSL program for it.
416 assert(!phase->effects.empty());
418 // Deduplicate the inputs.
419 sort(phase->inputs.begin(), phase->inputs.end());
420 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
422 // We added the effects from the output and back, but we need to output
423 // them in topological sort order in the shader.
424 phase->effects = topological_sort(phase->effects);
426 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
427 phase->input_needs_mipmaps = false;
428 for (unsigned i = 0; i < phase->effects.size(); ++i) {
429 Node *node = phase->effects[i];
430 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
432 for (unsigned i = 0; i < phase->effects.size(); ++i) {
433 Node *node = phase->effects[i];
434 if (node->effect->num_inputs() == 0) {
435 Input *input = static_cast<Input *>(node->effect);
436 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
437 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
441 // Tell each node which phase it ended up in, so that the unit test
442 // can check that the phases were split in the right place.
443 // Note that this ignores that effects may be part of multiple phases;
444 // if the unit tests need to test such cases, we'll reconsider.
445 for (unsigned i = 0; i < phase->effects.size(); ++i) {
446 phase->effects[i]->containing_phase = phase;
449 // Actually make the shader for this phase.
450 compile_glsl_program(phase);
452 // Initialize timer objects.
453 if (movit_timer_queries_supported) {
454 glGenQueries(1, &phase->timer_query_object);
455 phase->time_elapsed_ns = 0;
456 phase->num_measured_iterations = 0;
459 assert(completed_effects->count(output) == 0);
460 completed_effects->insert(make_pair(output, phase));
461 phases.push_back(phase);
465 void EffectChain::output_dot(const char *filename)
467 if (movit_debug_level != MOVIT_DEBUG_ON) {
471 FILE *fp = fopen(filename, "w");
477 fprintf(fp, "digraph G {\n");
478 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
479 for (unsigned i = 0; i < nodes.size(); ++i) {
480 // Find out which phase this event belongs to.
481 vector<int> in_phases;
482 for (unsigned j = 0; j < phases.size(); ++j) {
483 const Phase* p = phases[j];
484 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
485 in_phases.push_back(j);
489 if (in_phases.empty()) {
490 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
491 } else if (in_phases.size() == 1) {
492 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
493 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
494 (in_phases[0] % 8) + 1);
496 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
498 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
499 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
500 (in_phases[0] % 8) + 1);
503 char from_node_id[256];
504 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
506 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
507 char to_node_id[256];
508 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
510 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
511 output_dot_edge(fp, from_node_id, to_node_id, labels);
514 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
516 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
517 output_dot_edge(fp, from_node_id, "output", labels);
525 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
527 vector<string> labels;
529 if (to != NULL && to->effect->needs_texture_bounce()) {
530 labels.push_back("needs_bounce");
532 if (from->effect->changes_output_size()) {
533 labels.push_back("resize");
536 switch (from->output_color_space) {
537 case COLORSPACE_INVALID:
538 labels.push_back("spc[invalid]");
540 case COLORSPACE_REC_601_525:
541 labels.push_back("spc[rec601-525]");
543 case COLORSPACE_REC_601_625:
544 labels.push_back("spc[rec601-625]");
550 switch (from->output_gamma_curve) {
552 labels.push_back("gamma[invalid]");
555 labels.push_back("gamma[sRGB]");
557 case GAMMA_REC_601: // and GAMMA_REC_709
558 labels.push_back("gamma[rec601/709]");
564 switch (from->output_alpha_type) {
566 labels.push_back("alpha[invalid]");
569 labels.push_back("alpha[blank]");
571 case ALPHA_POSTMULTIPLIED:
572 labels.push_back("alpha[postmult]");
581 void EffectChain::output_dot_edge(FILE *fp,
582 const string &from_node_id,
583 const string &to_node_id,
584 const vector<string> &labels)
586 if (labels.empty()) {
587 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
589 string label = labels[0];
590 for (unsigned k = 1; k < labels.size(); ++k) {
591 label += ", " + labels[k];
593 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
597 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
599 unsigned scaled_width, scaled_height;
601 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
602 // Same aspect, or W/H > aspect (image is wider than the frame).
603 // In either case, keep width, and adjust height.
604 scaled_width = width;
605 scaled_height = lrintf(width * aspect_denom / aspect_nom);
607 // W/H < aspect (image is taller than the frame), so keep height,
609 scaled_width = lrintf(height * aspect_nom / aspect_denom);
610 scaled_height = height;
613 // We should be consistently larger or smaller then the existing choice,
614 // since we have the same aspect.
615 assert(!(scaled_width < *output_width && scaled_height > *output_height));
616 assert(!(scaled_height < *output_height && scaled_width > *output_width));
618 if (scaled_width >= *output_width && scaled_height >= *output_height) {
619 *output_width = scaled_width;
620 *output_height = scaled_height;
624 // Propagate input texture sizes throughout, and inform effects downstream.
625 // (Like a lot of other code, we depend on effects being in topological order.)
626 void EffectChain::inform_input_sizes(Phase *phase)
628 // All effects that have a defined size (inputs and RTT inputs)
629 // get that. Reset all others.
630 for (unsigned i = 0; i < phase->effects.size(); ++i) {
631 Node *node = phase->effects[i];
632 if (node->effect->num_inputs() == 0) {
633 Input *input = static_cast<Input *>(node->effect);
634 node->output_width = input->get_width();
635 node->output_height = input->get_height();
636 assert(node->output_width != 0);
637 assert(node->output_height != 0);
639 node->output_width = node->output_height = 0;
642 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
643 Phase *input = phase->inputs[i];
644 input->output_node->output_width = input->virtual_output_width;
645 input->output_node->output_height = input->virtual_output_height;
646 assert(input->output_node->output_width != 0);
647 assert(input->output_node->output_height != 0);
650 // Now propagate from the inputs towards the end, and inform as we go.
651 // The rules are simple:
653 // 1. Don't touch effects that already have given sizes (ie., inputs
654 // or effects that change the output size).
655 // 2. If all of your inputs have the same size, that will be your output size.
656 // 3. Otherwise, your output size is 0x0.
657 for (unsigned i = 0; i < phase->effects.size(); ++i) {
658 Node *node = phase->effects[i];
659 if (node->effect->num_inputs() == 0) {
662 unsigned this_output_width = 0;
663 unsigned this_output_height = 0;
664 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
665 Node *input = node->incoming_links[j];
666 node->effect->inform_input_size(j, input->output_width, input->output_height);
668 this_output_width = input->output_width;
669 this_output_height = input->output_height;
670 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
672 this_output_width = 0;
673 this_output_height = 0;
676 if (node->effect->changes_output_size()) {
677 // We cannot call get_output_size() before we've done inform_input_size()
679 unsigned real_width, real_height;
680 node->effect->get_output_size(&real_width, &real_height,
681 &node->output_width, &node->output_height);
682 assert(node->effect->sets_virtual_output_size() ||
683 (real_width == node->output_width &&
684 real_height == node->output_height));
686 node->output_width = this_output_width;
687 node->output_height = this_output_height;
692 // Note: You should call inform_input_sizes() before this, as the last effect's
693 // desired output size might change based on the inputs.
694 void EffectChain::find_output_size(Phase *phase)
696 Node *output_node = phase->effects.back();
698 // If the last effect explicitly sets an output size, use that.
699 if (output_node->effect->changes_output_size()) {
700 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
701 &phase->virtual_output_width, &phase->virtual_output_height);
702 assert(output_node->effect->sets_virtual_output_size() ||
703 (phase->output_width == phase->virtual_output_width &&
704 phase->output_height == phase->virtual_output_height));
708 // If all effects have the same size, use that.
709 unsigned output_width = 0, output_height = 0;
710 bool all_inputs_same_size = true;
712 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
713 Phase *input = phase->inputs[i];
714 assert(input->output_width != 0);
715 assert(input->output_height != 0);
716 if (output_width == 0 && output_height == 0) {
717 output_width = input->virtual_output_width;
718 output_height = input->virtual_output_height;
719 } else if (output_width != input->virtual_output_width ||
720 output_height != input->virtual_output_height) {
721 all_inputs_same_size = false;
724 for (unsigned i = 0; i < phase->effects.size(); ++i) {
725 Effect *effect = phase->effects[i]->effect;
726 if (effect->num_inputs() != 0) {
730 Input *input = static_cast<Input *>(effect);
731 if (output_width == 0 && output_height == 0) {
732 output_width = input->get_width();
733 output_height = input->get_height();
734 } else if (output_width != input->get_width() ||
735 output_height != input->get_height()) {
736 all_inputs_same_size = false;
740 if (all_inputs_same_size) {
741 assert(output_width != 0);
742 assert(output_height != 0);
743 phase->virtual_output_width = phase->output_width = output_width;
744 phase->virtual_output_height = phase->output_height = output_height;
748 // If not, fit all the inputs into the current aspect, and select the largest one.
751 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
752 Phase *input = phase->inputs[i];
753 assert(input->output_width != 0);
754 assert(input->output_height != 0);
755 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
757 for (unsigned i = 0; i < phase->effects.size(); ++i) {
758 Effect *effect = phase->effects[i]->effect;
759 if (effect->num_inputs() != 0) {
763 Input *input = static_cast<Input *>(effect);
764 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
766 assert(output_width != 0);
767 assert(output_height != 0);
768 phase->virtual_output_width = phase->output_width = output_width;
769 phase->virtual_output_height = phase->output_height = output_height;
772 void EffectChain::sort_all_nodes_topologically()
774 nodes = topological_sort(nodes);
777 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
779 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
780 vector<Node *> sorted_list;
781 for (unsigned i = 0; i < nodes.size(); ++i) {
782 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
784 reverse(sorted_list.begin(), sorted_list.end());
788 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
790 if (nodes_left_to_visit->count(node) == 0) {
793 nodes_left_to_visit->erase(node);
794 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
795 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
797 sorted_list->push_back(node);
800 void EffectChain::find_color_spaces_for_inputs()
802 for (unsigned i = 0; i < nodes.size(); ++i) {
803 Node *node = nodes[i];
804 if (node->disabled) {
807 if (node->incoming_links.size() == 0) {
808 Input *input = static_cast<Input *>(node->effect);
809 node->output_color_space = input->get_color_space();
810 node->output_gamma_curve = input->get_gamma_curve();
812 Effect::AlphaHandling alpha_handling = input->alpha_handling();
813 switch (alpha_handling) {
814 case Effect::OUTPUT_BLANK_ALPHA:
815 node->output_alpha_type = ALPHA_BLANK;
817 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
818 node->output_alpha_type = ALPHA_PREMULTIPLIED;
820 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
821 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
823 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
824 case Effect::DONT_CARE_ALPHA_TYPE:
829 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
830 assert(node->output_gamma_curve == GAMMA_LINEAR);
836 // Propagate gamma and color space information as far as we can in the graph.
837 // The rules are simple: Anything where all the inputs agree, get that as
838 // output as well. Anything else keeps having *_INVALID.
839 void EffectChain::propagate_gamma_and_color_space()
841 // We depend on going through the nodes in order.
842 sort_all_nodes_topologically();
844 for (unsigned i = 0; i < nodes.size(); ++i) {
845 Node *node = nodes[i];
846 if (node->disabled) {
849 assert(node->incoming_links.size() == node->effect->num_inputs());
850 if (node->incoming_links.size() == 0) {
851 assert(node->output_color_space != COLORSPACE_INVALID);
852 assert(node->output_gamma_curve != GAMMA_INVALID);
856 Colorspace color_space = node->incoming_links[0]->output_color_space;
857 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
858 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
859 if (node->incoming_links[j]->output_color_space != color_space) {
860 color_space = COLORSPACE_INVALID;
862 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
863 gamma_curve = GAMMA_INVALID;
867 // The conversion effects already have their outputs set correctly,
868 // so leave them alone.
869 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
870 node->output_color_space = color_space;
872 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
873 node->effect->effect_type_id() != "GammaExpansionEffect") {
874 node->output_gamma_curve = gamma_curve;
879 // Propagate alpha information as far as we can in the graph.
880 // Similar to propagate_gamma_and_color_space().
881 void EffectChain::propagate_alpha()
883 // We depend on going through the nodes in order.
884 sort_all_nodes_topologically();
886 for (unsigned i = 0; i < nodes.size(); ++i) {
887 Node *node = nodes[i];
888 if (node->disabled) {
891 assert(node->incoming_links.size() == node->effect->num_inputs());
892 if (node->incoming_links.size() == 0) {
893 assert(node->output_alpha_type != ALPHA_INVALID);
897 // The alpha multiplication/division effects are special cases.
898 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
899 assert(node->incoming_links.size() == 1);
900 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
901 node->output_alpha_type = ALPHA_PREMULTIPLIED;
904 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
905 assert(node->incoming_links.size() == 1);
906 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
907 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
911 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
912 // because they are the only one that _need_ postmultiplied alpha.
913 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
914 node->effect->effect_type_id() == "GammaExpansionEffect") {
915 assert(node->incoming_links.size() == 1);
916 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
917 node->output_alpha_type = ALPHA_BLANK;
918 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
919 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
921 node->output_alpha_type = ALPHA_INVALID;
926 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
927 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
928 // taken care of above. Rationale: Even if you could imagine
929 // e.g. an effect that took in an image and set alpha=1.0
930 // unconditionally, it wouldn't make any sense to have it as
931 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
932 // got its input pre- or postmultiplied, so it wouldn't know
933 // whether to divide away the old alpha or not.
934 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
935 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
936 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
937 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
939 // If the node has multiple inputs, check that they are all valid and
941 bool any_invalid = false;
942 bool any_premultiplied = false;
943 bool any_postmultiplied = false;
945 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
946 switch (node->incoming_links[j]->output_alpha_type) {
951 // Blank is good as both pre- and postmultiplied alpha,
952 // so just ignore it.
954 case ALPHA_PREMULTIPLIED:
955 any_premultiplied = true;
957 case ALPHA_POSTMULTIPLIED:
958 any_postmultiplied = true;
966 node->output_alpha_type = ALPHA_INVALID;
970 // Inputs must be of the same type.
971 if (any_premultiplied && any_postmultiplied) {
972 node->output_alpha_type = ALPHA_INVALID;
976 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
977 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
978 // If the effect has asked for premultiplied alpha, check that it has got it.
979 if (any_postmultiplied) {
980 node->output_alpha_type = ALPHA_INVALID;
981 } else if (!any_premultiplied &&
982 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
983 // Blank input alpha, and the effect preserves blank alpha.
984 node->output_alpha_type = ALPHA_BLANK;
986 node->output_alpha_type = ALPHA_PREMULTIPLIED;
989 // OK, all inputs are the same, and this effect is not going
991 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
992 if (any_premultiplied) {
993 node->output_alpha_type = ALPHA_PREMULTIPLIED;
994 } else if (any_postmultiplied) {
995 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
997 node->output_alpha_type = ALPHA_BLANK;
1003 bool EffectChain::node_needs_colorspace_fix(Node *node)
1005 if (node->disabled) {
1008 if (node->effect->num_inputs() == 0) {
1012 // propagate_gamma_and_color_space() has already set our output
1013 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1014 if (node->output_color_space == COLORSPACE_INVALID) {
1017 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1020 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1021 // the graph. Our strategy is not always optimal, but quite simple:
1022 // Find an effect that's as early as possible where the inputs are of
1023 // unacceptable colorspaces (that is, either different, or, if the effect only
1024 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1025 // propagate the information anew, and repeat until there are no more such
1027 void EffectChain::fix_internal_color_spaces()
1029 unsigned colorspace_propagation_pass = 0;
1033 for (unsigned i = 0; i < nodes.size(); ++i) {
1034 Node *node = nodes[i];
1035 if (!node_needs_colorspace_fix(node)) {
1039 // Go through each input that is not sRGB, and insert
1040 // a colorspace conversion after it.
1041 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1042 Node *input = node->incoming_links[j];
1043 assert(input->output_color_space != COLORSPACE_INVALID);
1044 if (input->output_color_space == COLORSPACE_sRGB) {
1047 Node *conversion = add_node(new ColorspaceConversionEffect());
1048 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1049 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1050 conversion->output_color_space = COLORSPACE_sRGB;
1051 replace_sender(input, conversion);
1052 connect_nodes(input, conversion);
1055 // Re-sort topologically, and propagate the new information.
1056 propagate_gamma_and_color_space();
1063 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1064 output_dot(filename);
1065 assert(colorspace_propagation_pass < 100);
1066 } while (found_any);
1068 for (unsigned i = 0; i < nodes.size(); ++i) {
1069 Node *node = nodes[i];
1070 if (node->disabled) {
1073 assert(node->output_color_space != COLORSPACE_INVALID);
1077 bool EffectChain::node_needs_alpha_fix(Node *node)
1079 if (node->disabled) {
1083 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1084 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1085 return (node->output_alpha_type == ALPHA_INVALID);
1088 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1089 // the graph. Similar to fix_internal_color_spaces().
1090 void EffectChain::fix_internal_alpha(unsigned step)
1092 unsigned alpha_propagation_pass = 0;
1096 for (unsigned i = 0; i < nodes.size(); ++i) {
1097 Node *node = nodes[i];
1098 if (!node_needs_alpha_fix(node)) {
1102 // If we need to fix up GammaExpansionEffect, then clearly something
1103 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1105 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1107 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1109 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1110 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1111 assert(node->incoming_links.size() == 1);
1112 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1113 desired_type = ALPHA_POSTMULTIPLIED;
1116 // Go through each input that is not premultiplied alpha, and insert
1117 // a conversion before it.
1118 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1119 Node *input = node->incoming_links[j];
1120 assert(input->output_alpha_type != ALPHA_INVALID);
1121 if (input->output_alpha_type == desired_type ||
1122 input->output_alpha_type == ALPHA_BLANK) {
1126 if (desired_type == ALPHA_PREMULTIPLIED) {
1127 conversion = add_node(new AlphaMultiplicationEffect());
1129 conversion = add_node(new AlphaDivisionEffect());
1131 conversion->output_alpha_type = desired_type;
1132 replace_sender(input, conversion);
1133 connect_nodes(input, conversion);
1136 // Re-sort topologically, and propagate the new information.
1137 propagate_gamma_and_color_space();
1145 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1146 output_dot(filename);
1147 assert(alpha_propagation_pass < 100);
1148 } while (found_any);
1150 for (unsigned i = 0; i < nodes.size(); ++i) {
1151 Node *node = nodes[i];
1152 if (node->disabled) {
1155 assert(node->output_alpha_type != ALPHA_INVALID);
1159 // Make so that the output is in the desired color space.
1160 void EffectChain::fix_output_color_space()
1162 Node *output = find_output_node();
1163 if (output->output_color_space != output_format.color_space) {
1164 Node *conversion = add_node(new ColorspaceConversionEffect());
1165 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1166 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1167 conversion->output_color_space = output_format.color_space;
1168 connect_nodes(output, conversion);
1170 propagate_gamma_and_color_space();
1174 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1175 void EffectChain::fix_output_alpha()
1177 Node *output = find_output_node();
1178 assert(output->output_alpha_type != ALPHA_INVALID);
1179 if (output->output_alpha_type == ALPHA_BLANK) {
1180 // No alpha output, so we don't care.
1183 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1184 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1185 Node *conversion = add_node(new AlphaDivisionEffect());
1186 connect_nodes(output, conversion);
1188 propagate_gamma_and_color_space();
1190 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1191 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1192 Node *conversion = add_node(new AlphaMultiplicationEffect());
1193 connect_nodes(output, conversion);
1195 propagate_gamma_and_color_space();
1199 bool EffectChain::node_needs_gamma_fix(Node *node)
1201 if (node->disabled) {
1205 // Small hack since the output is not an explicit node:
1206 // If we are the last node and our output is in the wrong
1207 // space compared to EffectChain's output, we need to fix it.
1208 // This will only take us to linear, but fix_output_gamma()
1209 // will come and take us to the desired output gamma
1212 // This needs to be before everything else, since it could
1213 // even apply to inputs (if they are the only effect).
1214 if (node->outgoing_links.empty() &&
1215 node->output_gamma_curve != output_format.gamma_curve &&
1216 node->output_gamma_curve != GAMMA_LINEAR) {
1220 if (node->effect->num_inputs() == 0) {
1224 // propagate_gamma_and_color_space() has already set our output
1225 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1226 // except for GammaCompressionEffect.
1227 if (node->output_gamma_curve == GAMMA_INVALID) {
1230 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1231 assert(node->incoming_links.size() == 1);
1232 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1235 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1238 // Very similar to fix_internal_color_spaces(), but for gamma.
1239 // There is one difference, though; before we start adding conversion nodes,
1240 // we see if we can get anything out of asking the sources to deliver
1241 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1242 // does that part, while fix_internal_gamma_by_inserting_nodes()
1243 // inserts nodes as needed afterwards.
1244 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1246 unsigned gamma_propagation_pass = 0;
1250 for (unsigned i = 0; i < nodes.size(); ++i) {
1251 Node *node = nodes[i];
1252 if (!node_needs_gamma_fix(node)) {
1256 // See if all inputs can give us linear gamma. If not, leave it.
1257 vector<Node *> nonlinear_inputs;
1258 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1259 assert(!nonlinear_inputs.empty());
1262 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1263 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1264 all_ok &= input->can_output_linear_gamma();
1271 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1272 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1273 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1276 // Re-sort topologically, and propagate the new information.
1277 propagate_gamma_and_color_space();
1284 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1285 output_dot(filename);
1286 assert(gamma_propagation_pass < 100);
1287 } while (found_any);
1290 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1292 unsigned gamma_propagation_pass = 0;
1296 for (unsigned i = 0; i < nodes.size(); ++i) {
1297 Node *node = nodes[i];
1298 if (!node_needs_gamma_fix(node)) {
1302 // Special case: We could be an input and still be asked to
1303 // fix our gamma; if so, we should be the only node
1304 // (as node_needs_gamma_fix() would only return true in
1305 // for an input in that case). That means we should insert
1306 // a conversion node _after_ ourselves.
1307 if (node->incoming_links.empty()) {
1308 assert(node->outgoing_links.empty());
1309 Node *conversion = add_node(new GammaExpansionEffect());
1310 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1311 conversion->output_gamma_curve = GAMMA_LINEAR;
1312 connect_nodes(node, conversion);
1315 // If not, go through each input that is not linear gamma,
1316 // and insert a gamma conversion after it.
1317 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1318 Node *input = node->incoming_links[j];
1319 assert(input->output_gamma_curve != GAMMA_INVALID);
1320 if (input->output_gamma_curve == GAMMA_LINEAR) {
1323 Node *conversion = add_node(new GammaExpansionEffect());
1324 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1325 conversion->output_gamma_curve = GAMMA_LINEAR;
1326 replace_sender(input, conversion);
1327 connect_nodes(input, conversion);
1330 // Re-sort topologically, and propagate the new information.
1332 propagate_gamma_and_color_space();
1339 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1340 output_dot(filename);
1341 assert(gamma_propagation_pass < 100);
1342 } while (found_any);
1344 for (unsigned i = 0; i < nodes.size(); ++i) {
1345 Node *node = nodes[i];
1346 if (node->disabled) {
1349 assert(node->output_gamma_curve != GAMMA_INVALID);
1353 // Make so that the output is in the desired gamma.
1354 // Note that this assumes linear input gamma, so it might create the need
1355 // for another pass of fix_internal_gamma().
1356 void EffectChain::fix_output_gamma()
1358 Node *output = find_output_node();
1359 if (output->output_gamma_curve != output_format.gamma_curve) {
1360 Node *conversion = add_node(new GammaCompressionEffect());
1361 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1362 conversion->output_gamma_curve = output_format.gamma_curve;
1363 connect_nodes(output, conversion);
1367 // If the user has requested dither, add a DitherEffect right at the end
1368 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1369 // since dither is about the only effect that can _not_ be done in linear space.
1370 void EffectChain::add_dither_if_needed()
1372 if (num_dither_bits == 0) {
1375 Node *output = find_output_node();
1376 Node *dither = add_node(new DitherEffect());
1377 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1378 connect_nodes(output, dither);
1380 dither_effect = dither->effect;
1383 // Find the output node. This is, simply, one that has no outgoing links.
1384 // If there are multiple ones, the graph is malformed (we do not support
1385 // multiple outputs right now).
1386 Node *EffectChain::find_output_node()
1388 vector<Node *> output_nodes;
1389 for (unsigned i = 0; i < nodes.size(); ++i) {
1390 Node *node = nodes[i];
1391 if (node->disabled) {
1394 if (node->outgoing_links.empty()) {
1395 output_nodes.push_back(node);
1398 assert(output_nodes.size() == 1);
1399 return output_nodes[0];
1402 void EffectChain::finalize()
1404 // Output the graph as it is before we do any conversions on it.
1405 output_dot("step0-start.dot");
1407 // Give each effect in turn a chance to rewrite its own part of the graph.
1408 // Note that if more effects are added as part of this, they will be
1409 // picked up as part of the same for loop, since they are added at the end.
1410 for (unsigned i = 0; i < nodes.size(); ++i) {
1411 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1413 output_dot("step1-rewritten.dot");
1415 find_color_spaces_for_inputs();
1416 output_dot("step2-input-colorspace.dot");
1419 output_dot("step3-propagated-alpha.dot");
1421 propagate_gamma_and_color_space();
1422 output_dot("step4-propagated-all.dot");
1424 fix_internal_color_spaces();
1425 fix_internal_alpha(6);
1426 fix_output_color_space();
1427 output_dot("step7-output-colorspacefix.dot");
1429 output_dot("step8-output-alphafix.dot");
1431 // Note that we need to fix gamma after colorspace conversion,
1432 // because colorspace conversions might create needs for gamma conversions.
1433 // Also, we need to run an extra pass of fix_internal_gamma() after
1434 // fixing the output gamma, as we only have conversions to/from linear,
1435 // and fix_internal_alpha() since GammaCompressionEffect needs
1436 // postmultiplied input.
1437 fix_internal_gamma_by_asking_inputs(9);
1438 fix_internal_gamma_by_inserting_nodes(10);
1440 output_dot("step11-output-gammafix.dot");
1442 output_dot("step12-output-alpha-propagated.dot");
1443 fix_internal_alpha(13);
1444 output_dot("step14-output-alpha-fixed.dot");
1445 fix_internal_gamma_by_asking_inputs(15);
1446 fix_internal_gamma_by_inserting_nodes(16);
1448 output_dot("step17-before-dither.dot");
1450 add_dither_if_needed();
1452 output_dot("step18-final.dot");
1454 // Construct all needed GLSL programs, starting at the output.
1455 // We need to keep track of which effects have already been computed,
1456 // as an effect with multiple users could otherwise be calculated
1458 map<Node *, Phase *> completed_effects;
1459 construct_phase(find_output_node(), &completed_effects);
1461 output_dot("step19-split-to-phases.dot");
1463 assert(phases[0]->inputs.empty());
1468 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1472 // Save original viewport.
1473 GLuint x = 0, y = 0;
1475 if (width == 0 && height == 0) {
1477 glGetIntegerv(GL_VIEWPORT, viewport);
1480 width = viewport[2];
1481 height = viewport[3];
1485 glDisable(GL_BLEND);
1487 glDisable(GL_DEPTH_TEST);
1489 glDepthMask(GL_FALSE);
1492 set<Phase *> generated_mipmaps;
1494 // We choose the simplest option of having one texture per output,
1495 // since otherwise this turns into an (albeit simple) register allocation problem.
1496 map<Phase *, GLuint> output_textures;
1498 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1499 Phase *phase = phases[phase_num];
1501 if (do_phase_timing) {
1502 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1504 if (phase_num == phases.size() - 1) {
1505 // Last phase goes to the output the user specified.
1506 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1508 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1509 assert(status == GL_FRAMEBUFFER_COMPLETE);
1510 glViewport(x, y, width, height);
1511 if (dither_effect != NULL) {
1512 CHECK(dither_effect->set_int("output_width", width));
1513 CHECK(dither_effect->set_int("output_height", height));
1516 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1517 if (do_phase_timing) {
1518 glEndQuery(GL_TIME_ELAPSED);
1522 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1523 texture_it != output_textures.end();
1525 resource_pool->release_2d_texture(texture_it->second);
1528 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1533 if (do_phase_timing) {
1534 // Get back the timer queries.
1535 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1536 Phase *phase = phases[phase_num];
1537 GLint available = 0;
1538 while (!available) {
1539 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1541 GLuint64 time_elapsed;
1542 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1543 phase->time_elapsed_ns += time_elapsed;
1544 ++phase->num_measured_iterations;
1549 void EffectChain::enable_phase_timing(bool enable)
1552 assert(movit_timer_queries_supported);
1554 this->do_phase_timing = enable;
1557 void EffectChain::reset_phase_timing()
1559 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1560 Phase *phase = phases[phase_num];
1561 phase->time_elapsed_ns = 0;
1562 phase->num_measured_iterations = 0;
1566 void EffectChain::print_phase_timing()
1568 double total_time_ms = 0.0;
1569 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1570 Phase *phase = phases[phase_num];
1571 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1572 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1573 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1574 if (effect_num != 0) {
1577 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1580 total_time_ms += avg_time_ms;
1582 printf("Total: %5.1f ms\n", total_time_ms);
1585 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1589 // Find a texture for this phase.
1590 inform_input_sizes(phase);
1592 find_output_size(phase);
1594 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1595 output_textures->insert(make_pair(phase, tex_num));
1598 const GLuint glsl_program_num = phase->glsl_program_num;
1600 glUseProgram(glsl_program_num);
1603 // Set up RTT inputs for this phase.
1604 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1605 glActiveTexture(GL_TEXTURE0 + sampler);
1606 Phase *input = phase->inputs[sampler];
1607 input->output_node->bound_sampler_num = sampler;
1608 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1610 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1611 glGenerateMipmap(GL_TEXTURE_2D);
1613 generated_mipmaps->insert(input);
1615 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1618 // And now the output. (Already set up for us if it is the last phase.)
1620 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1621 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1622 glViewport(0, 0, phase->output_width, phase->output_height);
1625 // Give the required parameters to all the effects.
1626 unsigned sampler_num = phase->inputs.size();
1627 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1628 Node *node = phase->effects[i];
1629 unsigned old_sampler_num = sampler_num;
1630 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1633 if (node->effect->is_single_texture()) {
1634 assert(sampler_num - old_sampler_num == 1);
1635 node->bound_sampler_num = old_sampler_num;
1637 node->bound_sampler_num = -1;
1642 float vertices[] = {
1649 glGenVertexArrays(1, &vao);
1651 glBindVertexArray(vao);
1654 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1655 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1657 glDrawArrays(GL_TRIANGLES, 0, 3);
1660 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1661 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1666 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1667 Node *node = phase->effects[i];
1668 node->effect->clear_gl_state();
1672 resource_pool->release_fbo(fbo);
1675 glDeleteVertexArrays(1, &vao);
1679 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1681 glActiveTexture(GL_TEXTURE0 + sampler_num);
1684 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1687 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1690 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1692 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1695 string texture_name = string("tex_") + effect_id;
1696 glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1700 } // namespace movit