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