1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
7 #include "resample_effect.h"
8 #include "effect_chain.h"
17 return 1.0f - fabs(x);
23 float lanczos_weight(float x, float a)
28 return sinc(M_PI * x) * sinc(M_PI * x / a);
32 // Euclid's algorithm, from Wikipedia.
33 unsigned gcd(unsigned a, unsigned b)
43 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
45 unsigned num_samples_saved = 0;
46 for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
47 // Copy the sample directly; it will be overwritten later if we can combine.
49 dst[j * 2 + 0] = src[i * 2 + 0];
50 dst[j * 2 + 1] = src[i * 2 + 1];
53 if (i == num_src_samples - 1) {
54 // Last sample; cannot combine.
57 assert(num_samples_saved <= max_samples_saved);
58 if (num_samples_saved == max_samples_saved) {
59 // We could maybe save more here, but other rows can't, so don't bother.
63 float w1 = src[i * 2 + 0];
64 float w2 = src[(i + 1) * 2 + 0];
66 // Differing signs; cannot combine.
70 float pos1 = src[i * 2 + 1];
71 float pos2 = src[(i + 1) * 2 + 1];
74 float offset, total_weight, sum_sq_error;
75 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
77 // If the interpolation error is larger than that of one level
78 // at 8-bit precision, don't combine.
79 if (sum_sq_error > 1.0f / (256.0f * 256.0f)) {
83 // OK, we can combine this and the next sample.
85 dst[j * 2 + 0] = total_weight;
86 dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
89 ++i; // Skip the next sample.
92 return num_samples_saved;
97 ResampleEffect::ResampleEffect()
101 register_int("width", &output_width);
102 register_int("height", &output_height);
104 // The first blur pass will forward resolution information to us.
105 hpass = new SingleResamplePassEffect(this);
106 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
107 vpass = new SingleResamplePassEffect(NULL);
108 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
113 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
115 Node *hpass_node = graph->add_node(hpass);
116 Node *vpass_node = graph->add_node(vpass);
117 graph->connect_nodes(hpass_node, vpass_node);
118 graph->replace_receiver(self, hpass_node);
119 graph->replace_sender(self, vpass_node);
120 self->disabled = true;
123 // We get this information forwarded from the first blur pass,
124 // since we are not part of the chain ourselves.
125 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
127 assert(input_num == 0);
131 input_height = height;
135 void ResampleEffect::update_size()
138 ok |= hpass->set_int("input_width", input_width);
139 ok |= hpass->set_int("input_height", input_height);
140 ok |= hpass->set_int("output_width", output_width);
141 ok |= hpass->set_int("output_height", input_height);
143 ok |= vpass->set_int("input_width", output_width);
144 ok |= vpass->set_int("input_height", input_height);
145 ok |= vpass->set_int("output_width", output_width);
146 ok |= vpass->set_int("output_height", output_height);
151 bool ResampleEffect::set_float(const std::string &key, float value) {
152 if (key == "width") {
153 output_width = value;
157 if (key == "height") {
158 output_height = value;
165 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
167 direction(HORIZONTAL),
170 last_input_width(-1),
171 last_input_height(-1),
172 last_output_width(-1),
173 last_output_height(-1)
175 register_int("direction", (int *)&direction);
176 register_int("input_width", &input_width);
177 register_int("input_height", &input_height);
178 register_int("output_width", &output_width);
179 register_int("output_height", &output_height);
181 glGenTextures(1, &texnum);
184 SingleResamplePassEffect::~SingleResamplePassEffect()
186 glDeleteTextures(1, &texnum);
189 std::string SingleResamplePassEffect::output_fragment_shader()
192 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
193 return buf + read_file("resample_effect.frag");
196 // Using vertical scaling as an example:
198 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
200 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
201 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
202 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
203 // and so on. For each y, we encode these along the x-axis (since that is spare),
204 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
206 // For horizontal scaling, we fill in the exact same texture;
207 // the shader just interprets is differently.
208 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
210 unsigned src_size, dst_size;
211 if (direction == SingleResamplePassEffect::HORIZONTAL) {
212 assert(input_height == output_height);
213 src_size = input_width;
214 dst_size = output_width;
215 } else if (direction == SingleResamplePassEffect::VERTICAL) {
216 assert(input_width == output_width);
217 src_size = input_height;
218 dst_size = output_height;
224 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
225 // set of samples over and over again in a loop. Thus, we can compute only
226 // the first such loop, and then ask the card to repeat the texture for us.
227 // This is both easier on the texture cache and lowers our CPU cost for
228 // generating the kernel somewhat.
229 num_loops = gcd(src_size, dst_size);
230 slice_height = 1.0f / num_loops;
231 unsigned dst_samples = dst_size / num_loops;
233 // Sample the kernel in the right place. A diagram with a triangular kernel
234 // (corresponding to linear filtering, and obviously with radius 1)
235 // for easier ASCII art drawing:
241 // x---x---x x x---x---x---x
243 // Scaling up (in this case, 2x) means sampling more densely:
249 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
251 // When scaling up, any destination pixel will only be influenced by a few
252 // (in this case, two) neighboring pixels, and more importantly, the number
253 // will not be influenced by the scaling factor. (Note, however, that the
254 // pixel centers have moved, due to OpenGL's center-pixel convention.)
255 // The only thing that changes is the weights themselves, as the sampling
256 // points are at different distances from the original pixels.
258 // Scaling down is a different story:
264 // --x------ x --x-------x--
266 // Again, the pixel centers have moved in a maybe unintuitive fashion,
267 // although when you consider that there are multiple source pixels around,
268 // it's not so bad as at first look:
274 // --x-------x-------x-------x--
276 // As you can see, the new pixels become averages of the two neighboring old
277 // ones (the situation for Lanczos is of course more complex).
279 // Anyhow, in this case we clearly need to look at more source pixels
280 // to compute the destination pixel, and how many depend on the scaling factor.
281 // Thus, the kernel width will vary with how much we scale.
282 float radius_scaling_factor = std::min(float(dst_size) / float(src_size), 1.0f);
283 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
284 int src_samples = int_radius * 2 + 1;
285 float *weights = new float[dst_samples * src_samples * 2];
286 for (unsigned y = 0; y < dst_samples; ++y) {
287 // Find the point around which we want to sample the source image,
288 // compensating for differing pixel centers as the scale changes.
289 float center_src_y = (y + 0.5f) * float(src_size) / float(dst_size) - 0.5f;
290 int base_src_y = lrintf(center_src_y);
292 // Now sample <int_radius> pixels on each side around that point.
293 for (int i = 0; i < src_samples; ++i) {
294 int src_y = base_src_y + i - int_radius;
295 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y), LANCZOS_RADIUS);
296 weights[(y * src_samples + i) * 2 + 0] = weight * radius_scaling_factor;
297 weights[(y * src_samples + i) * 2 + 1] = (src_y + 0.5) / float(src_size);
301 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
302 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
303 // two neighboring samples if their weights have differing signs, so we first need to
304 // figure out the maximum number of samples. Then, we downconvert all the weights to
305 // that number -- we could have gone for a variable-length system, but this is simpler,
306 // and the gains would probably be offset by the extra cost of checking when to stop.
308 // The greedy strategy for combining samples is optimal.
309 src_bilinear_samples = 0;
310 for (unsigned y = 0; y < dst_samples; ++y) {
311 unsigned num_samples_saved = combine_samples(weights + (y * src_samples) * 2, NULL, src_samples, UINT_MAX);
312 src_bilinear_samples = std::max<int>(src_bilinear_samples, src_samples - num_samples_saved);
315 // Now that we know the right width, actually combine the samples.
316 float *bilinear_weights = new float[dst_samples * src_bilinear_samples * 2];
317 for (unsigned y = 0; y < dst_samples; ++y) {
318 unsigned num_samples_saved = combine_samples(
319 weights + (y * src_samples) * 2,
320 bilinear_weights + (y * src_bilinear_samples) * 2,
322 src_samples - src_bilinear_samples);
323 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
326 // Encode as a two-component texture. Note the GL_REPEAT.
327 glActiveTexture(GL_TEXTURE0 + *sampler_num);
329 glBindTexture(GL_TEXTURE_2D, texnum);
331 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
337 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
341 delete[] bilinear_weights;
344 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
346 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
348 if (input_width != last_input_width ||
349 input_height != last_input_height ||
350 output_width != last_output_width ||
351 output_height != last_output_height) {
352 update_texture(glsl_program_num, prefix, sampler_num);
353 last_input_width = input_width;
354 last_input_height = input_height;
355 last_output_width = output_width;
356 last_output_height = output_height;
359 glActiveTexture(GL_TEXTURE0 + *sampler_num);
361 glBindTexture(GL_TEXTURE_2D, texnum);
364 set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
366 set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
367 set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
368 set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
370 // Instructions for how to convert integer sample numbers to positions in the weight texture.
371 set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
372 set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
374 // We specifically do not want mipmaps on the input texture;
375 // they break minification.
376 glActiveTexture(GL_TEXTURE0);
378 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);