1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
8 #include "resample_effect.h"
9 #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 about sqrt(2) of
78 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
79 // but since the artifacts are not really random, they can get quite
80 // visible. On the other hand, going to 0.25f, I can see no change at
81 // all with 8-bit output, so it would not seem to be worth it.)
82 if (sum_sq_error > 0.5f / (256.0f * 256.0f)) {
86 // OK, we can combine this and the next sample.
88 dst[j * 2 + 0] = total_weight;
89 dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
92 ++i; // Skip the next sample.
95 return num_samples_saved;
100 ResampleEffect::ResampleEffect()
104 register_int("width", &output_width);
105 register_int("height", &output_height);
107 // The first blur pass will forward resolution information to us.
108 hpass = new SingleResamplePassEffect(this);
109 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
110 vpass = new SingleResamplePassEffect(NULL);
111 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
116 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
118 Node *hpass_node = graph->add_node(hpass);
119 Node *vpass_node = graph->add_node(vpass);
120 graph->connect_nodes(hpass_node, vpass_node);
121 graph->replace_receiver(self, hpass_node);
122 graph->replace_sender(self, vpass_node);
123 self->disabled = true;
126 // We get this information forwarded from the first blur pass,
127 // since we are not part of the chain ourselves.
128 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
130 assert(input_num == 0);
134 input_height = height;
138 void ResampleEffect::update_size()
141 ok |= hpass->set_int("input_width", input_width);
142 ok |= hpass->set_int("input_height", input_height);
143 ok |= hpass->set_int("output_width", output_width);
144 ok |= hpass->set_int("output_height", input_height);
146 ok |= vpass->set_int("input_width", output_width);
147 ok |= vpass->set_int("input_height", input_height);
148 ok |= vpass->set_int("output_width", output_width);
149 ok |= vpass->set_int("output_height", output_height);
154 bool ResampleEffect::set_float(const std::string &key, float value) {
155 if (key == "width") {
156 output_width = value;
160 if (key == "height") {
161 output_height = value;
168 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
170 direction(HORIZONTAL),
173 last_input_width(-1),
174 last_input_height(-1),
175 last_output_width(-1),
176 last_output_height(-1)
178 register_int("direction", (int *)&direction);
179 register_int("input_width", &input_width);
180 register_int("input_height", &input_height);
181 register_int("output_width", &output_width);
182 register_int("output_height", &output_height);
184 glGenTextures(1, &texnum);
187 SingleResamplePassEffect::~SingleResamplePassEffect()
189 glDeleteTextures(1, &texnum);
192 std::string SingleResamplePassEffect::output_fragment_shader()
195 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
196 return buf + read_file("resample_effect.frag");
199 // Using vertical scaling as an example:
201 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
203 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
204 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
205 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
206 // and so on. For each y, we encode these along the x-axis (since that is spare),
207 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
209 // For horizontal scaling, we fill in the exact same texture;
210 // the shader just interprets is differently.
211 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
213 unsigned src_size, dst_size;
214 if (direction == SingleResamplePassEffect::HORIZONTAL) {
215 assert(input_height == output_height);
216 src_size = input_width;
217 dst_size = output_width;
218 } else if (direction == SingleResamplePassEffect::VERTICAL) {
219 assert(input_width == output_width);
220 src_size = input_height;
221 dst_size = output_height;
227 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
228 // set of samples over and over again in a loop. Thus, we can compute only
229 // the first such loop, and then ask the card to repeat the texture for us.
230 // This is both easier on the texture cache and lowers our CPU cost for
231 // generating the kernel somewhat.
232 num_loops = gcd(src_size, dst_size);
233 slice_height = 1.0f / num_loops;
234 unsigned dst_samples = dst_size / num_loops;
236 // Sample the kernel in the right place. A diagram with a triangular kernel
237 // (corresponding to linear filtering, and obviously with radius 1)
238 // for easier ASCII art drawing:
244 // x---x---x x x---x---x---x
246 // Scaling up (in this case, 2x) means sampling more densely:
252 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
254 // When scaling up, any destination pixel will only be influenced by a few
255 // (in this case, two) neighboring pixels, and more importantly, the number
256 // will not be influenced by the scaling factor. (Note, however, that the
257 // pixel centers have moved, due to OpenGL's center-pixel convention.)
258 // The only thing that changes is the weights themselves, as the sampling
259 // points are at different distances from the original pixels.
261 // Scaling down is a different story:
267 // --x------ x --x-------x--
269 // Again, the pixel centers have moved in a maybe unintuitive fashion,
270 // although when you consider that there are multiple source pixels around,
271 // it's not so bad as at first look:
277 // --x-------x-------x-------x--
279 // As you can see, the new pixels become averages of the two neighboring old
280 // ones (the situation for Lanczos is of course more complex).
282 // Anyhow, in this case we clearly need to look at more source pixels
283 // to compute the destination pixel, and how many depend on the scaling factor.
284 // Thus, the kernel width will vary with how much we scale.
285 float radius_scaling_factor = std::min(float(dst_size) / float(src_size), 1.0f);
286 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
287 int src_samples = int_radius * 2 + 1;
288 float *weights = new float[dst_samples * src_samples * 2];
289 for (unsigned y = 0; y < dst_samples; ++y) {
290 // Find the point around which we want to sample the source image,
291 // compensating for differing pixel centers as the scale changes.
292 float center_src_y = (y + 0.5f) * float(src_size) / float(dst_size) - 0.5f;
293 int base_src_y = lrintf(center_src_y);
295 // Now sample <int_radius> pixels on each side around that point.
296 for (int i = 0; i < src_samples; ++i) {
297 int src_y = base_src_y + i - int_radius;
298 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y), LANCZOS_RADIUS);
299 weights[(y * src_samples + i) * 2 + 0] = weight * radius_scaling_factor;
300 weights[(y * src_samples + i) * 2 + 1] = (src_y + 0.5) / float(src_size);
304 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
305 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
306 // two neighboring samples if their weights have differing signs, so we first need to
307 // figure out the maximum number of samples. Then, we downconvert all the weights to
308 // that number -- we could have gone for a variable-length system, but this is simpler,
309 // and the gains would probably be offset by the extra cost of checking when to stop.
311 // The greedy strategy for combining samples is optimal.
312 src_bilinear_samples = 0;
313 for (unsigned y = 0; y < dst_samples; ++y) {
314 unsigned num_samples_saved = combine_samples(weights + (y * src_samples) * 2, NULL, src_samples, UINT_MAX);
315 src_bilinear_samples = std::max<int>(src_bilinear_samples, src_samples - num_samples_saved);
318 // Now that we know the right width, actually combine the samples.
319 float *bilinear_weights = new float[dst_samples * src_bilinear_samples * 2];
320 for (unsigned y = 0; y < dst_samples; ++y) {
321 unsigned num_samples_saved = combine_samples(
322 weights + (y * src_samples) * 2,
323 bilinear_weights + (y * src_bilinear_samples) * 2,
325 src_samples - src_bilinear_samples);
326 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
329 // Encode as a two-component texture. Note the GL_REPEAT.
330 glActiveTexture(GL_TEXTURE0 + *sampler_num);
332 glBindTexture(GL_TEXTURE_2D, texnum);
334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
336 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
338 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
340 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
344 delete[] bilinear_weights;
347 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
349 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
351 assert(input_width > 0);
352 assert(input_height > 0);
353 assert(output_width > 0);
354 assert(output_height > 0);
356 if (input_width != last_input_width ||
357 input_height != last_input_height ||
358 output_width != last_output_width ||
359 output_height != last_output_height) {
360 update_texture(glsl_program_num, prefix, sampler_num);
361 last_input_width = input_width;
362 last_input_height = input_height;
363 last_output_width = output_width;
364 last_output_height = output_height;
367 glActiveTexture(GL_TEXTURE0 + *sampler_num);
369 glBindTexture(GL_TEXTURE_2D, texnum);
372 set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
374 set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
375 set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
376 set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
378 // Instructions for how to convert integer sample numbers to positions in the weight texture.
379 set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
380 set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
382 // We specifically do not want mipmaps on the input texture;
383 // they break minification.
384 glActiveTexture(GL_TEXTURE0);
386 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);