]> git.sesse.net Git - movit/blob - resample_effect.cpp
264e5c10195dc65cd6bd82eca537c412bc611e7c
[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 "resample_effect.h"
13 #include "util.h"
14
15 namespace {
16
17 float sinc(float x)
18 {
19         if (fabs(x) < 1e-6) {
20                 return 1.0f - fabs(x);
21         } else {
22                 return sin(x) / x;
23         }
24 }
25
26 float lanczos_weight(float x, float a)
27 {
28         if (fabs(x) > a) {
29                 return 0.0f;
30         } else {
31                 return sinc(M_PI * x) * sinc(M_PI * x / a);
32         }
33 }
34
35 // Euclid's algorithm, from Wikipedia.
36 unsigned gcd(unsigned a, unsigned b)
37 {
38         while (b != 0) {
39                 unsigned t = b;
40                 b = a % b;
41                 a = t;
42         }
43         return a;
44 }
45
46 unsigned combine_samples(float *src, float *dst, unsigned num_src_samples, unsigned max_samples_saved)
47 {
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.
51                 if (dst != NULL) {
52                         dst[j * 2 + 0] = src[i * 2 + 0];
53                         dst[j * 2 + 1] = src[i * 2 + 1];
54                 }
55
56                 if (i == num_src_samples - 1) {
57                         // Last sample; cannot combine.
58                         continue;
59                 }
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.
63                         continue;
64                 }
65
66                 float w1 = src[i * 2 + 0];
67                 float w2 = src[(i + 1) * 2 + 0];
68                 if (w1 * w2 < 0.0f) {
69                         // Differing signs; cannot combine.
70                         continue;
71                 }
72
73                 float pos1 = src[i * 2 + 1];
74                 float pos2 = src[(i + 1) * 2 + 1];
75                 assert(pos2 > pos1);
76
77                 float offset, total_weight, sum_sq_error;
78                 combine_two_samples(w1, w2, &offset, &total_weight, &sum_sq_error);
79
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)) {
86                         continue;
87                 }
88
89                 // OK, we can combine this and the next sample.
90                 if (dst != NULL) {
91                         dst[j * 2 + 0] = total_weight;
92                         dst[j * 2 + 1] = pos1 + offset * (pos2 - pos1);
93                 }
94
95                 ++i;  // Skip the next sample.
96                 ++num_samples_saved;
97         }
98         return num_samples_saved;
99 }
100
101 }  // namespace
102
103 ResampleEffect::ResampleEffect()
104         : input_width(1280),
105           input_height(720)
106 {
107         register_int("width", &output_width);
108         register_int("height", &output_height);
109
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));
115
116         update_size();
117 }
118
119 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
120 {
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;
127
128
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)
132 {
133         assert(input_num == 0);
134         assert(width != 0);
135         assert(height != 0);
136         input_width = width;
137         input_height = height;
138         update_size();
139 }
140                 
141 void ResampleEffect::update_size()
142 {
143         bool ok = true;
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);
148
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);
153
154         assert(ok);
155 }
156
157 bool ResampleEffect::set_float(const std::string &key, float value) {
158         if (key == "width") {
159                 output_width = value;
160                 update_size();
161                 return true;
162         }
163         if (key == "height") {
164                 output_height = value;
165                 update_size();
166                 return true;
167         }
168         return false;
169 }
170
171 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
172         : parent(parent),
173           direction(HORIZONTAL),
174           input_width(1280),
175           input_height(720),
176           last_input_width(-1),
177           last_input_height(-1),
178           last_output_width(-1),
179           last_output_height(-1)
180 {
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);
186
187         glGenTextures(1, &texnum);
188 }
189
190 SingleResamplePassEffect::~SingleResamplePassEffect()
191 {
192         glDeleteTextures(1, &texnum);
193 }
194
195 std::string SingleResamplePassEffect::output_fragment_shader()
196 {
197         char buf[256];
198         sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
199         return buf + read_file("resample_effect.frag");
200 }
201
202 // Using vertical scaling as an example:
203 //
204 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
205 //
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.
211 //
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)
215 {
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;
225         } else {
226                 assert(false);
227         }
228
229
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;
238
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:
242         //
243         //                *
244         //               / \                      |
245         //              /   \                     |
246         //             /     \                    |
247         //    x---x---x   x   x---x---x---x
248         //
249         // Scaling up (in this case, 2x) means sampling more densely:
250         //
251         //                *
252         //               / \                      |
253         //              /   \                     |
254         //             /     \                    |
255         //   x-x-x-x-x-x x x x-x-x-x-x-x-x-x
256         //
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.
263         //
264         // Scaling down is a different story:
265         //
266         //                *
267         //               / \                      |
268         //              /   \                     |
269         //             /     \                    |
270         //    --x------ x     --x-------x--
271         //
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:
275         //
276         //            *   *   *   *
277         //           / \ / \ / \ / \              |
278         //          /   X   X   X   \             |
279         //         /   / \ / \ / \   \            |
280         //    --x-------x-------x-------x--
281         //
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).
284         //
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);
297
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);
304                 }
305         }
306
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.
313         //
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);
319         }
320
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,
327                         src_samples,
328                         src_samples - src_bilinear_samples);
329                 assert(int(src_samples) - int(num_samples_saved) == src_bilinear_samples);
330         }       
331
332         // Encode as a two-component texture. Note the GL_REPEAT.
333         glActiveTexture(GL_TEXTURE0 + *sampler_num);
334         check_error();
335         glBindTexture(GL_TEXTURE_2D, texnum);
336         check_error();
337         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
338         check_error();
339         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
340         check_error();
341         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
342         check_error();
343         glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, src_bilinear_samples, dst_samples, 0, GL_RG, GL_FLOAT, bilinear_weights);
344         check_error();
345
346         delete[] weights;
347         delete[] bilinear_weights;
348 }
349
350 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
351 {
352         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
353
354         assert(input_width > 0);
355         assert(input_height > 0);
356         assert(output_width > 0);
357         assert(output_height > 0);
358
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;
368         }
369
370         glActiveTexture(GL_TEXTURE0 + *sampler_num);
371         check_error();
372         glBindTexture(GL_TEXTURE_2D, texnum);
373         check_error();
374
375         set_uniform_int(glsl_program_num, prefix, "sample_tex", *sampler_num);
376         ++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);
380
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);
384
385         // We specifically do not want mipmaps on the input texture;
386         // they break minification.
387         glActiveTexture(GL_TEXTURE0);
388         check_error();
389         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
390         check_error();
391 }