]> git.sesse.net Git - movit/blob - resample_effect.cpp
Use the -MP switch (make phony) for better dependency generation when files are removed.
[movit] / resample_effect.cpp
1 // Three-lobed Lanczos, the most common choice.
2 #define LANCZOS_RADIUS 3.0
3
4 #include <math.h>
5 #include <assert.h>
6
7 #include "resample_effect.h"
8 #include "effect_chain.h"
9 #include "util.h"
10 #include "opengl.h"
11
12 namespace {
13
14 float sinc(float x)
15 {
16         if (fabs(x) < 1e-6) {
17                 return 1.0f - fabs(x);
18         } else {
19                 return sin(x) / x;
20         }
21 }
22
23 float lanczos_weight(float x, float a)
24 {
25         if (fabs(x) > a) {
26                 return 0.0f;
27         } else {
28                 return sinc(M_PI * x) * sinc(M_PI * x / a);
29         }
30 }
31
32 // Euclid's algorithm, from Wikipedia.
33 unsigned gcd(unsigned a, unsigned b)
34 {
35         while (b != 0) {
36                 unsigned t = b;
37                 b = a % b;
38                 a = t;
39         }
40         return a;
41 }
42
43 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
44 {
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.
48                 if (dst != NULL) {
49                         dst[j * 2 + 0] = src[i * 2 + 0];
50                         dst[j * 2 + 1] = src[i * 2 + 1];
51                 }
52
53                 if (i == num_src_samples - 1) {
54                         // Last sample; cannot combine.
55                         continue;
56                 }
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.
60                         continue;
61                 }
62
63                 float w1 = src[i * 2 + 0];
64                 float w2 = src[(i + 1) * 2 + 0];
65                 if (w1 * w2 < 0.0f) {
66                         // Differing signs; cannot combine.
67                         continue;
68                 }
69
70                 float pos1 = src[i * 2 + 1];
71                 float pos2 = src[(i + 1) * 2 + 1];
72                 assert(pos2 > pos1);
73
74                 float offset, total_weight, sum_sq_error;
75                 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
76
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)) {
83                         continue;
84                 }
85
86                 // OK, we can combine this and the next sample.
87                 if (dst != NULL) {
88                         dst[j * 2 + 0] = total_weight;
89                         dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
90                 }
91
92                 ++i;  // Skip the next sample.
93                 ++num_samples_saved;
94         }
95         return num_samples_saved;
96 }
97
98 }  // namespace
99
100 ResampleEffect::ResampleEffect()
101         : input_width(1280),
102           input_height(720)
103 {
104         register_int("width", &output_width);
105         register_int("height", &output_height);
106
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));
112
113         update_size();
114 }
115
116 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
117 {
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;
124
125
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)
129 {
130         assert(input_num == 0);
131         assert(width != 0);
132         assert(height != 0);
133         input_width = width;
134         input_height = height;
135         update_size();
136 }
137                 
138 void ResampleEffect::update_size()
139 {
140         bool ok = true;
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);
145
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);
150
151         assert(ok);
152 }
153
154 bool ResampleEffect::set_float(const std::string &key, float value) {
155         if (key == "width") {
156                 output_width = value;
157                 update_size();
158                 return true;
159         }
160         if (key == "height") {
161                 output_height = value;
162                 update_size();
163                 return true;
164         }
165         return false;
166 }
167
168 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
169         : parent(parent),
170           direction(HORIZONTAL),
171           input_width(1280),
172           input_height(720),
173           last_input_width(-1),
174           last_input_height(-1),
175           last_output_width(-1),
176           last_output_height(-1)
177 {
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);
183
184         glGenTextures(1, &texnum);
185 }
186
187 SingleResamplePassEffect::~SingleResamplePassEffect()
188 {
189         glDeleteTextures(1, &texnum);
190 }
191
192 std::string SingleResamplePassEffect::output_fragment_shader()
193 {
194         char buf[256];
195         sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
196         return buf + read_file("resample_effect.frag");
197 }
198
199 // Using vertical scaling as an example:
200 //
201 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
202 //
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.
208 //
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)
212 {
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;
222         } else {
223                 assert(false);
224         }
225
226
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;
235
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:
239         //
240         //                *
241         //               / \                      |
242         //              /   \                     |
243         //             /     \                    |
244         //    x---x---x   x   x---x---x---x
245         //
246         // Scaling up (in this case, 2x) means sampling more densely:
247         //
248         //                *
249         //               / \                      |
250         //              /   \                     |
251         //             /     \                    |
252         //   x-x-x-x-x-x x x x-x-x-x-x-x-x-x
253         //
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.
260         //
261         // Scaling down is a different story:
262         //
263         //                *
264         //               / \                      |
265         //              /   \                     |
266         //             /     \                    |
267         //    --x------ x     --x-------x--
268         //
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:
272         //
273         //            *   *   *   *
274         //           / \ / \ / \ / \              |
275         //          /   X   X   X   \             |
276         //         /   / \ / \ / \   \            |
277         //    --x-------x-------x-------x--
278         //
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).
281         //
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);
294
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);
301                 }
302         }
303
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.
310         //
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);
316         }
317
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,
324                         src_samples,
325                         src_samples - src_bilinear_samples);
326                 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
327         }       
328
329         // Encode as a two-component texture. Note the GL_REPEAT.
330         glActiveTexture(GL_TEXTURE0 + *sampler_num);
331         check_error();
332         glBindTexture(GL_TEXTURE_2D, texnum);
333         check_error();
334         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
335         check_error();
336         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
337         check_error();
338         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
339         check_error();
340         glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
341         check_error();
342
343         delete[] weights;
344         delete[] bilinear_weights;
345 }
346
347 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
348 {
349         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
350
351         if (input_width != last_input_width ||
352             input_height != last_input_height ||
353             output_width != last_output_width ||
354             output_height != last_output_height) {
355                 update_texture(glsl_program_num, prefix, sampler_num);
356                 last_input_width = input_width;
357                 last_input_height = input_height;
358                 last_output_width = output_width;
359                 last_output_height = output_height;
360         }
361
362         glActiveTexture(GL_TEXTURE0 + *sampler_num);
363         check_error();
364         glBindTexture(GL_TEXTURE_2D, texnum);
365         check_error();
366
367         set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
368         ++sampler_num;
369         set_uniform_int(glsl_program_num, prefix, "num_samples", src_bilinear_samples);
370         set_uniform_float(glsl_program_num, prefix, "num_loops", num_loops);
371         set_uniform_float(glsl_program_num, prefix, "slice_height", slice_height);
372
373         // Instructions for how to convert integer sample numbers to positions in the weight texture.
374         set_uniform_float(glsl_program_num, prefix, "sample_x_scale", 1.0f / src_bilinear_samples);
375         set_uniform_float(glsl_program_num, prefix, "sample_x_offset", 0.5f / src_bilinear_samples);
376
377         // We specifically do not want mipmaps on the input texture;
378         // they break minification.
379         glActiveTexture(GL_TEXTURE0);
380         check_error();
381         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
382         check_error();
383 }