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