1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
11 #include "effect_chain.h"
12 #include "effect_util.h"
15 #include "resample_effect.h"
33 return 1.0f - fabs(x);
39 float lanczos_weight(float x, float a)
44 return sinc(M_PI * x) * sinc(M_PI * x / a);
48 // Euclid's algorithm, from Wikipedia.
49 unsigned gcd(unsigned a, unsigned b)
59 template<class DestFloat>
60 unsigned combine_samples(const Tap<float> *src, Tap<DestFloat> *dst, unsigned src_size, unsigned num_src_samples, unsigned max_samples_saved)
62 unsigned num_samples_saved = 0;
63 for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
64 // Copy the sample directly; it will be overwritten later if we can combine.
66 dst[j].weight = convert_float<float, DestFloat>(src[i].weight);
67 dst[j].pos = convert_float<float, DestFloat>(src[i].pos);
70 if (i == num_src_samples - 1) {
71 // Last sample; cannot combine.
74 assert(num_samples_saved <= max_samples_saved);
75 if (num_samples_saved == max_samples_saved) {
76 // We could maybe save more here, but other rows can't, so don't bother.
80 float w1 = src[i].weight;
81 float w2 = src[i + 1].weight;
83 // Differing signs; cannot combine.
87 float pos1 = src[i].pos;
88 float pos2 = src[i + 1].pos;
91 fp16_int_t pos, total_weight;
93 combine_two_samples(w1, w2, pos1, pos2, src_size, &pos, &total_weight, &sum_sq_error);
95 // If the interpolation error is larger than that of about sqrt(2) of
96 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
97 // but since the artifacts are not really random, they can get quite
98 // visible. On the other hand, going to 0.25f, I can see no change at
99 // all with 8-bit output, so it would not seem to be worth it.)
100 if (sum_sq_error > 0.5f / (255.0f * 255.0f)) {
104 // OK, we can combine this and the next sample.
106 dst[j].weight = total_weight;
110 ++i; // Skip the next sample.
113 return num_samples_saved;
116 // Make use of the bilinear filtering in the GPU to reduce the number of samples
117 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
118 // two neighboring samples if their weights have differing signs, so we first need to
119 // figure out the maximum number of samples. Then, we downconvert all the weights to
120 // that number -- we could have gone for a variable-length system, but this is simpler,
121 // and the gains would probably be offset by the extra cost of checking when to stop.
123 // The greedy strategy for combining samples is optimal.
124 template<class DestFloat>
125 unsigned combine_many_samples(const Tap<float> *weights, unsigned src_size, unsigned src_samples, unsigned dst_samples, Tap<DestFloat> **bilinear_weights)
127 int src_bilinear_samples = 0;
128 for (unsigned y = 0; y < dst_samples; ++y) {
129 unsigned num_samples_saved = combine_samples<DestFloat>(weights + y * src_samples, NULL, src_size, src_samples, UINT_MAX);
130 src_bilinear_samples = max<int>(src_bilinear_samples, src_samples - num_samples_saved);
133 // Now that we know the right width, actually combine the samples.
134 *bilinear_weights = new Tap<DestFloat>[dst_samples * src_bilinear_samples];
135 for (unsigned y = 0; y < dst_samples; ++y) {
136 Tap<DestFloat> *bilinear_weights_ptr = *bilinear_weights + y * src_bilinear_samples;
137 unsigned num_samples_saved = combine_samples(
138 weights + y * src_samples,
139 bilinear_weights_ptr,
142 src_samples - src_bilinear_samples);
143 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
145 // Normalize so that the sum becomes one. Note that we do it twice;
146 // this sometimes helps a tiny little bit when we have many samples.
147 for (int normalize_pass = 0; normalize_pass < 2; ++normalize_pass) {
149 for (int i = 0; i < src_bilinear_samples; ++i) {
150 sum += to_fp64(bilinear_weights_ptr[i].weight);
152 for (int i = 0; i < src_bilinear_samples; ++i) {
153 bilinear_weights_ptr[i].weight = from_fp64<DestFloat>(
154 to_fp64(bilinear_weights_ptr[i].weight) / sum);
158 return src_bilinear_samples;
161 // Compute the sum of squared errors between the ideal weights (which are
162 // assumed to fall exactly on pixel centers) and the weights that result
163 // from sampling at <bilinear_weights>. The primary reason for the difference
164 // is inaccuracy in the sampling positions, both due to limited precision
165 // in storing them (already inherent in sending them in as fp16_int_t)
166 // and in subtexel sampling precision (which we calculate in this function).
168 double compute_sum_sq_error(const Tap<float>* weights, unsigned num_weights,
169 const Tap<T>* bilinear_weights, unsigned num_bilinear_weights,
172 // Find the effective range of the bilinear-optimized kernel.
173 // Due to rounding of the positions, this is not necessarily the same
174 // as the intended range (ie., the range of the original weights).
175 int lower_pos = int(floor(to_fp64(bilinear_weights[0].pos) * size - 0.5));
176 int upper_pos = int(ceil(to_fp64(bilinear_weights[num_bilinear_weights - 1].pos) * size - 0.5)) + 2;
177 lower_pos = min<int>(lower_pos, lrintf(weights[0].pos * size - 0.5));
178 upper_pos = max<int>(upper_pos, lrintf(weights[num_weights - 1].pos * size - 0.5));
180 float* effective_weights = new float[upper_pos - lower_pos];
181 for (int i = 0; i < upper_pos - lower_pos; ++i) {
182 effective_weights[i] = 0.0f;
185 // Now find the effective weights that result from this sampling.
186 for (unsigned i = 0; i < num_bilinear_weights; ++i) {
187 const float pixel_pos = to_fp64(bilinear_weights[i].pos) * size - 0.5f;
188 const int x0 = int(floor(pixel_pos)) - lower_pos;
189 const int x1 = x0 + 1;
190 const float f = lrintf((pixel_pos - (x0 + lower_pos)) / movit_texel_subpixel_precision) * movit_texel_subpixel_precision;
194 assert(x0 < upper_pos - lower_pos);
195 assert(x1 < upper_pos - lower_pos);
197 effective_weights[x0] += to_fp64(bilinear_weights[i].weight) * (1.0 - f);
198 effective_weights[x1] += to_fp64(bilinear_weights[i].weight) * f;
201 // Subtract the desired weights to get the error.
202 for (unsigned i = 0; i < num_weights; ++i) {
203 const int x = lrintf(weights[i].pos * size - 0.5f) - lower_pos;
205 assert(x < upper_pos - lower_pos);
207 effective_weights[x] -= weights[i].weight;
210 double sum_sq_error = 0.0;
211 for (unsigned i = 0; i < num_weights; ++i) {
212 sum_sq_error += effective_weights[i] * effective_weights[i];
215 delete[] effective_weights;
221 ResampleEffect::ResampleEffect()
224 offset_x(0.0f), offset_y(0.0f),
225 zoom_x(1.0f), zoom_y(1.0f),
226 zoom_center_x(0.5f), zoom_center_y(0.5f)
228 register_int("width", &output_width);
229 register_int("height", &output_height);
231 // The first blur pass will forward resolution information to us.
232 hpass = new SingleResamplePassEffect(this);
233 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
234 vpass = new SingleResamplePassEffect(NULL);
235 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
240 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
242 Node *hpass_node = graph->add_node(hpass);
243 Node *vpass_node = graph->add_node(vpass);
244 graph->connect_nodes(hpass_node, vpass_node);
245 graph->replace_receiver(self, hpass_node);
246 graph->replace_sender(self, vpass_node);
247 self->disabled = true;
250 // We get this information forwarded from the first blur pass,
251 // since we are not part of the chain ourselves.
252 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
254 assert(input_num == 0);
258 input_height = height;
262 void ResampleEffect::update_size()
265 ok |= hpass->set_int("input_width", input_width);
266 ok |= hpass->set_int("input_height", input_height);
267 ok |= hpass->set_int("output_width", output_width);
268 ok |= hpass->set_int("output_height", input_height);
270 ok |= vpass->set_int("input_width", output_width);
271 ok |= vpass->set_int("input_height", input_height);
272 ok |= vpass->set_int("output_width", output_width);
273 ok |= vpass->set_int("output_height", output_height);
277 // The offset added due to zoom may have changed with the size.
278 update_offset_and_zoom();
281 void ResampleEffect::update_offset_and_zoom()
285 // Zoom from the right origin. (zoom_center is given in normalized coordinates,
287 float extra_offset_x = zoom_center_x * (1.0f - 1.0f / zoom_x) * input_width;
288 float extra_offset_y = (1.0f - zoom_center_y) * (1.0f - 1.0f / zoom_y) * input_height;
290 ok |= hpass->set_float("offset", extra_offset_x + offset_x);
291 ok |= vpass->set_float("offset", extra_offset_y - offset_y); // Compensate for the bottom-left origin.
292 ok |= hpass->set_float("zoom", zoom_x);
293 ok |= vpass->set_float("zoom", zoom_y);
298 bool ResampleEffect::set_float(const string &key, float value) {
299 if (key == "width") {
300 output_width = value;
304 if (key == "height") {
305 output_height = value;
311 update_offset_and_zoom();
316 update_offset_and_zoom();
319 if (key == "zoom_x") {
324 update_offset_and_zoom();
327 if (key == "zoom_y") {
332 update_offset_and_zoom();
335 if (key == "zoom_center_x") {
336 zoom_center_x = value;
337 update_offset_and_zoom();
340 if (key == "zoom_center_y") {
341 zoom_center_y = value;
342 update_offset_and_zoom();
348 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
350 direction(HORIZONTAL),
355 last_input_width(-1),
356 last_input_height(-1),
357 last_output_width(-1),
358 last_output_height(-1),
359 last_offset(0.0 / 0.0), // NaN.
360 last_zoom(0.0 / 0.0) // NaN.
362 register_int("direction", (int *)&direction);
363 register_int("input_width", &input_width);
364 register_int("input_height", &input_height);
365 register_int("output_width", &output_width);
366 register_int("output_height", &output_height);
367 register_float("offset", &offset);
368 register_float("zoom", &zoom);
370 glGenTextures(1, &texnum);
373 SingleResamplePassEffect::~SingleResamplePassEffect()
375 glDeleteTextures(1, &texnum);
378 string SingleResamplePassEffect::output_fragment_shader()
381 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
382 return buf + read_file("resample_effect.frag");
385 // Using vertical scaling as an example:
387 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
389 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
390 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
391 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
392 // and so on. For each y, we encode these along the x-axis (since that is spare),
393 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
395 // For horizontal scaling, we fill in the exact same texture;
396 // the shader just interprets it differently.
397 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
399 unsigned src_size, dst_size;
400 if (direction == SingleResamplePassEffect::HORIZONTAL) {
401 assert(input_height == output_height);
402 src_size = input_width;
403 dst_size = output_width;
404 } else if (direction == SingleResamplePassEffect::VERTICAL) {
405 assert(input_width == output_width);
406 src_size = input_height;
407 dst_size = output_height;
412 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
413 // set of samples over and over again in a loop. Thus, we can compute only
414 // the first such loop, and then ask the card to repeat the texture for us.
415 // This is both easier on the texture cache and lowers our CPU cost for
416 // generating the kernel somewhat.
417 float scaling_factor;
418 if (fabs(zoom - 1.0f) < 1e-6) {
419 num_loops = gcd(src_size, dst_size);
420 scaling_factor = float(dst_size) / float(src_size);
422 // If zooming is enabled (ie., zoom != 1), we turn off the looping.
423 // We _could_ perhaps do it for rational zoom levels (especially
424 // things like 2:1), but it doesn't seem to be worth it, given that
425 // the most common use case would seem to be varying the zoom
426 // from frame to frame.
428 scaling_factor = zoom * float(dst_size) / float(src_size);
430 slice_height = 1.0f / num_loops;
431 unsigned dst_samples = dst_size / num_loops;
433 // Sample the kernel in the right place. A diagram with a triangular kernel
434 // (corresponding to linear filtering, and obviously with radius 1)
435 // for easier ASCII art drawing:
441 // x---x---x x x---x---x---x
443 // Scaling up (in this case, 2x) means sampling more densely:
449 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
451 // When scaling up, any destination pixel will only be influenced by a few
452 // (in this case, two) neighboring pixels, and more importantly, the number
453 // will not be influenced by the scaling factor. (Note, however, that the
454 // pixel centers have moved, due to OpenGL's center-pixel convention.)
455 // The only thing that changes is the weights themselves, as the sampling
456 // points are at different distances from the original pixels.
458 // Scaling down is a different story:
464 // --x------ x --x-------x--
466 // Again, the pixel centers have moved in a maybe unintuitive fashion,
467 // although when you consider that there are multiple source pixels around,
468 // it's not so bad as at first look:
474 // --x-------x-------x-------x--
476 // As you can see, the new pixels become averages of the two neighboring old
477 // ones (the situation for Lanczos is of course more complex).
479 // Anyhow, in this case we clearly need to look at more source pixels
480 // to compute the destination pixel, and how many depend on the scaling factor.
481 // Thus, the kernel width will vary with how much we scale.
482 float radius_scaling_factor = min(scaling_factor, 1.0f);
483 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
484 int src_samples = int_radius * 2 + 1;
485 Tap<float> *weights = new Tap<float>[dst_samples * src_samples];
486 float subpixel_offset = offset - lrintf(offset); // The part not covered by whole_pixel_offset.
487 assert(subpixel_offset >= -0.5f && subpixel_offset <= 0.5f);
488 for (unsigned y = 0; y < dst_samples; ++y) {
489 // Find the point around which we want to sample the source image,
490 // compensating for differing pixel centers as the scale changes.
491 float center_src_y = (y + 0.5f) / scaling_factor - 0.5f;
492 int base_src_y = lrintf(center_src_y);
494 // Now sample <int_radius> pixels on each side around that point.
495 for (int i = 0; i < src_samples; ++i) {
496 int src_y = base_src_y + i - int_radius;
497 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y - subpixel_offset), LANCZOS_RADIUS);
498 weights[y * src_samples + i].weight = weight * radius_scaling_factor;
499 weights[y * src_samples + i].pos = (src_y + 0.5) / float(src_size);
503 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
504 // we need to make. Try fp16 first; if it's not accurate enough, we go to fp32.
505 Tap<fp16_int_t> *bilinear_weights_fp16;
506 src_bilinear_samples = combine_many_samples(weights, src_size, src_samples, dst_samples, &bilinear_weights_fp16);
507 Tap<float> *bilinear_weights_fp32 = NULL;
508 bool fallback_to_fp32 = false;
509 double max_sum_sq_error_fp16 = 0.0;
510 for (unsigned y = 0; y < dst_samples; ++y) {
511 double sum_sq_error_fp16 = compute_sum_sq_error(
512 weights + y * src_samples, src_samples,
513 bilinear_weights_fp16 + y * src_bilinear_samples, src_bilinear_samples,
515 max_sum_sq_error_fp16 = std::max(max_sum_sq_error_fp16, sum_sq_error_fp16);
518 // Our tolerance level for total error is a bit higher than the one for invididual
519 // samples, since one would assume overall errors in the shape don't matter as much.
520 if (max_sum_sq_error_fp16 > 2.0f / (255.0f * 255.0f)) {
521 fallback_to_fp32 = true;
522 src_bilinear_samples = combine_many_samples(weights, src_size, src_samples, dst_samples, &bilinear_weights_fp32);
525 // Encode as a two-component texture. Note the GL_REPEAT.
526 glActiveTexture(GL_TEXTURE0 + *sampler_num);
528 glBindTexture(GL_TEXTURE_2D, texnum);
530 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
532 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
534 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
536 if (fallback_to_fp32) {
537 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights_fp32);
539 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_HALF_FLOAT, bilinear_weights_fp16);
544 delete[] bilinear_weights_fp16;
545 delete[] bilinear_weights_fp32;
548 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
550 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
552 assert(input_width > 0);
553 assert(input_height > 0);
554 assert(output_width > 0);
555 assert(output_height > 0);
557 if (input_width != last_input_width ||
558 input_height != last_input_height ||
559 output_width != last_output_width ||
560 output_height != last_output_height ||
561 offset != last_offset ||
563 update_texture(glsl_program_num, prefix, sampler_num);
564 last_input_width = input_width;
565 last_input_height = input_height;
566 last_output_width = output_width;
567 last_output_height = output_height;
568 last_offset = offset;
572 glActiveTexture(GL_TEXTURE0 + *sampler_num);
574 glBindTexture(GL_TEXTURE_2D, texnum);
577 set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
579 set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
580 set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
581 set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
583 // Instructions for how to convert integer sample numbers to positions in the weight texture.
584 set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
585 set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
587 float whole_pixel_offset;
588 if (direction == SingleResamplePassEffect::VERTICAL) {
589 whole_pixel_offset = lrintf(offset) / float(input_height);
591 whole_pixel_offset = lrintf(offset) / float(input_width);
593 set_uniform_float(glsl_program_num, prefix, "whole_pixel_offset", whole_pixel_offset);
595 // We specifically do not want mipmaps on the input texture;
596 // they break minification.
597 Node *self = chain->find_node_for_effect(this);
598 glActiveTexture(chain->get_input_sampler(self, 0));
600 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);