]> git.sesse.net Git - movit/blob - resample_effect.cpp
Move the functionality for updating the support texture using glTexImage2D or glTexSu...
[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 <mutex>
13 #include <Eigen/Sparse>
14 #include <Eigen/SparseQR>
15 #include <Eigen/OrderingMethods>
16
17 #include "effect_chain.h"
18 #include "effect_util.h"
19 #include "fp16.h"
20 #include "init.h"
21 #include "resample_effect.h"
22 #include "util.h"
23
24 using namespace Eigen;
25 using namespace std;
26
27 namespace movit {
28
29 namespace {
30
31 float sinc(float x)
32 {
33         if (fabs(x) < 1e-6) {
34                 return 1.0f - fabs(x);
35         } else {
36                 return sin(x) / x;
37         }
38 }
39
40 float lanczos_weight(float x)
41 {
42         if (fabs(x) > LANCZOS_RADIUS) {
43                 return 0.0f;
44         } else {
45                 return sinc(M_PI * x) * sinc((M_PI / LANCZOS_RADIUS) * x);
46         }
47 }
48
49 // The weight function can be expensive to compute over and over again
50 // (which will happen during e.g. a zoom), but it is also easy to interpolate
51 // linearly. We compute the right half of the function (in the range of
52 // 0..LANCZOS_RADIUS), with two guard elements for easier interpolation, and
53 // linearly interpolate to get our function.
54 //
55 // We want to scale the table so that the maximum error is always smaller
56 // than 1e-6. As per http://www-solar.mcs.st-andrews.ac.uk/~clare/Lectures/num-analysis/Numan_chap3.pdf,
57 // the error for interpolating a function linearly between points [a,b] is
58 //
59 //   e = 1/2 (x-a)(x-b) f''(u_x)
60 //
61 // for some point u_x in [a,b] (where f(x) is our Lanczos function; we're
62 // assuming LANCZOS_RADIUS=3 from here on). Obviously this is bounded by
63 // f''(x) over the entire range. Numeric optimization shows the maximum of
64 // |f''(x)| to be in x=1.09369819474562880, with the value 2.40067758733152381.
65 // So if the steps between consecutive values are called d, we get
66 //
67 //   |e| <= 1/2 (d/2)^2 2.4007
68 //   |e| <= 0.1367 d^2
69 //
70 // Solve for e = 1e-6 yields a step size of 0.0027, which to cover the range
71 // 0..3 needs 1109 steps. We round up to the next power of two, just to be sure.
72 //
73 // You need to call lanczos_table_init_done before the first call to
74 // lanczos_weight_cached.
75 #define LANCZOS_TABLE_SIZE 2048
76 static once_flag lanczos_table_init_done;
77 float lanczos_table[LANCZOS_TABLE_SIZE + 2];
78
79 void init_lanczos_table()
80 {
81         for (unsigned i = 0; i < LANCZOS_TABLE_SIZE + 2; ++i) {
82                 lanczos_table[i] = lanczos_weight(float(i) * (LANCZOS_RADIUS / LANCZOS_TABLE_SIZE));
83         }
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, float pos1_pos2_diff, float inv_pos1_pos2_diff)
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 != nullptr) {
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, pos1_pos2_diff, inv_pos1_pos2_diff, 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 != nullptr) {
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         float pos1_pos2_diff = 1.0f / src_size;
214         float inv_pos1_pos2_diff = src_size;
215
216         unsigned max_samples_saved = UINT_MAX;
217         for (unsigned y = 0; y < dst_samples && max_samples_saved > 0; ++y) {
218                 unsigned num_samples_saved = combine_samples<DestFloat>(weights + y * src_samples, nullptr, num_subtexels, inv_num_subtexels, src_samples, max_samples_saved, pos1_pos2_diff, inv_pos1_pos2_diff);
219                 max_samples_saved = min(max_samples_saved, num_samples_saved);
220         }
221
222         // Now that we know the right width, actually combine the samples.
223         unsigned src_bilinear_samples = src_samples - max_samples_saved;
224         bilinear_weights->reset(new Tap<DestFloat>[dst_samples * src_bilinear_samples]);
225         for (unsigned y = 0; y < dst_samples; ++y) {
226                 Tap<DestFloat> *bilinear_weights_ptr = bilinear_weights->get() + y * src_bilinear_samples;
227                 unsigned num_samples_saved = combine_samples(
228                         weights + y * src_samples,
229                         bilinear_weights_ptr,
230                         num_subtexels,
231                         inv_num_subtexels,
232                         src_samples,
233                         max_samples_saved,
234                         pos1_pos2_diff,
235                         inv_pos1_pos2_diff);
236                 assert(num_samples_saved == max_samples_saved);
237                 normalize_sum(bilinear_weights_ptr, src_bilinear_samples);
238         }
239         return src_bilinear_samples;
240 }
241
242 // Compute the sum of squared errors between the ideal weights (which are
243 // assumed to fall exactly on pixel centers) and the weights that result
244 // from sampling at <bilinear_weights>. The primary reason for the difference
245 // is inaccuracy in the sampling positions, both due to limited precision
246 // in storing them (already inherent in sending them in as fp16_int_t)
247 // and in subtexel sampling precision (which we calculate in this function).
248 template<class T>
249 double compute_sum_sq_error(const Tap<float>* weights, unsigned num_weights,
250                             const Tap<T>* bilinear_weights, unsigned num_bilinear_weights,
251                             unsigned size)
252 {
253         // Find the effective range of the bilinear-optimized kernel.
254         // Due to rounding of the positions, this is not necessarily the same
255         // as the intended range (ie., the range of the original weights).
256         int lower_pos = int(floor(to_fp32(bilinear_weights[0].pos) * size - 0.5f));
257         int upper_pos = int(ceil(to_fp32(bilinear_weights[num_bilinear_weights - 1].pos) * size - 0.5f)) + 2;
258         lower_pos = min<int>(lower_pos, lrintf(weights[0].pos * size - 0.5f));
259         upper_pos = max<int>(upper_pos, lrintf(weights[num_weights - 1].pos * size - 0.5f) + 1);
260
261         float* effective_weights = new float[upper_pos - lower_pos];
262         for (int i = 0; i < upper_pos - lower_pos; ++i) {
263                 effective_weights[i] = 0.0f;
264         }
265
266         // Now find the effective weights that result from this sampling.
267         for (unsigned i = 0; i < num_bilinear_weights; ++i) {
268                 const float pixel_pos = to_fp32(bilinear_weights[i].pos) * size - 0.5f;
269                 const int x0 = int(floor(pixel_pos)) - lower_pos;
270                 const int x1 = x0 + 1;
271                 const float f = lrintf((pixel_pos - (x0 + lower_pos)) / movit_texel_subpixel_precision) * movit_texel_subpixel_precision;
272
273                 assert(x0 >= 0);
274                 assert(x1 >= 0);
275                 assert(x0 < upper_pos - lower_pos);
276                 assert(x1 < upper_pos - lower_pos);
277
278                 effective_weights[x0] += to_fp32(bilinear_weights[i].weight) * (1.0f - f);
279                 effective_weights[x1] += to_fp32(bilinear_weights[i].weight) * f;
280         }
281
282         // Subtract the desired weights to get the error.
283         for (unsigned i = 0; i < num_weights; ++i) {
284                 const int x = lrintf(weights[i].pos * size - 0.5f) - lower_pos;
285                 assert(x >= 0);
286                 assert(x < upper_pos - lower_pos);
287
288                 effective_weights[x] -= weights[i].weight;
289         }
290
291         double sum_sq_error = 0.0;
292         for (unsigned i = 0; i < num_weights; ++i) {
293                 sum_sq_error += effective_weights[i] * effective_weights[i];
294         }
295
296         delete[] effective_weights;
297         return sum_sq_error;
298 }
299
300 }  // namespace
301
302 ResampleEffect::ResampleEffect()
303         : owns_effects(true),
304           input_width(1280),
305           input_height(720),
306           offset_x(0.0f), offset_y(0.0f),
307           zoom_x(1.0f), zoom_y(1.0f),
308           zoom_center_x(0.5f), zoom_center_y(0.5f)
309 {
310         register_int("width", &output_width);
311         register_int("height", &output_height);
312
313         // The first blur pass will forward resolution information to us.
314         hpass = new SingleResamplePassEffect(this);
315         CHECK(hpass->set_int("direction", SingleResamplePassEffect::HORIZONTAL));
316         vpass = new SingleResamplePassEffect(nullptr);
317         CHECK(vpass->set_int("direction", SingleResamplePassEffect::VERTICAL));
318
319         update_size();
320 }
321
322 ResampleEffect::~ResampleEffect()
323 {
324         if (owns_effects) {
325                 delete hpass;
326                 delete vpass;
327         }
328 }
329
330 void ResampleEffect::rewrite_graph(EffectChain *graph, Node *self)
331 {
332         Node *hpass_node = graph->add_node(hpass);
333         Node *vpass_node = graph->add_node(vpass);
334         graph->connect_nodes(hpass_node, vpass_node);
335         graph->replace_receiver(self, hpass_node);
336         graph->replace_sender(self, vpass_node);
337         self->disabled = true;
338         owns_effects = false;
339
340
341 // We get this information forwarded from the first blur pass,
342 // since we are not part of the chain ourselves.
343 void ResampleEffect::inform_input_size(unsigned input_num, unsigned width, unsigned height)
344 {
345         assert(input_num == 0);
346         assert(width != 0);
347         assert(height != 0);
348         input_width = width;
349         input_height = height;
350         update_size();
351 }
352
353 void ResampleEffect::update_size()
354 {
355         bool ok = true;
356         ok |= hpass->set_int("input_width", input_width);
357         ok |= hpass->set_int("input_height", input_height);
358         ok |= hpass->set_int("output_width", output_width);
359         ok |= hpass->set_int("output_height", input_height);
360
361         ok |= vpass->set_int("input_width", output_width);
362         ok |= vpass->set_int("input_height", input_height);
363         ok |= vpass->set_int("output_width", output_width);
364         ok |= vpass->set_int("output_height", output_height);
365
366         assert(ok);
367
368         // The offset added due to zoom may have changed with the size.
369         update_offset_and_zoom();
370 }
371
372 void ResampleEffect::update_offset_and_zoom()
373 {
374         bool ok = true;
375
376         // Zoom from the right origin. (zoom_center is given in normalized coordinates,
377         // i.e. 0..1.)
378         float extra_offset_x = zoom_center_x * (1.0f - 1.0f / zoom_x) * input_width;
379         float extra_offset_y = (1.0f - zoom_center_y) * (1.0f - 1.0f / zoom_y) * input_height;
380
381         ok |= hpass->set_float("offset", extra_offset_x + offset_x);
382         ok |= vpass->set_float("offset", extra_offset_y - offset_y);  // Compensate for the bottom-left origin.
383         ok |= hpass->set_float("zoom", zoom_x);
384         ok |= vpass->set_float("zoom", zoom_y);
385
386         assert(ok);
387 }
388
389 bool ResampleEffect::set_float(const string &key, float value) {
390         if (key == "width") {
391                 output_width = value;
392                 update_size();
393                 return true;
394         }
395         if (key == "height") {
396                 output_height = value;
397                 update_size();
398                 return true;
399         }
400         if (key == "top") {
401                 offset_y = value;
402                 update_offset_and_zoom();
403                 return true;
404         }
405         if (key == "left") {
406                 offset_x = value;
407                 update_offset_and_zoom();
408                 return true;
409         }
410         if (key == "zoom_x") {
411                 if (value <= 0.0f) {
412                         return false;
413                 }
414                 zoom_x = value;
415                 update_offset_and_zoom();
416                 return true;
417         }
418         if (key == "zoom_y") {
419                 if (value <= 0.0f) {
420                         return false;
421                 }
422                 zoom_y = value;
423                 update_offset_and_zoom();
424                 return true;
425         }
426         if (key == "zoom_center_x") {
427                 zoom_center_x = value;
428                 update_offset_and_zoom();
429                 return true;
430         }
431         if (key == "zoom_center_y") {
432                 zoom_center_y = value;
433                 update_offset_and_zoom();
434                 return true;
435         }
436         return false;
437 }
438
439 SingleResamplePassEffect::SingleResamplePassEffect(ResampleEffect *parent)
440         : parent(parent),
441           direction(HORIZONTAL),
442           input_width(1280),
443           input_height(720),
444           offset(0.0),
445           zoom(1.0),
446           last_input_width(-1),
447           last_input_height(-1),
448           last_output_width(-1),
449           last_output_height(-1),
450           last_offset(0.0 / 0.0),  // NaN.
451           last_zoom(0.0 / 0.0)  // NaN.
452 {
453         register_int("direction", (int *)&direction);
454         register_int("input_width", &input_width);
455         register_int("input_height", &input_height);
456         register_int("output_width", &output_width);
457         register_int("output_height", &output_height);
458         register_float("offset", &offset);
459         register_float("zoom", &zoom);
460         register_uniform_sampler2d("sample_tex", &uniform_sample_tex);
461         register_uniform_int("num_samples", &uniform_num_samples);
462         register_uniform_float("num_loops", &uniform_num_loops);
463         register_uniform_float("slice_height", &uniform_slice_height);
464         register_uniform_float("sample_x_scale", &uniform_sample_x_scale);
465         register_uniform_float("sample_x_offset", &uniform_sample_x_offset);
466         register_uniform_float("whole_pixel_offset", &uniform_whole_pixel_offset);
467
468         call_once(lanczos_table_init_done, init_lanczos_table);
469 }
470
471 SingleResamplePassEffect::~SingleResamplePassEffect()
472 {
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         ScalingWeights weights = calculate_scaling_weights(src_size, dst_size, zoom, offset);
510         src_bilinear_samples = weights.src_bilinear_samples;
511         num_loops = weights.num_loops;
512         slice_height = 1.0f / weights.num_loops;
513
514         // Encode as a two-component texture. Note the GL_REPEAT.
515         glActiveTexture(GL_TEXTURE0 + *sampler_num);
516         check_error();
517         glBindTexture(GL_TEXTURE_2D, tex.get_texnum());
518         check_error();
519
520         GLenum type, internal_format;
521         void *pixels;
522         assert((weights.bilinear_weights_fp16 == nullptr) != (weights.bilinear_weights_fp32 == nullptr));
523         if (weights.bilinear_weights_fp32 != nullptr) {
524                 type = GL_FLOAT;
525                 internal_format = GL_RG32F;
526                 pixels = weights.bilinear_weights_fp32.get();
527         } else {
528                 type = GL_HALF_FLOAT;
529                 internal_format = GL_RG16F;
530                 pixels = weights.bilinear_weights_fp16.get();
531         }
532
533         tex.update(weights.src_bilinear_samples, weights.dst_samples, internal_format, GL_RG, type, pixels);
534 }
535
536 ScalingWeights calculate_scaling_weights(unsigned src_size, unsigned dst_size, float zoom, float offset)
537 {
538         // Only needed if run from outside ResampleEffect.
539         call_once(lanczos_table_init_done, init_lanczos_table);
540
541         // For many resamplings (e.g. 640 -> 1280), we will end up with the same
542         // set of samples over and over again in a loop. Thus, we can compute only
543         // the first such loop, and then ask the card to repeat the texture for us.
544         // This is both easier on the texture cache and lowers our CPU cost for
545         // generating the kernel somewhat.
546         float scaling_factor;
547         int num_loops;
548         if (fabs(zoom - 1.0f) < 1e-6) {
549                 num_loops = gcd(src_size, dst_size);
550                 scaling_factor = float(dst_size) / float(src_size);
551         } else {
552                 // If zooming is enabled (ie., zoom != 1), we turn off the looping.
553                 // We _could_ perhaps do it for rational zoom levels (especially
554                 // things like 2:1), but it doesn't seem to be worth it, given that
555                 // the most common use case would seem to be varying the zoom
556                 // from frame to frame.
557                 num_loops = 1;
558                 scaling_factor = zoom * float(dst_size) / float(src_size);
559         }
560         unsigned dst_samples = dst_size / num_loops;
561
562         // Sample the kernel in the right place. A diagram with a triangular kernel
563         // (corresponding to linear filtering, and obviously with radius 1)
564         // for easier ASCII art drawing:
565         //
566         //                *
567         //               / \                      |
568         //              /   \                     |
569         //             /     \                    |
570         //    x---x---x   x   x---x---x---x
571         //
572         // Scaling up (in this case, 2x) means sampling more densely:
573         //
574         //                *
575         //               / \                      |
576         //              /   \                     |
577         //             /     \                    |
578         //   x-x-x-x-x-x x x x-x-x-x-x-x-x-x
579         //
580         // When scaling up, any destination pixel will only be influenced by a few
581         // (in this case, two) neighboring pixels, and more importantly, the number
582         // will not be influenced by the scaling factor. (Note, however, that the
583         // pixel centers have moved, due to OpenGL's center-pixel convention.)
584         // The only thing that changes is the weights themselves, as the sampling
585         // points are at different distances from the original pixels.
586         //
587         // Scaling down is a different story:
588         //
589         //                *
590         //               / \                      |
591         //              /   \                     |
592         //             /     \                    |
593         //    --x------ x     --x-------x--
594         //
595         // Again, the pixel centers have moved in a maybe unintuitive fashion,
596         // although when you consider that there are multiple source pixels around,
597         // it's not so bad as at first look:
598         //
599         //            *   *   *   *
600         //           / \ / \ / \ / \              |
601         //          /   X   X   X   \             |
602         //         /   / \ / \ / \   \            |
603         //    --x-------x-------x-------x--
604         //
605         // As you can see, the new pixels become averages of the two neighboring old
606         // ones (the situation for Lanczos is of course more complex).
607         //
608         // Anyhow, in this case we clearly need to look at more source pixels
609         // to compute the destination pixel, and how many depend on the scaling factor.
610         // Thus, the kernel width will vary with how much we scale.
611         float radius_scaling_factor = min(scaling_factor, 1.0f);
612         int int_radius = lrintf(LANCZOS_RADIUS / radius_scaling_factor);
613         int src_samples = int_radius * 2 + 1;
614         unique_ptr<Tap<float>[]> weights(new Tap<float>[dst_samples * src_samples]);
615         float subpixel_offset = offset - lrintf(offset);  // The part not covered by whole_pixel_offset.
616         assert(subpixel_offset >= -0.5f && subpixel_offset <= 0.5f);
617         for (unsigned y = 0; y < dst_samples; ++y) {
618                 // Find the point around which we want to sample the source image,
619                 // compensating for differing pixel centers as the scale changes.
620                 float center_src_y = (y + 0.5f) / scaling_factor - 0.5f;
621                 int base_src_y = lrintf(center_src_y);
622
623                 // Now sample <int_radius> pixels on each side around that point.
624                 float inv_src_size = 1.0 / float(src_size);
625                 for (int i = 0; i < src_samples; ++i) {
626                         int src_y = base_src_y + i - int_radius;
627                         float weight = lanczos_weight_cached(radius_scaling_factor * (src_y - center_src_y - subpixel_offset));
628                         weights[y * src_samples + i].weight = weight * radius_scaling_factor;
629                         weights[y * src_samples + i].pos = (src_y + 0.5f) * inv_src_size;
630                 }
631         }
632
633         // Now make use of the bilinear filtering in the GPU to reduce the number of samples
634         // we need to make. Try fp16 first; if it's not accurate enough, we go to fp32.
635         // Our tolerance level for total error is a bit higher than the one for invididual
636         // samples, since one would assume overall errors in the shape don't matter as much.
637         const float max_error = 2.0f / (255.0f * 255.0f);
638         unique_ptr<Tap<fp16_int_t>[]> bilinear_weights_fp16;
639         int src_bilinear_samples = combine_many_samples(weights.get(), src_size, src_samples, dst_samples, &bilinear_weights_fp16);
640         unique_ptr<Tap<float>[]> bilinear_weights_fp32 = nullptr;
641         double max_sum_sq_error_fp16 = 0.0;
642         for (unsigned y = 0; y < dst_samples; ++y) {
643                 double sum_sq_error_fp16 = compute_sum_sq_error(
644                         weights.get() + y * src_samples, src_samples,
645                         bilinear_weights_fp16.get() + y * src_bilinear_samples, src_bilinear_samples,
646                         src_size);
647                 max_sum_sq_error_fp16 = std::max(max_sum_sq_error_fp16, sum_sq_error_fp16);
648                 if (max_sum_sq_error_fp16 > max_error) {
649                         break;
650                 }
651         }
652
653         if (max_sum_sq_error_fp16 > max_error) {
654                 bilinear_weights_fp16.reset();
655                 src_bilinear_samples = combine_many_samples(weights.get(), src_size, src_samples, dst_samples, &bilinear_weights_fp32);
656         }
657
658         ScalingWeights ret;
659         ret.src_bilinear_samples = src_bilinear_samples;
660         ret.dst_samples = dst_samples;
661         ret.num_loops = num_loops;
662         ret.bilinear_weights_fp16 = move(bilinear_weights_fp16);
663         ret.bilinear_weights_fp32 = move(bilinear_weights_fp32);
664         return ret;
665 }
666
667 void SingleResamplePassEffect::set_gl_state(GLuint glsl_program_num, const string &prefix, unsigned *sampler_num)
668 {
669         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
670
671         assert(input_width > 0);
672         assert(input_height > 0);
673         assert(output_width > 0);
674         assert(output_height > 0);
675
676         if (input_width != last_input_width ||
677             input_height != last_input_height ||
678             output_width != last_output_width ||
679             output_height != last_output_height ||
680             offset != last_offset ||
681             zoom != last_zoom) {
682                 update_texture(glsl_program_num, prefix, sampler_num);
683                 last_input_width = input_width;
684                 last_input_height = input_height;
685                 last_output_width = output_width;
686                 last_output_height = output_height;
687                 last_offset = offset;
688                 last_zoom = zoom;
689         }
690
691         glActiveTexture(GL_TEXTURE0 + *sampler_num);
692         check_error();
693         glBindTexture(GL_TEXTURE_2D, tex.get_texnum());
694         check_error();
695
696         uniform_sample_tex = *sampler_num;
697         ++*sampler_num;
698         uniform_num_samples = src_bilinear_samples;
699         uniform_num_loops = num_loops;
700         uniform_slice_height = slice_height;
701
702         // Instructions for how to convert integer sample numbers to positions in the weight texture.
703         uniform_sample_x_scale = 1.0f / src_bilinear_samples;
704         uniform_sample_x_offset = 0.5f / src_bilinear_samples;
705
706         if (direction == SingleResamplePassEffect::VERTICAL) {
707                 uniform_whole_pixel_offset = lrintf(offset) / float(input_height);
708         } else {
709                 uniform_whole_pixel_offset = lrintf(offset) / float(input_width);
710         }
711
712         // We specifically do not want mipmaps on the input texture;
713         // they break minification.
714         Node *self = chain->find_node_for_effect(this);
715         if (chain->has_input_sampler(self, 0)) {
716                 glActiveTexture(chain->get_input_sampler(self, 0));
717                 check_error();
718                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
719                 check_error();
720         }
721 }
722
723 Support2DTexture::Support2DTexture()
724 {
725         glGenTextures(1, &texnum);
726         check_error();
727         glBindTexture(GL_TEXTURE_2D, texnum);
728         check_error();
729         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
730         check_error();
731         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
732         check_error();
733         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
734         check_error();
735 }
736
737 Support2DTexture::~Support2DTexture()
738 {
739         glDeleteTextures(1, &texnum);
740         check_error();
741 }
742
743 void Support2DTexture::update(GLint width, GLint height, GLenum internal_format, GLenum format, GLenum type, const GLvoid * data)
744 {
745         glBindTexture(GL_TEXTURE_2D, texnum);
746         check_error();
747         if (width == last_texture_width &&
748             height == last_texture_height &&
749             internal_format == last_texture_internal_format) {
750                 // Texture dimensions and type are unchanged; it is more efficient
751                 // to just update it rather than making an entirely new texture.
752                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data);
753                 check_error();
754         } else {
755                 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, data);
756                 check_error();
757                 last_texture_width = width;
758                 last_texture_height = height;
759                 last_texture_internal_format = internal_format;
760         }
761 }
762
763 }  // namespace movit