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