]> git.sesse.net Git - movit/blob - resample_effect.cpp
Switch to autoconf to find libraries.
[movit] / resample_effect.cpp
1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
3
4 #include <GL/glew.h>
5 #include <assert.h>
6 #include <limits.h>
7 #include <math.h>
8 #include <stdio.h>
9 #include <algorithm>
10
11 #include "effect_chain.h"
12 #include "effect_util.h"
13 #include "resample_effect.h"
14 #include "util.h"
15
16 namespace {
17
18 float sinc(float x)
19 {
20         if (fabs(x) < 1e-6) {
21                 return 1.0f - fabs(x);
22         } else {
23                 return sin(x) / x;
24         }
25 }
26
27 float lanczos_weight(float x, float a)
28 {
29         if (fabs(x) > a) {
30                 return 0.0f;
31         } else {
32                 return sinc(M_PI * x) * sinc(M_PI * x / a);
33         }
34 }
35
36 // Euclid's algorithm, from Wikipedia.
37 unsigned gcd(unsigned a, unsigned b)
38 {
39         while (b != 0) {
40                 unsigned t = b;
41                 b = a % b;
42                 a = t;
43         }
44         return a;
45 }
46
47 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
48 {
49         unsigned num_samples_saved = 0;
50         for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
51                 // Copy the sample directly; it will be overwritten later if we can combine.
52                 if (dst != NULL) {
53                         dst[j * 2 + 0] = src[i * 2 + 0];
54                         dst[j * 2 + 1] = src[i * 2 + 1];
55                 }
56
57                 if (i == num_src_samples - 1) {
58                         // Last sample; cannot combine.
59                         continue;
60                 }
61                 assert(num_samples_saved <= max_samples_saved);
62                 if (num_samples_saved == max_samples_saved) {
63                         // We could maybe save more here, but other rows can't, so don't bother.
64                         continue;
65                 }
66
67                 float w1 = src[i * 2 + 0];
68                 float w2 = src[(i + 1) * 2 + 0];
69                 if (w1 * w2 < 0.0f) {
70                         // Differing signs; cannot combine.
71                         continue;
72                 }
73
74                 float pos1 = src[i * 2 + 1];
75                 float pos2 = src[(i + 1) * 2 + 1];
76                 assert(pos2 > pos1);
77
78                 float offset, total_weight, sum_sq_error;
79                 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
80
81                 // If the interpolation error is larger than that of about sqrt(2) of
82                 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
83                 // but since the artifacts are not really random, they can get quite
84                 // visible. On the other hand, going to 0.25f, I can see no change at
85                 // all with 8-bit output, so it would not seem to be worth it.)
86                 if (sum_sq_error > 0.5f / (256.0f * 256.0f)) {
87                         continue;
88                 }
89
90                 // OK, we can combine this and the next sample.
91                 if (dst != NULL) {
92                         dst[j * 2 + 0] = total_weight;
93                         dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
94                 }
95
96                 ++i;  // Skip the next sample.
97                 ++num_samples_saved;
98         }
99         return num_samples_saved;
100 }
101
102 }  // namespace
103
104 ResampleEffect::ResampleEffect()
105         : input_width(1280),
106           input_height(720)
107 {
108         register_int("width", &output_width);
109         register_int("height", &output_height);
110
111         // The first blur pass will forward resolution information to us.
112         hpass = new SingleResamplePassEffect(this);
113         CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
114         vpass = new SingleResamplePassEffect(NULL);
115         CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
116
117         update_size();
118 }
119
120 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
121 {
122         Node *hpass_node = graph->add_node(hpass);
123         Node *vpass_node = graph->add_node(vpass);
124         graph->connect_nodes(hpass_node, vpass_node);
125         graph->replace_receiver(self, hpass_node);
126         graph->replace_sender(self, vpass_node);
127         self->disabled = true;
128
129
130 // We get this information forwarded from the first blur pass,
131 // since we are not part of the chain ourselves.
132 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
133 {
134         assert(input_num == 0);
135         assert(width != 0);
136         assert(height != 0);
137         input_width = width;
138         input_height = height;
139         update_size();
140 }
141                 
142 void ResampleEffect::update_size()
143 {
144         bool ok = true;
145         ok |= hpass->set_int("input_width", input_width);
146         ok |= hpass->set_int("input_height", input_height);
147         ok |= hpass->set_int("output_width", output_width);
148         ok |= hpass->set_int("output_height", input_height);
149
150         ok |= vpass->set_int("input_width", output_width);
151         ok |= vpass->set_int("input_height", input_height);
152         ok |= vpass->set_int("output_width", output_width);
153         ok |= vpass->set_int("output_height", output_height);
154
155         assert(ok);
156 }
157
158 bool ResampleEffect::set_float(const std::string &key, float value) {
159         if (key == "width") {
160                 output_width = value;
161                 update_size();
162                 return true;
163         }
164         if (key == "height") {
165                 output_height = value;
166                 update_size();
167                 return true;
168         }
169         return false;
170 }
171
172 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
173         : parent(parent),
174           direction(HORIZONTAL),
175           input_width(1280),
176           input_height(720),
177           last_input_width(-1),
178           last_input_height(-1),
179           last_output_width(-1),
180           last_output_height(-1)
181 {
182         register_int("direction", (int *)&direction);
183         register_int("input_width", &input_width);
184         register_int("input_height", &input_height);
185         register_int("output_width", &output_width);
186         register_int("output_height", &output_height);
187
188         glGenTextures(1, &texnum);
189 }
190
191 SingleResamplePassEffect::~SingleResamplePassEffect()
192 {
193         glDeleteTextures(1, &texnum);
194 }
195
196 std::string SingleResamplePassEffect::output_fragment_shader()
197 {
198         char buf[256];
199         sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
200         return buf + read_file("resample_effect.frag");
201 }
202
203 // Using vertical scaling as an example:
204 //
205 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
206 //
207 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
208 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
209 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
210 // and so on. For each y, we encode these along the x-axis (since that is spare),
211 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
212 //
213 // For horizontal scaling, we fill in the exact same texture;
214 // the shader just interprets is differently.
215 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
216 {
217         unsigned src_size, dst_size;
218         if (direction == SingleResamplePassEffect::HORIZONTAL) {
219                 assert(input_height == output_height);
220                 src_size = input_width;
221                 dst_size = output_width;
222         } else if (direction == SingleResamplePassEffect::VERTICAL) {
223                 assert(input_width == output_width);
224                 src_size = input_height;
225                 dst_size = output_height;
226         } else {
227                 assert(false);
228         }
229
230
231         // For many resamplings (e.g. 640 -> 1280), we will end up with the same
232         // set of samples over and over again in a loop. Thus, we can compute only
233         // the first such loop, and then ask the card to repeat the texture for us.
234         // This is both easier on the texture cache and lowers our CPU cost for
235         // generating the kernel somewhat.
236         num_loops = gcd(src_size, dst_size);
237         slice_height = 1.0f / num_loops;
238         unsigned dst_samples = dst_size / num_loops;
239
240         // Sample the kernel in the right place. A diagram with a triangular kernel
241         // (corresponding to linear filtering, and obviously with radius 1)
242         // for easier ASCII art drawing:
243         //
244         //                *
245         //               / \                      |
246         //              /   \                     |
247         //             /     \                    |
248         //    x---x---x   x   x---x---x---x
249         //
250         // Scaling up (in this case, 2x) means sampling more densely:
251         //
252         //                *
253         //               / \                      |
254         //              /   \                     |
255         //             /     \                    |
256         //   x-x-x-x-x-x x x x-x-x-x-x-x-x-x
257         //
258         // When scaling up, any destination pixel will only be influenced by a few
259         // (in this case, two) neighboring pixels, and more importantly, the number
260         // will not be influenced by the scaling factor. (Note, however, that the
261         // pixel centers have moved, due to OpenGL's center-pixel convention.)
262         // The only thing that changes is the weights themselves, as the sampling
263         // points are at different distances from the original pixels.
264         //
265         // Scaling down is a different story:
266         //
267         //                *
268         //               / \                      |
269         //              /   \                     |
270         //             /     \                    |
271         //    --x------ x     --x-------x--
272         //
273         // Again, the pixel centers have moved in a maybe unintuitive fashion,
274         // although when you consider that there are multiple source pixels around,
275         // it's not so bad as at first look:
276         //
277         //            *   *   *   *
278         //           / \ / \ / \ / \              |
279         //          /   X   X   X   \             |
280         //         /   / \ / \ / \   \            |
281         //    --x-------x-------x-------x--
282         //
283         // As you can see, the new pixels become averages of the two neighboring old
284         // ones (the situation for Lanczos is of course more complex).
285         //
286         // Anyhow, in this case we clearly need to look at more source pixels
287         // to compute the destination pixel, and how many depend on the scaling factor.
288         // Thus, the kernel width will vary with how much we scale.
289         float radius_scaling_factor = std::min(float(dst_size) / float(src_size), 1.0f);
290         int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
291         int src_samples = int_radius * 2 + 1;
292         float *weights = new float[dst_samples * src_samples * 2];
293         for (unsigned y = 0; y < dst_samples; ++y) {
294                 // Find the point around which we want to sample the source image,
295                 // compensating for differing pixel centers as the scale changes.
296                 float center_src_y = (y + 0.5f) * float(src_size) / float(dst_size) - 0.5f;
297                 int base_src_y = lrintf(center_src_y);
298
299                 // Now sample <int_radius> pixels on each side around that point.
300                 for (int i = 0; i < src_samples; ++i) {
301                         int src_y = base_src_y + i - int_radius;
302                         float weight = lanczos_weight(radius_scaling_factor * (src_y - center_src_y), LANCZOS_RADIUS);
303                         weights[(y * src_samples + i) * 2 + 0] = weight * radius_scaling_factor;
304                         weights[(y * src_samples + i) * 2 + 1] = (src_y + 0.5) / float(src_size);
305                 }
306         }
307
308         // Now make use of the bilinear filtering in the GPU to reduce the number of samples
309         // we need to make. This is a bit more complex than BlurEffect since we cannot combine
310         // two neighboring samples if their weights have differing signs, so we first need to
311         // figure out the maximum number of samples. Then, we downconvert all the weights to
312         // that number -- we could have gone for a variable-length system, but this is simpler,
313         // and the gains would probably be offset by the extra cost of checking when to stop.
314         //
315         // The greedy strategy for combining samples is optimal.
316         src_bilinear_samples = 0;
317         for (unsigned y = 0; y < dst_samples; ++y) {
318                 unsigned num_samples_saved = combine_samples(weights + (y * src_samples) * 2, NULL, src_samples, UINT_MAX);
319                 src_bilinear_samples = std::max<int>(src_bilinear_samples, src_samples - num_samples_saved);
320         }
321
322         // Now that we know the right width, actually combine the samples.
323         float *bilinear_weights = new float[dst_samples * src_bilinear_samples * 2];
324         for (unsigned y = 0; y < dst_samples; ++y) {
325                 unsigned num_samples_saved = combine_samples(
326                         weights + (y * src_samples) * 2,
327                         bilinear_weights + (y * src_bilinear_samples) * 2,
328                         src_samples,
329                         src_samples - src_bilinear_samples);
330                 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
331         }       
332
333         // Encode as a two-component texture. Note the GL_REPEAT.
334         glActiveTexture(GL_TEXTURE0 + *sampler_num);
335         check_error();
336         glBindTexture(GL_TEXTURE_2D, texnum);
337         check_error();
338         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
339         check_error();
340         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
341         check_error();
342         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
343         check_error();
344         glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
345         check_error();
346
347         delete[] weights;
348         delete[] bilinear_weights;
349 }
350
351 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
352 {
353         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
354
355         assert(input_width > 0);
356         assert(input_height > 0);
357         assert(output_width > 0);
358         assert(output_height > 0);
359
360         if (input_width != last_input_width ||
361             input_height != last_input_height ||
362             output_width != last_output_width ||
363             output_height != last_output_height) {
364                 update_texture(glsl_program_num, prefix, sampler_num);
365                 last_input_width = input_width;
366                 last_input_height = input_height;
367                 last_output_width = output_width;
368                 last_output_height = output_height;
369         }
370
371         glActiveTexture(GL_TEXTURE0 + *sampler_num);
372         check_error();
373         glBindTexture(GL_TEXTURE_2D, texnum);
374         check_error();
375
376         set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
377         ++sampler_num;
378         set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
379         set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
380         set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
381
382         // Instructions for how to convert integer sample numbers to positions in the weight texture.
383         set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
384         set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
385
386         // We specifically do not want mipmaps on the input texture;
387         // they break minification.
388         glActiveTexture(GL_TEXTURE0);
389         check_error();
390         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
391         check_error();
392 }