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