]> git.sesse.net Git - movit/blob - resample_effect.cpp
Remove some unneeded conversions from ResampleEffect. Speeds up texture generation...
[movit] / resample_effect.cpp
1 // Three-lobed Lanczos, the most common choice.
2 // Note that if you change this, the accuracy for LANCZOS_TABLE_SIZE
3 // needs to be recomputed.
4 #define LANCZOS_RADIUS 3.0f
5
6 #include <epoxy/gl.h>
7 #include <assert.h>
8 #include <limits.h>
9 #include <math.h>
10 #include <stdio.h>
11 #include <algorithm>
12 #include <Eigen/Sparse>
13 #include <Eigen/SparseQR>
14 #include <Eigen/OrderingMethods>
15
16 #include "effect_chain.h"
17 #include "effect_util.h"
18 #include "fp16.h"
19 #include "init.h"
20 #include "resample_effect.h"
21 #include "util.h"
22
23 using namespace Eigen;
24 using namespace std;
25
26 namespace movit {
27
28 namespace {
29
30 float sinc(float x)
31 {
32         if (fabs(x) < 1e-6) {
33                 return 1.0f - fabs(x);
34         } else {
35                 return sin(x) / x;
36         }
37 }
38
39 float lanczos_weight(float x)
40 {
41         if (fabs(x) > LANCZOS_RADIUS) {
42                 return 0.0f;
43         } else {
44                 return sinc(M_PI * x) * sinc((M_PI / LANCZOS_RADIUS) * x);
45         }
46 }
47
48 // The weight function can be expensive to compute over and over again
49 // (which will happen during e.g. a zoom), but it is also easy to interpolate
50 // linearly. We compute the right half of the function (in the range of
51 // 0..LANCZOS_RADIUS), with two guard elements for easier interpolation, and
52 // linearly interpolate to get our function.
53 //
54 // We want to scale the table so that the maximum error is always smaller
55 // than 1e-6. As per http://www-solar.mcs.st-andrews.ac.uk/~clare/Lectures/num-analysis/Numan_chap3.pdf,
56 // the error for interpolating a function linearly between points [a,b] is
57 //
58 //   e = 1/2 (x-a)(x-b) f''(u_x)
59 //
60 // for some point u_x in [a,b] (where f(x) is our Lanczos function; we're
61 // assuming LANCZOS_RADIUS=3 from here on). Obviously this is bounded by
62 // f''(x) over the entire range. Numeric optimization shows the maximum of
63 // |f''(x)| to be in x=1.09369819474562880, with the value 2.40067758733152381.
64 // So if the steps between consecutive values are called d, we get
65 //
66 //   |e| <= 1/2 (d/2)^2 2.4007
67 //   |e| <= 0.1367 d^2
68 //
69 // Solve for e = 1e-6 yields a step size of 0.0027, which to cover the range
70 // 0..3 needs 1109 steps. We round up to the next power of two, just to be sure.
71 //
72 // You need to call lanczos_table_init_done before the first call to
73 // lanczos_weight_cached.
74 #define LANCZOS_TABLE_SIZE 2048
75 bool lanczos_table_init_done = false;
76 float lanczos_table[LANCZOS_TABLE_SIZE + 2];
77
78 void init_lanczos_table()
79 {
80         for (unsigned i = 0; i < LANCZOS_TABLE_SIZE + 2; ++i) {
81                 lanczos_table[i] = lanczos_weight(float(i) * (LANCZOS_RADIUS / LANCZOS_TABLE_SIZE));
82         }
83         lanczos_table_init_done = true;
84 }
85
86 float lanczos_weight_cached(float x)
87 {
88         x = fabs(x);
89         if (x > LANCZOS_RADIUS) {
90                 return 0.0f;
91         }
92         float table_pos = x * (LANCZOS_TABLE_SIZE / LANCZOS_RADIUS);
93         unsigned table_pos_int = int(table_pos);  // Truncate towards zero.
94         float table_pos_frac = table_pos - table_pos_int;
95         assert(table_pos < LANCZOS_TABLE_SIZE + 2);
96         return lanczos_table[table_pos_int] +
97                 table_pos_frac * (lanczos_table[table_pos_int + 1] - lanczos_table[table_pos_int]);
98 }
99
100 // Euclid's algorithm, from Wikipedia.
101 unsigned gcd(unsigned a, unsigned b)
102 {
103         while (b != 0) {
104                 unsigned t = b;
105                 b = a % b;
106                 a = t;
107         }
108         return a;
109 }
110
111 template<class DestFloat>
112 unsigned combine_samples(const Tap<float> *src, Tap<DestFloat> *dst, float num_subtexels, float inv_num_subtexels, unsigned num_src_samples, unsigned max_samples_saved)
113 {
114         // Cut off near-zero values at both sides.
115         unsigned num_samples_saved = 0;
116         while (num_samples_saved < max_samples_saved &&
117                num_src_samples > 0 &&
118                fabs(src[0].weight) < 1e-6) {
119                 ++src;
120                 --num_src_samples;
121                 ++num_samples_saved;
122         }
123         while (num_samples_saved < max_samples_saved &&
124                num_src_samples > 0 &&
125                fabs(src[num_src_samples - 1].weight) < 1e-6) {
126                 --num_src_samples;
127                 ++num_samples_saved;
128         }
129
130         for (unsigned i = 0, j = 0; i < num_src_samples; ++i, ++j) {
131                 // Copy the sample directly; it will be overwritten later if we can combine.
132                 if (dst != NULL) {
133                         dst[j].weight = convert_float<float, DestFloat>(src[i].weight);
134                         dst[j].pos = convert_float<float, DestFloat>(src[i].pos);
135                 }
136
137                 if (i == num_src_samples - 1) {
138                         // Last sample; cannot combine.
139                         continue;
140                 }
141                 assert(num_samples_saved <= max_samples_saved);
142                 if (num_samples_saved == max_samples_saved) {
143                         // We could maybe save more here, but other rows can't, so don't bother.
144                         continue;
145                 }
146
147                 float w1 = src[i].weight;
148                 float w2 = src[i + 1].weight;
149                 if (w1 * w2 < 0.0f) {
150                         // Differing signs; cannot combine.
151                         continue;
152                 }
153
154                 float pos1 = src[i].pos;
155                 float pos2 = src[i + 1].pos;
156                 assert(pos2 > pos1);
157
158                 DestFloat pos, total_weight;
159                 float sum_sq_error;
160                 combine_two_samples(w1, w2, pos1, pos2, num_subtexels, inv_num_subtexels, &pos, &total_weight, &sum_sq_error);
161
162                 // If the interpolation error is larger than that of about sqrt(2) of
163                 // a level at 8-bit precision, don't combine. (You'd think 1.0 was enough,
164                 // but since the artifacts are not really random, they can get quite
165                 // visible. On the other hand, going to 0.25f, I can see no change at
166                 // all with 8-bit output, so it would not seem to be worth it.)
167                 if (sum_sq_error > 0.5f / (255.0f * 255.0f)) {
168                         continue;
169                 }
170
171                 // OK, we can combine this and the next sample.
172                 if (dst != NULL) {
173                         dst[j].weight = total_weight;
174                         dst[j].pos = pos;
175                 }
176
177                 ++i;  // Skip the next sample.
178                 ++num_samples_saved;
179         }
180         return num_samples_saved;
181 }
182
183 // Normalize so that the sum becomes one. Note that we do it twice;
184 // this sometimes helps a tiny little bit when we have many samples.
185 template<class T>
186 void normalize_sum(Tap<T>* vals, unsigned num)
187 {
188         for (int normalize_pass = 0; normalize_pass < 2; ++normalize_pass) {
189                 float sum = 0.0;
190                 for (unsigned i = 0; i < num; ++i) {
191                         sum += to_fp32(vals[i].weight);
192                 }
193                 float inv_sum = 1.0 / sum;
194                 for (unsigned i = 0; i < num; ++i) {
195                         vals[i].weight = from_fp32<T>(to_fp32(vals[i].weight) * inv_sum);
196                 }
197         }
198 }
199
200 // Make use of the bilinear filtering in the GPU to reduce the number of samples
201 // we need to make. This is a bit more complex than BlurEffect since we cannot combine
202 // two neighboring samples if their weights have differing signs, so we first need to
203 // figure out the maximum number of samples. Then, we downconvert all the weights to
204 // that number -- we could have gone for a variable-length system, but this is simpler,
205 // and the gains would probably be offset by the extra cost of checking when to stop.
206 //
207 // The greedy strategy for combining samples is optimal.
208 template<class DestFloat>
209 unsigned combine_many_samples(const Tap<float> *weights, unsigned src_size, unsigned src_samples, unsigned dst_samples, unique_ptr<Tap<DestFloat>[]> *bilinear_weights)
210 {
211         float num_subtexels = src_size / movit_texel_subpixel_precision;
212         float inv_num_subtexels = movit_texel_subpixel_precision / src_size;
213
214         unsigned max_samples_saved = UINT_MAX;
215         for (unsigned y = 0; y < dst_samples && max_samples_saved > 0; ++y) {
216                 unsigned num_samples_saved = combine_samples<DestFloat>(weights + y * src_samples, NULL, num_subtexels, inv_num_subtexels, src_samples, max_samples_saved);
217                 max_samples_saved = min(max_samples_saved, num_samples_saved);
218         }
219
220         // Now that we know the right width, actually combine the samples.
221         unsigned src_bilinear_samples = src_samples - max_samples_saved;
222         bilinear_weights->reset(new Tap<DestFloat>[dst_samples * src_bilinear_samples]);
223         for (unsigned y = 0; y < dst_samples; ++y) {
224                 Tap<DestFloat> *bilinear_weights_ptr = bilinear_weights->get() + y * src_bilinear_samples;
225                 unsigned num_samples_saved = combine_samples(
226                         weights + y * src_samples,
227                         bilinear_weights_ptr,
228                         num_subtexels,
229                         inv_num_subtexels,
230                         src_samples,
231                         max_samples_saved);
232                 assert(num_samples_saved == max_samples_saved);
233                 normalize_sum(bilinear_weights_ptr, src_bilinear_samples);
234         }
235         return src_bilinear_samples;
236 }
237
238 // Compute the sum of squared errors between the ideal weights (which are
239 // assumed to fall exactly on pixel centers) and the weights that result
240 // from sampling at <bilinear_weights>. The primary reason for the difference
241 // is inaccuracy in the sampling positions, both due to limited precision
242 // in storing them (already inherent in sending them in as fp16_int_t)
243 // and in subtexel sampling precision (which we calculate in this function).
244 template<class T>
245 double compute_sum_sq_error(const Tap<float>* weights, unsigned num_weights,
246                             const Tap<T>* bilinear_weights, unsigned num_bilinear_weights,
247                             unsigned size)
248 {
249         // Find the effective range of the bilinear-optimized kernel.
250         // Due to rounding of the positions, this is not necessarily the same
251         // as the intended range (ie., the range of the original weights).
252         int lower_pos = int(floor(to_fp32(bilinear_weights[0].pos) * size - 0.5f));
253         int upper_pos = int(ceil(to_fp32(bilinear_weights[num_bilinear_weights - 1].pos) * size - 0.5f)) + 2;
254         lower_pos = min<int>(lower_pos, lrintf(weights[0].pos * size - 0.5f));
255         upper_pos = max<int>(upper_pos, lrintf(weights[num_weights - 1].pos * size - 0.5f) + 1);
256
257         float* effective_weights = new float[upper_pos - lower_pos];
258         for (int i = 0; i < upper_pos - lower_pos; ++i) {
259                 effective_weights[i] = 0.0f;
260         }
261
262         // Now find the effective weights that result from this sampling.
263         for (unsigned i = 0; i < num_bilinear_weights; ++i) {
264                 const float pixel_pos = to_fp32(bilinear_weights[i].pos) * size - 0.5f;
265                 const int x0 = int(floor(pixel_pos)) - lower_pos;
266                 const int x1 = x0 + 1;
267                 const float f = lrintf((pixel_pos - (x0 + lower_pos)) / movit_texel_subpixel_precision) * movit_texel_subpixel_precision;
268
269                 assert(x0 >= 0);
270                 assert(x1 >= 0);
271                 assert(x0 < upper_pos - lower_pos);
272                 assert(x1 < upper_pos - lower_pos);
273
274                 effective_weights[x0] += to_fp32(bilinear_weights[i].weight) * (1.0f - f);
275                 effective_weights[x1] += to_fp32(bilinear_weights[i].weight) * f;
276         }
277
278         // Subtract the desired weights to get the error.
279         for (unsigned i = 0; i < num_weights; ++i) {
280                 const int x = lrintf(weights[i].pos * size - 0.5f) - lower_pos;
281                 assert(x >= 0);
282                 assert(x < upper_pos - lower_pos);
283
284                 effective_weights[x] -= weights[i].weight;
285         }
286
287         double sum_sq_error = 0.0;
288         for (unsigned i = 0; i < num_weights; ++i) {
289                 sum_sq_error += effective_weights[i] * effective_weights[i];
290         }
291
292         delete[] effective_weights;
293         return sum_sq_error;
294 }
295
296 }  // namespace
297
298 ResampleEffect::ResampleEffect()
299         : input_width(1280),
300           input_height(720),
301           offset_x(0.0f), offset_y(0.0f),
302           zoom_x(1.0f), zoom_y(1.0f),
303           zoom_center_x(0.5f), zoom_center_y(0.5f)
304 {
305         register_int("width", &output_width);
306         register_int("height", &output_height);
307
308         // The first blur pass will forward resolution information to us.
309         hpass = new SingleResamplePassEffect(this);
310         CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
311         vpass = new SingleResamplePassEffect(NULL);
312         CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
313
314         update_size();
315 }
316
317 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
318 {
319         Node *hpass_node = graph->add_node(hpass);
320         Node *vpass_node = graph->add_node(vpass);
321         graph->connect_nodes(hpass_node, vpass_node);
322         graph->replace_receiver(self, hpass_node);
323         graph->replace_sender(self, vpass_node);
324         self->disabled = true;
325
326
327 // We get this information forwarded from the first blur pass,
328 // since we are not part of the chain ourselves.
329 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
330 {
331         assert(input_num == 0);
332         assert(width != 0);
333         assert(height != 0);
334         input_width = width;
335         input_height = height;
336         update_size();
337 }
338
339 void ResampleEffect::update_size()
340 {
341         bool ok = true;
342         ok |= hpass->set_int("input_width", input_width);
343         ok |= hpass->set_int("input_height", input_height);
344         ok |= hpass->set_int("output_width", output_width);
345         ok |= hpass->set_int("output_height", input_height);
346
347         ok |= vpass->set_int("input_width", output_width);
348         ok |= vpass->set_int("input_height", input_height);
349         ok |= vpass->set_int("output_width", output_width);
350         ok |= vpass->set_int("output_height", output_height);
351
352         assert(ok);
353
354         // The offset added due to zoom may have changed with the size.
355         update_offset_and_zoom();
356 }
357
358 void ResampleEffect::update_offset_and_zoom()
359 {
360         bool ok = true;
361
362         // Zoom from the right origin. (zoom_center is given in normalized coordinates,
363         // i.e. 0..1.)
364         float extra_offset_x = zoom_center_x * (1.0f - 1.0f / zoom_x) * input_width;
365         float extra_offset_y = (1.0f - zoom_center_y) * (1.0f - 1.0f / zoom_y) * input_height;
366
367         ok |= hpass->set_float("offset", extra_offset_x + offset_x);
368         ok |= vpass->set_float("offset", extra_offset_y - offset_y);  // Compensate for the bottom-left origin.
369         ok |= hpass->set_float("zoom", zoom_x);
370         ok |= vpass->set_float("zoom", zoom_y);
371
372         assert(ok);
373 }
374
375 bool ResampleEffect::set_float(const string &key, float value) {
376         if (key == "width") {
377                 output_width = value;
378                 update_size();
379                 return true;
380         }
381         if (key == "height") {
382                 output_height = value;
383                 update_size();
384                 return true;
385         }
386         if (key == "top") {
387                 offset_y = value;
388                 update_offset_and_zoom();
389                 return true;
390         }
391         if (key == "left") {
392                 offset_x = value;
393                 update_offset_and_zoom();
394                 return true;
395         }
396         if (key == "zoom_x") {
397                 if (value <= 0.0f) {
398                         return false;
399                 }
400                 zoom_x = value;
401                 update_offset_and_zoom();
402                 return true;
403         }
404         if (key == "zoom_y") {
405                 if (value <= 0.0f) {
406                         return false;
407                 }
408                 zoom_y = value;
409                 update_offset_and_zoom();
410                 return true;
411         }
412         if (key == "zoom_center_x") {
413                 zoom_center_x = value;
414                 update_offset_and_zoom();
415                 return true;
416         }
417         if (key == "zoom_center_y") {
418                 zoom_center_y = value;
419                 update_offset_and_zoom();
420                 return true;
421         }
422         return false;
423 }
424
425 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
426         : parent(parent),
427           direction(HORIZONTAL),
428           input_width(1280),
429           input_height(720),
430           offset(0.0),
431           zoom(1.0),
432           last_input_width(-1),
433           last_input_height(-1),
434           last_output_width(-1),
435           last_output_height(-1),
436           last_offset(0.0 / 0.0),  // NaN.
437           last_zoom(0.0 / 0.0),  // NaN.
438           last_texture_width(-1), last_texture_height(-1)
439 {
440         register_int("direction", (int *)&direction);
441         register_int("input_width", &input_width);
442         register_int("input_height", &input_height);
443         register_int("output_width", &output_width);
444         register_int("output_height", &output_height);
445         register_float("offset", &offset);
446         register_float("zoom", &zoom);
447         register_uniform_sampler2d("sample_tex", &uniform_sample_tex);
448         register_uniform_int("num_samples", &uniform_num_samples);
449         register_uniform_float("num_loops", &uniform_num_loops);
450         register_uniform_float("slice_height", &uniform_slice_height);
451         register_uniform_float("sample_x_scale", &uniform_sample_x_scale);
452         register_uniform_float("sample_x_offset", &uniform_sample_x_offset);
453         register_uniform_float("whole_pixel_offset", &uniform_whole_pixel_offset);
454
455         glGenTextures(1, &texnum);
456
457         if (!lanczos_table_init_done) {
458                 // Could in theory race between two threads if we are unlucky,
459                 // but that is harmless, since they'll write the same data.
460                 init_lanczos_table();
461         }
462 }
463
464 SingleResamplePassEffect::~SingleResamplePassEffect()
465 {
466         glDeleteTextures(1, &texnum);
467 }
468
469 string SingleResamplePassEffect::output_fragment_shader()
470 {
471         char buf[256];
472         sprintf(buf, "#define DIRECTION_VERTICAL %d\n", (direction == VERTICAL));
473         return buf + read_file("resample_effect.frag");
474 }
475
476 // Using vertical scaling as an example:
477 //
478 // Generally out[y] = w0 * in[yi] + w1 * in[yi + 1] + w2 * in[yi + 2] + ...
479 //
480 // Obviously, yi will depend on y (in a not-quite-linear way), but so will
481 // the weights w0, w1, w2, etc.. The easiest way of doing this is to encode,
482 // for each sample, the weight and the yi value, e.g. <yi, w0>, <yi + 1, w1>,
483 // and so on. For each y, we encode these along the x-axis (since that is spare),
484 // so out[0] will read from parameters <x,y> = <0,0>, <1,0>, <2,0> and so on.
485 //
486 // For horizontal scaling, we fill in the exact same texture;
487 // the shader just interprets it differently.
488 void SingleResamplePassEffect::update_texture(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
489 {
490         unsigned src_size, dst_size;
491         if (direction == SingleResamplePassEffect::HORIZONTAL) {
492                 assert(input_height == output_height);
493                 src_size = input_width;
494                 dst_size = output_width;
495         } else if (direction == SingleResamplePassEffect::VERTICAL) {
496                 assert(input_width == output_width);
497                 src_size = input_height;
498                 dst_size = output_height;
499         } else {
500                 assert(false);
501         }
502
503         ScalingWeights weights = calculate_scaling_weights(src_size, dst_size, zoom, offset);
504         src_bilinear_samples = weights.src_bilinear_samples;
505         num_loops = weights.num_loops;
506         slice_height = 1.0f / weights.num_loops;
507
508         // Encode as a two-component texture. Note the GL_REPEAT.
509         glActiveTexture(GL_TEXTURE0 + *sampler_num);
510         check_error();
511         glBindTexture(GL_TEXTURE_2D, texnum);
512         check_error();
513         if (last_texture_width == -1) {
514                 // Need to set this state the first time.
515                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
516                 check_error();
517                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
518                 check_error();
519                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
520                 check_error();
521         }
522
523         GLenum type, internal_format;
524         void *pixels;
525         assert((weights.bilinear_weights_fp16 == nullptr) != (weights.bilinear_weights_fp32 == nullptr));
526         if (weights.bilinear_weights_fp32 != nullptr) {
527                 type = GL_FLOAT;
528                 internal_format = GL_RG32F;
529                 pixels = weights.bilinear_weights_fp32.get();
530         } else {
531                 type = GL_HALF_FLOAT;
532                 internal_format = GL_RG16F;
533                 pixels = weights.bilinear_weights_fp16.get();
534         }
535
536         if (int(weights.src_bilinear_samples) == last_texture_width &&
537             int(weights.dst_samples) == last_texture_height &&
538             internal_format == last_texture_internal_format) {
539                 // Texture dimensions and type are unchanged; it is more efficient
540                 // to just update it rather than making an entirely new texture.
541                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, weights.src_bilinear_samples, weights.dst_samples, GL_RG, type, pixels);
542         } else {
543                 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, weights.src_bilinear_samples, weights.dst_samples, 0, GL_RG, type, pixels);
544                 last_texture_width = weights.src_bilinear_samples;
545                 last_texture_height = weights.dst_samples;
546                 last_texture_internal_format = internal_format;
547         }
548         check_error();
549 }
550
551 ScalingWeights calculate_scaling_weights(unsigned src_size, unsigned dst_size, float zoom, float offset)
552 {
553         if (!lanczos_table_init_done) {
554                 // Only needed if run from outside ResampleEffect.
555                 init_lanczos_table();
556         }
557
558         // For many resamplings (e.g. 640 -> 1280), we will end up with the same
559         // set of samples over and over again in a loop. Thus, we can compute only
560         // the first such loop, and then ask the card to repeat the texture for us.
561         // This is both easier on the texture cache and lowers our CPU cost for
562         // generating the kernel somewhat.
563         float scaling_factor;
564         int num_loops;
565         if (fabs(zoom - 1.0f) < 1e-6) {
566                 num_loops = gcd(src_size, dst_size);
567                 scaling_factor = float(dst_size) / float(src_size);
568         } else {
569                 // If zooming is enabled (ie., zoom != 1), we turn off the looping.
570                 // We _could_ perhaps do it for rational zoom levels (especially
571                 // things like 2:1), but it doesn't seem to be worth it, given that
572                 // the most common use case would seem to be varying the zoom
573                 // from frame to frame.
574                 num_loops = 1;
575                 scaling_factor = zoom * float(dst_size) / float(src_size);
576         }
577         unsigned dst_samples = dst_size / num_loops;
578
579         // Sample the kernel in the right place. A diagram with a triangular kernel
580         // (corresponding to linear filtering, and obviously with radius 1)
581         // for easier ASCII art drawing:
582         //
583         //                *
584         //               / \                      |
585         //              /   \                     |
586         //             /     \                    |
587         //    x---x---x   x   x---x---x---x
588         //
589         // Scaling up (in this case, 2x) means sampling more densely:
590         //
591         //                *
592         //               / \                      |
593         //              /   \                     |
594         //             /     \                    |
595         //   x-x-x-x-x-x x x x-x-x-x-x-x-x-x
596         //
597         // When scaling up, any destination pixel will only be influenced by a few
598         // (in this case, two) neighboring pixels, and more importantly, the number
599         // will not be influenced by the scaling factor. (Note, however, that the
600         // pixel centers have moved, due to OpenGL's center-pixel convention.)
601         // The only thing that changes is the weights themselves, as the sampling
602         // points are at different distances from the original pixels.
603         //
604         // Scaling down is a different story:
605         //
606         //                *
607         //               / \                      |
608         //              /   \                     |
609         //             /     \                    |
610         //    --x------ x     --x-------x--
611         //
612         // Again, the pixel centers have moved in a maybe unintuitive fashion,
613         // although when you consider that there are multiple source pixels around,
614         // it's not so bad as at first look:
615         //
616         //            *   *   *   *
617         //           / \ / \ / \ / \              |
618         //          /   X   X   X   \             |
619         //         /   / \ / \ / \   \            |
620         //    --x-------x-------x-------x--
621         //
622         // As you can see, the new pixels become averages of the two neighboring old
623         // ones (the situation for Lanczos is of course more complex).
624         //
625         // Anyhow, in this case we clearly need to look at more source pixels
626         // to compute the destination pixel, and how many depend on the scaling factor.
627         // Thus, the kernel width will vary with how much we scale.
628         float radius_scaling_factor = min(scaling_factor, 1.0f);
629         int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
630         int src_samples = int_radius * 2 + 1;
631         unique_ptr<Tap<float>[]> weights(new Tap<float>[dst_samples * src_samples]);
632         float subpixel_offset = offset - lrintf(offset);  // The part not covered by whole_pixel_offset.
633         assert(subpixel_offset >= -0.5f && subpixel_offset <= 0.5f);
634         for (unsigned y = 0; y < dst_samples; ++y) {
635                 // Find the point around which we want to sample the source image,
636                 // compensating for differing pixel centers as the scale changes.
637                 float center_src_y = (y + 0.5f) / scaling_factor - 0.5f;
638                 int base_src_y = lrintf(center_src_y);
639
640                 // Now sample <int_radius> pixels on each side around that point.
641                 float inv_src_size = 1.0 / float(src_size);
642                 for (int i = 0; i < src_samples; ++i) {
643                         int src_y = base_src_y + i - int_radius;
644                         float weight = lanczos_weight_cached(radius_scaling_factor * (src_y - center_src_y - subpixel_offset));
645                         weights[y * src_samples + i].weight = weight * radius_scaling_factor;
646                         weights[y * src_samples + i].pos = (src_y + 0.5f) * inv_src_size;
647                 }
648         }
649
650         // Now make use of the bilinear filtering in the GPU to reduce the number of samples
651         // we need to make. Try fp16 first; if it's not accurate enough, we go to fp32.
652         // Our tolerance level for total error is a bit higher than the one for invididual
653         // samples, since one would assume overall errors in the shape don't matter as much.
654         const float max_error = 2.0f / (255.0f * 255.0f);
655         unique_ptr<Tap<fp16_int_t>[]> bilinear_weights_fp16;
656         int src_bilinear_samples = combine_many_samples(weights.get(), src_size, src_samples, dst_samples, &bilinear_weights_fp16);
657         unique_ptr<Tap<float>[]> bilinear_weights_fp32 = NULL;
658         double max_sum_sq_error_fp16 = 0.0;
659         for (unsigned y = 0; y < dst_samples; ++y) {
660                 double sum_sq_error_fp16 = compute_sum_sq_error(
661                         weights.get() + y * src_samples, src_samples,
662                         bilinear_weights_fp16.get() + y * src_bilinear_samples, src_bilinear_samples,
663                         src_size);
664                 max_sum_sq_error_fp16 = std::max(max_sum_sq_error_fp16, sum_sq_error_fp16);
665                 if (max_sum_sq_error_fp16 > max_error) {
666                         break;
667                 }
668         }
669
670         if (max_sum_sq_error_fp16 > max_error) {
671                 bilinear_weights_fp16.reset();
672                 src_bilinear_samples = combine_many_samples(weights.get(), src_size, src_samples, dst_samples, &bilinear_weights_fp32);
673         }
674
675         ScalingWeights ret;
676         ret.src_bilinear_samples = src_bilinear_samples;
677         ret.dst_samples = dst_samples;
678         ret.num_loops = num_loops;
679         ret.bilinear_weights_fp16 = move(bilinear_weights_fp16);
680         ret.bilinear_weights_fp32 = move(bilinear_weights_fp32);
681         return ret;
682 }
683
684 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
685 {
686         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
687
688         assert(input_width > 0);
689         assert(input_height > 0);
690         assert(output_width > 0);
691         assert(output_height > 0);
692
693         if (input_width != last_input_width ||
694             input_height != last_input_height ||
695             output_width != last_output_width ||
696             output_height != last_output_height ||
697             offset != last_offset ||
698             zoom != last_zoom) {
699                 update_texture(glsl_program_num, prefix, sampler_num);
700                 last_input_width = input_width;
701                 last_input_height = input_height;
702                 last_output_width = output_width;
703                 last_output_height = output_height;
704                 last_offset = offset;
705                 last_zoom = zoom;
706         }
707
708         glActiveTexture(GL_TEXTURE0 + *sampler_num);
709         check_error();
710         glBindTexture(GL_TEXTURE_2D, texnum);
711         check_error();
712
713         uniform_sample_tex = *sampler_num;
714         ++*sampler_num;
715         uniform_num_samples = src_bilinear_samples;
716         uniform_num_loops = num_loops;
717         uniform_slice_height = slice_height;
718
719         // Instructions for how to convert integer sample numbers to positions in the weight texture.
720         uniform_sample_x_scale = 1.0f / src_bilinear_samples;
721         uniform_sample_x_offset = 0.5f / src_bilinear_samples;
722
723         if (direction == SingleResamplePassEffect::VERTICAL) {
724                 uniform_whole_pixel_offset = lrintf(offset) / float(input_height);
725         } else {
726                 uniform_whole_pixel_offset = lrintf(offset) / float(input_width);
727         }
728
729         // We specifically do not want mipmaps on the input texture;
730         // they break minification.
731         Node *self = chain->find_node_for_effect(this);
732         if (chain->has_input_sampler(self, 0)) {
733                 glActiveTexture(chain->get_input_sampler(self, 0));
734                 check_error();
735                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
736                 check_error();
737         }
738 }
739
740 }  // namespace movit