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