1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
11 #include "effect_chain.h"
12 #include "resample_effect.h"
20 return 1.0f - fabs(x);
26 float lanczos_weight(float x, float a)
31 return sinc(M_PI * x) * sinc(M_PI * x / a);
35 // Euclid's algorithm, from Wikipedia.
36 unsigned gcd(unsigned a, unsigned b)
46 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
48 unsigned num_samples_saved = 0;
49 for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
50 // Copy the sample directly; it will be overwritten later if we can combine.
52 dst[j * 2 + 0] = src[i * 2 + 0];
53 dst[j * 2 + 1] = src[i * 2 + 1];
56 if (i == num_src_samples - 1) {
57 // Last sample; cannot combine.
60 assert(num_samples_saved <= max_samples_saved);
61 if (num_samples_saved == max_samples_saved) {
62 // We could maybe save more here, but other rows can't, so don't bother.
66 float w1 = src[i * 2 + 0];
67 float w2 = src[(i + 1) * 2 + 0];
69 // Differing signs; cannot combine.
73 float pos1 = src[i * 2 + 1];
74 float pos2 = src[(i + 1) * 2 + 1];
77 float offset, total_weight, sum_sq_error;
78 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
80 // If the interpolation error is larger than that of about sqrt(2) of
81 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
82 // but since the artifacts are not really random, they can get quite
83 // visible. On the other hand, going to 0.25f, I can see no change at
84 // all with 8-bit output, so it would not seem to be worth it.)
85 if (sum_sq_error > 0.5f / (256.0f * 256.0f)) {
89 // OK, we can combine this and the next sample.
91 dst[j * 2 + 0] = total_weight;
92 dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
95 ++i; // Skip the next sample.
98 return num_samples_saved;
103 ResampleEffect::ResampleEffect()
107 register_int("width", &output_width);
108 register_int("height", &output_height);
110 // The first blur pass will forward resolution information to us.
111 hpass = new SingleResamplePassEffect(this);
112 CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
113 vpass = new SingleResamplePassEffect(NULL);
114 CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
119 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
121 Node *hpass_node = graph->add_node(hpass);
122 Node *vpass_node = graph->add_node(vpass);
123 graph->connect_nodes(hpass_node, vpass_node);
124 graph->replace_receiver(self, hpass_node);
125 graph->replace_sender(self, vpass_node);
126 self->disabled = true;
129 // We get this information forwarded from the first blur pass,
130 // since we are not part of the chain ourselves.
131 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
133 assert(input_num == 0);
137 input_height = height;
141 void ResampleEffect::update_size()
144 ok |= hpass->set_int("input_width", input_width);
145 ok |= hpass->set_int("input_height", input_height);
146 ok |= hpass->set_int("output_width", output_width);
147 ok |= hpass->set_int("output_height", input_height);
149 ok |= vpass->set_int("input_width", output_width);
150 ok |= vpass->set_int("input_height", input_height);
151 ok |= vpass->set_int("output_width", output_width);
152 ok |= vpass->set_int("output_height", output_height);
157 bool ResampleEffect::set_float(const std::string &key, float value) {
158 if (key == "width") {
159 output_width = value;
163 if (key == "height") {
164 output_height = value;
171 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
173 direction(HORIZONTAL),
176 last_input_width(-1),
177 last_input_height(-1),
178 last_output_width(-1),
179 last_output_height(-1)
181 register_int("direction", (int *)&direction);
182 register_int("input_width", &input_width);
183 register_int("input_height", &input_height);
184 register_int("output_width", &output_width);
185 register_int("output_height", &output_height);
187 glGenTextures(1, &texnum);
190 SingleResamplePassEffect::~SingleResamplePassEffect()
192 glDeleteTextures(1, &texnum);
195 std::string SingleResamplePassEffect::output_fragment_shader()
198 sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
199 return buf + read_file("resample_effect.frag");
202 // Using vertical scaling as an example:
204 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
206 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
207 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
208 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
209 // and so on. For each y, we encode these along the x-axis (since that is spare),
210 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
212 // For horizontal scaling, we fill in the exact same texture;
213 // the shader just interprets is differently.
214 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
216 unsigned src_size, dst_size;
217 if (direction == SingleResamplePassEffect::HORIZONTAL) {
218 assert(input_height == output_height);
219 src_size = input_width;
220 dst_size = output_width;
221 } else if (direction == SingleResamplePassEffect::VERTICAL) {
222 assert(input_width == output_width);
223 src_size = input_height;
224 dst_size = output_height;
230 // For many resamplings (e.g. 640 -> 1280), we will end up with the same
231 // set of samples over and over again in a loop. Thus, we can compute only
232 // the first such loop, and then ask the card to repeat the texture for us.
233 // This is both easier on the texture cache and lowers our CPU cost for
234 // generating the kernel somewhat.
235 num_loops = gcd(src_size, dst_size);
236 slice_height = 1.0f / num_loops;
237 unsigned dst_samples = dst_size / num_loops;
239 // Sample the kernel in the right place. A diagram with a triangular kernel
240 // (corresponding to linear filtering, and obviously with radius 1)
241 // for easier ASCII art drawing:
247 // x---x---x x x---x---x---x
249 // Scaling up (in this case, 2x) means sampling more densely:
255 // x-x-x-x-x-x x x x-x-x-x-x-x-x-x
257 // When scaling up, any destination pixel will only be influenced by a few
258 // (in this case, two) neighboring pixels, and more importantly, the number
259 // will not be influenced by the scaling factor. (Note, however, that the
260 // pixel centers have moved, due to OpenGL's center-pixel convention.)
261 // The only thing that changes is the weights themselves, as the sampling
262 // points are at different distances from the original pixels.
264 // Scaling down is a different story:
270 // --x------ x --x-------x--
272 // Again, the pixel centers have moved in a maybe unintuitive fashion,
273 // although when you consider that there are multiple source pixels around,
274 // it's not so bad as at first look:
280 // --x-------x-------x-------x--
282 // As you can see, the new pixels become averages of the two neighboring old
283 // ones (the situation for Lanczos is of course more complex).
285 // Anyhow, in this case we clearly need to look at more source pixels
286 // to compute the destination pixel, and how many depend on the scaling factor.
287 // Thus, the kernel width will vary with how much we scale.
288 float radius_scaling_factor = std::min(float(dst_size) / float(src_size), 1.0f);
289 int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
290 int src_samples = int_radius * 2 + 1;
291 float *weights = new float[dst_samples * src_samples * 2];
292 for (unsigned y = 0; y < dst_samples; ++y) {
293 // Find the point around which we want to sample the source image,
294 // compensating for differing pixel centers as the scale changes.
295 float center_src_y = (y + 0.5f) * float(src_size) / float(dst_size) - 0.5f;
296 int base_src_y = lrintf(center_src_y);
298 // Now sample <int_radius> pixels on each side around that point.
299 for (int i = 0; i < src_samples; ++i) {
300 int src_y = base_src_y + i - int_radius;
301 float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y), LANCZOS_RADIUS);
302 weights[(y * src_samples + i) * 2 + 0] = weight * radius_scaling_factor;
303 weights[(y * src_samples + i) * 2 + 1] = (src_y + 0.5) / float(src_size);
307 // Now make use of the bilinear filtering in the GPU to reduce the number of samples
308 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
309 // two neighboring samples if their weights have differing signs, so we first need to
310 // figure out the maximum number of samples. Then, we downconvert all the weights to
311 // that number -- we could have gone for a variable-length system, but this is simpler,
312 // and the gains would probably be offset by the extra cost of checking when to stop.
314 // The greedy strategy for combining samples is optimal.
315 src_bilinear_samples = 0;
316 for (unsigned y = 0; y < dst_samples; ++y) {
317 unsigned num_samples_saved = combine_samples(weights + (y * src_samples) * 2, NULL, src_samples, UINT_MAX);
318 src_bilinear_samples = std::max<int>(src_bilinear_samples, src_samples - num_samples_saved);
321 // Now that we know the right width, actually combine the samples.
322 float *bilinear_weights = new float[dst_samples * src_bilinear_samples * 2];
323 for (unsigned y = 0; y < dst_samples; ++y) {
324 unsigned num_samples_saved = combine_samples(
325 weights + (y * src_samples) * 2,
326 bilinear_weights + (y * src_bilinear_samples) * 2,
328 src_samples - src_bilinear_samples);
329 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
332 // Encode as a two-component texture. Note the GL_REPEAT.
333 glActiveTexture(GL_TEXTURE0 + *sampler_num);
335 glBindTexture(GL_TEXTURE_2D, texnum);
337 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
339 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
341 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
343 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
347 delete[] bilinear_weights;
350 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
352 Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
354 assert(input_width > 0);
355 assert(input_height > 0);
356 assert(output_width > 0);
357 assert(output_height > 0);
359 if (input_width != last_input_width ||
360 input_height != last_input_height ||
361 output_width != last_output_width ||
362 output_height != last_output_height) {
363 update_texture(glsl_program_num, prefix, sampler_num);
364 last_input_width = input_width;
365 last_input_height = input_height;
366 last_output_width = output_width;
367 last_output_height = output_height;
370 glActiveTexture(GL_TEXTURE0 + *sampler_num);
372 glBindTexture(GL_TEXTURE_2D, texnum);
375 set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
377 set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
378 set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
379 set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
381 // Instructions for how to convert integer sample numbers to positions in the weight texture.
382 set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
383 set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
385 // We specifically do not want mipmaps on the input texture;
386 // they break minification.
387 glActiveTexture(GL_TEXTURE0);
389 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);