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