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