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