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),
43 resource_pool(resource_pool),
44 do_phase_timing(false) {
45 if (resource_pool == NULL) {
46 this->resource_pool = new ResourcePool();
47 owns_resource_pool = true;
49 owns_resource_pool = false;
53 EffectChain::~EffectChain()
55 for (unsigned i = 0; i < nodes.size(); ++i) {
56 delete nodes[i]->effect;
59 for (unsigned i = 0; i < phases.size(); ++i) {
60 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
63 if (owns_resource_pool) {
68 Input *EffectChain::add_input(Input *input)
71 inputs.push_back(input);
76 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
79 output_format = format;
80 output_alpha_format = alpha_format;
81 output_color_type = OUTPUT_COLOR_RGB;
84 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
85 const YCbCrFormat &ycbcr_format)
88 output_format = format;
89 output_alpha_format = alpha_format;
90 output_color_type = OUTPUT_COLOR_YCBCR;
91 output_ycbcr_format = ycbcr_format;
93 assert(ycbcr_format.chroma_subsampling_x == 1);
94 assert(ycbcr_format.chroma_subsampling_y == 1);
97 Node *EffectChain::add_node(Effect *effect)
99 for (unsigned i = 0; i < nodes.size(); ++i) {
100 assert(nodes[i]->effect != effect);
103 Node *node = new Node;
104 node->effect = effect;
105 node->disabled = false;
106 node->output_color_space = COLORSPACE_INVALID;
107 node->output_gamma_curve = GAMMA_INVALID;
108 node->output_alpha_type = ALPHA_INVALID;
109 node->needs_mipmaps = false;
110 node->one_to_one_sampling = false;
112 nodes.push_back(node);
113 node_map[effect] = node;
114 effect->inform_added(this);
118 void EffectChain::connect_nodes(Node *sender, Node *receiver)
120 sender->outgoing_links.push_back(receiver);
121 receiver->incoming_links.push_back(sender);
124 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
126 new_receiver->incoming_links = old_receiver->incoming_links;
127 old_receiver->incoming_links.clear();
129 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
130 Node *sender = new_receiver->incoming_links[i];
131 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
132 if (sender->outgoing_links[j] == old_receiver) {
133 sender->outgoing_links[j] = new_receiver;
139 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
141 new_sender->outgoing_links = old_sender->outgoing_links;
142 old_sender->outgoing_links.clear();
144 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
145 Node *receiver = new_sender->outgoing_links[i];
146 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
147 if (receiver->incoming_links[j] == old_sender) {
148 receiver->incoming_links[j] = new_sender;
154 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
156 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
157 if (sender->outgoing_links[i] == receiver) {
158 sender->outgoing_links[i] = middle;
159 middle->incoming_links.push_back(sender);
162 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
163 if (receiver->incoming_links[i] == sender) {
164 receiver->incoming_links[i] = middle;
165 middle->outgoing_links.push_back(receiver);
169 assert(middle->incoming_links.size() == middle->effect->num_inputs());
172 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
174 assert(node->effect->needs_texture_bounce());
175 assert(input_num < node->incoming_links.size());
176 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
177 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
178 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
181 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
183 if (node->output_gamma_curve == GAMMA_LINEAR &&
184 node->effect->effect_type_id() != "GammaCompressionEffect") {
187 if (node->effect->num_inputs() == 0) {
188 nonlinear_inputs->push_back(node);
190 assert(node->effect->num_inputs() == node->incoming_links.size());
191 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
192 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
197 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
200 assert(inputs.size() == effect->num_inputs());
201 Node *node = add_node(effect);
202 for (unsigned i = 0; i < inputs.size(); ++i) {
203 assert(node_map.count(inputs[i]) != 0);
204 connect_nodes(node_map[inputs[i]], node);
209 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
210 string replace_prefix(const string &text, const string &prefix)
215 while (start < text.size()) {
216 size_t pos = text.find("PREFIX(", start);
217 if (pos == string::npos) {
218 output.append(text.substr(start, string::npos));
222 output.append(text.substr(start, pos - start));
223 output.append(prefix);
226 pos += strlen("PREFIX(");
228 // Output stuff until we find the matching ), which we then eat.
230 size_t end_arg_pos = pos;
231 while (end_arg_pos < text.size()) {
232 if (text[end_arg_pos] == '(') {
234 } else if (text[end_arg_pos] == ')') {
242 output.append(text.substr(pos, end_arg_pos - pos));
250 void EffectChain::compile_glsl_program(Phase *phase)
252 string frag_shader_header = read_version_dependent_file("header", "frag");
253 string frag_shader = "";
255 // Create functions for all the texture inputs that we need.
256 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
257 Node *input = phase->inputs[i]->output_node;
259 sprintf(effect_id, "in%u", i);
260 phase->effect_ids.insert(make_pair(input, effect_id));
262 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
263 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
264 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
265 frag_shader += "}\n";
269 // Give each effect in the phase its own ID.
270 for (unsigned i = 0; i < phase->effects.size(); ++i) {
271 Node *node = phase->effects[i];
273 sprintf(effect_id, "eff%u", i);
274 phase->effect_ids.insert(make_pair(node, effect_id));
277 for (unsigned i = 0; i < phase->effects.size(); ++i) {
278 Node *node = phase->effects[i];
279 const string effect_id = phase->effect_ids[node];
280 if (node->incoming_links.size() == 1) {
281 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
283 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
285 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
291 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
292 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
293 frag_shader += "#undef PREFIX\n";
294 frag_shader += "#undef FUNCNAME\n";
295 if (node->incoming_links.size() == 1) {
296 frag_shader += "#undef INPUT\n";
298 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
300 sprintf(buf, "#undef INPUT%d\n", j + 1);
306 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
307 frag_shader.append(read_version_dependent_file("footer", "frag"));
309 // Collect uniforms from all effects and output them. Note that this needs
310 // to happen after output_fragment_shader(), even though the uniforms come
311 // before in the output source, since output_fragment_shader() is allowed
312 // to register new uniforms (e.g. arrays that are of unknown length until
313 // finalization time).
314 // TODO: Make a uniform block for platforms that support it.
315 string frag_shader_uniforms = "";
316 for (unsigned i = 0; i < phase->effects.size(); ++i) {
317 Node *node = phase->effects[i];
318 Effect *effect = node->effect;
319 const string effect_id = phase->effect_ids[node];
320 for (unsigned j = 0; j < effect->uniforms_bool.size(); ++j) {
321 phase->uniforms_bool.push_back(effect->uniforms_bool[j]);
322 phase->uniforms_bool.back().prefix = effect_id;
323 frag_shader_uniforms += string("uniform bool ") + effect_id
324 + "_" + effect->uniforms_bool[j].name + ";\n";
326 for (unsigned j = 0; j < effect->uniforms_int.size(); ++j) {
327 phase->uniforms_int.push_back(effect->uniforms_int[j]);
328 phase->uniforms_int.back().prefix = effect_id;
329 frag_shader_uniforms += string("uniform int ") + effect_id
330 + "_" + effect->uniforms_int[j].name + ";\n";
332 for (unsigned j = 0; j < effect->uniforms_sampler2d.size(); ++j) {
333 phase->uniforms_int.push_back(effect->uniforms_sampler2d[j]);
334 phase->uniforms_int.back().prefix = effect_id;
335 frag_shader_uniforms += string("uniform sampler2D ") + effect_id
336 + "_" + effect->uniforms_sampler2d[j].name + ";\n";
338 for (unsigned j = 0; j < effect->uniforms_float.size(); ++j) {
339 phase->uniforms_float.push_back(effect->uniforms_float[j]);
340 phase->uniforms_float.back().prefix = effect_id;
341 frag_shader_uniforms += string("uniform float ") + effect_id
342 + "_" + effect->uniforms_float[j].name + ";\n";
344 for (unsigned j = 0; j < effect->uniforms_vec2.size(); ++j) {
345 phase->uniforms_vec2.push_back(effect->uniforms_vec2[j]);
346 phase->uniforms_vec2.back().prefix = effect_id;
347 frag_shader_uniforms += string("uniform vec2 ") + effect_id
348 + "_" + effect->uniforms_vec2[j].name + ";\n";
350 for (unsigned j = 0; j < effect->uniforms_vec3.size(); ++j) {
351 phase->uniforms_vec3.push_back(effect->uniforms_vec3[j]);
352 phase->uniforms_vec3.back().prefix = effect_id;
353 frag_shader_uniforms += string("uniform vec3 ") + effect_id
354 + "_" + effect->uniforms_vec3[j].name + ";\n";
356 for (unsigned j = 0; j < effect->uniforms_vec4.size(); ++j) {
357 phase->uniforms_vec4.push_back(effect->uniforms_vec4[j]);
358 phase->uniforms_vec4.back().prefix = effect_id;
359 frag_shader_uniforms += string("uniform vec4 ") + effect_id
360 + "_" + effect->uniforms_vec4[j].name + ";\n";
362 for (unsigned j = 0; j < effect->uniforms_vec2_array.size(); ++j) {
364 phase->uniforms_vec2.push_back(effect->uniforms_vec2_array[j]);
365 phase->uniforms_vec2.back().prefix = effect_id;
366 snprintf(buf, sizeof(buf), "uniform vec2 %s_%s[%d];\n",
367 effect_id.c_str(), effect->uniforms_vec2_array[j].name.c_str(),
368 int(effect->uniforms_vec2_array[j].num_values));
369 frag_shader_uniforms += buf;
371 for (unsigned j = 0; j < effect->uniforms_vec4_array.size(); ++j) {
373 phase->uniforms_vec4.push_back(effect->uniforms_vec4_array[j]);
374 phase->uniforms_vec4.back().prefix = effect_id;
375 snprintf(buf, sizeof(buf), "uniform vec4 %s_%s[%d];\n",
376 effect_id.c_str(), effect->uniforms_vec4_array[j].name.c_str(),
377 int(effect->uniforms_vec4_array[j].num_values));
378 frag_shader_uniforms += buf;
380 for (unsigned j = 0; j < effect->uniforms_mat3.size(); ++j) {
381 phase->uniforms_mat3.push_back(effect->uniforms_mat3[j]);
382 phase->uniforms_mat3.back().prefix = effect_id;
383 frag_shader_uniforms += string("uniform mat3 ") + effect_id
384 + "_" + effect->uniforms_mat3[j].name + ";\n";
388 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
390 string vert_shader = read_version_dependent_file("vs", "vert");
391 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
393 // Collect the resulting program numbers for each uniform.
394 for (unsigned i = 0; i < phase->uniforms_bool.size(); ++i) {
395 Uniform<bool> &uniform = phase->uniforms_bool[i];
396 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
398 for (unsigned i = 0; i < phase->uniforms_int.size(); ++i) {
399 Uniform<int> &uniform = phase->uniforms_int[i];
400 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
402 for (unsigned i = 0; i < phase->uniforms_float.size(); ++i) {
403 Uniform<float> &uniform = phase->uniforms_float[i];
404 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
406 for (unsigned i = 0; i < phase->uniforms_vec2.size(); ++i) {
407 Uniform<float> &uniform = phase->uniforms_vec2[i];
408 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
410 for (unsigned i = 0; i < phase->uniforms_vec3.size(); ++i) {
411 Uniform<float> &uniform = phase->uniforms_vec3[i];
412 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
414 for (unsigned i = 0; i < phase->uniforms_vec4.size(); ++i) {
415 Uniform<float> &uniform = phase->uniforms_vec4[i];
416 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
418 for (unsigned i = 0; i < phase->uniforms_mat3.size(); ++i) {
419 Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
420 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
424 // Construct GLSL programs, starting at the given effect and following
425 // the chain from there. We end a program every time we come to an effect
426 // marked as "needs texture bounce", one that is used by multiple other
427 // effects, every time we need to bounce due to output size change
428 // (not all size changes require ending), and of course at the end.
430 // We follow a quite simple depth-first search from the output, although
431 // without recursing explicitly within each phase.
432 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
434 if (completed_effects->count(output)) {
435 return (*completed_effects)[output];
438 Phase *phase = new Phase;
439 phase->output_node = output;
441 // If the output effect has one-to-one sampling, we try to trace this
442 // status down through the dependency chain. This is important in case
443 // we hit an effect that changes output size (and not sets a virtual
444 // output size); if we have one-to-one sampling, we don't have to break
446 output->one_to_one_sampling = output->effect->one_to_one_sampling();
448 // Effects that we have yet to calculate, but that we know should
449 // be in the current phase.
450 stack<Node *> effects_todo_this_phase;
451 effects_todo_this_phase.push(output);
453 while (!effects_todo_this_phase.empty()) {
454 Node *node = effects_todo_this_phase.top();
455 effects_todo_this_phase.pop();
457 if (node->effect->needs_mipmaps()) {
458 node->needs_mipmaps = true;
461 // This should currently only happen for effects that are inputs
462 // (either true inputs or phase outputs). We special-case inputs,
463 // and then deduplicate phase outputs below.
464 if (node->effect->num_inputs() == 0) {
465 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
469 assert(completed_effects->count(node) == 0);
472 phase->effects.push_back(node);
474 // Find all the dependencies of this effect, and add them to the stack.
475 vector<Node *> deps = node->incoming_links;
476 assert(node->effect->num_inputs() == deps.size());
477 for (unsigned i = 0; i < deps.size(); ++i) {
478 bool start_new_phase = false;
480 if (node->effect->needs_texture_bounce() &&
481 !deps[i]->effect->is_single_texture()) {
482 start_new_phase = true;
485 // Propagate information about needing mipmaps down the chain,
486 // breaking the phase if we notice an incompatibility.
488 // Note that we cannot do this propagation as a normal pass,
489 // because it needs information about where the phases end
490 // (we should not propagate the flag across phases).
491 if (node->needs_mipmaps) {
492 if (deps[i]->effect->num_inputs() == 0) {
493 Input *input = static_cast<Input *>(deps[i]->effect);
494 start_new_phase |= !input->can_supply_mipmaps();
496 deps[i]->needs_mipmaps = true;
500 if (deps[i]->outgoing_links.size() > 1) {
501 if (!deps[i]->effect->is_single_texture()) {
502 // More than one effect uses this as the input,
503 // and it is not a texture itself.
504 // The easiest thing to do (and probably also the safest
505 // performance-wise in most cases) is to bounce it to a texture
506 // and then let the next passes read from that.
507 start_new_phase = true;
509 assert(deps[i]->effect->num_inputs() == 0);
511 // For textures, we try to be slightly more clever;
512 // if none of our outputs need a bounce, we don't bounce
513 // but instead simply use the effect many times.
515 // Strictly speaking, we could bounce it for some outputs
516 // and use it directly for others, but the processing becomes
517 // somewhat simpler if the effect is only used in one such way.
518 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
519 Node *rdep = deps[i]->outgoing_links[j];
520 start_new_phase |= rdep->effect->needs_texture_bounce();
525 if (deps[i]->effect->sets_virtual_output_size()) {
526 assert(deps[i]->effect->changes_output_size());
527 // If the next effect sets a virtual size to rely on OpenGL's
528 // bilinear sampling, we'll really need to break the phase here.
529 start_new_phase = true;
530 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
531 // If the next effect changes size and we don't have one-to-one sampling,
532 // we also need to break here.
533 start_new_phase = true;
536 if (start_new_phase) {
537 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
539 effects_todo_this_phase.push(deps[i]);
541 // Propagate the one-to-one status down through the dependency.
542 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
543 deps[i]->effect->one_to_one_sampling();
548 // No more effects to do this phase. Take all the ones we have,
549 // and create a GLSL program for it.
550 assert(!phase->effects.empty());
552 // Deduplicate the inputs.
553 sort(phase->inputs.begin(), phase->inputs.end());
554 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
556 // We added the effects from the output and back, but we need to output
557 // them in topological sort order in the shader.
558 phase->effects = topological_sort(phase->effects);
560 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
561 phase->input_needs_mipmaps = false;
562 for (unsigned i = 0; i < phase->effects.size(); ++i) {
563 Node *node = phase->effects[i];
564 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
566 for (unsigned i = 0; i < phase->effects.size(); ++i) {
567 Node *node = phase->effects[i];
568 if (node->effect->num_inputs() == 0) {
569 Input *input = static_cast<Input *>(node->effect);
570 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
571 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
575 // Tell each node which phase it ended up in, so that the unit test
576 // can check that the phases were split in the right place.
577 // Note that this ignores that effects may be part of multiple phases;
578 // if the unit tests need to test such cases, we'll reconsider.
579 for (unsigned i = 0; i < phase->effects.size(); ++i) {
580 phase->effects[i]->containing_phase = phase;
583 // Actually make the shader for this phase.
584 compile_glsl_program(phase);
586 // Initialize timer objects.
587 if (movit_timer_queries_supported) {
588 glGenQueries(1, &phase->timer_query_object);
589 phase->time_elapsed_ns = 0;
590 phase->num_measured_iterations = 0;
593 assert(completed_effects->count(output) == 0);
594 completed_effects->insert(make_pair(output, phase));
595 phases.push_back(phase);
599 void EffectChain::output_dot(const char *filename)
601 if (movit_debug_level != MOVIT_DEBUG_ON) {
605 FILE *fp = fopen(filename, "w");
611 fprintf(fp, "digraph G {\n");
612 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
613 for (unsigned i = 0; i < nodes.size(); ++i) {
614 // Find out which phase this event belongs to.
615 vector<int> in_phases;
616 for (unsigned j = 0; j < phases.size(); ++j) {
617 const Phase* p = phases[j];
618 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
619 in_phases.push_back(j);
623 if (in_phases.empty()) {
624 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
625 } else if (in_phases.size() == 1) {
626 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
627 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
628 (in_phases[0] % 8) + 1);
630 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
632 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
633 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
634 (in_phases[0] % 8) + 1);
637 char from_node_id[256];
638 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
640 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
641 char to_node_id[256];
642 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
644 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
645 output_dot_edge(fp, from_node_id, to_node_id, labels);
648 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
650 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
651 output_dot_edge(fp, from_node_id, "output", labels);
659 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
661 vector<string> labels;
663 if (to != NULL && to->effect->needs_texture_bounce()) {
664 labels.push_back("needs_bounce");
666 if (from->effect->changes_output_size()) {
667 labels.push_back("resize");
670 switch (from->output_color_space) {
671 case COLORSPACE_INVALID:
672 labels.push_back("spc[invalid]");
674 case COLORSPACE_REC_601_525:
675 labels.push_back("spc[rec601-525]");
677 case COLORSPACE_REC_601_625:
678 labels.push_back("spc[rec601-625]");
684 switch (from->output_gamma_curve) {
686 labels.push_back("gamma[invalid]");
689 labels.push_back("gamma[sRGB]");
691 case GAMMA_REC_601: // and GAMMA_REC_709
692 labels.push_back("gamma[rec601/709]");
698 switch (from->output_alpha_type) {
700 labels.push_back("alpha[invalid]");
703 labels.push_back("alpha[blank]");
705 case ALPHA_POSTMULTIPLIED:
706 labels.push_back("alpha[postmult]");
715 void EffectChain::output_dot_edge(FILE *fp,
716 const string &from_node_id,
717 const string &to_node_id,
718 const vector<string> &labels)
720 if (labels.empty()) {
721 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
723 string label = labels[0];
724 for (unsigned k = 1; k < labels.size(); ++k) {
725 label += ", " + labels[k];
727 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
731 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
733 unsigned scaled_width, scaled_height;
735 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
736 // Same aspect, or W/H > aspect (image is wider than the frame).
737 // In either case, keep width, and adjust height.
738 scaled_width = width;
739 scaled_height = lrintf(width * aspect_denom / aspect_nom);
741 // W/H < aspect (image is taller than the frame), so keep height,
743 scaled_width = lrintf(height * aspect_nom / aspect_denom);
744 scaled_height = height;
747 // We should be consistently larger or smaller then the existing choice,
748 // since we have the same aspect.
749 assert(!(scaled_width < *output_width && scaled_height > *output_height));
750 assert(!(scaled_height < *output_height && scaled_width > *output_width));
752 if (scaled_width >= *output_width && scaled_height >= *output_height) {
753 *output_width = scaled_width;
754 *output_height = scaled_height;
758 // Propagate input texture sizes throughout, and inform effects downstream.
759 // (Like a lot of other code, we depend on effects being in topological order.)
760 void EffectChain::inform_input_sizes(Phase *phase)
762 // All effects that have a defined size (inputs and RTT inputs)
763 // get that. Reset all others.
764 for (unsigned i = 0; i < phase->effects.size(); ++i) {
765 Node *node = phase->effects[i];
766 if (node->effect->num_inputs() == 0) {
767 Input *input = static_cast<Input *>(node->effect);
768 node->output_width = input->get_width();
769 node->output_height = input->get_height();
770 assert(node->output_width != 0);
771 assert(node->output_height != 0);
773 node->output_width = node->output_height = 0;
776 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
777 Phase *input = phase->inputs[i];
778 input->output_node->output_width = input->virtual_output_width;
779 input->output_node->output_height = input->virtual_output_height;
780 assert(input->output_node->output_width != 0);
781 assert(input->output_node->output_height != 0);
784 // Now propagate from the inputs towards the end, and inform as we go.
785 // The rules are simple:
787 // 1. Don't touch effects that already have given sizes (ie., inputs
788 // or effects that change the output size).
789 // 2. If all of your inputs have the same size, that will be your output size.
790 // 3. Otherwise, your output size is 0x0.
791 for (unsigned i = 0; i < phase->effects.size(); ++i) {
792 Node *node = phase->effects[i];
793 if (node->effect->num_inputs() == 0) {
796 unsigned this_output_width = 0;
797 unsigned this_output_height = 0;
798 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
799 Node *input = node->incoming_links[j];
800 node->effect->inform_input_size(j, input->output_width, input->output_height);
802 this_output_width = input->output_width;
803 this_output_height = input->output_height;
804 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
806 this_output_width = 0;
807 this_output_height = 0;
810 if (node->effect->changes_output_size()) {
811 // We cannot call get_output_size() before we've done inform_input_size()
813 unsigned real_width, real_height;
814 node->effect->get_output_size(&real_width, &real_height,
815 &node->output_width, &node->output_height);
816 assert(node->effect->sets_virtual_output_size() ||
817 (real_width == node->output_width &&
818 real_height == node->output_height));
820 node->output_width = this_output_width;
821 node->output_height = this_output_height;
826 // Note: You should call inform_input_sizes() before this, as the last effect's
827 // desired output size might change based on the inputs.
828 void EffectChain::find_output_size(Phase *phase)
830 Node *output_node = phase->effects.back();
832 // If the last effect explicitly sets an output size, use that.
833 if (output_node->effect->changes_output_size()) {
834 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
835 &phase->virtual_output_width, &phase->virtual_output_height);
836 assert(output_node->effect->sets_virtual_output_size() ||
837 (phase->output_width == phase->virtual_output_width &&
838 phase->output_height == phase->virtual_output_height));
842 // If all effects have the same size, use that.
843 unsigned output_width = 0, output_height = 0;
844 bool all_inputs_same_size = true;
846 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
847 Phase *input = phase->inputs[i];
848 assert(input->output_width != 0);
849 assert(input->output_height != 0);
850 if (output_width == 0 && output_height == 0) {
851 output_width = input->virtual_output_width;
852 output_height = input->virtual_output_height;
853 } else if (output_width != input->virtual_output_width ||
854 output_height != input->virtual_output_height) {
855 all_inputs_same_size = false;
858 for (unsigned i = 0; i < phase->effects.size(); ++i) {
859 Effect *effect = phase->effects[i]->effect;
860 if (effect->num_inputs() != 0) {
864 Input *input = static_cast<Input *>(effect);
865 if (output_width == 0 && output_height == 0) {
866 output_width = input->get_width();
867 output_height = input->get_height();
868 } else if (output_width != input->get_width() ||
869 output_height != input->get_height()) {
870 all_inputs_same_size = false;
874 if (all_inputs_same_size) {
875 assert(output_width != 0);
876 assert(output_height != 0);
877 phase->virtual_output_width = phase->output_width = output_width;
878 phase->virtual_output_height = phase->output_height = output_height;
882 // If not, fit all the inputs into the current aspect, and select the largest one.
885 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
886 Phase *input = phase->inputs[i];
887 assert(input->output_width != 0);
888 assert(input->output_height != 0);
889 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
891 for (unsigned i = 0; i < phase->effects.size(); ++i) {
892 Effect *effect = phase->effects[i]->effect;
893 if (effect->num_inputs() != 0) {
897 Input *input = static_cast<Input *>(effect);
898 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
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;
906 void EffectChain::sort_all_nodes_topologically()
908 nodes = topological_sort(nodes);
911 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
913 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
914 vector<Node *> sorted_list;
915 for (unsigned i = 0; i < nodes.size(); ++i) {
916 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
918 reverse(sorted_list.begin(), sorted_list.end());
922 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
924 if (nodes_left_to_visit->count(node) == 0) {
927 nodes_left_to_visit->erase(node);
928 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
929 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
931 sorted_list->push_back(node);
934 void EffectChain::find_color_spaces_for_inputs()
936 for (unsigned i = 0; i < nodes.size(); ++i) {
937 Node *node = nodes[i];
938 if (node->disabled) {
941 if (node->incoming_links.size() == 0) {
942 Input *input = static_cast<Input *>(node->effect);
943 node->output_color_space = input->get_color_space();
944 node->output_gamma_curve = input->get_gamma_curve();
946 Effect::AlphaHandling alpha_handling = input->alpha_handling();
947 switch (alpha_handling) {
948 case Effect::OUTPUT_BLANK_ALPHA:
949 node->output_alpha_type = ALPHA_BLANK;
951 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
952 node->output_alpha_type = ALPHA_PREMULTIPLIED;
954 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
955 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
957 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
958 case Effect::DONT_CARE_ALPHA_TYPE:
963 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
964 assert(node->output_gamma_curve == GAMMA_LINEAR);
970 // Propagate gamma and color space information as far as we can in the graph.
971 // The rules are simple: Anything where all the inputs agree, get that as
972 // output as well. Anything else keeps having *_INVALID.
973 void EffectChain::propagate_gamma_and_color_space()
975 // We depend on going through the nodes in order.
976 sort_all_nodes_topologically();
978 for (unsigned i = 0; i < nodes.size(); ++i) {
979 Node *node = nodes[i];
980 if (node->disabled) {
983 assert(node->incoming_links.size() == node->effect->num_inputs());
984 if (node->incoming_links.size() == 0) {
985 assert(node->output_color_space != COLORSPACE_INVALID);
986 assert(node->output_gamma_curve != GAMMA_INVALID);
990 Colorspace color_space = node->incoming_links[0]->output_color_space;
991 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
992 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
993 if (node->incoming_links[j]->output_color_space != color_space) {
994 color_space = COLORSPACE_INVALID;
996 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
997 gamma_curve = GAMMA_INVALID;
1001 // The conversion effects already have their outputs set correctly,
1002 // so leave them alone.
1003 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1004 node->output_color_space = color_space;
1006 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1007 node->effect->effect_type_id() != "GammaExpansionEffect") {
1008 node->output_gamma_curve = gamma_curve;
1013 // Propagate alpha information as far as we can in the graph.
1014 // Similar to propagate_gamma_and_color_space().
1015 void EffectChain::propagate_alpha()
1017 // We depend on going through the nodes in order.
1018 sort_all_nodes_topologically();
1020 for (unsigned i = 0; i < nodes.size(); ++i) {
1021 Node *node = nodes[i];
1022 if (node->disabled) {
1025 assert(node->incoming_links.size() == node->effect->num_inputs());
1026 if (node->incoming_links.size() == 0) {
1027 assert(node->output_alpha_type != ALPHA_INVALID);
1031 // The alpha multiplication/division effects are special cases.
1032 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1033 assert(node->incoming_links.size() == 1);
1034 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1035 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1038 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1039 assert(node->incoming_links.size() == 1);
1040 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1041 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1045 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1046 // because they are the only one that _need_ postmultiplied alpha.
1047 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1048 node->effect->effect_type_id() == "GammaExpansionEffect") {
1049 assert(node->incoming_links.size() == 1);
1050 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1051 node->output_alpha_type = ALPHA_BLANK;
1052 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1053 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1055 node->output_alpha_type = ALPHA_INVALID;
1060 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1061 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1062 // taken care of above. Rationale: Even if you could imagine
1063 // e.g. an effect that took in an image and set alpha=1.0
1064 // unconditionally, it wouldn't make any sense to have it as
1065 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1066 // got its input pre- or postmultiplied, so it wouldn't know
1067 // whether to divide away the old alpha or not.
1068 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1069 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1070 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1071 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1073 // If the node has multiple inputs, check that they are all valid and
1075 bool any_invalid = false;
1076 bool any_premultiplied = false;
1077 bool any_postmultiplied = false;
1079 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1080 switch (node->incoming_links[j]->output_alpha_type) {
1085 // Blank is good as both pre- and postmultiplied alpha,
1086 // so just ignore it.
1088 case ALPHA_PREMULTIPLIED:
1089 any_premultiplied = true;
1091 case ALPHA_POSTMULTIPLIED:
1092 any_postmultiplied = true;
1100 node->output_alpha_type = ALPHA_INVALID;
1104 // Inputs must be of the same type.
1105 if (any_premultiplied && any_postmultiplied) {
1106 node->output_alpha_type = ALPHA_INVALID;
1110 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1111 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1112 // If the effect has asked for premultiplied alpha, check that it has got it.
1113 if (any_postmultiplied) {
1114 node->output_alpha_type = ALPHA_INVALID;
1115 } else if (!any_premultiplied &&
1116 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1117 // Blank input alpha, and the effect preserves blank alpha.
1118 node->output_alpha_type = ALPHA_BLANK;
1120 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1123 // OK, all inputs are the same, and this effect is not going
1125 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1126 if (any_premultiplied) {
1127 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1128 } else if (any_postmultiplied) {
1129 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1131 node->output_alpha_type = ALPHA_BLANK;
1137 bool EffectChain::node_needs_colorspace_fix(Node *node)
1139 if (node->disabled) {
1142 if (node->effect->num_inputs() == 0) {
1146 // propagate_gamma_and_color_space() has already set our output
1147 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1148 if (node->output_color_space == COLORSPACE_INVALID) {
1151 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1154 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1155 // the graph. Our strategy is not always optimal, but quite simple:
1156 // Find an effect that's as early as possible where the inputs are of
1157 // unacceptable colorspaces (that is, either different, or, if the effect only
1158 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1159 // propagate the information anew, and repeat until there are no more such
1161 void EffectChain::fix_internal_color_spaces()
1163 unsigned colorspace_propagation_pass = 0;
1167 for (unsigned i = 0; i < nodes.size(); ++i) {
1168 Node *node = nodes[i];
1169 if (!node_needs_colorspace_fix(node)) {
1173 // Go through each input that is not sRGB, and insert
1174 // a colorspace conversion after it.
1175 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1176 Node *input = node->incoming_links[j];
1177 assert(input->output_color_space != COLORSPACE_INVALID);
1178 if (input->output_color_space == COLORSPACE_sRGB) {
1181 Node *conversion = add_node(new ColorspaceConversionEffect());
1182 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1183 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1184 conversion->output_color_space = COLORSPACE_sRGB;
1185 replace_sender(input, conversion);
1186 connect_nodes(input, conversion);
1189 // Re-sort topologically, and propagate the new information.
1190 propagate_gamma_and_color_space();
1197 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1198 output_dot(filename);
1199 assert(colorspace_propagation_pass < 100);
1200 } while (found_any);
1202 for (unsigned i = 0; i < nodes.size(); ++i) {
1203 Node *node = nodes[i];
1204 if (node->disabled) {
1207 assert(node->output_color_space != COLORSPACE_INVALID);
1211 bool EffectChain::node_needs_alpha_fix(Node *node)
1213 if (node->disabled) {
1217 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1218 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1219 return (node->output_alpha_type == ALPHA_INVALID);
1222 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1223 // the graph. Similar to fix_internal_color_spaces().
1224 void EffectChain::fix_internal_alpha(unsigned step)
1226 unsigned alpha_propagation_pass = 0;
1230 for (unsigned i = 0; i < nodes.size(); ++i) {
1231 Node *node = nodes[i];
1232 if (!node_needs_alpha_fix(node)) {
1236 // If we need to fix up GammaExpansionEffect, then clearly something
1237 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1239 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1241 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1243 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1244 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1245 assert(node->incoming_links.size() == 1);
1246 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1247 desired_type = ALPHA_POSTMULTIPLIED;
1250 // Go through each input that is not premultiplied alpha, and insert
1251 // a conversion before it.
1252 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1253 Node *input = node->incoming_links[j];
1254 assert(input->output_alpha_type != ALPHA_INVALID);
1255 if (input->output_alpha_type == desired_type ||
1256 input->output_alpha_type == ALPHA_BLANK) {
1260 if (desired_type == ALPHA_PREMULTIPLIED) {
1261 conversion = add_node(new AlphaMultiplicationEffect());
1263 conversion = add_node(new AlphaDivisionEffect());
1265 conversion->output_alpha_type = desired_type;
1266 replace_sender(input, conversion);
1267 connect_nodes(input, conversion);
1270 // Re-sort topologically, and propagate the new information.
1271 propagate_gamma_and_color_space();
1279 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1280 output_dot(filename);
1281 assert(alpha_propagation_pass < 100);
1282 } while (found_any);
1284 for (unsigned i = 0; i < nodes.size(); ++i) {
1285 Node *node = nodes[i];
1286 if (node->disabled) {
1289 assert(node->output_alpha_type != ALPHA_INVALID);
1293 // Make so that the output is in the desired color space.
1294 void EffectChain::fix_output_color_space()
1296 Node *output = find_output_node();
1297 if (output->output_color_space != output_format.color_space) {
1298 Node *conversion = add_node(new ColorspaceConversionEffect());
1299 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1300 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1301 conversion->output_color_space = output_format.color_space;
1302 connect_nodes(output, conversion);
1304 propagate_gamma_and_color_space();
1308 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1309 void EffectChain::fix_output_alpha()
1311 Node *output = find_output_node();
1312 assert(output->output_alpha_type != ALPHA_INVALID);
1313 if (output->output_alpha_type == ALPHA_BLANK) {
1314 // No alpha output, so we don't care.
1317 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1318 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1319 Node *conversion = add_node(new AlphaDivisionEffect());
1320 connect_nodes(output, conversion);
1322 propagate_gamma_and_color_space();
1324 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1325 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1326 Node *conversion = add_node(new AlphaMultiplicationEffect());
1327 connect_nodes(output, conversion);
1329 propagate_gamma_and_color_space();
1333 bool EffectChain::node_needs_gamma_fix(Node *node)
1335 if (node->disabled) {
1339 // Small hack since the output is not an explicit node:
1340 // If we are the last node and our output is in the wrong
1341 // space compared to EffectChain's output, we need to fix it.
1342 // This will only take us to linear, but fix_output_gamma()
1343 // will come and take us to the desired output gamma
1346 // This needs to be before everything else, since it could
1347 // even apply to inputs (if they are the only effect).
1348 if (node->outgoing_links.empty() &&
1349 node->output_gamma_curve != output_format.gamma_curve &&
1350 node->output_gamma_curve != GAMMA_LINEAR) {
1354 if (node->effect->num_inputs() == 0) {
1358 // propagate_gamma_and_color_space() has already set our output
1359 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1360 // except for GammaCompressionEffect.
1361 if (node->output_gamma_curve == GAMMA_INVALID) {
1364 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1365 assert(node->incoming_links.size() == 1);
1366 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1369 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1372 // Very similar to fix_internal_color_spaces(), but for gamma.
1373 // There is one difference, though; before we start adding conversion nodes,
1374 // we see if we can get anything out of asking the sources to deliver
1375 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1376 // does that part, while fix_internal_gamma_by_inserting_nodes()
1377 // inserts nodes as needed afterwards.
1378 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1380 unsigned gamma_propagation_pass = 0;
1384 for (unsigned i = 0; i < nodes.size(); ++i) {
1385 Node *node = nodes[i];
1386 if (!node_needs_gamma_fix(node)) {
1390 // See if all inputs can give us linear gamma. If not, leave it.
1391 vector<Node *> nonlinear_inputs;
1392 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1393 assert(!nonlinear_inputs.empty());
1396 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1397 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1398 all_ok &= input->can_output_linear_gamma();
1405 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1406 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1407 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1410 // Re-sort topologically, and propagate the new information.
1411 propagate_gamma_and_color_space();
1418 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1419 output_dot(filename);
1420 assert(gamma_propagation_pass < 100);
1421 } while (found_any);
1424 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1426 unsigned gamma_propagation_pass = 0;
1430 for (unsigned i = 0; i < nodes.size(); ++i) {
1431 Node *node = nodes[i];
1432 if (!node_needs_gamma_fix(node)) {
1436 // Special case: We could be an input and still be asked to
1437 // fix our gamma; if so, we should be the only node
1438 // (as node_needs_gamma_fix() would only return true in
1439 // for an input in that case). That means we should insert
1440 // a conversion node _after_ ourselves.
1441 if (node->incoming_links.empty()) {
1442 assert(node->outgoing_links.empty());
1443 Node *conversion = add_node(new GammaExpansionEffect());
1444 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1445 conversion->output_gamma_curve = GAMMA_LINEAR;
1446 connect_nodes(node, conversion);
1449 // If not, go through each input that is not linear gamma,
1450 // and insert a gamma conversion after it.
1451 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1452 Node *input = node->incoming_links[j];
1453 assert(input->output_gamma_curve != GAMMA_INVALID);
1454 if (input->output_gamma_curve == GAMMA_LINEAR) {
1457 Node *conversion = add_node(new GammaExpansionEffect());
1458 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1459 conversion->output_gamma_curve = GAMMA_LINEAR;
1460 replace_sender(input, conversion);
1461 connect_nodes(input, conversion);
1464 // Re-sort topologically, and propagate the new information.
1466 propagate_gamma_and_color_space();
1473 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1474 output_dot(filename);
1475 assert(gamma_propagation_pass < 100);
1476 } while (found_any);
1478 for (unsigned i = 0; i < nodes.size(); ++i) {
1479 Node *node = nodes[i];
1480 if (node->disabled) {
1483 assert(node->output_gamma_curve != GAMMA_INVALID);
1487 // Make so that the output is in the desired gamma.
1488 // Note that this assumes linear input gamma, so it might create the need
1489 // for another pass of fix_internal_gamma().
1490 void EffectChain::fix_output_gamma()
1492 Node *output = find_output_node();
1493 if (output->output_gamma_curve != output_format.gamma_curve) {
1494 Node *conversion = add_node(new GammaCompressionEffect());
1495 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1496 conversion->output_gamma_curve = output_format.gamma_curve;
1497 connect_nodes(output, conversion);
1501 // If the user has requested Y'CbCr output, we need to do this conversion
1502 // _after_ GammaCompressionEffect etc., but before dither (see below).
1503 // This is because Y'CbCr, with the exception of a special optional mode
1504 // in Rec. 2020 (which we currently don't support), is defined to work on
1505 // gamma-encoded data.
1506 void EffectChain::add_ycbcr_conversion_if_needed()
1508 assert(output_color_type == OUTPUT_COLOR_RGB || output_color_type == OUTPUT_COLOR_YCBCR);
1509 if (output_color_type != OUTPUT_COLOR_YCBCR) {
1512 Node *output = find_output_node();
1513 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1514 connect_nodes(output, ycbcr);
1517 // If the user has requested dither, add a DitherEffect right at the end
1518 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1519 // since dither is about the only effect that can _not_ be done in linear space.
1520 void EffectChain::add_dither_if_needed()
1522 if (num_dither_bits == 0) {
1525 Node *output = find_output_node();
1526 Node *dither = add_node(new DitherEffect());
1527 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1528 connect_nodes(output, dither);
1530 dither_effect = dither->effect;
1533 // Find the output node. This is, simply, one that has no outgoing links.
1534 // If there are multiple ones, the graph is malformed (we do not support
1535 // multiple outputs right now).
1536 Node *EffectChain::find_output_node()
1538 vector<Node *> output_nodes;
1539 for (unsigned i = 0; i < nodes.size(); ++i) {
1540 Node *node = nodes[i];
1541 if (node->disabled) {
1544 if (node->outgoing_links.empty()) {
1545 output_nodes.push_back(node);
1548 assert(output_nodes.size() == 1);
1549 return output_nodes[0];
1552 void EffectChain::finalize()
1554 // Output the graph as it is before we do any conversions on it.
1555 output_dot("step0-start.dot");
1557 // Give each effect in turn a chance to rewrite its own part of the graph.
1558 // Note that if more effects are added as part of this, they will be
1559 // picked up as part of the same for loop, since they are added at the end.
1560 for (unsigned i = 0; i < nodes.size(); ++i) {
1561 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1563 output_dot("step1-rewritten.dot");
1565 find_color_spaces_for_inputs();
1566 output_dot("step2-input-colorspace.dot");
1569 output_dot("step3-propagated-alpha.dot");
1571 propagate_gamma_and_color_space();
1572 output_dot("step4-propagated-all.dot");
1574 fix_internal_color_spaces();
1575 fix_internal_alpha(6);
1576 fix_output_color_space();
1577 output_dot("step7-output-colorspacefix.dot");
1579 output_dot("step8-output-alphafix.dot");
1581 // Note that we need to fix gamma after colorspace conversion,
1582 // because colorspace conversions might create needs for gamma conversions.
1583 // Also, we need to run an extra pass of fix_internal_gamma() after
1584 // fixing the output gamma, as we only have conversions to/from linear,
1585 // and fix_internal_alpha() since GammaCompressionEffect needs
1586 // postmultiplied input.
1587 fix_internal_gamma_by_asking_inputs(9);
1588 fix_internal_gamma_by_inserting_nodes(10);
1590 output_dot("step11-output-gammafix.dot");
1592 output_dot("step12-output-alpha-propagated.dot");
1593 fix_internal_alpha(13);
1594 output_dot("step14-output-alpha-fixed.dot");
1595 fix_internal_gamma_by_asking_inputs(15);
1596 fix_internal_gamma_by_inserting_nodes(16);
1598 output_dot("step17-before-ycbcr.dot");
1599 add_ycbcr_conversion_if_needed();
1601 output_dot("step18-before-dither.dot");
1602 add_dither_if_needed();
1604 output_dot("step19-final.dot");
1606 // Construct all needed GLSL programs, starting at the output.
1607 // We need to keep track of which effects have already been computed,
1608 // as an effect with multiple users could otherwise be calculated
1610 map<Node *, Phase *> completed_effects;
1611 construct_phase(find_output_node(), &completed_effects);
1613 output_dot("step20-split-to-phases.dot");
1615 assert(phases[0]->inputs.empty());
1620 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1624 // Save original viewport.
1625 GLuint x = 0, y = 0;
1627 if (width == 0 && height == 0) {
1629 glGetIntegerv(GL_VIEWPORT, viewport);
1632 width = viewport[2];
1633 height = viewport[3];
1637 glDisable(GL_BLEND);
1639 glDisable(GL_DEPTH_TEST);
1641 glDepthMask(GL_FALSE);
1644 set<Phase *> generated_mipmaps;
1646 // We choose the simplest option of having one texture per output,
1647 // since otherwise this turns into an (albeit simple) register allocation problem.
1648 map<Phase *, GLuint> output_textures;
1650 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1651 Phase *phase = phases[phase_num];
1653 if (do_phase_timing) {
1654 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1656 if (phase_num == phases.size() - 1) {
1657 // Last phase goes to the output the user specified.
1658 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1660 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1661 assert(status == GL_FRAMEBUFFER_COMPLETE);
1662 glViewport(x, y, width, height);
1663 if (dither_effect != NULL) {
1664 CHECK(dither_effect->set_int("output_width", width));
1665 CHECK(dither_effect->set_int("output_height", height));
1668 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1669 if (do_phase_timing) {
1670 glEndQuery(GL_TIME_ELAPSED);
1674 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1675 texture_it != output_textures.end();
1677 resource_pool->release_2d_texture(texture_it->second);
1680 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1685 if (do_phase_timing) {
1686 // Get back the timer queries.
1687 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1688 Phase *phase = phases[phase_num];
1689 GLint available = 0;
1690 while (!available) {
1691 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1693 GLuint64 time_elapsed;
1694 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1695 phase->time_elapsed_ns += time_elapsed;
1696 ++phase->num_measured_iterations;
1701 void EffectChain::enable_phase_timing(bool enable)
1704 assert(movit_timer_queries_supported);
1706 this->do_phase_timing = enable;
1709 void EffectChain::reset_phase_timing()
1711 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1712 Phase *phase = phases[phase_num];
1713 phase->time_elapsed_ns = 0;
1714 phase->num_measured_iterations = 0;
1718 void EffectChain::print_phase_timing()
1720 double total_time_ms = 0.0;
1721 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1722 Phase *phase = phases[phase_num];
1723 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1724 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1725 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1726 if (effect_num != 0) {
1729 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1732 total_time_ms += avg_time_ms;
1734 printf("Total: %5.1f ms\n", total_time_ms);
1737 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1741 // Find a texture for this phase.
1742 inform_input_sizes(phase);
1744 find_output_size(phase);
1746 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1747 output_textures->insert(make_pair(phase, tex_num));
1750 const GLuint glsl_program_num = phase->glsl_program_num;
1752 glUseProgram(glsl_program_num);
1755 // Set up RTT inputs for this phase.
1756 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1757 glActiveTexture(GL_TEXTURE0 + sampler);
1758 Phase *input = phase->inputs[sampler];
1759 input->output_node->bound_sampler_num = sampler;
1760 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1762 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1763 glGenerateMipmap(GL_TEXTURE_2D);
1765 generated_mipmaps->insert(input);
1767 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1770 // And now the output. (Already set up for us if it is the last phase.)
1772 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1773 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1774 glViewport(0, 0, phase->output_width, phase->output_height);
1777 // Give the required parameters to all the effects.
1778 unsigned sampler_num = phase->inputs.size();
1779 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1780 Node *node = phase->effects[i];
1781 unsigned old_sampler_num = sampler_num;
1782 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1785 if (node->effect->is_single_texture()) {
1786 assert(sampler_num - old_sampler_num == 1);
1787 node->bound_sampler_num = old_sampler_num;
1789 node->bound_sampler_num = -1;
1793 // Uniforms need to come after set_gl_state(), since they can be updated
1795 setup_uniforms(phase);
1798 float vertices[] = {
1805 glGenVertexArrays(1, &vao);
1807 glBindVertexArray(vao);
1810 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1811 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1813 glDrawArrays(GL_TRIANGLES, 0, 3);
1816 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1817 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1822 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1823 Node *node = phase->effects[i];
1824 node->effect->clear_gl_state();
1828 resource_pool->release_fbo(fbo);
1831 glDeleteVertexArrays(1, &vao);
1835 void EffectChain::setup_uniforms(Phase *phase)
1837 // TODO: Use UBO blocks.
1838 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
1839 const Uniform<bool> &uniform = phase->uniforms_bool[i];
1840 assert(uniform.num_values == 1);
1841 if (uniform.location != -1) {
1842 glUniform1i(uniform.location, *uniform.value);
1845 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
1846 const Uniform<int> &uniform = phase->uniforms_int[i];
1847 if (uniform.location != -1) {
1848 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1851 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
1852 const Uniform<float> &uniform = phase->uniforms_float[i];
1853 if (uniform.location != -1) {
1854 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
1857 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
1858 const Uniform<float> &uniform = phase->uniforms_vec2[i];
1859 if (uniform.location != -1) {
1860 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
1863 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
1864 const Uniform<float> &uniform = phase->uniforms_vec3[i];
1865 if (uniform.location != -1) {
1866 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
1869 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
1870 const Uniform<float> &uniform = phase->uniforms_vec4[i];
1871 if (uniform.location != -1) {
1872 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
1875 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
1876 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
1877 assert(uniform.num_values == 1);
1878 if (uniform.location != -1) {
1879 // Convert to float (GLSL has no double matrices).
1881 for (unsigned y = 0; y < 3; ++y) {
1882 for (unsigned x = 0; x < 3; ++x) {
1883 matrixf[y + x * 3] = (*uniform.value)(y, x);
1886 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
1891 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1893 glActiveTexture(GL_TEXTURE0 + sampler_num);
1896 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1899 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1902 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1904 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1907 string texture_name = string("tex_") + effect_id;
1908 glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1912 } // namespace movit