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