1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
10 #include <Eigen/Sparse>
11 #include <Eigen/SparseQR>
12 #include <Eigen/OrderingMethods>
14 #include "effect_chain.h"
15 #include "effect_util.h"
18 #include "resample_effect.h"
21 using namespace Eigen;
37 return 1.0f - fabs(x);
43 float lanczos_weight(float x, float a)
48 return sinc(M_PI * x) * sinc(M_PI * x / a);
52 // Euclid's algorithm, from Wikipedia.
53 unsigned gcd(unsigned a, unsigned b)
63 template<class DestFloat>
64 unsigned combine_samples(const Tap<float> *src, Tap<DestFloat> *dst, float num_subtexels, float inv_num_subtexels, unsigned num_src_samples, unsigned max_samples_saved)
66 // Cut off near-zero values at both sides.
67 unsigned num_samples_saved = 0;
68 while (num_samples_saved < max_samples_saved &&
69 num_src_samples > 0 &&
70 fabs(src[0].weight) < 1e-6) {
75 while (num_samples_saved < max_samples_saved &&
76 num_src_samples > 0 &&
77 fabs(src[num_src_samples - 1].weight) < 1e-6) {
82 for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
83 // Copy the sample directly; it will be overwritten later if we can combine.
85 dst[j].weight = convert_float<float, DestFloat>(src[i].weight);
86 dst[j].pos = convert_float<float, DestFloat>(src[i].pos);
89 if (i == num_src_samples - 1) {
90 // Last sample; cannot combine.
93 assert(num_samples_saved <= max_samples_saved);
94 if (num_samples_saved == max_samples_saved) {
95 // We could maybe save more here, but other rows can't, so don't bother.
99 float w1 = src[i].weight;
100 float w2 = src[i + 1].weight;
101 if (w1 * w2 < 0.0f) {
102 // Differing signs; cannot combine.
106 float pos1 = src[i].pos;
107 float pos2 = src[i + 1].pos;
110 fp16_int_t pos, total_weight;
112 combine_two_samples(w1, w2, pos1, pos2, num_subtexels, inv_num_subtexels, &pos, &total_weight, &sum_sq_error);
114 // If the interpolation error is larger than that of about sqrt(2) of
115 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
116 // but since the artifacts are not really random, they can get quite
117 // visible. On the other hand, going to 0.25f, I can see no change at
118 // all with 8-bit output, so it would not seem to be worth it.)
119 if (sum_sq_error > 0.5f / (255.0f * 255.0f)) {
123 // OK, we can combine this and the next sample.
125 dst[j].weight = total_weight;
129 ++i; // Skip the next sample.
132 return num_samples_saved;
135 // Normalize so that the sum becomes one. Note that we do it twice;
136 // this sometimes helps a tiny little bit when we have many samples.
138 void normalize_sum(Tap<T>* vals, unsigned num)
140 for (int normalize_pass = 0; normalize_pass < 2; ++normalize_pass) {
142 for (unsigned i = 0; i < num; ++i) {
143 sum += to_fp64(vals[i].weight);
145 for (unsigned i = 0; i < num; ++i) {
146 vals[i].weight = from_fp64<T>(to_fp64(vals[i].weight) / sum);
151 // Make use of the bilinear filtering in the GPU to reduce the number of samples
152 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
153 // two neighboring samples if their weights have differing signs, so we first need to
154 // figure out the maximum number of samples. Then, we downconvert all the weights to
155 // that number -- we could have gone for a variable-length system, but this is simpler,
156 // and the gains would probably be offset by the extra cost of checking when to stop.
158 // The greedy strategy for combining samples is optimal.
159 template<class DestFloat>
160 unsigned combine_many_samples(const Tap<float> *weights, unsigned src_size, unsigned src_samples, unsigned dst_samples, Tap<DestFloat> **bilinear_weights)
162 float num_subtexels = src_size / movit_texel_subpixel_precision;
163 float inv_num_subtexels = movit_texel_subpixel_precision / src_size;
164 int src_bilinear_samples = 0;
166 for (unsigned y = 0; y < dst_samples; ++y) {
167 unsigned num_samples_saved = combine_samples<DestFloat>(weights + y * src_samples, NULL, num_subtexels, inv_num_subtexels, src_samples, UINT_MAX);
168 src_bilinear_samples = max<int>(src_bilinear_samples, src_samples - num_samples_saved);
171 // Now that we know the right width, actually combine the samples.
172 *bilinear_weights = new Tap<DestFloat>[dst_samples * src_bilinear_samples];
173 for (unsigned y = 0; y < dst_samples; ++y) {
174 Tap<DestFloat> *bilinear_weights_ptr = *bilinear_weights + y * src_bilinear_samples;
175 unsigned num_samples_saved = combine_samples(
176 weights + y * src_samples,
177 bilinear_weights_ptr,
181 src_samples - src_bilinear_samples);
182 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
183 normalize_sum(bilinear_weights_ptr, src_bilinear_samples);
185 return src_bilinear_samples;
188 // Compute the sum of squared errors between the ideal weights (which are
189 // assumed to fall exactly on pixel centers) and the weights that result
190 // from sampling at <bilinear_weights>. The primary reason for the difference
191 // is inaccuracy in the sampling positions, both due to limited precision
192 // in storing them (already inherent in sending them in as fp16_int_t)
193 // and in subtexel sampling precision (which we calculate in this function).
195 double compute_sum_sq_error(const Tap<float>* weights, unsigned num_weights,
196 const Tap<T>* bilinear_weights, unsigned num_bilinear_weights,
199 // Find the effective range of the bilinear-optimized kernel.
200 // Due to rounding of the positions, this is not necessarily the same
201 // as the intended range (ie., the range of the original weights).
202 int lower_pos = int(floor(to_fp64(bilinear_weights[0].pos) * size - 0.5));
203 int upper_pos = int(ceil(to_fp64(bilinear_weights[num_bilinear_weights - 1].pos) * size - 0.5)) + 2;
204 lower_pos = min<int>(lower_pos, lrintf(weights[0].pos * size - 0.5));
205 upper_pos = max<int>(upper_pos, lrintf(weights[num_weights - 1].pos * size - 0.5) + 1);
207 float* effective_weights = new float[upper_pos - lower_pos];
208 for (int i = 0; i < upper_pos - lower_pos; ++i) {
209 effective_weights[i] = 0.0f;
212 // Now find the effective weights that result from this sampling.
213 for (unsigned i = 0; i < num_bilinear_weights; ++i) {
214 const float pixel_pos = to_fp64(bilinear_weights[i].pos) * size - 0.5f;
215 const int x0 = int(floor(pixel_pos)) - lower_pos;
216 const int x1 = x0 + 1;
217 const float f = lrintf((pixel_pos - (x0 + lower_pos)) / movit_texel_subpixel_precision) * movit_texel_subpixel_precision;
221 assert(x0 < upper_pos - lower_pos);
222 assert(x1 < upper_pos - lower_pos);
224 effective_weights[x0] += to_fp64(bilinear_weights[i].weight) * (1.0 - f);
225 effective_weights[x1] += to_fp64(bilinear_weights[i].weight) * f;
228 // Subtract the desired weights to get the error.
229 for (unsigned i = 0; i < num_weights; ++i) {
230 const int x = lrintf(weights[i].pos * size - 0.5f) - lower_pos;
232 assert(x < upper_pos - lower_pos);
234 effective_weights[x] -= weights[i].weight;
237 double sum_sq_error = 0.0;
238 for (unsigned i = 0; i < num_weights; ++i) {
239 sum_sq_error += effective_weights[i] * effective_weights[i];
242 delete[] effective_weights;
248 ResampleEffect::ResampleEffect()
251 offset_x(0.0f), offset_y(0.0f),
252 zoom_x(1.0f), zoom_y(1.0f),
253 zoom_center_x(0.5f), zoom_center_y(0.5f)
255 register_int("width", &output_width);
256 register_int("height", &output_height);
258 // The first blur pass will forward resolution information to us.
259 hpass = new SingleResamplePassEffect(this);
260 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
261 vpass = new SingleResamplePassEffect(NULL);
262 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
267 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
269 Node *hpass_node = graph->add_node(hpass);
270 Node *vpass_node = graph->add_node(vpass);
271 graph->connect_nodes(hpass_node, vpass_node);
272 graph->replace_receiver(self, hpass_node);
273 graph->replace_sender(self, vpass_node);
274 self->disabled = true;
277 // We get this information forwarded from the first blur pass,
278 // since we are not part of the chain ourselves.
279 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
281 assert(input_num == 0);
285 input_height = height;
289 void ResampleEffect::update_size()
292 ok |= hpass->set_int("input_width", input_width);
293 ok |= hpass->set_int("input_height", input_height);
294 ok |= hpass->set_int("output_width", output_width);
295 ok |= hpass->set_int("output_height", input_height);
297 ok |= vpass->set_int("input_width", output_width);
298 ok |= vpass->set_int("input_height", input_height);
299 ok |= vpass->set_int("output_width", output_width);
300 ok |= vpass->set_int("output_height", output_height);
304 // The offset added due to zoom may have changed with the size.
305 update_offset_and_zoom();
308 void ResampleEffect::update_offset_and_zoom()
312 // Zoom from the right origin. (zoom_center is given in normalized coordinates,
314 float extra_offset_x = zoom_center_x * (1.0f - 1.0f / zoom_x) * input_width;
315 float extra_offset_y = (1.0f - zoom_center_y) * (1.0f - 1.0f / zoom_y) * input_height;
317 ok |= hpass->set_float("offset", extra_offset_x + offset_x);
318 ok |= vpass->set_float("offset", extra_offset_y - offset_y); // Compensate for the bottom-left origin.
319 ok |= hpass->set_float("zoom", zoom_x);
320 ok |= vpass->set_float("zoom", zoom_y);
325 bool ResampleEffect::set_float(const string &key, float value) {
326 if (key == "width") {
327 output_width = value;
331 if (key == "height") {
332 output_height = value;
338 update_offset_and_zoom();
343 update_offset_and_zoom();
346 if (key == "zoom_x") {
351 update_offset_and_zoom();
354 if (key == "zoom_y") {
359 update_offset_and_zoom();
362 if (key == "zoom_center_x") {
363 zoom_center_x = value;
364 update_offset_and_zoom();
367 if (key == "zoom_center_y") {
368 zoom_center_y = value;
369 update_offset_and_zoom();
375 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
377 direction(HORIZONTAL),
382 last_input_width(-1),
383 last_input_height(-1),
384 last_output_width(-1),
385 last_output_height(-1),
386 last_offset(0.0 / 0.0), // NaN.
387 last_zoom(0.0 / 0.0), // NaN.
388 last_texture_width(-1), last_texture_height(-1)
390 register_int("direction", (int *)&direction);
391 register_int("input_width", &input_width);
392 register_int("input_height", &input_height);
393 register_int("output_width", &output_width);
394 register_int("output_height", &output_height);
395 register_float("offset", &offset);
396 register_float("zoom", &zoom);
397 register_uniform_sampler2d("sample_tex", &uniform_sample_tex);
398 register_uniform_int("num_samples", &uniform_num_samples); // FIXME: What about GLSL pre-1.30?
399 register_uniform_float("num_loops", &uniform_num_loops);
400 register_uniform_float("slice_height", &uniform_slice_height);
401 register_uniform_float("sample_x_scale", &uniform_sample_x_scale);
402 register_uniform_float("sample_x_offset", &uniform_sample_x_offset);
403 register_uniform_float("whole_pixel_offset", &uniform_whole_pixel_offset);
405 glGenTextures(1, &texnum);
408 SingleResamplePassEffect::~SingleResamplePassEffect()
410 glDeleteTextures(1, &texnum);
413 string SingleResamplePassEffect::output_fragment_shader()
416 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
417 return buf + read_file("resample_effect.frag");
420 // Using vertical scaling as an example:
422 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
424 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
425 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
426 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
427 // and so on. For each y, we encode these along the x-axis (since that is spare),
428 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
430 // For horizontal scaling, we fill in the exact same texture;
431 // the shader just interprets it differently.
432 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
434 unsigned src_size, dst_size;
435 if (direction == SingleResamplePassEffect::HORIZONTAL) {
436 assert(input_height == output_height);
437 src_size = input_width;
438 dst_size = output_width;
439 } else if (direction == SingleResamplePassEffect::VERTICAL) {
440 assert(input_width == output_width);
441 src_size = input_height;
442 dst_size = output_height;
447 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
448 // set of samples over and over again in a loop. Thus, we can compute only
449 // the first such loop, and then ask the card to repeat the texture for us.
450 // This is both easier on the texture cache and lowers our CPU cost for
451 // generating the kernel somewhat.
452 float scaling_factor;
453 if (fabs(zoom - 1.0f) < 1e-6) {
454 num_loops = gcd(src_size, dst_size);
455 scaling_factor = float(dst_size) / float(src_size);
457 // If zooming is enabled (ie., zoom != 1), we turn off the looping.
458 // We _could_ perhaps do it for rational zoom levels (especially
459 // things like 2:1), but it doesn't seem to be worth it, given that
460 // the most common use case would seem to be varying the zoom
461 // from frame to frame.
463 scaling_factor = zoom * float(dst_size) / float(src_size);
465 slice_height = 1.0f / num_loops;
466 unsigned dst_samples = dst_size / num_loops;
468 // Sample the kernel in the right place. A diagram with a triangular kernel
469 // (corresponding to linear filtering, and obviously with radius 1)
470 // for easier ASCII art drawing:
476 // x---x---x x x---x---x---x
478 // Scaling up (in this case, 2x) means sampling more densely:
484 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
486 // When scaling up, any destination pixel will only be influenced by a few
487 // (in this case, two) neighboring pixels, and more importantly, the number
488 // will not be influenced by the scaling factor. (Note, however, that the
489 // pixel centers have moved, due to OpenGL's center-pixel convention.)
490 // The only thing that changes is the weights themselves, as the sampling
491 // points are at different distances from the original pixels.
493 // Scaling down is a different story:
499 // --x------ x --x-------x--
501 // Again, the pixel centers have moved in a maybe unintuitive fashion,
502 // although when you consider that there are multiple source pixels around,
503 // it's not so bad as at first look:
509 // --x-------x-------x-------x--
511 // As you can see, the new pixels become averages of the two neighboring old
512 // ones (the situation for Lanczos is of course more complex).
514 // Anyhow, in this case we clearly need to look at more source pixels
515 // to compute the destination pixel, and how many depend on the scaling factor.
516 // Thus, the kernel width will vary with how much we scale.
517 float radius_scaling_factor = min(scaling_factor, 1.0f);
518 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
519 int src_samples = int_radius * 2 + 1;
520 Tap<float> *weights = new Tap<float>[dst_samples * src_samples];
521 float subpixel_offset = offset - lrintf(offset); // The part not covered by whole_pixel_offset.
522 assert(subpixel_offset >= -0.5f && subpixel_offset <= 0.5f);
523 for (unsigned y = 0; y < dst_samples; ++y) {
524 // Find the point around which we want to sample the source image,
525 // compensating for differing pixel centers as the scale changes.
526 float center_src_y = (y + 0.5f) / scaling_factor - 0.5f;
527 int base_src_y = lrintf(center_src_y);
529 // Now sample <int_radius> pixels on each side around that point.
530 for (int i = 0; i < src_samples; ++i) {
531 int src_y = base_src_y + i - int_radius;
532 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y - subpixel_offset), LANCZOS_RADIUS);
533 weights[y * src_samples + i].weight = weight * radius_scaling_factor;
534 weights[y * src_samples + i].pos = (src_y + 0.5) / float(src_size);
538 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
539 // we need to make. Try fp16 first; if it's not accurate enough, we go to fp32.
540 // Our tolerance level for total error is a bit higher than the one for invididual
541 // samples, since one would assume overall errors in the shape don't matter as much.
542 const float max_error = 2.0f / (255.0f * 255.0f);
543 Tap<fp16_int_t> *bilinear_weights_fp16;
544 src_bilinear_samples = combine_many_samples(weights, src_size, src_samples, dst_samples, &bilinear_weights_fp16);
545 Tap<float> *bilinear_weights_fp32 = NULL;
546 bool fallback_to_fp32 = false;
547 double max_sum_sq_error_fp16 = 0.0;
548 for (unsigned y = 0; y < dst_samples; ++y) {
549 double sum_sq_error_fp16 = compute_sum_sq_error(
550 weights + y * src_samples, src_samples,
551 bilinear_weights_fp16 + y * src_bilinear_samples, src_bilinear_samples,
553 max_sum_sq_error_fp16 = std::max(max_sum_sq_error_fp16, sum_sq_error_fp16);
554 if (max_sum_sq_error_fp16 > max_error) {
559 if (max_sum_sq_error_fp16 > max_error) {
560 fallback_to_fp32 = true;
561 src_bilinear_samples = combine_many_samples(weights, src_size, src_samples, dst_samples, &bilinear_weights_fp32);
564 // Encode as a two-component texture. Note the GL_REPEAT.
565 glActiveTexture(GL_TEXTURE0 + *sampler_num);
567 glBindTexture(GL_TEXTURE_2D, texnum);
569 if (last_texture_width == -1) {
570 // Need to set this state the first time.
571 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
573 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
575 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
579 GLenum type, internal_format;
581 if (fallback_to_fp32) {
583 internal_format = GL_RG32F;
584 pixels = bilinear_weights_fp32;
586 type = GL_HALF_FLOAT;
587 internal_format = GL_RG16F;
588 pixels = bilinear_weights_fp16;
591 if (int(src_bilinear_samples) == last_texture_width &&
592 int(dst_samples) == last_texture_height &&
593 internal_format == last_texture_internal_format) {
594 // Texture dimensions and type are unchanged; it is more efficient
595 // to just update it rather than making an entirely new texture.
596 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, src_bilinear_samples, dst_samples, GL_RG, type, pixels);
598 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, src_bilinear_samples, dst_samples, 0, GL_RG, type, pixels);
599 last_texture_width = src_bilinear_samples;
600 last_texture_height = dst_samples;
601 last_texture_internal_format = internal_format;
606 delete[] bilinear_weights_fp16;
607 delete[] bilinear_weights_fp32;
610 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
612 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
614 assert(input_width > 0);
615 assert(input_height > 0);
616 assert(output_width > 0);
617 assert(output_height > 0);
619 if (input_width != last_input_width ||
620 input_height != last_input_height ||
621 output_width != last_output_width ||
622 output_height != last_output_height ||
623 offset != last_offset ||
625 update_texture(glsl_program_num, prefix, sampler_num);
626 last_input_width = input_width;
627 last_input_height = input_height;
628 last_output_width = output_width;
629 last_output_height = output_height;
630 last_offset = offset;
634 glActiveTexture(GL_TEXTURE0 + *sampler_num);
636 glBindTexture(GL_TEXTURE_2D, texnum);
639 uniform_sample_tex = *sampler_num;
641 uniform_num_samples = src_bilinear_samples;
642 uniform_num_loops = num_loops;
643 uniform_slice_height = slice_height;
645 // Instructions for how to convert integer sample numbers to positions in the weight texture.
646 uniform_sample_x_scale = 1.0f / src_bilinear_samples;
647 uniform_sample_x_offset = 0.5f / src_bilinear_samples;
649 if (direction == SingleResamplePassEffect::VERTICAL) {
650 uniform_whole_pixel_offset = lrintf(offset) / float(input_height);
652 uniform_whole_pixel_offset = lrintf(offset) / float(input_width);
655 // We specifically do not want mipmaps on the input texture;
656 // they break minification.
657 Node *self = chain->find_node_for_effect(this);
658 glActiveTexture(chain->get_input_sampler(self, 0));
660 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);