1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
11 #include "effect_chain.h"
12 #include "effect_util.h"
14 #include "resample_effect.h"
26 return 1.0f - fabs(x);
32 float lanczos_weight(float x, float a)
37 return sinc(M_PI * x) * sinc(M_PI * x / a);
41 // Euclid's algorithm, from Wikipedia.
42 unsigned gcd(unsigned a, unsigned b)
52 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
54 unsigned num_samples_saved = 0;
55 for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
56 // Copy the sample directly; it will be overwritten later if we can combine.
58 dst[j * 2 + 0] = src[i * 2 + 0];
59 dst[j * 2 + 1] = src[i * 2 + 1];
62 if (i == num_src_samples - 1) {
63 // Last sample; cannot combine.
66 assert(num_samples_saved <= max_samples_saved);
67 if (num_samples_saved == max_samples_saved) {
68 // We could maybe save more here, but other rows can't, so don't bother.
72 float w1 = src[i * 2 + 0];
73 float w2 = src[(i + 1) * 2 + 0];
75 // Differing signs; cannot combine.
79 float pos1 = src[i * 2 + 1];
80 float pos2 = src[(i + 1) * 2 + 1];
83 float offset, total_weight, sum_sq_error;
84 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
86 // If the interpolation error is larger than that of about sqrt(2) of
87 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
88 // but since the artifacts are not really random, they can get quite
89 // visible. On the other hand, going to 0.25f, I can see no change at
90 // all with 8-bit output, so it would not seem to be worth it.)
91 if (sum_sq_error > 0.5f / (256.0f * 256.0f)) {
95 // OK, we can combine this and the next sample.
97 dst[j * 2 + 0] = total_weight;
98 dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
101 ++i; // Skip the next sample.
104 return num_samples_saved;
109 ResampleEffect::ResampleEffect()
113 register_int("width", &output_width);
114 register_int("height", &output_height);
116 // The first blur pass will forward resolution information to us.
117 hpass = new SingleResamplePassEffect(this);
118 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
119 vpass = new SingleResamplePassEffect(NULL);
120 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
125 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
127 Node *hpass_node = graph->add_node(hpass);
128 Node *vpass_node = graph->add_node(vpass);
129 graph->connect_nodes(hpass_node, vpass_node);
130 graph->replace_receiver(self, hpass_node);
131 graph->replace_sender(self, vpass_node);
132 self->disabled = true;
135 // We get this information forwarded from the first blur pass,
136 // since we are not part of the chain ourselves.
137 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
139 assert(input_num == 0);
143 input_height = height;
147 void ResampleEffect::update_size()
150 ok |= hpass->set_int("input_width", input_width);
151 ok |= hpass->set_int("input_height", input_height);
152 ok |= hpass->set_int("output_width", output_width);
153 ok |= hpass->set_int("output_height", input_height);
155 ok |= vpass->set_int("input_width", output_width);
156 ok |= vpass->set_int("input_height", input_height);
157 ok |= vpass->set_int("output_width", output_width);
158 ok |= vpass->set_int("output_height", output_height);
163 bool ResampleEffect::set_float(const string &key, float value) {
164 if (key == "width") {
165 output_width = value;
169 if (key == "height") {
170 output_height = value;
175 // Compensate for the bottom-left origin.
176 return vpass->set_float("offset", -value);
179 return hpass->set_float("offset", value);
184 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
186 direction(HORIZONTAL),
190 last_input_width(-1),
191 last_input_height(-1),
192 last_output_width(-1),
193 last_output_height(-1),
194 last_offset(0.0 / 0.0) // NaN.
196 register_int("direction", (int *)&direction);
197 register_int("input_width", &input_width);
198 register_int("input_height", &input_height);
199 register_int("output_width", &output_width);
200 register_int("output_height", &output_height);
201 register_float("offset", &offset);
203 glGenTextures(1, &texnum);
206 SingleResamplePassEffect::~SingleResamplePassEffect()
208 glDeleteTextures(1, &texnum);
211 string SingleResamplePassEffect::output_fragment_shader()
214 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
215 return buf + read_file("resample_effect.frag");
218 // Using vertical scaling as an example:
220 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
222 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
223 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
224 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
225 // and so on. For each y, we encode these along the x-axis (since that is spare),
226 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
228 // For horizontal scaling, we fill in the exact same texture;
229 // the shader just interprets it differently.
230 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
232 unsigned src_size, dst_size;
233 if (direction == SingleResamplePassEffect::HORIZONTAL) {
234 assert(input_height == output_height);
235 src_size = input_width;
236 dst_size = output_width;
237 } else if (direction == SingleResamplePassEffect::VERTICAL) {
238 assert(input_width == output_width);
239 src_size = input_height;
240 dst_size = output_height;
245 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
246 // set of samples over and over again in a loop. Thus, we can compute only
247 // the first such loop, and then ask the card to repeat the texture for us.
248 // This is both easier on the texture cache and lowers our CPU cost for
249 // generating the kernel somewhat.
250 num_loops = gcd(src_size, dst_size);
251 slice_height = 1.0f / num_loops;
252 unsigned dst_samples = dst_size / num_loops;
254 // Sample the kernel in the right place. A diagram with a triangular kernel
255 // (corresponding to linear filtering, and obviously with radius 1)
256 // for easier ASCII art drawing:
262 // x---x---x x x---x---x---x
264 // Scaling up (in this case, 2x) means sampling more densely:
270 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
272 // When scaling up, any destination pixel will only be influenced by a few
273 // (in this case, two) neighboring pixels, and more importantly, the number
274 // will not be influenced by the scaling factor. (Note, however, that the
275 // pixel centers have moved, due to OpenGL's center-pixel convention.)
276 // The only thing that changes is the weights themselves, as the sampling
277 // points are at different distances from the original pixels.
279 // Scaling down is a different story:
285 // --x------ x --x-------x--
287 // Again, the pixel centers have moved in a maybe unintuitive fashion,
288 // although when you consider that there are multiple source pixels around,
289 // it's not so bad as at first look:
295 // --x-------x-------x-------x--
297 // As you can see, the new pixels become averages of the two neighboring old
298 // ones (the situation for Lanczos is of course more complex).
300 // Anyhow, in this case we clearly need to look at more source pixels
301 // to compute the destination pixel, and how many depend on the scaling factor.
302 // Thus, the kernel width will vary with how much we scale.
303 float radius_scaling_factor = min(float(dst_size) / float(src_size), 1.0f);
304 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
305 int src_samples = int_radius * 2 + 1;
306 float *weights = new float[dst_samples * src_samples * 2];
307 float subpixel_offset = offset - lrintf(offset); // The part not covered by whole_pixel_offset.
308 assert(subpixel_offset >= -0.5f && subpixel_offset <= 0.5f);
309 for (unsigned y = 0; y < dst_samples; ++y) {
310 // Find the point around which we want to sample the source image,
311 // compensating for differing pixel centers as the scale changes.
312 float center_src_y = (y + 0.5f) * float(src_size) / float(dst_size) - 0.5f;
313 int base_src_y = lrintf(center_src_y);
315 // Now sample <int_radius> pixels on each side around that point.
316 for (int i = 0; i < src_samples; ++i) {
317 int src_y = base_src_y + i - int_radius;
318 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y - subpixel_offset), LANCZOS_RADIUS);
319 weights[(y * src_samples + i) * 2 + 0] = weight * radius_scaling_factor;
320 weights[(y * src_samples + i) * 2 + 1] = (src_y + 0.5) / float(src_size);
324 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
325 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
326 // two neighboring samples if their weights have differing signs, so we first need to
327 // figure out the maximum number of samples. Then, we downconvert all the weights to
328 // that number -- we could have gone for a variable-length system, but this is simpler,
329 // and the gains would probably be offset by the extra cost of checking when to stop.
331 // The greedy strategy for combining samples is optimal.
332 src_bilinear_samples = 0;
333 for (unsigned y = 0; y < dst_samples; ++y) {
334 unsigned num_samples_saved = combine_samples(weights + (y * src_samples) * 2, NULL, src_samples, UINT_MAX);
335 src_bilinear_samples = max<int>(src_bilinear_samples, src_samples - num_samples_saved);
338 // Now that we know the right width, actually combine the samples.
339 float *bilinear_weights = new float[dst_samples * src_bilinear_samples * 2];
340 fp16_int_t *bilinear_weights_fp16 = new fp16_int_t[dst_samples * src_bilinear_samples * 2];
341 for (unsigned y = 0; y < dst_samples; ++y) {
342 float *bilinear_weights_ptr = bilinear_weights + (y * src_bilinear_samples) * 2;
343 fp16_int_t *bilinear_weights_fp16_ptr = bilinear_weights_fp16 + (y * src_bilinear_samples) * 2;
344 unsigned num_samples_saved = combine_samples(
345 weights + (y * src_samples) * 2,
346 bilinear_weights_ptr,
348 src_samples - src_bilinear_samples);
349 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
352 for (int i = 0; i < src_bilinear_samples; ++i) {
353 bilinear_weights_fp16_ptr[i * 2 + 0] = fp64_to_fp16(bilinear_weights_ptr[i * 2 + 0]);
354 bilinear_weights_fp16_ptr[i * 2 + 1] = fp64_to_fp16(bilinear_weights_ptr[i * 2 + 1]);
357 // Normalize so that the sum becomes one. Note that we do it twice;
358 // this sometimes helps a tiny little bit when we have many samples.
359 for (int normalize_pass = 0; normalize_pass < 2; ++normalize_pass) {
361 for (int i = 0; i < src_bilinear_samples; ++i) {
362 sum += fp16_to_fp64(bilinear_weights_fp16_ptr[i * 2 + 0]);
364 for (int i = 0; i < src_bilinear_samples; ++i) {
365 bilinear_weights_fp16_ptr[i * 2 + 0] = fp64_to_fp16(
366 fp16_to_fp64(bilinear_weights_fp16_ptr[i * 2 + 0]) / sum);
371 // Encode as a two-component texture. Note the GL_REPEAT.
372 glActiveTexture(GL_TEXTURE0 + *sampler_num);
374 glBindTexture(GL_TEXTURE_2D, texnum);
376 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
378 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
380 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
382 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_HALF_FLOAT, bilinear_weights_fp16);
386 delete[] bilinear_weights;
387 delete[] bilinear_weights_fp16;
390 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
392 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
394 assert(input_width > 0);
395 assert(input_height > 0);
396 assert(output_width > 0);
397 assert(output_height > 0);
399 if (input_width != last_input_width ||
400 input_height != last_input_height ||
401 output_width != last_output_width ||
402 output_height != last_output_height ||
403 offset != last_offset) {
404 update_texture(glsl_program_num, prefix, sampler_num);
405 last_input_width = input_width;
406 last_input_height = input_height;
407 last_output_width = output_width;
408 last_output_height = output_height;
409 last_offset = offset;
412 glActiveTexture(GL_TEXTURE0 + *sampler_num);
414 glBindTexture(GL_TEXTURE_2D, texnum);
417 set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
419 set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
420 set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
421 set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
423 // Instructions for how to convert integer sample numbers to positions in the weight texture.
424 set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
425 set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
427 float whole_pixel_offset;
428 if (direction == SingleResamplePassEffect::VERTICAL) {
429 whole_pixel_offset = lrintf(offset) / float(input_height);
431 whole_pixel_offset = lrintf(offset) / float(input_width);
433 set_uniform_float(glsl_program_num, prefix, "whole_pixel_offset", whole_pixel_offset);
435 // We specifically do not want mipmaps on the input texture;
436 // they break minification.
437 Node *self = chain->find_node_for_effect(this);
438 glActiveTexture(chain->get_input_sampler(self, 0));
440 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);