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_sampler2d.size(); ++j) {
321 phase->uniforms_sampler2d.push_back(effect->uniforms_sampler2d[j]);
322 phase->uniforms_sampler2d.back().prefix = effect_id;
323 frag_shader_uniforms += string("uniform sampler2D ") + effect_id
324 + "_" + effect->uniforms_sampler2d[j].name + ";\n";
326 for (unsigned j = 0; j < effect->uniforms_bool.size(); ++j) {
327 phase->uniforms_bool.push_back(effect->uniforms_bool[j]);
328 phase->uniforms_bool.back().prefix = effect_id;
329 frag_shader_uniforms += string("uniform bool ") + effect_id
330 + "_" + effect->uniforms_bool[j].name + ";\n";
332 for (unsigned j = 0; j < effect->uniforms_int.size(); ++j) {
333 phase->uniforms_int.push_back(effect->uniforms_int[j]);
334 phase->uniforms_int.back().prefix = effect_id;
335 frag_shader_uniforms += string("uniform int ") + effect_id
336 + "_" + effect->uniforms_int[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_sampler2d.size(); ++i) {
395 Uniform<int> &uniform = phase->uniforms_sampler2d[i];
396 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
398 for (unsigned i = 0; i < phase->uniforms_bool.size(); ++i) {
399 Uniform<bool> &uniform = phase->uniforms_bool[i];
400 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
402 for (unsigned i = 0; i < phase->uniforms_int.size(); ++i) {
403 Uniform<int> &uniform = phase->uniforms_int[i];
404 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
406 for (unsigned i = 0; i < phase->uniforms_float.size(); ++i) {
407 Uniform<float> &uniform = phase->uniforms_float[i];
408 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
410 for (unsigned i = 0; i < phase->uniforms_vec2.size(); ++i) {
411 Uniform<float> &uniform = phase->uniforms_vec2[i];
412 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
414 for (unsigned i = 0; i < phase->uniforms_vec3.size(); ++i) {
415 Uniform<float> &uniform = phase->uniforms_vec3[i];
416 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
418 for (unsigned i = 0; i < phase->uniforms_vec4.size(); ++i) {
419 Uniform<float> &uniform = phase->uniforms_vec4[i];
420 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
422 for (unsigned i = 0; i < phase->uniforms_mat3.size(); ++i) {
423 Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
424 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
428 // Construct GLSL programs, starting at the given effect and following
429 // the chain from there. We end a program every time we come to an effect
430 // marked as "needs texture bounce", one that is used by multiple other
431 // effects, every time we need to bounce due to output size change
432 // (not all size changes require ending), and of course at the end.
434 // We follow a quite simple depth-first search from the output, although
435 // without recursing explicitly within each phase.
436 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
438 if (completed_effects->count(output)) {
439 return (*completed_effects)[output];
442 Phase *phase = new Phase;
443 phase->output_node = output;
445 // If the output effect has one-to-one sampling, we try to trace this
446 // status down through the dependency chain. This is important in case
447 // we hit an effect that changes output size (and not sets a virtual
448 // output size); if we have one-to-one sampling, we don't have to break
450 output->one_to_one_sampling = output->effect->one_to_one_sampling();
452 // Effects that we have yet to calculate, but that we know should
453 // be in the current phase.
454 stack<Node *> effects_todo_this_phase;
455 effects_todo_this_phase.push(output);
457 while (!effects_todo_this_phase.empty()) {
458 Node *node = effects_todo_this_phase.top();
459 effects_todo_this_phase.pop();
461 if (node->effect->needs_mipmaps()) {
462 node->needs_mipmaps = true;
465 // This should currently only happen for effects that are inputs
466 // (either true inputs or phase outputs). We special-case inputs,
467 // and then deduplicate phase outputs below.
468 if (node->effect->num_inputs() == 0) {
469 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
473 assert(completed_effects->count(node) == 0);
476 phase->effects.push_back(node);
478 // Find all the dependencies of this effect, and add them to the stack.
479 vector<Node *> deps = node->incoming_links;
480 assert(node->effect->num_inputs() == deps.size());
481 for (unsigned i = 0; i < deps.size(); ++i) {
482 bool start_new_phase = false;
484 if (node->effect->needs_texture_bounce() &&
485 !deps[i]->effect->is_single_texture()) {
486 start_new_phase = true;
489 // Propagate information about needing mipmaps down the chain,
490 // breaking the phase if we notice an incompatibility.
492 // Note that we cannot do this propagation as a normal pass,
493 // because it needs information about where the phases end
494 // (we should not propagate the flag across phases).
495 if (node->needs_mipmaps) {
496 if (deps[i]->effect->num_inputs() == 0) {
497 Input *input = static_cast<Input *>(deps[i]->effect);
498 start_new_phase |= !input->can_supply_mipmaps();
500 deps[i]->needs_mipmaps = true;
504 if (deps[i]->outgoing_links.size() > 1) {
505 if (!deps[i]->effect->is_single_texture()) {
506 // More than one effect uses this as the input,
507 // and it is not a texture itself.
508 // The easiest thing to do (and probably also the safest
509 // performance-wise in most cases) is to bounce it to a texture
510 // and then let the next passes read from that.
511 start_new_phase = true;
513 assert(deps[i]->effect->num_inputs() == 0);
515 // For textures, we try to be slightly more clever;
516 // if none of our outputs need a bounce, we don't bounce
517 // but instead simply use the effect many times.
519 // Strictly speaking, we could bounce it for some outputs
520 // and use it directly for others, but the processing becomes
521 // somewhat simpler if the effect is only used in one such way.
522 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
523 Node *rdep = deps[i]->outgoing_links[j];
524 start_new_phase |= rdep->effect->needs_texture_bounce();
529 if (deps[i]->effect->sets_virtual_output_size()) {
530 assert(deps[i]->effect->changes_output_size());
531 // If the next effect sets a virtual size to rely on OpenGL's
532 // bilinear sampling, we'll really need to break the phase here.
533 start_new_phase = true;
534 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
535 // If the next effect changes size and we don't have one-to-one sampling,
536 // we also need to break here.
537 start_new_phase = true;
540 if (start_new_phase) {
541 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
543 effects_todo_this_phase.push(deps[i]);
545 // Propagate the one-to-one status down through the dependency.
546 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
547 deps[i]->effect->one_to_one_sampling();
552 // No more effects to do this phase. Take all the ones we have,
553 // and create a GLSL program for it.
554 assert(!phase->effects.empty());
556 // Deduplicate the inputs.
557 sort(phase->inputs.begin(), phase->inputs.end());
558 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
560 // We added the effects from the output and back, but we need to output
561 // them in topological sort order in the shader.
562 phase->effects = topological_sort(phase->effects);
564 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
565 phase->input_needs_mipmaps = false;
566 for (unsigned i = 0; i < phase->effects.size(); ++i) {
567 Node *node = phase->effects[i];
568 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
570 for (unsigned i = 0; i < phase->effects.size(); ++i) {
571 Node *node = phase->effects[i];
572 if (node->effect->num_inputs() == 0) {
573 Input *input = static_cast<Input *>(node->effect);
574 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
575 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
579 // Tell each node which phase it ended up in, so that the unit test
580 // can check that the phases were split in the right place.
581 // Note that this ignores that effects may be part of multiple phases;
582 // if the unit tests need to test such cases, we'll reconsider.
583 for (unsigned i = 0; i < phase->effects.size(); ++i) {
584 phase->effects[i]->containing_phase = phase;
587 // Actually make the shader for this phase.
588 compile_glsl_program(phase);
590 // Initialize timer objects.
591 if (movit_timer_queries_supported) {
592 glGenQueries(1, &phase->timer_query_object);
593 phase->time_elapsed_ns = 0;
594 phase->num_measured_iterations = 0;
597 assert(completed_effects->count(output) == 0);
598 completed_effects->insert(make_pair(output, phase));
599 phases.push_back(phase);
603 void EffectChain::output_dot(const char *filename)
605 if (movit_debug_level != MOVIT_DEBUG_ON) {
609 FILE *fp = fopen(filename, "w");
615 fprintf(fp, "digraph G {\n");
616 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
617 for (unsigned i = 0; i < nodes.size(); ++i) {
618 // Find out which phase this event belongs to.
619 vector<int> in_phases;
620 for (unsigned j = 0; j < phases.size(); ++j) {
621 const Phase* p = phases[j];
622 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
623 in_phases.push_back(j);
627 if (in_phases.empty()) {
628 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
629 } else if (in_phases.size() == 1) {
630 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
631 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
632 (in_phases[0] % 8) + 1);
634 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
636 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
637 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
638 (in_phases[0] % 8) + 1);
641 char from_node_id[256];
642 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
644 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
645 char to_node_id[256];
646 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
648 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
649 output_dot_edge(fp, from_node_id, to_node_id, labels);
652 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
654 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
655 output_dot_edge(fp, from_node_id, "output", labels);
663 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
665 vector<string> labels;
667 if (to != NULL && to->effect->needs_texture_bounce()) {
668 labels.push_back("needs_bounce");
670 if (from->effect->changes_output_size()) {
671 labels.push_back("resize");
674 switch (from->output_color_space) {
675 case COLORSPACE_INVALID:
676 labels.push_back("spc[invalid]");
678 case COLORSPACE_REC_601_525:
679 labels.push_back("spc[rec601-525]");
681 case COLORSPACE_REC_601_625:
682 labels.push_back("spc[rec601-625]");
688 switch (from->output_gamma_curve) {
690 labels.push_back("gamma[invalid]");
693 labels.push_back("gamma[sRGB]");
695 case GAMMA_REC_601: // and GAMMA_REC_709
696 labels.push_back("gamma[rec601/709]");
702 switch (from->output_alpha_type) {
704 labels.push_back("alpha[invalid]");
707 labels.push_back("alpha[blank]");
709 case ALPHA_POSTMULTIPLIED:
710 labels.push_back("alpha[postmult]");
719 void EffectChain::output_dot_edge(FILE *fp,
720 const string &from_node_id,
721 const string &to_node_id,
722 const vector<string> &labels)
724 if (labels.empty()) {
725 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
727 string label = labels[0];
728 for (unsigned k = 1; k < labels.size(); ++k) {
729 label += ", " + labels[k];
731 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
735 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
737 unsigned scaled_width, scaled_height;
739 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
740 // Same aspect, or W/H > aspect (image is wider than the frame).
741 // In either case, keep width, and adjust height.
742 scaled_width = width;
743 scaled_height = lrintf(width * aspect_denom / aspect_nom);
745 // W/H < aspect (image is taller than the frame), so keep height,
747 scaled_width = lrintf(height * aspect_nom / aspect_denom);
748 scaled_height = height;
751 // We should be consistently larger or smaller then the existing choice,
752 // since we have the same aspect.
753 assert(!(scaled_width < *output_width && scaled_height > *output_height));
754 assert(!(scaled_height < *output_height && scaled_width > *output_width));
756 if (scaled_width >= *output_width && scaled_height >= *output_height) {
757 *output_width = scaled_width;
758 *output_height = scaled_height;
762 // Propagate input texture sizes throughout, and inform effects downstream.
763 // (Like a lot of other code, we depend on effects being in topological order.)
764 void EffectChain::inform_input_sizes(Phase *phase)
766 // All effects that have a defined size (inputs and RTT inputs)
767 // get that. Reset all others.
768 for (unsigned i = 0; i < phase->effects.size(); ++i) {
769 Node *node = phase->effects[i];
770 if (node->effect->num_inputs() == 0) {
771 Input *input = static_cast<Input *>(node->effect);
772 node->output_width = input->get_width();
773 node->output_height = input->get_height();
774 assert(node->output_width != 0);
775 assert(node->output_height != 0);
777 node->output_width = node->output_height = 0;
780 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
781 Phase *input = phase->inputs[i];
782 input->output_node->output_width = input->virtual_output_width;
783 input->output_node->output_height = input->virtual_output_height;
784 assert(input->output_node->output_width != 0);
785 assert(input->output_node->output_height != 0);
788 // Now propagate from the inputs towards the end, and inform as we go.
789 // The rules are simple:
791 // 1. Don't touch effects that already have given sizes (ie., inputs
792 // or effects that change the output size).
793 // 2. If all of your inputs have the same size, that will be your output size.
794 // 3. Otherwise, your output size is 0x0.
795 for (unsigned i = 0; i < phase->effects.size(); ++i) {
796 Node *node = phase->effects[i];
797 if (node->effect->num_inputs() == 0) {
800 unsigned this_output_width = 0;
801 unsigned this_output_height = 0;
802 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
803 Node *input = node->incoming_links[j];
804 node->effect->inform_input_size(j, input->output_width, input->output_height);
806 this_output_width = input->output_width;
807 this_output_height = input->output_height;
808 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
810 this_output_width = 0;
811 this_output_height = 0;
814 if (node->effect->changes_output_size()) {
815 // We cannot call get_output_size() before we've done inform_input_size()
817 unsigned real_width, real_height;
818 node->effect->get_output_size(&real_width, &real_height,
819 &node->output_width, &node->output_height);
820 assert(node->effect->sets_virtual_output_size() ||
821 (real_width == node->output_width &&
822 real_height == node->output_height));
824 node->output_width = this_output_width;
825 node->output_height = this_output_height;
830 // Note: You should call inform_input_sizes() before this, as the last effect's
831 // desired output size might change based on the inputs.
832 void EffectChain::find_output_size(Phase *phase)
834 Node *output_node = phase->effects.back();
836 // If the last effect explicitly sets an output size, use that.
837 if (output_node->effect->changes_output_size()) {
838 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
839 &phase->virtual_output_width, &phase->virtual_output_height);
840 assert(output_node->effect->sets_virtual_output_size() ||
841 (phase->output_width == phase->virtual_output_width &&
842 phase->output_height == phase->virtual_output_height));
846 // If all effects have the same size, use that.
847 unsigned output_width = 0, output_height = 0;
848 bool all_inputs_same_size = true;
850 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
851 Phase *input = phase->inputs[i];
852 assert(input->output_width != 0);
853 assert(input->output_height != 0);
854 if (output_width == 0 && output_height == 0) {
855 output_width = input->virtual_output_width;
856 output_height = input->virtual_output_height;
857 } else if (output_width != input->virtual_output_width ||
858 output_height != input->virtual_output_height) {
859 all_inputs_same_size = false;
862 for (unsigned i = 0; i < phase->effects.size(); ++i) {
863 Effect *effect = phase->effects[i]->effect;
864 if (effect->num_inputs() != 0) {
868 Input *input = static_cast<Input *>(effect);
869 if (output_width == 0 && output_height == 0) {
870 output_width = input->get_width();
871 output_height = input->get_height();
872 } else if (output_width != input->get_width() ||
873 output_height != input->get_height()) {
874 all_inputs_same_size = false;
878 if (all_inputs_same_size) {
879 assert(output_width != 0);
880 assert(output_height != 0);
881 phase->virtual_output_width = phase->output_width = output_width;
882 phase->virtual_output_height = phase->output_height = output_height;
886 // If not, fit all the inputs into the current aspect, and select the largest one.
889 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
890 Phase *input = phase->inputs[i];
891 assert(input->output_width != 0);
892 assert(input->output_height != 0);
893 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
895 for (unsigned i = 0; i < phase->effects.size(); ++i) {
896 Effect *effect = phase->effects[i]->effect;
897 if (effect->num_inputs() != 0) {
901 Input *input = static_cast<Input *>(effect);
902 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
904 assert(output_width != 0);
905 assert(output_height != 0);
906 phase->virtual_output_width = phase->output_width = output_width;
907 phase->virtual_output_height = phase->output_height = output_height;
910 void EffectChain::sort_all_nodes_topologically()
912 nodes = topological_sort(nodes);
915 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
917 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
918 vector<Node *> sorted_list;
919 for (unsigned i = 0; i < nodes.size(); ++i) {
920 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
922 reverse(sorted_list.begin(), sorted_list.end());
926 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
928 if (nodes_left_to_visit->count(node) == 0) {
931 nodes_left_to_visit->erase(node);
932 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
933 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
935 sorted_list->push_back(node);
938 void EffectChain::find_color_spaces_for_inputs()
940 for (unsigned i = 0; i < nodes.size(); ++i) {
941 Node *node = nodes[i];
942 if (node->disabled) {
945 if (node->incoming_links.size() == 0) {
946 Input *input = static_cast<Input *>(node->effect);
947 node->output_color_space = input->get_color_space();
948 node->output_gamma_curve = input->get_gamma_curve();
950 Effect::AlphaHandling alpha_handling = input->alpha_handling();
951 switch (alpha_handling) {
952 case Effect::OUTPUT_BLANK_ALPHA:
953 node->output_alpha_type = ALPHA_BLANK;
955 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
956 node->output_alpha_type = ALPHA_PREMULTIPLIED;
958 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
959 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
961 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
962 case Effect::DONT_CARE_ALPHA_TYPE:
967 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
968 assert(node->output_gamma_curve == GAMMA_LINEAR);
974 // Propagate gamma and color space information as far as we can in the graph.
975 // The rules are simple: Anything where all the inputs agree, get that as
976 // output as well. Anything else keeps having *_INVALID.
977 void EffectChain::propagate_gamma_and_color_space()
979 // We depend on going through the nodes in order.
980 sort_all_nodes_topologically();
982 for (unsigned i = 0; i < nodes.size(); ++i) {
983 Node *node = nodes[i];
984 if (node->disabled) {
987 assert(node->incoming_links.size() == node->effect->num_inputs());
988 if (node->incoming_links.size() == 0) {
989 assert(node->output_color_space != COLORSPACE_INVALID);
990 assert(node->output_gamma_curve != GAMMA_INVALID);
994 Colorspace color_space = node->incoming_links[0]->output_color_space;
995 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
996 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
997 if (node->incoming_links[j]->output_color_space != color_space) {
998 color_space = COLORSPACE_INVALID;
1000 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1001 gamma_curve = GAMMA_INVALID;
1005 // The conversion effects already have their outputs set correctly,
1006 // so leave them alone.
1007 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1008 node->output_color_space = color_space;
1010 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1011 node->effect->effect_type_id() != "GammaExpansionEffect") {
1012 node->output_gamma_curve = gamma_curve;
1017 // Propagate alpha information as far as we can in the graph.
1018 // Similar to propagate_gamma_and_color_space().
1019 void EffectChain::propagate_alpha()
1021 // We depend on going through the nodes in order.
1022 sort_all_nodes_topologically();
1024 for (unsigned i = 0; i < nodes.size(); ++i) {
1025 Node *node = nodes[i];
1026 if (node->disabled) {
1029 assert(node->incoming_links.size() == node->effect->num_inputs());
1030 if (node->incoming_links.size() == 0) {
1031 assert(node->output_alpha_type != ALPHA_INVALID);
1035 // The alpha multiplication/division effects are special cases.
1036 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1037 assert(node->incoming_links.size() == 1);
1038 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1039 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1042 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1043 assert(node->incoming_links.size() == 1);
1044 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1045 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1049 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1050 // because they are the only one that _need_ postmultiplied alpha.
1051 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1052 node->effect->effect_type_id() == "GammaExpansionEffect") {
1053 assert(node->incoming_links.size() == 1);
1054 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1055 node->output_alpha_type = ALPHA_BLANK;
1056 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1057 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1059 node->output_alpha_type = ALPHA_INVALID;
1064 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1065 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1066 // taken care of above. Rationale: Even if you could imagine
1067 // e.g. an effect that took in an image and set alpha=1.0
1068 // unconditionally, it wouldn't make any sense to have it as
1069 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1070 // got its input pre- or postmultiplied, so it wouldn't know
1071 // whether to divide away the old alpha or not.
1072 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1073 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1074 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1075 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1077 // If the node has multiple inputs, check that they are all valid and
1079 bool any_invalid = false;
1080 bool any_premultiplied = false;
1081 bool any_postmultiplied = false;
1083 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1084 switch (node->incoming_links[j]->output_alpha_type) {
1089 // Blank is good as both pre- and postmultiplied alpha,
1090 // so just ignore it.
1092 case ALPHA_PREMULTIPLIED:
1093 any_premultiplied = true;
1095 case ALPHA_POSTMULTIPLIED:
1096 any_postmultiplied = true;
1104 node->output_alpha_type = ALPHA_INVALID;
1108 // Inputs must be of the same type.
1109 if (any_premultiplied && any_postmultiplied) {
1110 node->output_alpha_type = ALPHA_INVALID;
1114 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1115 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1116 // If the effect has asked for premultiplied alpha, check that it has got it.
1117 if (any_postmultiplied) {
1118 node->output_alpha_type = ALPHA_INVALID;
1119 } else if (!any_premultiplied &&
1120 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1121 // Blank input alpha, and the effect preserves blank alpha.
1122 node->output_alpha_type = ALPHA_BLANK;
1124 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1127 // OK, all inputs are the same, and this effect is not going
1129 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1130 if (any_premultiplied) {
1131 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1132 } else if (any_postmultiplied) {
1133 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1135 node->output_alpha_type = ALPHA_BLANK;
1141 bool EffectChain::node_needs_colorspace_fix(Node *node)
1143 if (node->disabled) {
1146 if (node->effect->num_inputs() == 0) {
1150 // propagate_gamma_and_color_space() has already set our output
1151 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1152 if (node->output_color_space == COLORSPACE_INVALID) {
1155 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1158 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1159 // the graph. Our strategy is not always optimal, but quite simple:
1160 // Find an effect that's as early as possible where the inputs are of
1161 // unacceptable colorspaces (that is, either different, or, if the effect only
1162 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1163 // propagate the information anew, and repeat until there are no more such
1165 void EffectChain::fix_internal_color_spaces()
1167 unsigned colorspace_propagation_pass = 0;
1171 for (unsigned i = 0; i < nodes.size(); ++i) {
1172 Node *node = nodes[i];
1173 if (!node_needs_colorspace_fix(node)) {
1177 // Go through each input that is not sRGB, and insert
1178 // a colorspace conversion after it.
1179 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1180 Node *input = node->incoming_links[j];
1181 assert(input->output_color_space != COLORSPACE_INVALID);
1182 if (input->output_color_space == COLORSPACE_sRGB) {
1185 Node *conversion = add_node(new ColorspaceConversionEffect());
1186 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1187 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1188 conversion->output_color_space = COLORSPACE_sRGB;
1189 replace_sender(input, conversion);
1190 connect_nodes(input, conversion);
1193 // Re-sort topologically, and propagate the new information.
1194 propagate_gamma_and_color_space();
1201 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1202 output_dot(filename);
1203 assert(colorspace_propagation_pass < 100);
1204 } while (found_any);
1206 for (unsigned i = 0; i < nodes.size(); ++i) {
1207 Node *node = nodes[i];
1208 if (node->disabled) {
1211 assert(node->output_color_space != COLORSPACE_INVALID);
1215 bool EffectChain::node_needs_alpha_fix(Node *node)
1217 if (node->disabled) {
1221 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1222 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1223 return (node->output_alpha_type == ALPHA_INVALID);
1226 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1227 // the graph. Similar to fix_internal_color_spaces().
1228 void EffectChain::fix_internal_alpha(unsigned step)
1230 unsigned alpha_propagation_pass = 0;
1234 for (unsigned i = 0; i < nodes.size(); ++i) {
1235 Node *node = nodes[i];
1236 if (!node_needs_alpha_fix(node)) {
1240 // If we need to fix up GammaExpansionEffect, then clearly something
1241 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1243 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1245 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1247 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1248 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1249 assert(node->incoming_links.size() == 1);
1250 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1251 desired_type = ALPHA_POSTMULTIPLIED;
1254 // Go through each input that is not premultiplied alpha, and insert
1255 // a conversion before it.
1256 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1257 Node *input = node->incoming_links[j];
1258 assert(input->output_alpha_type != ALPHA_INVALID);
1259 if (input->output_alpha_type == desired_type ||
1260 input->output_alpha_type == ALPHA_BLANK) {
1264 if (desired_type == ALPHA_PREMULTIPLIED) {
1265 conversion = add_node(new AlphaMultiplicationEffect());
1267 conversion = add_node(new AlphaDivisionEffect());
1269 conversion->output_alpha_type = desired_type;
1270 replace_sender(input, conversion);
1271 connect_nodes(input, conversion);
1274 // Re-sort topologically, and propagate the new information.
1275 propagate_gamma_and_color_space();
1283 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1284 output_dot(filename);
1285 assert(alpha_propagation_pass < 100);
1286 } while (found_any);
1288 for (unsigned i = 0; i < nodes.size(); ++i) {
1289 Node *node = nodes[i];
1290 if (node->disabled) {
1293 assert(node->output_alpha_type != ALPHA_INVALID);
1297 // Make so that the output is in the desired color space.
1298 void EffectChain::fix_output_color_space()
1300 Node *output = find_output_node();
1301 if (output->output_color_space != output_format.color_space) {
1302 Node *conversion = add_node(new ColorspaceConversionEffect());
1303 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1304 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1305 conversion->output_color_space = output_format.color_space;
1306 connect_nodes(output, conversion);
1308 propagate_gamma_and_color_space();
1312 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1313 void EffectChain::fix_output_alpha()
1315 Node *output = find_output_node();
1316 assert(output->output_alpha_type != ALPHA_INVALID);
1317 if (output->output_alpha_type == ALPHA_BLANK) {
1318 // No alpha output, so we don't care.
1321 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1322 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1323 Node *conversion = add_node(new AlphaDivisionEffect());
1324 connect_nodes(output, conversion);
1326 propagate_gamma_and_color_space();
1328 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1329 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1330 Node *conversion = add_node(new AlphaMultiplicationEffect());
1331 connect_nodes(output, conversion);
1333 propagate_gamma_and_color_space();
1337 bool EffectChain::node_needs_gamma_fix(Node *node)
1339 if (node->disabled) {
1343 // Small hack since the output is not an explicit node:
1344 // If we are the last node and our output is in the wrong
1345 // space compared to EffectChain's output, we need to fix it.
1346 // This will only take us to linear, but fix_output_gamma()
1347 // will come and take us to the desired output gamma
1350 // This needs to be before everything else, since it could
1351 // even apply to inputs (if they are the only effect).
1352 if (node->outgoing_links.empty() &&
1353 node->output_gamma_curve != output_format.gamma_curve &&
1354 node->output_gamma_curve != GAMMA_LINEAR) {
1358 if (node->effect->num_inputs() == 0) {
1362 // propagate_gamma_and_color_space() has already set our output
1363 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1364 // except for GammaCompressionEffect.
1365 if (node->output_gamma_curve == GAMMA_INVALID) {
1368 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1369 assert(node->incoming_links.size() == 1);
1370 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1373 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1376 // Very similar to fix_internal_color_spaces(), but for gamma.
1377 // There is one difference, though; before we start adding conversion nodes,
1378 // we see if we can get anything out of asking the sources to deliver
1379 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1380 // does that part, while fix_internal_gamma_by_inserting_nodes()
1381 // inserts nodes as needed afterwards.
1382 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1384 unsigned gamma_propagation_pass = 0;
1388 for (unsigned i = 0; i < nodes.size(); ++i) {
1389 Node *node = nodes[i];
1390 if (!node_needs_gamma_fix(node)) {
1394 // See if all inputs can give us linear gamma. If not, leave it.
1395 vector<Node *> nonlinear_inputs;
1396 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1397 assert(!nonlinear_inputs.empty());
1400 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1401 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1402 all_ok &= input->can_output_linear_gamma();
1409 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1410 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1411 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1414 // Re-sort topologically, and propagate the new information.
1415 propagate_gamma_and_color_space();
1422 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1423 output_dot(filename);
1424 assert(gamma_propagation_pass < 100);
1425 } while (found_any);
1428 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1430 unsigned gamma_propagation_pass = 0;
1434 for (unsigned i = 0; i < nodes.size(); ++i) {
1435 Node *node = nodes[i];
1436 if (!node_needs_gamma_fix(node)) {
1440 // Special case: We could be an input and still be asked to
1441 // fix our gamma; if so, we should be the only node
1442 // (as node_needs_gamma_fix() would only return true in
1443 // for an input in that case). That means we should insert
1444 // a conversion node _after_ ourselves.
1445 if (node->incoming_links.empty()) {
1446 assert(node->outgoing_links.empty());
1447 Node *conversion = add_node(new GammaExpansionEffect());
1448 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1449 conversion->output_gamma_curve = GAMMA_LINEAR;
1450 connect_nodes(node, conversion);
1453 // If not, go through each input that is not linear gamma,
1454 // and insert a gamma conversion after it.
1455 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1456 Node *input = node->incoming_links[j];
1457 assert(input->output_gamma_curve != GAMMA_INVALID);
1458 if (input->output_gamma_curve == GAMMA_LINEAR) {
1461 Node *conversion = add_node(new GammaExpansionEffect());
1462 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1463 conversion->output_gamma_curve = GAMMA_LINEAR;
1464 replace_sender(input, conversion);
1465 connect_nodes(input, conversion);
1468 // Re-sort topologically, and propagate the new information.
1470 propagate_gamma_and_color_space();
1477 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1478 output_dot(filename);
1479 assert(gamma_propagation_pass < 100);
1480 } while (found_any);
1482 for (unsigned i = 0; i < nodes.size(); ++i) {
1483 Node *node = nodes[i];
1484 if (node->disabled) {
1487 assert(node->output_gamma_curve != GAMMA_INVALID);
1491 // Make so that the output is in the desired gamma.
1492 // Note that this assumes linear input gamma, so it might create the need
1493 // for another pass of fix_internal_gamma().
1494 void EffectChain::fix_output_gamma()
1496 Node *output = find_output_node();
1497 if (output->output_gamma_curve != output_format.gamma_curve) {
1498 Node *conversion = add_node(new GammaCompressionEffect());
1499 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1500 conversion->output_gamma_curve = output_format.gamma_curve;
1501 connect_nodes(output, conversion);
1505 // If the user has requested Y'CbCr output, we need to do this conversion
1506 // _after_ GammaCompressionEffect etc., but before dither (see below).
1507 // This is because Y'CbCr, with the exception of a special optional mode
1508 // in Rec. 2020 (which we currently don't support), is defined to work on
1509 // gamma-encoded data.
1510 void EffectChain::add_ycbcr_conversion_if_needed()
1512 assert(output_color_type == OUTPUT_COLOR_RGB || output_color_type == OUTPUT_COLOR_YCBCR);
1513 if (output_color_type != OUTPUT_COLOR_YCBCR) {
1516 Node *output = find_output_node();
1517 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1518 connect_nodes(output, ycbcr);
1521 // If the user has requested dither, add a DitherEffect right at the end
1522 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1523 // since dither is about the only effect that can _not_ be done in linear space.
1524 void EffectChain::add_dither_if_needed()
1526 if (num_dither_bits == 0) {
1529 Node *output = find_output_node();
1530 Node *dither = add_node(new DitherEffect());
1531 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1532 connect_nodes(output, dither);
1534 dither_effect = dither->effect;
1537 // Find the output node. This is, simply, one that has no outgoing links.
1538 // If there are multiple ones, the graph is malformed (we do not support
1539 // multiple outputs right now).
1540 Node *EffectChain::find_output_node()
1542 vector<Node *> output_nodes;
1543 for (unsigned i = 0; i < nodes.size(); ++i) {
1544 Node *node = nodes[i];
1545 if (node->disabled) {
1548 if (node->outgoing_links.empty()) {
1549 output_nodes.push_back(node);
1552 assert(output_nodes.size() == 1);
1553 return output_nodes[0];
1556 void EffectChain::finalize()
1558 // Output the graph as it is before we do any conversions on it.
1559 output_dot("step0-start.dot");
1561 // Give each effect in turn a chance to rewrite its own part of the graph.
1562 // Note that if more effects are added as part of this, they will be
1563 // picked up as part of the same for loop, since they are added at the end.
1564 for (unsigned i = 0; i < nodes.size(); ++i) {
1565 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1567 output_dot("step1-rewritten.dot");
1569 find_color_spaces_for_inputs();
1570 output_dot("step2-input-colorspace.dot");
1573 output_dot("step3-propagated-alpha.dot");
1575 propagate_gamma_and_color_space();
1576 output_dot("step4-propagated-all.dot");
1578 fix_internal_color_spaces();
1579 fix_internal_alpha(6);
1580 fix_output_color_space();
1581 output_dot("step7-output-colorspacefix.dot");
1583 output_dot("step8-output-alphafix.dot");
1585 // Note that we need to fix gamma after colorspace conversion,
1586 // because colorspace conversions might create needs for gamma conversions.
1587 // Also, we need to run an extra pass of fix_internal_gamma() after
1588 // fixing the output gamma, as we only have conversions to/from linear,
1589 // and fix_internal_alpha() since GammaCompressionEffect needs
1590 // postmultiplied input.
1591 fix_internal_gamma_by_asking_inputs(9);
1592 fix_internal_gamma_by_inserting_nodes(10);
1594 output_dot("step11-output-gammafix.dot");
1596 output_dot("step12-output-alpha-propagated.dot");
1597 fix_internal_alpha(13);
1598 output_dot("step14-output-alpha-fixed.dot");
1599 fix_internal_gamma_by_asking_inputs(15);
1600 fix_internal_gamma_by_inserting_nodes(16);
1602 output_dot("step17-before-ycbcr.dot");
1603 add_ycbcr_conversion_if_needed();
1605 output_dot("step18-before-dither.dot");
1606 add_dither_if_needed();
1608 output_dot("step19-final.dot");
1610 // Construct all needed GLSL programs, starting at the output.
1611 // We need to keep track of which effects have already been computed,
1612 // as an effect with multiple users could otherwise be calculated
1614 map<Node *, Phase *> completed_effects;
1615 construct_phase(find_output_node(), &completed_effects);
1617 output_dot("step20-split-to-phases.dot");
1619 assert(phases[0]->inputs.empty());
1624 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1628 // Save original viewport.
1629 GLuint x = 0, y = 0;
1631 if (width == 0 && height == 0) {
1633 glGetIntegerv(GL_VIEWPORT, viewport);
1636 width = viewport[2];
1637 height = viewport[3];
1641 glDisable(GL_BLEND);
1643 glDisable(GL_DEPTH_TEST);
1645 glDepthMask(GL_FALSE);
1648 set<Phase *> generated_mipmaps;
1650 // We choose the simplest option of having one texture per output,
1651 // since otherwise this turns into an (albeit simple) register allocation problem.
1652 map<Phase *, GLuint> output_textures;
1654 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1655 Phase *phase = phases[phase_num];
1657 if (do_phase_timing) {
1658 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1660 if (phase_num == phases.size() - 1) {
1661 // Last phase goes to the output the user specified.
1662 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1664 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1665 assert(status == GL_FRAMEBUFFER_COMPLETE);
1666 glViewport(x, y, width, height);
1667 if (dither_effect != NULL) {
1668 CHECK(dither_effect->set_int("output_width", width));
1669 CHECK(dither_effect->set_int("output_height", height));
1672 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1673 if (do_phase_timing) {
1674 glEndQuery(GL_TIME_ELAPSED);
1678 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1679 texture_it != output_textures.end();
1681 resource_pool->release_2d_texture(texture_it->second);
1684 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1689 if (do_phase_timing) {
1690 // Get back the timer queries.
1691 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1692 Phase *phase = phases[phase_num];
1693 GLint available = 0;
1694 while (!available) {
1695 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1697 GLuint64 time_elapsed;
1698 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1699 phase->time_elapsed_ns += time_elapsed;
1700 ++phase->num_measured_iterations;
1705 void EffectChain::enable_phase_timing(bool enable)
1708 assert(movit_timer_queries_supported);
1710 this->do_phase_timing = enable;
1713 void EffectChain::reset_phase_timing()
1715 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1716 Phase *phase = phases[phase_num];
1717 phase->time_elapsed_ns = 0;
1718 phase->num_measured_iterations = 0;
1722 void EffectChain::print_phase_timing()
1724 double total_time_ms = 0.0;
1725 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1726 Phase *phase = phases[phase_num];
1727 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1728 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1729 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1730 if (effect_num != 0) {
1733 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1736 total_time_ms += avg_time_ms;
1738 printf("Total: %5.1f ms\n", total_time_ms);
1741 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1745 // Find a texture for this phase.
1746 inform_input_sizes(phase);
1748 find_output_size(phase);
1750 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1751 output_textures->insert(make_pair(phase, tex_num));
1754 const GLuint glsl_program_num = phase->glsl_program_num;
1756 glUseProgram(glsl_program_num);
1759 // Set up RTT inputs for this phase.
1760 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1761 glActiveTexture(GL_TEXTURE0 + sampler);
1762 Phase *input = phase->inputs[sampler];
1763 input->output_node->bound_sampler_num = sampler;
1764 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1766 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1767 glGenerateMipmap(GL_TEXTURE_2D);
1769 generated_mipmaps->insert(input);
1771 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1774 // And now the output. (Already set up for us if it is the last phase.)
1776 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1777 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1778 glViewport(0, 0, phase->output_width, phase->output_height);
1781 // Give the required parameters to all the effects.
1782 unsigned sampler_num = phase->inputs.size();
1783 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1784 Node *node = phase->effects[i];
1785 unsigned old_sampler_num = sampler_num;
1786 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1789 if (node->effect->is_single_texture()) {
1790 assert(sampler_num - old_sampler_num == 1);
1791 node->bound_sampler_num = old_sampler_num;
1793 node->bound_sampler_num = -1;
1797 // Uniforms need to come after set_gl_state(), since they can be updated
1799 setup_uniforms(phase);
1802 float vertices[] = {
1809 glGenVertexArrays(1, &vao);
1811 glBindVertexArray(vao);
1814 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1815 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1817 glDrawArrays(GL_TRIANGLES, 0, 3);
1820 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1821 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1826 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1827 Node *node = phase->effects[i];
1828 node->effect->clear_gl_state();
1832 resource_pool->release_fbo(fbo);
1835 glDeleteVertexArrays(1, &vao);
1839 void EffectChain::setup_uniforms(Phase *phase)
1841 // TODO: Use UBO blocks.
1842 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
1843 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
1844 if (uniform.location != -1) {
1845 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1848 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
1849 const Uniform<bool> &uniform = phase->uniforms_bool[i];
1850 assert(uniform.num_values == 1);
1851 if (uniform.location != -1) {
1852 glUniform1i(uniform.location, *uniform.value);
1855 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
1856 const Uniform<int> &uniform = phase->uniforms_int[i];
1857 if (uniform.location != -1) {
1858 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1861 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
1862 const Uniform<float> &uniform = phase->uniforms_float[i];
1863 if (uniform.location != -1) {
1864 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
1867 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
1868 const Uniform<float> &uniform = phase->uniforms_vec2[i];
1869 if (uniform.location != -1) {
1870 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
1873 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
1874 const Uniform<float> &uniform = phase->uniforms_vec3[i];
1875 if (uniform.location != -1) {
1876 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
1879 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
1880 const Uniform<float> &uniform = phase->uniforms_vec4[i];
1881 if (uniform.location != -1) {
1882 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
1885 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
1886 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
1887 assert(uniform.num_values == 1);
1888 if (uniform.location != -1) {
1889 // Convert to float (GLSL has no double matrices).
1891 for (unsigned y = 0; y < 3; ++y) {
1892 for (unsigned x = 0; x < 3; ++x) {
1893 matrixf[y + x * 3] = (*uniform.value)(y, x);
1896 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
1901 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1903 glActiveTexture(GL_TEXTURE0 + sampler_num);
1906 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1909 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1912 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1914 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1917 string texture_name = string("tex_") + effect_id;
1918 glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1922 } // namespace movit