1 #define GL_GLEXT_PROTOTYPES 1
17 #include "alpha_division_effect.h"
18 #include "alpha_multiplication_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "dither_effect.h"
22 #include "effect_chain.h"
23 #include "effect_util.h"
24 #include "gamma_compression_effect.h"
25 #include "gamma_expansion_effect.h"
28 #include "resource_pool.h"
30 #include "ycbcr_conversion_effect.h"
32 using namespace Eigen;
37 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
38 : aspect_nom(aspect_nom),
39 aspect_denom(aspect_denom),
40 output_color_rgba(false),
41 output_color_ycbcr(false),
44 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
46 resource_pool(resource_pool),
47 do_phase_timing(false) {
48 if (resource_pool == NULL) {
49 this->resource_pool = new ResourcePool();
50 owns_resource_pool = true;
52 owns_resource_pool = false;
56 EffectChain::~EffectChain()
58 for (unsigned i = 0; i < nodes.size(); ++i) {
59 delete nodes[i]->effect;
62 for (unsigned i = 0; i < phases.size(); ++i) {
63 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
66 if (owns_resource_pool) {
71 Input *EffectChain::add_input(Input *input)
74 inputs.push_back(input);
79 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
82 assert(!output_color_rgba);
83 output_format = format;
84 output_alpha_format = alpha_format;
85 output_color_rgba = true;
88 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
89 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting)
92 assert(!output_color_ycbcr);
93 output_format = format;
94 output_alpha_format = alpha_format;
95 output_color_ycbcr = true;
96 output_ycbcr_format = ycbcr_format;
97 output_ycbcr_splitting = output_splitting;
99 assert(ycbcr_format.chroma_subsampling_x == 1);
100 assert(ycbcr_format.chroma_subsampling_y == 1);
103 Node *EffectChain::add_node(Effect *effect)
105 for (unsigned i = 0; i < nodes.size(); ++i) {
106 assert(nodes[i]->effect != effect);
109 Node *node = new Node;
110 node->effect = effect;
111 node->disabled = false;
112 node->output_color_space = COLORSPACE_INVALID;
113 node->output_gamma_curve = GAMMA_INVALID;
114 node->output_alpha_type = ALPHA_INVALID;
115 node->needs_mipmaps = false;
116 node->one_to_one_sampling = false;
118 nodes.push_back(node);
119 node_map[effect] = node;
120 effect->inform_added(this);
124 void EffectChain::connect_nodes(Node *sender, Node *receiver)
126 sender->outgoing_links.push_back(receiver);
127 receiver->incoming_links.push_back(sender);
130 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
132 new_receiver->incoming_links = old_receiver->incoming_links;
133 old_receiver->incoming_links.clear();
135 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
136 Node *sender = new_receiver->incoming_links[i];
137 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
138 if (sender->outgoing_links[j] == old_receiver) {
139 sender->outgoing_links[j] = new_receiver;
145 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
147 new_sender->outgoing_links = old_sender->outgoing_links;
148 old_sender->outgoing_links.clear();
150 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
151 Node *receiver = new_sender->outgoing_links[i];
152 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
153 if (receiver->incoming_links[j] == old_sender) {
154 receiver->incoming_links[j] = new_sender;
160 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
162 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
163 if (sender->outgoing_links[i] == receiver) {
164 sender->outgoing_links[i] = middle;
165 middle->incoming_links.push_back(sender);
168 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
169 if (receiver->incoming_links[i] == sender) {
170 receiver->incoming_links[i] = middle;
171 middle->outgoing_links.push_back(receiver);
175 assert(middle->incoming_links.size() == middle->effect->num_inputs());
178 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
180 assert(node->effect->needs_texture_bounce());
181 assert(input_num < node->incoming_links.size());
182 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
183 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
184 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
187 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
189 if (node->output_gamma_curve == GAMMA_LINEAR &&
190 node->effect->effect_type_id() != "GammaCompressionEffect") {
193 if (node->effect->num_inputs() == 0) {
194 nonlinear_inputs->push_back(node);
196 assert(node->effect->num_inputs() == node->incoming_links.size());
197 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
198 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
203 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
206 assert(inputs.size() == effect->num_inputs());
207 Node *node = add_node(effect);
208 for (unsigned i = 0; i < inputs.size(); ++i) {
209 assert(node_map.count(inputs[i]) != 0);
210 connect_nodes(node_map[inputs[i]], node);
215 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
216 string replace_prefix(const string &text, const string &prefix)
221 while (start < text.size()) {
222 size_t pos = text.find("PREFIX(", start);
223 if (pos == string::npos) {
224 output.append(text.substr(start, string::npos));
228 output.append(text.substr(start, pos - start));
229 output.append(prefix);
232 pos += strlen("PREFIX(");
234 // Output stuff until we find the matching ), which we then eat.
236 size_t end_arg_pos = pos;
237 while (end_arg_pos < text.size()) {
238 if (text[end_arg_pos] == '(') {
240 } else if (text[end_arg_pos] == ')') {
248 output.append(text.substr(pos, end_arg_pos - pos));
259 void extract_uniform_declarations(const vector<Uniform<T> > &effect_uniforms,
260 const string &type_specifier,
261 const string &effect_id,
262 vector<Uniform<T> > *phase_uniforms,
265 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
266 phase_uniforms->push_back(effect_uniforms[i]);
267 phase_uniforms->back().prefix = effect_id;
269 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
270 + "_" + effect_uniforms[i].name + ";\n";
275 void extract_uniform_array_declarations(const vector<Uniform<T> > &effect_uniforms,
276 const string &type_specifier,
277 const string &effect_id,
278 vector<Uniform<T> > *phase_uniforms,
281 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
282 phase_uniforms->push_back(effect_uniforms[i]);
283 phase_uniforms->back().prefix = effect_id;
286 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
287 type_specifier.c_str(), effect_id.c_str(),
288 effect_uniforms[i].name.c_str(),
289 int(effect_uniforms[i].num_values));
295 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T> > *phase_uniforms)
297 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
298 Uniform<T> &uniform = (*phase_uniforms)[i];
299 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
305 void EffectChain::compile_glsl_program(Phase *phase)
307 string frag_shader_header = read_version_dependent_file("header", "frag");
308 string frag_shader = "";
310 // Create functions and uniforms for all the texture inputs that we need.
311 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
312 Node *input = phase->inputs[i]->output_node;
314 sprintf(effect_id, "in%u", i);
315 phase->effect_ids.insert(make_pair(input, effect_id));
317 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
318 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
319 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
320 frag_shader += "}\n";
323 Uniform<int> uniform;
324 uniform.name = effect_id;
325 uniform.value = &phase->input_samplers[i];
326 uniform.prefix = "tex";
327 uniform.num_values = 1;
328 uniform.location = -1;
329 phase->uniforms_sampler2d.push_back(uniform);
332 // Give each effect in the phase its own ID.
333 for (unsigned i = 0; i < phase->effects.size(); ++i) {
334 Node *node = phase->effects[i];
336 sprintf(effect_id, "eff%u", i);
337 phase->effect_ids.insert(make_pair(node, effect_id));
340 for (unsigned i = 0; i < phase->effects.size(); ++i) {
341 Node *node = phase->effects[i];
342 const string effect_id = phase->effect_ids[node];
343 if (node->incoming_links.size() == 1) {
344 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
346 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
348 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
354 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
355 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
356 frag_shader += "#undef PREFIX\n";
357 frag_shader += "#undef FUNCNAME\n";
358 if (node->incoming_links.size() == 1) {
359 frag_shader += "#undef INPUT\n";
361 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
363 sprintf(buf, "#undef INPUT%d\n", j + 1);
369 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
371 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
372 if (phase->output_node->outgoing_links.empty() && output_color_ycbcr) {
373 switch (output_ycbcr_splitting) {
374 case YCBCR_OUTPUT_INTERLEAVED:
377 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
378 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
380 case YCBCR_OUTPUT_PLANAR:
381 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
387 if (output_color_rgba) {
388 // Note: Needs to come in the header, because not only the
389 // output needs to see it (YCbCrConversionEffect and DitherEffect
391 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
394 frag_shader.append(read_file("footer.frag"));
396 // Collect uniforms from all effects and output them. Note that this needs
397 // to happen after output_fragment_shader(), even though the uniforms come
398 // before in the output source, since output_fragment_shader() is allowed
399 // to register new uniforms (e.g. arrays that are of unknown length until
400 // finalization time).
401 // TODO: Make a uniform block for platforms that support it.
402 string frag_shader_uniforms = "";
403 for (unsigned i = 0; i < phase->effects.size(); ++i) {
404 Node *node = phase->effects[i];
405 Effect *effect = node->effect;
406 const string effect_id = phase->effect_ids[node];
407 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
408 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
409 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
410 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
411 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
412 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
413 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
414 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
415 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
416 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
419 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
421 string vert_shader = read_version_dependent_file("vs", "vert");
423 // If we're the last phase and need to flip the picture to compensate for
424 // the origin, tell the vertex shader so.
425 if (phase->output_node->outgoing_links.empty() && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
426 const string needle = "#define FLIP_ORIGIN 0";
427 size_t pos = vert_shader.find(needle);
428 assert(pos != string::npos);
430 vert_shader[pos + needle.size() - 1] = '1';
433 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
435 // Collect the resulting location numbers for each uniform.
436 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
437 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
438 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
439 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
440 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
441 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
442 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
443 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
446 // Construct GLSL programs, starting at the given effect and following
447 // the chain from there. We end a program every time we come to an effect
448 // marked as "needs texture bounce", one that is used by multiple other
449 // effects, every time we need to bounce due to output size change
450 // (not all size changes require ending), and of course at the end.
452 // We follow a quite simple depth-first search from the output, although
453 // without recursing explicitly within each phase.
454 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
456 if (completed_effects->count(output)) {
457 return (*completed_effects)[output];
460 Phase *phase = new Phase;
461 phase->output_node = output;
463 // If the output effect has one-to-one sampling, we try to trace this
464 // status down through the dependency chain. This is important in case
465 // we hit an effect that changes output size (and not sets a virtual
466 // output size); if we have one-to-one sampling, we don't have to break
468 output->one_to_one_sampling = output->effect->one_to_one_sampling();
470 // Effects that we have yet to calculate, but that we know should
471 // be in the current phase.
472 stack<Node *> effects_todo_this_phase;
473 effects_todo_this_phase.push(output);
475 while (!effects_todo_this_phase.empty()) {
476 Node *node = effects_todo_this_phase.top();
477 effects_todo_this_phase.pop();
479 if (node->effect->needs_mipmaps()) {
480 node->needs_mipmaps = true;
483 // This should currently only happen for effects that are inputs
484 // (either true inputs or phase outputs). We special-case inputs,
485 // and then deduplicate phase outputs below.
486 if (node->effect->num_inputs() == 0) {
487 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
491 assert(completed_effects->count(node) == 0);
494 phase->effects.push_back(node);
496 // Find all the dependencies of this effect, and add them to the stack.
497 vector<Node *> deps = node->incoming_links;
498 assert(node->effect->num_inputs() == deps.size());
499 for (unsigned i = 0; i < deps.size(); ++i) {
500 bool start_new_phase = false;
502 if (node->effect->needs_texture_bounce() &&
503 !deps[i]->effect->is_single_texture()) {
504 start_new_phase = true;
507 // Propagate information about needing mipmaps down the chain,
508 // breaking the phase if we notice an incompatibility.
510 // Note that we cannot do this propagation as a normal pass,
511 // because it needs information about where the phases end
512 // (we should not propagate the flag across phases).
513 if (node->needs_mipmaps) {
514 if (deps[i]->effect->num_inputs() == 0) {
515 Input *input = static_cast<Input *>(deps[i]->effect);
516 start_new_phase |= !input->can_supply_mipmaps();
518 deps[i]->needs_mipmaps = true;
522 if (deps[i]->outgoing_links.size() > 1) {
523 if (!deps[i]->effect->is_single_texture()) {
524 // More than one effect uses this as the input,
525 // and it is not a texture itself.
526 // The easiest thing to do (and probably also the safest
527 // performance-wise in most cases) is to bounce it to a texture
528 // and then let the next passes read from that.
529 start_new_phase = true;
531 assert(deps[i]->effect->num_inputs() == 0);
533 // For textures, we try to be slightly more clever;
534 // if none of our outputs need a bounce, we don't bounce
535 // but instead simply use the effect many times.
537 // Strictly speaking, we could bounce it for some outputs
538 // and use it directly for others, but the processing becomes
539 // somewhat simpler if the effect is only used in one such way.
540 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
541 Node *rdep = deps[i]->outgoing_links[j];
542 start_new_phase |= rdep->effect->needs_texture_bounce();
547 if (deps[i]->effect->sets_virtual_output_size()) {
548 assert(deps[i]->effect->changes_output_size());
549 // If the next effect sets a virtual size to rely on OpenGL's
550 // bilinear sampling, we'll really need to break the phase here.
551 start_new_phase = true;
552 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
553 // If the next effect changes size and we don't have one-to-one sampling,
554 // we also need to break here.
555 start_new_phase = true;
558 if (start_new_phase) {
559 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
561 effects_todo_this_phase.push(deps[i]);
563 // Propagate the one-to-one status down through the dependency.
564 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
565 deps[i]->effect->one_to_one_sampling();
570 // No more effects to do this phase. Take all the ones we have,
571 // and create a GLSL program for it.
572 assert(!phase->effects.empty());
574 // Deduplicate the inputs.
575 sort(phase->inputs.begin(), phase->inputs.end());
576 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
578 // Allocate samplers for each input.
579 phase->input_samplers.resize(phase->inputs.size());
581 // We added the effects from the output and back, but we need to output
582 // them in topological sort order in the shader.
583 phase->effects = topological_sort(phase->effects);
585 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
586 phase->input_needs_mipmaps = false;
587 for (unsigned i = 0; i < phase->effects.size(); ++i) {
588 Node *node = phase->effects[i];
589 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
591 for (unsigned i = 0; i < phase->effects.size(); ++i) {
592 Node *node = phase->effects[i];
593 if (node->effect->num_inputs() == 0) {
594 Input *input = static_cast<Input *>(node->effect);
595 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
596 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
600 // Tell each node which phase it ended up in, so that the unit test
601 // can check that the phases were split in the right place.
602 // Note that this ignores that effects may be part of multiple phases;
603 // if the unit tests need to test such cases, we'll reconsider.
604 for (unsigned i = 0; i < phase->effects.size(); ++i) {
605 phase->effects[i]->containing_phase = phase;
608 // Actually make the shader for this phase.
609 compile_glsl_program(phase);
611 // Initialize timer objects.
612 if (movit_timer_queries_supported) {
613 glGenQueries(1, &phase->timer_query_object);
614 phase->time_elapsed_ns = 0;
615 phase->num_measured_iterations = 0;
618 assert(completed_effects->count(output) == 0);
619 completed_effects->insert(make_pair(output, phase));
620 phases.push_back(phase);
624 void EffectChain::output_dot(const char *filename)
626 if (movit_debug_level != MOVIT_DEBUG_ON) {
630 FILE *fp = fopen(filename, "w");
636 fprintf(fp, "digraph G {\n");
637 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
638 for (unsigned i = 0; i < nodes.size(); ++i) {
639 // Find out which phase this event belongs to.
640 vector<int> in_phases;
641 for (unsigned j = 0; j < phases.size(); ++j) {
642 const Phase* p = phases[j];
643 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
644 in_phases.push_back(j);
648 if (in_phases.empty()) {
649 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
650 } else if (in_phases.size() == 1) {
651 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
652 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
653 (in_phases[0] % 8) + 1);
655 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
657 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
658 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
659 (in_phases[0] % 8) + 1);
662 char from_node_id[256];
663 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
665 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
666 char to_node_id[256];
667 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
669 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
670 output_dot_edge(fp, from_node_id, to_node_id, labels);
673 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
675 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
676 output_dot_edge(fp, from_node_id, "output", labels);
684 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
686 vector<string> labels;
688 if (to != NULL && to->effect->needs_texture_bounce()) {
689 labels.push_back("needs_bounce");
691 if (from->effect->changes_output_size()) {
692 labels.push_back("resize");
695 switch (from->output_color_space) {
696 case COLORSPACE_INVALID:
697 labels.push_back("spc[invalid]");
699 case COLORSPACE_REC_601_525:
700 labels.push_back("spc[rec601-525]");
702 case COLORSPACE_REC_601_625:
703 labels.push_back("spc[rec601-625]");
709 switch (from->output_gamma_curve) {
711 labels.push_back("gamma[invalid]");
714 labels.push_back("gamma[sRGB]");
716 case GAMMA_REC_601: // and GAMMA_REC_709
717 labels.push_back("gamma[rec601/709]");
723 switch (from->output_alpha_type) {
725 labels.push_back("alpha[invalid]");
728 labels.push_back("alpha[blank]");
730 case ALPHA_POSTMULTIPLIED:
731 labels.push_back("alpha[postmult]");
740 void EffectChain::output_dot_edge(FILE *fp,
741 const string &from_node_id,
742 const string &to_node_id,
743 const vector<string> &labels)
745 if (labels.empty()) {
746 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
748 string label = labels[0];
749 for (unsigned k = 1; k < labels.size(); ++k) {
750 label += ", " + labels[k];
752 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
756 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
758 unsigned scaled_width, scaled_height;
760 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
761 // Same aspect, or W/H > aspect (image is wider than the frame).
762 // In either case, keep width, and adjust height.
763 scaled_width = width;
764 scaled_height = lrintf(width * aspect_denom / aspect_nom);
766 // W/H < aspect (image is taller than the frame), so keep height,
768 scaled_width = lrintf(height * aspect_nom / aspect_denom);
769 scaled_height = height;
772 // We should be consistently larger or smaller then the existing choice,
773 // since we have the same aspect.
774 assert(!(scaled_width < *output_width && scaled_height > *output_height));
775 assert(!(scaled_height < *output_height && scaled_width > *output_width));
777 if (scaled_width >= *output_width && scaled_height >= *output_height) {
778 *output_width = scaled_width;
779 *output_height = scaled_height;
783 // Propagate input texture sizes throughout, and inform effects downstream.
784 // (Like a lot of other code, we depend on effects being in topological order.)
785 void EffectChain::inform_input_sizes(Phase *phase)
787 // All effects that have a defined size (inputs and RTT inputs)
788 // get that. Reset all others.
789 for (unsigned i = 0; i < phase->effects.size(); ++i) {
790 Node *node = phase->effects[i];
791 if (node->effect->num_inputs() == 0) {
792 Input *input = static_cast<Input *>(node->effect);
793 node->output_width = input->get_width();
794 node->output_height = input->get_height();
795 assert(node->output_width != 0);
796 assert(node->output_height != 0);
798 node->output_width = node->output_height = 0;
801 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
802 Phase *input = phase->inputs[i];
803 input->output_node->output_width = input->virtual_output_width;
804 input->output_node->output_height = input->virtual_output_height;
805 assert(input->output_node->output_width != 0);
806 assert(input->output_node->output_height != 0);
809 // Now propagate from the inputs towards the end, and inform as we go.
810 // The rules are simple:
812 // 1. Don't touch effects that already have given sizes (ie., inputs
813 // or effects that change the output size).
814 // 2. If all of your inputs have the same size, that will be your output size.
815 // 3. Otherwise, your output size is 0x0.
816 for (unsigned i = 0; i < phase->effects.size(); ++i) {
817 Node *node = phase->effects[i];
818 if (node->effect->num_inputs() == 0) {
821 unsigned this_output_width = 0;
822 unsigned this_output_height = 0;
823 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
824 Node *input = node->incoming_links[j];
825 node->effect->inform_input_size(j, input->output_width, input->output_height);
827 this_output_width = input->output_width;
828 this_output_height = input->output_height;
829 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
831 this_output_width = 0;
832 this_output_height = 0;
835 if (node->effect->changes_output_size()) {
836 // We cannot call get_output_size() before we've done inform_input_size()
838 unsigned real_width, real_height;
839 node->effect->get_output_size(&real_width, &real_height,
840 &node->output_width, &node->output_height);
841 assert(node->effect->sets_virtual_output_size() ||
842 (real_width == node->output_width &&
843 real_height == node->output_height));
845 node->output_width = this_output_width;
846 node->output_height = this_output_height;
851 // Note: You should call inform_input_sizes() before this, as the last effect's
852 // desired output size might change based on the inputs.
853 void EffectChain::find_output_size(Phase *phase)
855 Node *output_node = phase->effects.back();
857 // If the last effect explicitly sets an output size, use that.
858 if (output_node->effect->changes_output_size()) {
859 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
860 &phase->virtual_output_width, &phase->virtual_output_height);
861 assert(output_node->effect->sets_virtual_output_size() ||
862 (phase->output_width == phase->virtual_output_width &&
863 phase->output_height == phase->virtual_output_height));
867 // If all effects have the same size, use that.
868 unsigned output_width = 0, output_height = 0;
869 bool all_inputs_same_size = true;
871 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
872 Phase *input = phase->inputs[i];
873 assert(input->output_width != 0);
874 assert(input->output_height != 0);
875 if (output_width == 0 && output_height == 0) {
876 output_width = input->virtual_output_width;
877 output_height = input->virtual_output_height;
878 } else if (output_width != input->virtual_output_width ||
879 output_height != input->virtual_output_height) {
880 all_inputs_same_size = false;
883 for (unsigned i = 0; i < phase->effects.size(); ++i) {
884 Effect *effect = phase->effects[i]->effect;
885 if (effect->num_inputs() != 0) {
889 Input *input = static_cast<Input *>(effect);
890 if (output_width == 0 && output_height == 0) {
891 output_width = input->get_width();
892 output_height = input->get_height();
893 } else if (output_width != input->get_width() ||
894 output_height != input->get_height()) {
895 all_inputs_same_size = false;
899 if (all_inputs_same_size) {
900 assert(output_width != 0);
901 assert(output_height != 0);
902 phase->virtual_output_width = phase->output_width = output_width;
903 phase->virtual_output_height = phase->output_height = output_height;
907 // If not, fit all the inputs into the current aspect, and select the largest one.
910 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
911 Phase *input = phase->inputs[i];
912 assert(input->output_width != 0);
913 assert(input->output_height != 0);
914 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
916 for (unsigned i = 0; i < phase->effects.size(); ++i) {
917 Effect *effect = phase->effects[i]->effect;
918 if (effect->num_inputs() != 0) {
922 Input *input = static_cast<Input *>(effect);
923 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
925 assert(output_width != 0);
926 assert(output_height != 0);
927 phase->virtual_output_width = phase->output_width = output_width;
928 phase->virtual_output_height = phase->output_height = output_height;
931 void EffectChain::sort_all_nodes_topologically()
933 nodes = topological_sort(nodes);
936 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
938 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
939 vector<Node *> sorted_list;
940 for (unsigned i = 0; i < nodes.size(); ++i) {
941 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
943 reverse(sorted_list.begin(), sorted_list.end());
947 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
949 if (nodes_left_to_visit->count(node) == 0) {
952 nodes_left_to_visit->erase(node);
953 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
954 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
956 sorted_list->push_back(node);
959 void EffectChain::find_color_spaces_for_inputs()
961 for (unsigned i = 0; i < nodes.size(); ++i) {
962 Node *node = nodes[i];
963 if (node->disabled) {
966 if (node->incoming_links.size() == 0) {
967 Input *input = static_cast<Input *>(node->effect);
968 node->output_color_space = input->get_color_space();
969 node->output_gamma_curve = input->get_gamma_curve();
971 Effect::AlphaHandling alpha_handling = input->alpha_handling();
972 switch (alpha_handling) {
973 case Effect::OUTPUT_BLANK_ALPHA:
974 node->output_alpha_type = ALPHA_BLANK;
976 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
977 node->output_alpha_type = ALPHA_PREMULTIPLIED;
979 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
980 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
982 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
983 case Effect::DONT_CARE_ALPHA_TYPE:
988 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
989 assert(node->output_gamma_curve == GAMMA_LINEAR);
995 // Propagate gamma and color space information as far as we can in the graph.
996 // The rules are simple: Anything where all the inputs agree, get that as
997 // output as well. Anything else keeps having *_INVALID.
998 void EffectChain::propagate_gamma_and_color_space()
1000 // We depend on going through the nodes in order.
1001 sort_all_nodes_topologically();
1003 for (unsigned i = 0; i < nodes.size(); ++i) {
1004 Node *node = nodes[i];
1005 if (node->disabled) {
1008 assert(node->incoming_links.size() == node->effect->num_inputs());
1009 if (node->incoming_links.size() == 0) {
1010 assert(node->output_color_space != COLORSPACE_INVALID);
1011 assert(node->output_gamma_curve != GAMMA_INVALID);
1015 Colorspace color_space = node->incoming_links[0]->output_color_space;
1016 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1017 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1018 if (node->incoming_links[j]->output_color_space != color_space) {
1019 color_space = COLORSPACE_INVALID;
1021 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1022 gamma_curve = GAMMA_INVALID;
1026 // The conversion effects already have their outputs set correctly,
1027 // so leave them alone.
1028 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1029 node->output_color_space = color_space;
1031 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1032 node->effect->effect_type_id() != "GammaExpansionEffect") {
1033 node->output_gamma_curve = gamma_curve;
1038 // Propagate alpha information as far as we can in the graph.
1039 // Similar to propagate_gamma_and_color_space().
1040 void EffectChain::propagate_alpha()
1042 // We depend on going through the nodes in order.
1043 sort_all_nodes_topologically();
1045 for (unsigned i = 0; i < nodes.size(); ++i) {
1046 Node *node = nodes[i];
1047 if (node->disabled) {
1050 assert(node->incoming_links.size() == node->effect->num_inputs());
1051 if (node->incoming_links.size() == 0) {
1052 assert(node->output_alpha_type != ALPHA_INVALID);
1056 // The alpha multiplication/division effects are special cases.
1057 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1058 assert(node->incoming_links.size() == 1);
1059 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1060 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1063 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1064 assert(node->incoming_links.size() == 1);
1065 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1066 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1070 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1071 // because they are the only one that _need_ postmultiplied alpha.
1072 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1073 node->effect->effect_type_id() == "GammaExpansionEffect") {
1074 assert(node->incoming_links.size() == 1);
1075 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1076 node->output_alpha_type = ALPHA_BLANK;
1077 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1078 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1080 node->output_alpha_type = ALPHA_INVALID;
1085 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1086 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1087 // taken care of above. Rationale: Even if you could imagine
1088 // e.g. an effect that took in an image and set alpha=1.0
1089 // unconditionally, it wouldn't make any sense to have it as
1090 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1091 // got its input pre- or postmultiplied, so it wouldn't know
1092 // whether to divide away the old alpha or not.
1093 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1094 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1095 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1096 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1098 // If the node has multiple inputs, check that they are all valid and
1100 bool any_invalid = false;
1101 bool any_premultiplied = false;
1102 bool any_postmultiplied = false;
1104 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1105 switch (node->incoming_links[j]->output_alpha_type) {
1110 // Blank is good as both pre- and postmultiplied alpha,
1111 // so just ignore it.
1113 case ALPHA_PREMULTIPLIED:
1114 any_premultiplied = true;
1116 case ALPHA_POSTMULTIPLIED:
1117 any_postmultiplied = true;
1125 node->output_alpha_type = ALPHA_INVALID;
1129 // Inputs must be of the same type.
1130 if (any_premultiplied && any_postmultiplied) {
1131 node->output_alpha_type = ALPHA_INVALID;
1135 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1136 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1137 // If the effect has asked for premultiplied alpha, check that it has got it.
1138 if (any_postmultiplied) {
1139 node->output_alpha_type = ALPHA_INVALID;
1140 } else if (!any_premultiplied &&
1141 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1142 // Blank input alpha, and the effect preserves blank alpha.
1143 node->output_alpha_type = ALPHA_BLANK;
1145 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1148 // OK, all inputs are the same, and this effect is not going
1150 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1151 if (any_premultiplied) {
1152 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1153 } else if (any_postmultiplied) {
1154 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1156 node->output_alpha_type = ALPHA_BLANK;
1162 bool EffectChain::node_needs_colorspace_fix(Node *node)
1164 if (node->disabled) {
1167 if (node->effect->num_inputs() == 0) {
1171 // propagate_gamma_and_color_space() has already set our output
1172 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1173 if (node->output_color_space == COLORSPACE_INVALID) {
1176 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1179 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1180 // the graph. Our strategy is not always optimal, but quite simple:
1181 // Find an effect that's as early as possible where the inputs are of
1182 // unacceptable colorspaces (that is, either different, or, if the effect only
1183 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1184 // propagate the information anew, and repeat until there are no more such
1186 void EffectChain::fix_internal_color_spaces()
1188 unsigned colorspace_propagation_pass = 0;
1192 for (unsigned i = 0; i < nodes.size(); ++i) {
1193 Node *node = nodes[i];
1194 if (!node_needs_colorspace_fix(node)) {
1198 // Go through each input that is not sRGB, and insert
1199 // a colorspace conversion after it.
1200 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1201 Node *input = node->incoming_links[j];
1202 assert(input->output_color_space != COLORSPACE_INVALID);
1203 if (input->output_color_space == COLORSPACE_sRGB) {
1206 Node *conversion = add_node(new ColorspaceConversionEffect());
1207 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1208 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1209 conversion->output_color_space = COLORSPACE_sRGB;
1210 replace_sender(input, conversion);
1211 connect_nodes(input, conversion);
1214 // Re-sort topologically, and propagate the new information.
1215 propagate_gamma_and_color_space();
1222 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1223 output_dot(filename);
1224 assert(colorspace_propagation_pass < 100);
1225 } while (found_any);
1227 for (unsigned i = 0; i < nodes.size(); ++i) {
1228 Node *node = nodes[i];
1229 if (node->disabled) {
1232 assert(node->output_color_space != COLORSPACE_INVALID);
1236 bool EffectChain::node_needs_alpha_fix(Node *node)
1238 if (node->disabled) {
1242 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1243 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1244 return (node->output_alpha_type == ALPHA_INVALID);
1247 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1248 // the graph. Similar to fix_internal_color_spaces().
1249 void EffectChain::fix_internal_alpha(unsigned step)
1251 unsigned alpha_propagation_pass = 0;
1255 for (unsigned i = 0; i < nodes.size(); ++i) {
1256 Node *node = nodes[i];
1257 if (!node_needs_alpha_fix(node)) {
1261 // If we need to fix up GammaExpansionEffect, then clearly something
1262 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1264 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1266 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1268 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1269 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1270 assert(node->incoming_links.size() == 1);
1271 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1272 desired_type = ALPHA_POSTMULTIPLIED;
1275 // Go through each input that is not premultiplied alpha, and insert
1276 // a conversion before it.
1277 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1278 Node *input = node->incoming_links[j];
1279 assert(input->output_alpha_type != ALPHA_INVALID);
1280 if (input->output_alpha_type == desired_type ||
1281 input->output_alpha_type == ALPHA_BLANK) {
1285 if (desired_type == ALPHA_PREMULTIPLIED) {
1286 conversion = add_node(new AlphaMultiplicationEffect());
1288 conversion = add_node(new AlphaDivisionEffect());
1290 conversion->output_alpha_type = desired_type;
1291 replace_sender(input, conversion);
1292 connect_nodes(input, conversion);
1295 // Re-sort topologically, and propagate the new information.
1296 propagate_gamma_and_color_space();
1304 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1305 output_dot(filename);
1306 assert(alpha_propagation_pass < 100);
1307 } while (found_any);
1309 for (unsigned i = 0; i < nodes.size(); ++i) {
1310 Node *node = nodes[i];
1311 if (node->disabled) {
1314 assert(node->output_alpha_type != ALPHA_INVALID);
1318 // Make so that the output is in the desired color space.
1319 void EffectChain::fix_output_color_space()
1321 Node *output = find_output_node();
1322 if (output->output_color_space != output_format.color_space) {
1323 Node *conversion = add_node(new ColorspaceConversionEffect());
1324 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1325 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1326 conversion->output_color_space = output_format.color_space;
1327 connect_nodes(output, conversion);
1329 propagate_gamma_and_color_space();
1333 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1334 void EffectChain::fix_output_alpha()
1336 Node *output = find_output_node();
1337 assert(output->output_alpha_type != ALPHA_INVALID);
1338 if (output->output_alpha_type == ALPHA_BLANK) {
1339 // No alpha output, so we don't care.
1342 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1343 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1344 Node *conversion = add_node(new AlphaDivisionEffect());
1345 connect_nodes(output, conversion);
1347 propagate_gamma_and_color_space();
1349 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1350 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1351 Node *conversion = add_node(new AlphaMultiplicationEffect());
1352 connect_nodes(output, conversion);
1354 propagate_gamma_and_color_space();
1358 bool EffectChain::node_needs_gamma_fix(Node *node)
1360 if (node->disabled) {
1364 // Small hack since the output is not an explicit node:
1365 // If we are the last node and our output is in the wrong
1366 // space compared to EffectChain's output, we need to fix it.
1367 // This will only take us to linear, but fix_output_gamma()
1368 // will come and take us to the desired output gamma
1371 // This needs to be before everything else, since it could
1372 // even apply to inputs (if they are the only effect).
1373 if (node->outgoing_links.empty() &&
1374 node->output_gamma_curve != output_format.gamma_curve &&
1375 node->output_gamma_curve != GAMMA_LINEAR) {
1379 if (node->effect->num_inputs() == 0) {
1383 // propagate_gamma_and_color_space() has already set our output
1384 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1385 // except for GammaCompressionEffect.
1386 if (node->output_gamma_curve == GAMMA_INVALID) {
1389 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1390 assert(node->incoming_links.size() == 1);
1391 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1394 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1397 // Very similar to fix_internal_color_spaces(), but for gamma.
1398 // There is one difference, though; before we start adding conversion nodes,
1399 // we see if we can get anything out of asking the sources to deliver
1400 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1401 // does that part, while fix_internal_gamma_by_inserting_nodes()
1402 // inserts nodes as needed afterwards.
1403 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1405 unsigned gamma_propagation_pass = 0;
1409 for (unsigned i = 0; i < nodes.size(); ++i) {
1410 Node *node = nodes[i];
1411 if (!node_needs_gamma_fix(node)) {
1415 // See if all inputs can give us linear gamma. If not, leave it.
1416 vector<Node *> nonlinear_inputs;
1417 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1418 assert(!nonlinear_inputs.empty());
1421 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1422 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1423 all_ok &= input->can_output_linear_gamma();
1430 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1431 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1432 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1435 // Re-sort topologically, and propagate the new information.
1436 propagate_gamma_and_color_space();
1443 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1444 output_dot(filename);
1445 assert(gamma_propagation_pass < 100);
1446 } while (found_any);
1449 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1451 unsigned gamma_propagation_pass = 0;
1455 for (unsigned i = 0; i < nodes.size(); ++i) {
1456 Node *node = nodes[i];
1457 if (!node_needs_gamma_fix(node)) {
1461 // Special case: We could be an input and still be asked to
1462 // fix our gamma; if so, we should be the only node
1463 // (as node_needs_gamma_fix() would only return true in
1464 // for an input in that case). That means we should insert
1465 // a conversion node _after_ ourselves.
1466 if (node->incoming_links.empty()) {
1467 assert(node->outgoing_links.empty());
1468 Node *conversion = add_node(new GammaExpansionEffect());
1469 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1470 conversion->output_gamma_curve = GAMMA_LINEAR;
1471 connect_nodes(node, conversion);
1474 // If not, go through each input that is not linear gamma,
1475 // and insert a gamma conversion after it.
1476 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1477 Node *input = node->incoming_links[j];
1478 assert(input->output_gamma_curve != GAMMA_INVALID);
1479 if (input->output_gamma_curve == GAMMA_LINEAR) {
1482 Node *conversion = add_node(new GammaExpansionEffect());
1483 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1484 conversion->output_gamma_curve = GAMMA_LINEAR;
1485 replace_sender(input, conversion);
1486 connect_nodes(input, conversion);
1489 // Re-sort topologically, and propagate the new information.
1491 propagate_gamma_and_color_space();
1498 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1499 output_dot(filename);
1500 assert(gamma_propagation_pass < 100);
1501 } while (found_any);
1503 for (unsigned i = 0; i < nodes.size(); ++i) {
1504 Node *node = nodes[i];
1505 if (node->disabled) {
1508 assert(node->output_gamma_curve != GAMMA_INVALID);
1512 // Make so that the output is in the desired gamma.
1513 // Note that this assumes linear input gamma, so it might create the need
1514 // for another pass of fix_internal_gamma().
1515 void EffectChain::fix_output_gamma()
1517 Node *output = find_output_node();
1518 if (output->output_gamma_curve != output_format.gamma_curve) {
1519 Node *conversion = add_node(new GammaCompressionEffect());
1520 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1521 conversion->output_gamma_curve = output_format.gamma_curve;
1522 connect_nodes(output, conversion);
1526 // If the user has requested Y'CbCr output, we need to do this conversion
1527 // _after_ GammaCompressionEffect etc., but before dither (see below).
1528 // This is because Y'CbCr, with the exception of a special optional mode
1529 // in Rec. 2020 (which we currently don't support), is defined to work on
1530 // gamma-encoded data.
1531 void EffectChain::add_ycbcr_conversion_if_needed()
1533 assert(output_color_rgba || output_color_ycbcr);
1534 if (!output_color_ycbcr) {
1537 Node *output = find_output_node();
1538 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1539 connect_nodes(output, ycbcr);
1542 // If the user has requested dither, add a DitherEffect right at the end
1543 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1544 // since dither is about the only effect that can _not_ be done in linear space.
1545 void EffectChain::add_dither_if_needed()
1547 if (num_dither_bits == 0) {
1550 Node *output = find_output_node();
1551 Node *dither = add_node(new DitherEffect());
1552 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1553 connect_nodes(output, dither);
1555 dither_effect = dither->effect;
1558 // Find the output node. This is, simply, one that has no outgoing links.
1559 // If there are multiple ones, the graph is malformed (we do not support
1560 // multiple outputs right now).
1561 Node *EffectChain::find_output_node()
1563 vector<Node *> output_nodes;
1564 for (unsigned i = 0; i < nodes.size(); ++i) {
1565 Node *node = nodes[i];
1566 if (node->disabled) {
1569 if (node->outgoing_links.empty()) {
1570 output_nodes.push_back(node);
1573 assert(output_nodes.size() == 1);
1574 return output_nodes[0];
1577 void EffectChain::finalize()
1579 // Output the graph as it is before we do any conversions on it.
1580 output_dot("step0-start.dot");
1582 // Give each effect in turn a chance to rewrite its own part of the graph.
1583 // Note that if more effects are added as part of this, they will be
1584 // picked up as part of the same for loop, since they are added at the end.
1585 for (unsigned i = 0; i < nodes.size(); ++i) {
1586 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1588 output_dot("step1-rewritten.dot");
1590 find_color_spaces_for_inputs();
1591 output_dot("step2-input-colorspace.dot");
1594 output_dot("step3-propagated-alpha.dot");
1596 propagate_gamma_and_color_space();
1597 output_dot("step4-propagated-all.dot");
1599 fix_internal_color_spaces();
1600 fix_internal_alpha(6);
1601 fix_output_color_space();
1602 output_dot("step7-output-colorspacefix.dot");
1604 output_dot("step8-output-alphafix.dot");
1606 // Note that we need to fix gamma after colorspace conversion,
1607 // because colorspace conversions might create needs for gamma conversions.
1608 // Also, we need to run an extra pass of fix_internal_gamma() after
1609 // fixing the output gamma, as we only have conversions to/from linear,
1610 // and fix_internal_alpha() since GammaCompressionEffect needs
1611 // postmultiplied input.
1612 fix_internal_gamma_by_asking_inputs(9);
1613 fix_internal_gamma_by_inserting_nodes(10);
1615 output_dot("step11-output-gammafix.dot");
1617 output_dot("step12-output-alpha-propagated.dot");
1618 fix_internal_alpha(13);
1619 output_dot("step14-output-alpha-fixed.dot");
1620 fix_internal_gamma_by_asking_inputs(15);
1621 fix_internal_gamma_by_inserting_nodes(16);
1623 output_dot("step17-before-ycbcr.dot");
1624 add_ycbcr_conversion_if_needed();
1626 output_dot("step18-before-dither.dot");
1627 add_dither_if_needed();
1629 output_dot("step19-final.dot");
1631 // Construct all needed GLSL programs, starting at the output.
1632 // We need to keep track of which effects have already been computed,
1633 // as an effect with multiple users could otherwise be calculated
1635 map<Node *, Phase *> completed_effects;
1636 construct_phase(find_output_node(), &completed_effects);
1638 output_dot("step20-split-to-phases.dot");
1640 assert(phases[0]->inputs.empty());
1645 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1649 // This needs to be set anew, in case we are coming from a different context
1650 // from when we initialized.
1652 glDisable(GL_DITHER);
1655 // Save original viewport.
1656 GLuint x = 0, y = 0;
1658 if (width == 0 && height == 0) {
1660 glGetIntegerv(GL_VIEWPORT, viewport);
1663 width = viewport[2];
1664 height = viewport[3];
1669 glDisable(GL_BLEND);
1671 glDisable(GL_DEPTH_TEST);
1673 glDepthMask(GL_FALSE);
1676 // Generate a VAO. All the phases should have exactly the same vertex attributes,
1677 // so it's safe to reuse this.
1678 float vertices[] = {
1685 glGenVertexArrays(1, &vao);
1687 glBindVertexArray(vao);
1690 GLuint position_vbo = fill_vertex_attribute(phases[0]->glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1691 GLuint texcoord_vbo = fill_vertex_attribute(phases[0]->glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1693 set<Phase *> generated_mipmaps;
1695 // We choose the simplest option of having one texture per output,
1696 // since otherwise this turns into an (albeit simple) register allocation problem.
1697 map<Phase *, GLuint> output_textures;
1699 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1700 Phase *phase = phases[phase_num];
1702 if (do_phase_timing) {
1703 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1705 if (phase_num == phases.size() - 1) {
1706 // Last phase goes to the output the user specified.
1707 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1709 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1710 assert(status == GL_FRAMEBUFFER_COMPLETE);
1711 glViewport(x, y, width, height);
1712 if (dither_effect != NULL) {
1713 CHECK(dither_effect->set_int("output_width", width));
1714 CHECK(dither_effect->set_int("output_height", height));
1717 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1718 if (do_phase_timing) {
1719 glEndQuery(GL_TIME_ELAPSED);
1723 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1724 texture_it != output_textures.end();
1726 resource_pool->release_2d_texture(texture_it->second);
1729 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1734 cleanup_vertex_attribute(phases[0]->glsl_program_num, "position", position_vbo);
1735 cleanup_vertex_attribute(phases[0]->glsl_program_num, "texcoord", texcoord_vbo);
1737 glDeleteVertexArrays(1, &vao);
1740 if (do_phase_timing) {
1741 // Get back the timer queries.
1742 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1743 Phase *phase = phases[phase_num];
1744 GLint available = 0;
1745 while (!available) {
1746 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1748 GLuint64 time_elapsed;
1749 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1750 phase->time_elapsed_ns += time_elapsed;
1751 ++phase->num_measured_iterations;
1756 void EffectChain::enable_phase_timing(bool enable)
1759 assert(movit_timer_queries_supported);
1761 this->do_phase_timing = enable;
1764 void EffectChain::reset_phase_timing()
1766 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1767 Phase *phase = phases[phase_num];
1768 phase->time_elapsed_ns = 0;
1769 phase->num_measured_iterations = 0;
1773 void EffectChain::print_phase_timing()
1775 double total_time_ms = 0.0;
1776 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1777 Phase *phase = phases[phase_num];
1778 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1779 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1780 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1781 if (effect_num != 0) {
1784 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1787 total_time_ms += avg_time_ms;
1789 printf("Total: %5.1f ms\n", total_time_ms);
1792 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1796 // Find a texture for this phase.
1797 inform_input_sizes(phase);
1799 find_output_size(phase);
1801 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1802 output_textures->insert(make_pair(phase, tex_num));
1805 const GLuint glsl_program_num = phase->glsl_program_num;
1807 glUseProgram(glsl_program_num);
1810 // Set up RTT inputs for this phase.
1811 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1812 glActiveTexture(GL_TEXTURE0 + sampler);
1813 Phase *input = phase->inputs[sampler];
1814 input->output_node->bound_sampler_num = sampler;
1815 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1817 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1818 glGenerateMipmap(GL_TEXTURE_2D);
1820 generated_mipmaps->insert(input);
1822 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
1823 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
1826 // And now the output. (Already set up for us if it is the last phase.)
1828 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1829 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1830 glViewport(0, 0, phase->output_width, phase->output_height);
1833 // Give the required parameters to all the effects.
1834 unsigned sampler_num = phase->inputs.size();
1835 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1836 Node *node = phase->effects[i];
1837 unsigned old_sampler_num = sampler_num;
1838 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1841 if (node->effect->is_single_texture()) {
1842 assert(sampler_num - old_sampler_num == 1);
1843 node->bound_sampler_num = old_sampler_num;
1845 node->bound_sampler_num = -1;
1849 // Uniforms need to come after set_gl_state(), since they can be updated
1851 setup_uniforms(phase);
1853 glDrawArrays(GL_TRIANGLES, 0, 3);
1859 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1860 Node *node = phase->effects[i];
1861 node->effect->clear_gl_state();
1865 resource_pool->release_fbo(fbo);
1869 void EffectChain::setup_uniforms(Phase *phase)
1871 // TODO: Use UBO blocks.
1872 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
1873 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
1874 if (uniform.location != -1) {
1875 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1878 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
1879 const Uniform<bool> &uniform = phase->uniforms_bool[i];
1880 assert(uniform.num_values == 1);
1881 if (uniform.location != -1) {
1882 glUniform1i(uniform.location, *uniform.value);
1885 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
1886 const Uniform<int> &uniform = phase->uniforms_int[i];
1887 if (uniform.location != -1) {
1888 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1891 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
1892 const Uniform<float> &uniform = phase->uniforms_float[i];
1893 if (uniform.location != -1) {
1894 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
1897 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
1898 const Uniform<float> &uniform = phase->uniforms_vec2[i];
1899 if (uniform.location != -1) {
1900 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
1903 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
1904 const Uniform<float> &uniform = phase->uniforms_vec3[i];
1905 if (uniform.location != -1) {
1906 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
1909 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
1910 const Uniform<float> &uniform = phase->uniforms_vec4[i];
1911 if (uniform.location != -1) {
1912 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
1915 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
1916 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
1917 assert(uniform.num_values == 1);
1918 if (uniform.location != -1) {
1919 // Convert to float (GLSL has no double matrices).
1921 for (unsigned y = 0; y < 3; ++y) {
1922 for (unsigned x = 0; x < 3; ++x) {
1923 matrixf[y + x * 3] = (*uniform.value)(y, x);
1926 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
1931 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
1933 glActiveTexture(GL_TEXTURE0 + sampler_num);
1936 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1939 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1942 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1944 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1948 } // namespace movit