]> git.sesse.net Git - ffmpeg/blob - libswscale/utils.c
6034b704658d14b9e7967eb5493f1ac2790f67fe
[ffmpeg] / libswscale / utils.c
1 /*
2  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni@gmx.at>
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "config.h"
22
23 #define _SVID_SOURCE // needed for MAP_ANONYMOUS
24 #include <assert.h>
25 #include <inttypes.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include <string.h>
29 #if HAVE_SYS_MMAN_H
30 #include <sys/mman.h>
31 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
32 #define MAP_ANONYMOUS MAP_ANON
33 #endif
34 #endif
35 #if HAVE_VIRTUALALLOC
36 #define WIN32_LEAN_AND_MEAN
37 #include <windows.h>
38 #endif
39
40 #include "libavutil/attributes.h"
41 #include "libavutil/avutil.h"
42 #include "libavutil/bswap.h"
43 #include "libavutil/cpu.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/mathematics.h"
46 #include "libavutil/opt.h"
47 #include "libavutil/pixdesc.h"
48 #include "libavutil/ppc/cpu.h"
49 #include "libavutil/x86/asm.h"
50 #include "libavutil/x86/cpu.h"
51 #include "rgb2rgb.h"
52 #include "swscale.h"
53 #include "swscale_internal.h"
54
55 unsigned swscale_version(void)
56 {
57     return LIBSWSCALE_VERSION_INT;
58 }
59
60 const char *swscale_configuration(void)
61 {
62     return LIBAV_CONFIGURATION;
63 }
64
65 const char *swscale_license(void)
66 {
67 #define LICENSE_PREFIX "libswscale license: "
68     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
69 }
70
71 #define RET 0xC3 // near return opcode for x86
72
73 typedef struct FormatEntry {
74     uint8_t is_supported_in         :1;
75     uint8_t is_supported_out        :1;
76     uint8_t is_supported_endianness :1;
77 } FormatEntry;
78
79 static const FormatEntry format_entries[AV_PIX_FMT_NB] = {
80     [AV_PIX_FMT_YUV420P]     = { 1, 1 },
81     [AV_PIX_FMT_YUYV422]     = { 1, 1 },
82     [AV_PIX_FMT_RGB24]       = { 1, 1 },
83     [AV_PIX_FMT_BGR24]       = { 1, 1 },
84     [AV_PIX_FMT_YUV422P]     = { 1, 1 },
85     [AV_PIX_FMT_YUV444P]     = { 1, 1 },
86     [AV_PIX_FMT_YUV410P]     = { 1, 1 },
87     [AV_PIX_FMT_YUV411P]     = { 1, 1 },
88     [AV_PIX_FMT_GRAY8]       = { 1, 1 },
89     [AV_PIX_FMT_MONOWHITE]   = { 1, 1 },
90     [AV_PIX_FMT_MONOBLACK]   = { 1, 1 },
91     [AV_PIX_FMT_PAL8]        = { 1, 0 },
92     [AV_PIX_FMT_YUVJ420P]    = { 1, 1 },
93     [AV_PIX_FMT_YUVJ422P]    = { 1, 1 },
94     [AV_PIX_FMT_YUVJ444P]    = { 1, 1 },
95     [AV_PIX_FMT_YVYU422]     = { 1, 1 },
96     [AV_PIX_FMT_UYVY422]     = { 1, 1 },
97     [AV_PIX_FMT_UYYVYY411]   = { 0, 0 },
98     [AV_PIX_FMT_BGR8]        = { 1, 1 },
99     [AV_PIX_FMT_BGR4]        = { 0, 1 },
100     [AV_PIX_FMT_BGR4_BYTE]   = { 1, 1 },
101     [AV_PIX_FMT_RGB8]        = { 1, 1 },
102     [AV_PIX_FMT_RGB4]        = { 0, 1 },
103     [AV_PIX_FMT_RGB4_BYTE]   = { 1, 1 },
104     [AV_PIX_FMT_NV12]        = { 1, 1 },
105     [AV_PIX_FMT_NV21]        = { 1, 1 },
106     [AV_PIX_FMT_ARGB]        = { 1, 1 },
107     [AV_PIX_FMT_RGBA]        = { 1, 1 },
108     [AV_PIX_FMT_ABGR]        = { 1, 1 },
109     [AV_PIX_FMT_BGRA]        = { 1, 1 },
110     [AV_PIX_FMT_GRAY12BE]    = { 1, 1 },
111     [AV_PIX_FMT_GRAY12LE]    = { 1, 1 },
112     [AV_PIX_FMT_GRAY16BE]    = { 1, 1 },
113     [AV_PIX_FMT_GRAY16LE]    = { 1, 1 },
114     [AV_PIX_FMT_YUV440P]     = { 1, 1 },
115     [AV_PIX_FMT_YUVJ440P]    = { 1, 1 },
116     [AV_PIX_FMT_YUVA420P]    = { 1, 1 },
117     [AV_PIX_FMT_YUVA422P]    = { 1, 1 },
118     [AV_PIX_FMT_YUVA444P]    = { 1, 1 },
119     [AV_PIX_FMT_YUVA420P9BE] = { 1, 1 },
120     [AV_PIX_FMT_YUVA420P9LE] = { 1, 1 },
121     [AV_PIX_FMT_YUVA422P9BE] = { 1, 1 },
122     [AV_PIX_FMT_YUVA422P9LE] = { 1, 1 },
123     [AV_PIX_FMT_YUVA444P9BE] = { 1, 1 },
124     [AV_PIX_FMT_YUVA444P9LE] = { 1, 1 },
125     [AV_PIX_FMT_YUVA420P10BE]= { 1, 1 },
126     [AV_PIX_FMT_YUVA420P10LE]= { 1, 1 },
127     [AV_PIX_FMT_YUVA422P10BE]= { 1, 1 },
128     [AV_PIX_FMT_YUVA422P10LE]= { 1, 1 },
129     [AV_PIX_FMT_YUVA444P10BE]= { 1, 1 },
130     [AV_PIX_FMT_YUVA444P10LE]= { 1, 1 },
131     [AV_PIX_FMT_YUVA420P16BE]= { 1, 1 },
132     [AV_PIX_FMT_YUVA420P16LE]= { 1, 1 },
133     [AV_PIX_FMT_YUVA422P16BE]= { 1, 1 },
134     [AV_PIX_FMT_YUVA422P16LE]= { 1, 1 },
135     [AV_PIX_FMT_YUVA444P16BE]= { 1, 1 },
136     [AV_PIX_FMT_YUVA444P16LE]= { 1, 1 },
137     [AV_PIX_FMT_RGB48BE]     = { 1, 1 },
138     [AV_PIX_FMT_RGB48LE]     = { 1, 1 },
139     [AV_PIX_FMT_RGBA64BE]    = { 0, 0, 1 },
140     [AV_PIX_FMT_RGBA64LE]    = { 0, 0, 1 },
141     [AV_PIX_FMT_RGB565BE]    = { 1, 1 },
142     [AV_PIX_FMT_RGB565LE]    = { 1, 1 },
143     [AV_PIX_FMT_RGB555BE]    = { 1, 1 },
144     [AV_PIX_FMT_RGB555LE]    = { 1, 1 },
145     [AV_PIX_FMT_BGR565BE]    = { 1, 1 },
146     [AV_PIX_FMT_BGR565LE]    = { 1, 1 },
147     [AV_PIX_FMT_BGR555BE]    = { 1, 1 },
148     [AV_PIX_FMT_BGR555LE]    = { 1, 1 },
149     [AV_PIX_FMT_YUV420P16LE] = { 1, 1 },
150     [AV_PIX_FMT_YUV420P16BE] = { 1, 1 },
151     [AV_PIX_FMT_YUV422P16LE] = { 1, 1 },
152     [AV_PIX_FMT_YUV422P16BE] = { 1, 1 },
153     [AV_PIX_FMT_YUV444P16LE] = { 1, 1 },
154     [AV_PIX_FMT_YUV444P16BE] = { 1, 1 },
155     [AV_PIX_FMT_RGB444LE]    = { 1, 1 },
156     [AV_PIX_FMT_RGB444BE]    = { 1, 1 },
157     [AV_PIX_FMT_BGR444LE]    = { 1, 1 },
158     [AV_PIX_FMT_BGR444BE]    = { 1, 1 },
159     [AV_PIX_FMT_YA8]         = { 1, 0 },
160     [AV_PIX_FMT_YA16BE]      = { 1, 0 },
161     [AV_PIX_FMT_YA16LE]      = { 1, 0 },
162     [AV_PIX_FMT_BGR48BE]     = { 1, 1 },
163     [AV_PIX_FMT_BGR48LE]     = { 1, 1 },
164     [AV_PIX_FMT_BGRA64BE]    = { 0, 0, 1 },
165     [AV_PIX_FMT_BGRA64LE]    = { 0, 0, 1 },
166     [AV_PIX_FMT_YUV420P9BE]  = { 1, 1 },
167     [AV_PIX_FMT_YUV420P9LE]  = { 1, 1 },
168     [AV_PIX_FMT_YUV420P10BE] = { 1, 1 },
169     [AV_PIX_FMT_YUV420P10LE] = { 1, 1 },
170     [AV_PIX_FMT_YUV420P12BE] = { 1, 1 },
171     [AV_PIX_FMT_YUV420P12LE] = { 1, 1 },
172     [AV_PIX_FMT_YUV422P9BE]  = { 1, 1 },
173     [AV_PIX_FMT_YUV422P9LE]  = { 1, 1 },
174     [AV_PIX_FMT_YUV422P10BE] = { 1, 1 },
175     [AV_PIX_FMT_YUV422P10LE] = { 1, 1 },
176     [AV_PIX_FMT_YUV422P12BE] = { 1, 1 },
177     [AV_PIX_FMT_YUV422P12LE] = { 1, 1 },
178     [AV_PIX_FMT_YUV444P9BE]  = { 1, 1 },
179     [AV_PIX_FMT_YUV444P9LE]  = { 1, 1 },
180     [AV_PIX_FMT_YUV444P10BE] = { 1, 1 },
181     [AV_PIX_FMT_YUV444P10LE] = { 1, 1 },
182     [AV_PIX_FMT_YUV444P12BE] = { 1, 1 },
183     [AV_PIX_FMT_YUV444P12LE] = { 1, 1 },
184     [AV_PIX_FMT_GBRP]        = { 1, 1 },
185     [AV_PIX_FMT_GBRP9LE]     = { 1, 1 },
186     [AV_PIX_FMT_GBRP9BE]     = { 1, 1 },
187     [AV_PIX_FMT_GBRP10LE]    = { 1, 1 },
188     [AV_PIX_FMT_GBRP10BE]    = { 1, 1 },
189     [AV_PIX_FMT_GBRP12LE]    = { 1, 1 },
190     [AV_PIX_FMT_GBRP12BE]    = { 1, 1 },
191     [AV_PIX_FMT_GBRP16LE]    = { 1, 0 },
192     [AV_PIX_FMT_GBRP16BE]    = { 1, 0 },
193     [AV_PIX_FMT_GBRAP]       = { 1, 1 },
194     [AV_PIX_FMT_GBRAP12LE]   = { 1, 1 },
195     [AV_PIX_FMT_GBRAP12BE]   = { 1, 1 },
196     [AV_PIX_FMT_GBRAP16LE]   = { 1, 0 },
197     [AV_PIX_FMT_GBRAP16BE]   = { 1, 0 },
198     [AV_PIX_FMT_XYZ12BE]     = { 0, 0, 1 },
199     [AV_PIX_FMT_XYZ12LE]     = { 0, 0, 1 },
200     [AV_PIX_FMT_P010LE]      = { 1, 0 },
201     [AV_PIX_FMT_P010BE]      = { 1, 0 },
202 };
203
204 int sws_isSupportedInput(enum AVPixelFormat pix_fmt)
205 {
206     return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
207            format_entries[pix_fmt].is_supported_in : 0;
208 }
209
210 int sws_isSupportedOutput(enum AVPixelFormat pix_fmt)
211 {
212     return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
213            format_entries[pix_fmt].is_supported_out : 0;
214 }
215
216 int sws_isSupportedEndiannessConversion(enum AVPixelFormat pix_fmt)
217 {
218     return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
219            format_entries[pix_fmt].is_supported_endianness : 0;
220 }
221
222 const char *sws_format_name(enum AVPixelFormat format)
223 {
224     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
225     if (desc)
226         return desc->name;
227     else
228         return "Unknown format";
229 }
230
231 static double getSplineCoeff(double a, double b, double c, double d,
232                              double dist)
233 {
234     if (dist <= 1.0)
235         return ((d * dist + c) * dist + b) * dist + a;
236     else
237         return getSplineCoeff(0.0,
238                                b + 2.0 * c + 3.0 * d,
239                                c + 3.0 * d,
240                               -b - 3.0 * c - 6.0 * d,
241                               dist - 1.0);
242 }
243
244 static av_cold int initFilter(int16_t **outFilter, int32_t **filterPos,
245                               int *outFilterSize, int xInc, int srcW,
246                               int dstW, int filterAlign, int one,
247                               int flags, int cpu_flags,
248                               SwsVector *srcFilter, SwsVector *dstFilter,
249                               double param[2], int is_horizontal)
250 {
251     int i;
252     int filterSize;
253     int filter2Size;
254     int minFilterSize;
255     int64_t *filter    = NULL;
256     int64_t *filter2   = NULL;
257     const int64_t fone = 1LL << 54;
258     int ret            = -1;
259
260     emms_c(); // FIXME should not be required but IS (even for non-MMX versions)
261
262     // NOTE: the +3 is for the MMX(+1) / SSE(+3) scaler which reads over the end
263     FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW + 3) * sizeof(**filterPos), fail);
264
265     if (FFABS(xInc - 0x10000) < 10) { // unscaled
266         int i;
267         filterSize = 1;
268         FF_ALLOCZ_OR_GOTO(NULL, filter,
269                           dstW * sizeof(*filter) * filterSize, fail);
270
271         for (i = 0; i < dstW; i++) {
272             filter[i * filterSize] = fone;
273             (*filterPos)[i]        = i;
274         }
275     } else if (flags & SWS_POINT) { // lame looking point sampling mode
276         int i;
277         int xDstInSrc;
278         filterSize = 1;
279         FF_ALLOC_OR_GOTO(NULL, filter,
280                          dstW * sizeof(*filter) * filterSize, fail);
281
282         xDstInSrc = xInc / 2 - 0x8000;
283         for (i = 0; i < dstW; i++) {
284             int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;
285
286             (*filterPos)[i] = xx;
287             filter[i]       = fone;
288             xDstInSrc      += xInc;
289         }
290     } else if ((xInc <= (1 << 16) && (flags & SWS_AREA)) ||
291                (flags & SWS_FAST_BILINEAR)) { // bilinear upscale
292         int i;
293         int xDstInSrc;
294         filterSize = 2;
295         FF_ALLOC_OR_GOTO(NULL, filter,
296                          dstW * sizeof(*filter) * filterSize, fail);
297
298         xDstInSrc = xInc / 2 - 0x8000;
299         for (i = 0; i < dstW; i++) {
300             int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;
301             int j;
302
303             (*filterPos)[i] = xx;
304             // bilinear upscale / linear interpolate / area averaging
305             for (j = 0; j < filterSize; j++) {
306                 int64_t coeff = fone - FFABS((xx << 16) - xDstInSrc) *
307                                 (fone >> 16);
308                 if (coeff < 0)
309                     coeff = 0;
310                 filter[i * filterSize + j] = coeff;
311                 xx++;
312             }
313             xDstInSrc += xInc;
314         }
315     } else {
316         int64_t xDstInSrc;
317         int sizeFactor;
318
319         if (flags & SWS_BICUBIC)
320             sizeFactor = 4;
321         else if (flags & SWS_X)
322             sizeFactor = 8;
323         else if (flags & SWS_AREA)
324             sizeFactor = 1;     // downscale only, for upscale it is bilinear
325         else if (flags & SWS_GAUSS)
326             sizeFactor = 8;     // infinite ;)
327         else if (flags & SWS_LANCZOS)
328             sizeFactor = param[0] != SWS_PARAM_DEFAULT ? ceil(2 * param[0]) : 6;
329         else if (flags & SWS_SINC)
330             sizeFactor = 20;    // infinite ;)
331         else if (flags & SWS_SPLINE)
332             sizeFactor = 20;    // infinite ;)
333         else if (flags & SWS_BILINEAR)
334             sizeFactor = 2;
335         else {
336             sizeFactor = 0;     // GCC warning killer
337             assert(0);
338         }
339
340         if (xInc <= 1 << 16)
341             filterSize = 1 + sizeFactor;    // upscale
342         else
343             filterSize = 1 + (sizeFactor * srcW + dstW - 1) / dstW;
344
345         filterSize = FFMIN(filterSize, srcW - 2);
346         filterSize = FFMAX(filterSize, 1);
347
348         FF_ALLOC_OR_GOTO(NULL, filter,
349                          dstW * sizeof(*filter) * filterSize, fail);
350
351         xDstInSrc = xInc - 0x10000;
352         for (i = 0; i < dstW; i++) {
353             int xx = (xDstInSrc - ((int64_t)(filterSize - 2) << 16)) / (1 << 17);
354             int j;
355             (*filterPos)[i] = xx;
356             for (j = 0; j < filterSize; j++) {
357                 int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;
358                 double floatd;
359                 int64_t coeff;
360
361                 if (xInc > 1 << 16)
362                     d = d * dstW / srcW;
363                 floatd = d * (1.0 / (1 << 30));
364
365                 if (flags & SWS_BICUBIC) {
366                     int64_t B = (param[0] != SWS_PARAM_DEFAULT ? param[0] :   0) * (1 << 24);
367                     int64_t C = (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1 << 24);
368
369                     if (d >= 1LL << 31) {
370                         coeff = 0.0;
371                     } else {
372                         int64_t dd  = (d  * d) >> 30;
373                         int64_t ddd = (dd * d) >> 30;
374
375                         if (d < 1LL << 30)
376                             coeff =  (12 * (1 << 24) -  9 * B - 6 * C) * ddd +
377                                     (-18 * (1 << 24) + 12 * B + 6 * C) *  dd +
378                                       (6 * (1 << 24) -  2 * B)         * (1 << 30);
379                         else
380                             coeff =      (-B -  6 * C) * ddd +
381                                       (6 * B + 30 * C) * dd  +
382                                     (-12 * B - 48 * C) * d   +
383                                       (8 * B + 24 * C) * (1 << 30);
384                     }
385                     coeff *= fone >> (30 + 24);
386                 }
387                 else if (flags & SWS_X) {
388                     double A = param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;
389                     double c;
390
391                     if (floatd < 1.0)
392                         c = cos(floatd * M_PI);
393                     else
394                         c = -1.0;
395                     if (c < 0.0)
396                         c = -pow(-c, A);
397                     else
398                         c = pow(c, A);
399                     coeff = (c * 0.5 + 0.5) * fone;
400                 } else if (flags & SWS_AREA) {
401                     int64_t d2 = d - (1 << 29);
402                     if (d2 * xInc < -(1LL << (29 + 16)))
403                         coeff = 1.0 * (1LL << (30 + 16));
404                     else if (d2 * xInc < (1LL << (29 + 16)))
405                         coeff = -d2 * xInc + (1LL << (29 + 16));
406                     else
407                         coeff = 0.0;
408                     coeff *= fone >> (30 + 16);
409                 } else if (flags & SWS_GAUSS) {
410                     double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
411                     coeff = (pow(2.0, -p * floatd * floatd)) * fone;
412                 } else if (flags & SWS_SINC) {
413                     coeff = (d ? sin(floatd * M_PI) / (floatd * M_PI) : 1.0) * fone;
414                 } else if (flags & SWS_LANCZOS) {
415                     double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
416                     coeff = (d ? sin(floatd * M_PI) * sin(floatd * M_PI / p) /
417                              (floatd * floatd * M_PI * M_PI / p) : 1.0) * fone;
418                     if (floatd > p)
419                         coeff = 0;
420                 } else if (flags & SWS_BILINEAR) {
421                     coeff = (1 << 30) - d;
422                     if (coeff < 0)
423                         coeff = 0;
424                     coeff *= fone >> 30;
425                 } else if (flags & SWS_SPLINE) {
426                     double p = -2.196152422706632;
427                     coeff = getSplineCoeff(1.0, 0.0, p, -p - 1.0, floatd) * fone;
428                 } else {
429                     coeff = 0.0; // GCC warning killer
430                     assert(0);
431                 }
432
433                 filter[i * filterSize + j] = coeff;
434                 xx++;
435             }
436             xDstInSrc += 2 * xInc;
437         }
438     }
439
440     /* apply src & dst Filter to filter -> filter2
441      * av_free(filter);
442      */
443     assert(filterSize > 0);
444     filter2Size = filterSize;
445     if (srcFilter)
446         filter2Size += srcFilter->length - 1;
447     if (dstFilter)
448         filter2Size += dstFilter->length - 1;
449     assert(filter2Size > 0);
450     FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size * dstW * sizeof(*filter2), fail);
451
452     for (i = 0; i < dstW; i++) {
453         int j, k;
454
455         if (srcFilter) {
456             for (k = 0; k < srcFilter->length; k++) {
457                 for (j = 0; j < filterSize; j++)
458                     filter2[i * filter2Size + k + j] +=
459                         srcFilter->coeff[k] * filter[i * filterSize + j];
460             }
461         } else {
462             for (j = 0; j < filterSize; j++)
463                 filter2[i * filter2Size + j] = filter[i * filterSize + j];
464         }
465         // FIXME dstFilter
466
467         (*filterPos)[i] += (filterSize - 1) / 2 - (filter2Size - 1) / 2;
468     }
469     av_freep(&filter);
470
471     /* try to reduce the filter-size (step1 find size and shift left) */
472     // Assume it is near normalized (*0.5 or *2.0 is OK but * 0.001 is not).
473     minFilterSize = 0;
474     for (i = dstW - 1; i >= 0; i--) {
475         int min = filter2Size;
476         int j;
477         int64_t cutOff = 0.0;
478
479         /* get rid of near zero elements on the left by shifting left */
480         for (j = 0; j < filter2Size; j++) {
481             int k;
482             cutOff += FFABS(filter2[i * filter2Size]);
483
484             if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)
485                 break;
486
487             /* preserve monotonicity because the core can't handle the
488              * filter otherwise */
489             if (i < dstW - 1 && (*filterPos)[i] >= (*filterPos)[i + 1])
490                 break;
491
492             // move filter coefficients left
493             for (k = 1; k < filter2Size; k++)
494                 filter2[i * filter2Size + k - 1] = filter2[i * filter2Size + k];
495             filter2[i * filter2Size + k - 1] = 0;
496             (*filterPos)[i]++;
497         }
498
499         cutOff = 0;
500         /* count near zeros on the right */
501         for (j = filter2Size - 1; j > 0; j--) {
502             cutOff += FFABS(filter2[i * filter2Size + j]);
503
504             if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)
505                 break;
506             min--;
507         }
508
509         if (min > minFilterSize)
510             minFilterSize = min;
511     }
512
513     if (PPC_ALTIVEC(cpu_flags)) {
514         // we can handle the special case 4, so we don't want to go the full 8
515         if (minFilterSize < 5)
516             filterAlign = 4;
517
518         /* We really don't want to waste our time doing useless computation, so
519          * fall back on the scalar C code for very small filters.
520          * Vectorizing is worth it only if you have a decent-sized vector. */
521         if (minFilterSize < 3)
522             filterAlign = 1;
523     }
524
525     if (INLINE_MMX(cpu_flags)) {
526         // special case for unscaled vertical filtering
527         if (minFilterSize == 1 && filterAlign == 2)
528             filterAlign = 1;
529     }
530
531     assert(minFilterSize > 0);
532     filterSize = (minFilterSize + (filterAlign - 1)) & (~(filterAlign - 1));
533     assert(filterSize > 0);
534     filter = av_malloc(filterSize * dstW * sizeof(*filter));
535     if (filterSize >= MAX_FILTER_SIZE * 16 /
536                       ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)
537         goto fail;
538     *outFilterSize = filterSize;
539
540     if (flags & SWS_PRINT_INFO)
541         av_log(NULL, AV_LOG_VERBOSE,
542                "SwScaler: reducing / aligning filtersize %d -> %d\n",
543                filter2Size, filterSize);
544     /* try to reduce the filter-size (step2 reduce it) */
545     for (i = 0; i < dstW; i++) {
546         int j;
547
548         for (j = 0; j < filterSize; j++) {
549             if (j >= filter2Size)
550                 filter[i * filterSize + j] = 0;
551             else
552                 filter[i * filterSize + j] = filter2[i * filter2Size + j];
553             if ((flags & SWS_BITEXACT) && j >= minFilterSize)
554                 filter[i * filterSize + j] = 0;
555         }
556     }
557
558     // FIXME try to align filterPos if possible
559
560     // fix borders
561     if (is_horizontal) {
562         for (i = 0; i < dstW; i++) {
563             int j;
564             if ((*filterPos)[i] < 0) {
565                 // move filter coefficients left to compensate for filterPos
566                 for (j = 1; j < filterSize; j++) {
567                     int left = FFMAX(j + (*filterPos)[i], 0);
568                     filter[i * filterSize + left] += filter[i * filterSize + j];
569                     filter[i * filterSize + j]     = 0;
570                 }
571                 (*filterPos)[i] = 0;
572             }
573
574             if ((*filterPos)[i] + filterSize > srcW) {
575                 int shift = (*filterPos)[i] + filterSize - srcW;
576                 // move filter coefficients right to compensate for filterPos
577                 for (j = filterSize - 2; j >= 0; j--) {
578                     int right = FFMIN(j + shift, filterSize - 1);
579                     filter[i * filterSize + right] += filter[i * filterSize + j];
580                     filter[i * filterSize + j]      = 0;
581                 }
582                 (*filterPos)[i] = srcW - filterSize;
583             }
584         }
585     }
586
587     // Note the +1 is for the MMX scaler which reads over the end
588     /* align at 16 for AltiVec (needed by hScale_altivec_real) */
589     FF_ALLOCZ_OR_GOTO(NULL, *outFilter,
590                       *outFilterSize * (dstW + 3) * sizeof(int16_t), fail);
591
592     /* normalize & store in outFilter */
593     for (i = 0; i < dstW; i++) {
594         int j;
595         int64_t error = 0;
596         int64_t sum   = 0;
597
598         for (j = 0; j < filterSize; j++) {
599             sum += filter[i * filterSize + j];
600         }
601         sum = (sum + one / 2) / one;
602         for (j = 0; j < *outFilterSize; j++) {
603             int64_t v = filter[i * filterSize + j] + error;
604             int intV  = ROUNDED_DIV(v, sum);
605             (*outFilter)[i * (*outFilterSize) + j] = intV;
606             error                                  = v - intV * sum;
607         }
608     }
609
610     (*filterPos)[dstW + 0] =
611     (*filterPos)[dstW + 1] =
612     (*filterPos)[dstW + 2] = (*filterPos)[dstW - 1]; /* the MMX/SSE scaler will
613                                                       * read over the end */
614     for (i = 0; i < *outFilterSize; i++) {
615         int k = (dstW - 1) * (*outFilterSize) + i;
616         (*outFilter)[k + 1 * (*outFilterSize)] =
617         (*outFilter)[k + 2 * (*outFilterSize)] =
618         (*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];
619     }
620
621     ret = 0;
622
623 fail:
624     av_free(filter);
625     av_free(filter2);
626     return ret;
627 }
628
629 #if HAVE_MMXEXT_INLINE
630 static av_cold int init_hscaler_mmxext(int dstW, int xInc, uint8_t *filterCode,
631                                        int16_t *filter, int32_t *filterPos,
632                                        int numSplits)
633 {
634     uint8_t *fragmentA;
635     x86_reg imm8OfPShufW1A;
636     x86_reg imm8OfPShufW2A;
637     x86_reg fragmentLengthA;
638     uint8_t *fragmentB;
639     x86_reg imm8OfPShufW1B;
640     x86_reg imm8OfPShufW2B;
641     x86_reg fragmentLengthB;
642     int fragmentPos;
643
644     int xpos, i;
645
646     // create an optimized horizontal scaling routine
647     /* This scaler is made of runtime-generated MMXEXT code using specially tuned
648      * pshufw instructions. For every four output pixels, if four input pixels
649      * are enough for the fast bilinear scaling, then a chunk of fragmentB is
650      * used. If five input pixels are needed, then a chunk of fragmentA is used.
651      */
652
653     // code fragment
654
655     __asm__ volatile (
656         "jmp                         9f                 \n\t"
657         // Begin
658         "0:                                             \n\t"
659         "movq  (%%"FF_REG_d", %%"FF_REG_a"), %%mm3      \n\t"
660         "movd  (%%"FF_REG_c", %%"FF_REG_S"), %%mm0      \n\t"
661         "movd 1(%%"FF_REG_c", %%"FF_REG_S"), %%mm1      \n\t"
662         "punpcklbw                %%mm7, %%mm1          \n\t"
663         "punpcklbw                %%mm7, %%mm0          \n\t"
664         "pshufw                   $0xFF, %%mm1, %%mm1   \n\t"
665         "1:                                             \n\t"
666         "pshufw                   $0xFF, %%mm0, %%mm0   \n\t"
667         "2:                                             \n\t"
668         "psubw                    %%mm1, %%mm0          \n\t"
669         "movl 8(%%"FF_REG_b", %%"FF_REG_a"), %%esi      \n\t"
670         "pmullw                   %%mm3, %%mm0          \n\t"
671         "psllw                       $7, %%mm1          \n\t"
672         "paddw                    %%mm1, %%mm0          \n\t"
673
674         "movq       %%mm0, (%%"FF_REG_D", %%"FF_REG_a") \n\t"
675
676         "add                         $8, %%"FF_REG_a"   \n\t"
677         // End
678         "9:                                             \n\t"
679         // "int $3                                         \n\t"
680         "lea       " LOCAL_MANGLE(0b) ", %0             \n\t"
681         "lea       " LOCAL_MANGLE(1b) ", %1             \n\t"
682         "lea       " LOCAL_MANGLE(2b) ", %2             \n\t"
683         "dec                         %1                 \n\t"
684         "dec                         %2                 \n\t"
685         "sub                         %0, %1             \n\t"
686         "sub                         %0, %2             \n\t"
687         "lea       " LOCAL_MANGLE(9b) ", %3             \n\t"
688         "sub                         %0, %3             \n\t"
689
690
691         : "=r" (fragmentA), "=r" (imm8OfPShufW1A), "=r" (imm8OfPShufW2A),
692           "=r" (fragmentLengthA)
693         );
694
695     __asm__ volatile (
696         "jmp                         9f                 \n\t"
697         // Begin
698         "0:                                             \n\t"
699         "movq (%%"FF_REG_d", %%"FF_REG_a"), %%mm3       \n\t"
700         "movd (%%"FF_REG_c", %%"FF_REG_S"), %%mm0       \n\t"
701         "punpcklbw                %%mm7, %%mm0          \n\t"
702         "pshufw                   $0xFF, %%mm0, %%mm1   \n\t"
703         "1:                                             \n\t"
704         "pshufw                   $0xFF, %%mm0, %%mm0   \n\t"
705         "2:                                             \n\t"
706         "psubw                    %%mm1, %%mm0          \n\t"
707         "movl 8(%%"FF_REG_b", %%"FF_REG_a"), %%esi      \n\t"
708         "pmullw                   %%mm3, %%mm0          \n\t"
709         "psllw                       $7, %%mm1          \n\t"
710         "paddw                    %%mm1, %%mm0          \n\t"
711
712         "movq       %%mm0, (%%"FF_REG_D", %%"FF_REG_a") \n\t"
713
714         "add                      $8, %%"FF_REG_a"      \n\t"
715         // End
716         "9:                                             \n\t"
717         // "int                       $3                   \n\t"
718         "lea       " LOCAL_MANGLE(0b) ", %0             \n\t"
719         "lea       " LOCAL_MANGLE(1b) ", %1             \n\t"
720         "lea       " LOCAL_MANGLE(2b) ", %2             \n\t"
721         "dec                         %1                 \n\t"
722         "dec                         %2                 \n\t"
723         "sub                         %0, %1             \n\t"
724         "sub                         %0, %2             \n\t"
725         "lea       " LOCAL_MANGLE(9b) ", %3             \n\t"
726         "sub                         %0, %3             \n\t"
727
728
729         : "=r" (fragmentB), "=r" (imm8OfPShufW1B), "=r" (imm8OfPShufW2B),
730           "=r" (fragmentLengthB)
731         );
732
733     xpos        = 0; // lumXInc/2 - 0x8000; // difference between pixel centers
734     fragmentPos = 0;
735
736     for (i = 0; i < dstW / numSplits; i++) {
737         int xx = xpos >> 16;
738
739         if ((i & 3) == 0) {
740             int a                  = 0;
741             int b                  = ((xpos + xInc) >> 16) - xx;
742             int c                  = ((xpos + xInc * 2) >> 16) - xx;
743             int d                  = ((xpos + xInc * 3) >> 16) - xx;
744             int inc                = (d + 1 < 4);
745             uint8_t *fragment      = (d + 1 < 4) ? fragmentB : fragmentA;
746             x86_reg imm8OfPShufW1  = (d + 1 < 4) ? imm8OfPShufW1B : imm8OfPShufW1A;
747             x86_reg imm8OfPShufW2  = (d + 1 < 4) ? imm8OfPShufW2B : imm8OfPShufW2A;
748             x86_reg fragmentLength = (d + 1 < 4) ? fragmentLengthB : fragmentLengthA;
749             int maxShift           = 3 - (d + inc);
750             int shift              = 0;
751
752             if (filterCode) {
753                 filter[i]        = ((xpos              & 0xFFFF) ^ 0xFFFF) >> 9;
754                 filter[i + 1]    = (((xpos + xInc)     & 0xFFFF) ^ 0xFFFF) >> 9;
755                 filter[i + 2]    = (((xpos + xInc * 2) & 0xFFFF) ^ 0xFFFF) >> 9;
756                 filter[i + 3]    = (((xpos + xInc * 3) & 0xFFFF) ^ 0xFFFF) >> 9;
757                 filterPos[i / 2] = xx;
758
759                 memcpy(filterCode + fragmentPos, fragment, fragmentLength);
760
761                 filterCode[fragmentPos + imm8OfPShufW1] =  (a + inc)       |
762                                                           ((b + inc) << 2) |
763                                                           ((c + inc) << 4) |
764                                                           ((d + inc) << 6);
765                 filterCode[fragmentPos + imm8OfPShufW2] =  a | (b << 2) |
766                                                                (c << 4) |
767                                                                (d << 6);
768
769                 if (i + 4 - inc >= dstW)
770                     shift = maxShift;               // avoid overread
771                 else if ((filterPos[i / 2] & 3) <= maxShift)
772                     shift = filterPos[i / 2] & 3;   // align
773
774                 if (shift && i >= shift) {
775                     filterCode[fragmentPos + imm8OfPShufW1] += 0x55 * shift;
776                     filterCode[fragmentPos + imm8OfPShufW2] += 0x55 * shift;
777                     filterPos[i / 2]                        -= shift;
778                 }
779             }
780
781             fragmentPos += fragmentLength;
782
783             if (filterCode)
784                 filterCode[fragmentPos] = RET;
785         }
786         xpos += xInc;
787     }
788     if (filterCode)
789         filterPos[((i / 2) + 1) & (~1)] = xpos >> 16;  // needed to jump to the next part
790
791     return fragmentPos + 1;
792 }
793 #endif /* HAVE_MMXEXT_INLINE */
794
795 static void getSubSampleFactors(int *h, int *v, enum AVPixelFormat format)
796 {
797     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
798     *h = desc->log2_chroma_w;
799     *v = desc->log2_chroma_h;
800 }
801
802 int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4],
803                              int srcRange, const int table[4], int dstRange,
804                              int brightness, int contrast, int saturation)
805 {
806     const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(c->dstFormat);
807     const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(c->srcFormat);
808     memcpy(c->srcColorspaceTable, inv_table, sizeof(int) * 4);
809     memcpy(c->dstColorspaceTable, table, sizeof(int) * 4);
810
811     c->brightness = brightness;
812     c->contrast   = contrast;
813     c->saturation = saturation;
814     c->srcRange   = srcRange;
815     c->dstRange   = dstRange;
816     if (isYUV(c->dstFormat) || isGray(c->dstFormat))
817         return -1;
818
819     c->dstFormatBpp = av_get_bits_per_pixel(desc_dst);
820     c->srcFormatBpp = av_get_bits_per_pixel(desc_src);
821
822     ff_yuv2rgb_c_init_tables(c, inv_table, srcRange, brightness,
823                              contrast, saturation);
824     // FIXME factorize
825
826     if (ARCH_PPC)
827         ff_yuv2rgb_init_tables_ppc(c, inv_table, brightness,
828                                    contrast, saturation);
829     return 0;
830 }
831
832 int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table,
833                              int *srcRange, int **table, int *dstRange,
834                              int *brightness, int *contrast, int *saturation)
835 {
836     if (isYUV(c->dstFormat) || isGray(c->dstFormat))
837         return -1;
838
839     *inv_table  = c->srcColorspaceTable;
840     *table      = c->dstColorspaceTable;
841     *srcRange   = c->srcRange;
842     *dstRange   = c->dstRange;
843     *brightness = c->brightness;
844     *contrast   = c->contrast;
845     *saturation = c->saturation;
846
847     return 0;
848 }
849
850 static int handle_jpeg(enum AVPixelFormat *format)
851 {
852     switch (*format) {
853     case AV_PIX_FMT_YUVJ420P:
854         *format = AV_PIX_FMT_YUV420P;
855         return 1;
856     case AV_PIX_FMT_YUVJ422P:
857         *format = AV_PIX_FMT_YUV422P;
858         return 1;
859     case AV_PIX_FMT_YUVJ444P:
860         *format = AV_PIX_FMT_YUV444P;
861         return 1;
862     case AV_PIX_FMT_YUVJ440P:
863         *format = AV_PIX_FMT_YUV440P;
864         return 1;
865     default:
866         return 0;
867     }
868 }
869
870 SwsContext *sws_alloc_context(void)
871 {
872     SwsContext *c = av_mallocz(sizeof(SwsContext));
873
874     if (c) {
875         c->av_class = &ff_sws_context_class;
876         av_opt_set_defaults(c);
877     }
878
879     return c;
880 }
881
882 av_cold int sws_init_context(SwsContext *c, SwsFilter *srcFilter,
883                              SwsFilter *dstFilter)
884 {
885     int i;
886     int usesVFilter, usesHFilter;
887     int unscaled;
888     SwsFilter dummyFilter = { NULL, NULL, NULL, NULL };
889     int srcW              = c->srcW;
890     int srcH              = c->srcH;
891     int dstW              = c->dstW;
892     int dstH              = c->dstH;
893     int dst_stride        = FFALIGN(dstW * sizeof(int16_t) + 16, 16);
894     int dst_stride_px     = dst_stride >> 1;
895     int flags, cpu_flags;
896     enum AVPixelFormat srcFormat = c->srcFormat;
897     enum AVPixelFormat dstFormat = c->dstFormat;
898     const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(srcFormat);
899     const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(dstFormat);
900
901     cpu_flags = av_get_cpu_flags();
902     flags     = c->flags;
903     emms_c();
904     if (!rgb15to16)
905         ff_rgb2rgb_init();
906
907     unscaled = (srcW == dstW && srcH == dstH);
908
909     if (!(unscaled && sws_isSupportedEndiannessConversion(srcFormat) &&
910           av_pix_fmt_swap_endianness(srcFormat) == dstFormat)) {
911     if (!sws_isSupportedInput(srcFormat)) {
912         av_log(c, AV_LOG_ERROR, "%s is not supported as input pixel format\n",
913                sws_format_name(srcFormat));
914         return AVERROR(EINVAL);
915     }
916     if (!sws_isSupportedOutput(dstFormat)) {
917         av_log(c, AV_LOG_ERROR, "%s is not supported as output pixel format\n",
918                sws_format_name(dstFormat));
919         return AVERROR(EINVAL);
920     }
921     }
922
923     i = flags & (SWS_POINT         |
924                  SWS_AREA          |
925                  SWS_BILINEAR      |
926                  SWS_FAST_BILINEAR |
927                  SWS_BICUBIC       |
928                  SWS_X             |
929                  SWS_GAUSS         |
930                  SWS_LANCZOS       |
931                  SWS_SINC          |
932                  SWS_SPLINE        |
933                  SWS_BICUBLIN);
934
935     /* provide a default scaler if not set by caller */
936     if (!i) {
937         if (dstW < srcW && dstH < srcH)
938             flags |= SWS_GAUSS;
939         else if (dstW > srcW && dstH > srcH)
940             flags |= SWS_SINC;
941         else
942             flags |= SWS_LANCZOS;
943         c->flags = flags;
944     } else if (i & (i - 1)) {
945         av_log(c, AV_LOG_ERROR,
946                "Exactly one scaler algorithm must be chosen\n");
947         return AVERROR(EINVAL);
948     }
949     /* sanity check */
950     if (srcW < 4 || srcH < 1 || dstW < 8 || dstH < 1) {
951         /* FIXME check if these are enough and try to lower them after
952          * fixing the relevant parts of the code */
953         av_log(c, AV_LOG_ERROR, "%dx%d -> %dx%d is invalid scaling dimension\n",
954                srcW, srcH, dstW, dstH);
955         return AVERROR(EINVAL);
956     }
957
958     if (!dstFilter)
959         dstFilter = &dummyFilter;
960     if (!srcFilter)
961         srcFilter = &dummyFilter;
962
963     c->lumXInc      = (((int64_t)srcW << 16) + (dstW >> 1)) / dstW;
964     c->lumYInc      = (((int64_t)srcH << 16) + (dstH >> 1)) / dstH;
965     c->dstFormatBpp = av_get_bits_per_pixel(desc_dst);
966     c->srcFormatBpp = av_get_bits_per_pixel(desc_src);
967     c->vRounder     = 4 * 0x0001000100010001ULL;
968
969     usesVFilter = (srcFilter->lumV && srcFilter->lumV->length > 1) ||
970                   (srcFilter->chrV && srcFilter->chrV->length > 1) ||
971                   (dstFilter->lumV && dstFilter->lumV->length > 1) ||
972                   (dstFilter->chrV && dstFilter->chrV->length > 1);
973     usesHFilter = (srcFilter->lumH && srcFilter->lumH->length > 1) ||
974                   (srcFilter->chrH && srcFilter->chrH->length > 1) ||
975                   (dstFilter->lumH && dstFilter->lumH->length > 1) ||
976                   (dstFilter->chrH && dstFilter->chrH->length > 1);
977
978     getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat);
979     getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat);
980
981     if (isPlanarRGB(dstFormat)) {
982         if (!(flags & SWS_FULL_CHR_H_INT)) {
983             av_log(c, AV_LOG_DEBUG,
984                    "%s output is not supported with half chroma resolution, switching to full\n",
985                    av_get_pix_fmt_name(dstFormat));
986             flags   |= SWS_FULL_CHR_H_INT;
987             c->flags = flags;
988         }
989     }
990
991     /* reuse chroma for 2 pixels RGB/BGR unless user wants full
992      * chroma interpolation */
993     if (flags & SWS_FULL_CHR_H_INT &&
994         isAnyRGB(dstFormat)        &&
995         !isPlanarRGB(dstFormat)    &&
996         dstFormat != AV_PIX_FMT_RGBA  &&
997         dstFormat != AV_PIX_FMT_ARGB  &&
998         dstFormat != AV_PIX_FMT_BGRA  &&
999         dstFormat != AV_PIX_FMT_ABGR  &&
1000         dstFormat != AV_PIX_FMT_RGB24 &&
1001         dstFormat != AV_PIX_FMT_BGR24) {
1002         av_log(c, AV_LOG_ERROR,
1003                "full chroma interpolation for destination format '%s' not yet implemented\n",
1004                sws_format_name(dstFormat));
1005         flags   &= ~SWS_FULL_CHR_H_INT;
1006         c->flags = flags;
1007     }
1008     if (isAnyRGB(dstFormat) && !(flags & SWS_FULL_CHR_H_INT))
1009         c->chrDstHSubSample = 1;
1010
1011     // drop some chroma lines if the user wants it
1012     c->vChrDrop          = (flags & SWS_SRC_V_CHR_DROP_MASK) >>
1013                            SWS_SRC_V_CHR_DROP_SHIFT;
1014     c->chrSrcVSubSample += c->vChrDrop;
1015
1016     /* drop every other pixel for chroma calculation unless user
1017      * wants full chroma */
1018     if (isAnyRGB(srcFormat) && !(flags & SWS_FULL_CHR_H_INP)   &&
1019         srcFormat != AV_PIX_FMT_RGB8 && srcFormat != AV_PIX_FMT_BGR8 &&
1020         srcFormat != AV_PIX_FMT_RGB4 && srcFormat != AV_PIX_FMT_BGR4 &&
1021         srcFormat != AV_PIX_FMT_RGB4_BYTE && srcFormat != AV_PIX_FMT_BGR4_BYTE &&
1022         srcFormat != AV_PIX_FMT_GBRP9BE   && srcFormat != AV_PIX_FMT_GBRP9LE  &&
1023         srcFormat != AV_PIX_FMT_GBRP10BE  && srcFormat != AV_PIX_FMT_GBRP10LE &&
1024         srcFormat != AV_PIX_FMT_GBRP12BE  && srcFormat != AV_PIX_FMT_GBRP12LE &&
1025         srcFormat != AV_PIX_FMT_GBRP16BE  && srcFormat != AV_PIX_FMT_GBRP16LE &&
1026         ((dstW >> c->chrDstHSubSample) <= (srcW >> 1) ||
1027          (flags & SWS_FAST_BILINEAR)))
1028         c->chrSrcHSubSample = 1;
1029
1030     // Note the AV_CEIL_RSHIFT is so that we always round toward +inf.
1031     c->chrSrcW = AV_CEIL_RSHIFT(srcW, c->chrSrcHSubSample);
1032     c->chrSrcH = AV_CEIL_RSHIFT(srcH, c->chrSrcVSubSample);
1033     c->chrDstW = AV_CEIL_RSHIFT(dstW, c->chrDstHSubSample);
1034     c->chrDstH = AV_CEIL_RSHIFT(dstH, c->chrDstVSubSample);
1035
1036     /* unscaled special cases */
1037     if (unscaled && !usesHFilter && !usesVFilter &&
1038         (c->srcRange == c->dstRange || isAnyRGB(dstFormat))) {
1039         ff_get_unscaled_swscale(c);
1040
1041         if (c->swscale) {
1042             if (flags & SWS_PRINT_INFO)
1043                 av_log(c, AV_LOG_INFO,
1044                        "using unscaled %s -> %s special converter\n",
1045                        sws_format_name(srcFormat), sws_format_name(dstFormat));
1046             return 0;
1047         }
1048     }
1049
1050     c->srcBpc = desc_src->comp[0].depth;
1051     if (c->srcBpc < 8)
1052         c->srcBpc = 8;
1053     c->dstBpc = desc_dst->comp[0].depth;
1054     if (c->dstBpc < 8)
1055         c->dstBpc = 8;
1056     if (c->dstBpc == 16)
1057         dst_stride <<= 1;
1058     FF_ALLOC_OR_GOTO(c, c->formatConvBuffer,
1059                      (FFALIGN(srcW, 16) * 2 * FFALIGN(c->srcBpc, 8) >> 3) + 16,
1060                      fail);
1061     if (INLINE_MMXEXT(cpu_flags) && c->srcBpc == 8 && c->dstBpc <= 12) {
1062         c->canMMXEXTBeUsed = (dstW >= srcW && (dstW & 31) == 0 &&
1063                               (srcW & 15) == 0) ? 1 : 0;
1064         if (!c->canMMXEXTBeUsed && dstW >= srcW && (srcW & 15) == 0
1065             && (flags & SWS_FAST_BILINEAR)) {
1066             if (flags & SWS_PRINT_INFO)
1067                 av_log(c, AV_LOG_INFO,
1068                        "output width is not a multiple of 32 -> no MMXEXT scaler\n");
1069         }
1070         if (usesHFilter)
1071             c->canMMXEXTBeUsed = 0;
1072     } else
1073         c->canMMXEXTBeUsed = 0;
1074
1075     c->chrXInc = (((int64_t)c->chrSrcW << 16) + (c->chrDstW >> 1)) / c->chrDstW;
1076     c->chrYInc = (((int64_t)c->chrSrcH << 16) + (c->chrDstH >> 1)) / c->chrDstH;
1077
1078     /* Match pixel 0 of the src to pixel 0 of dst and match pixel n-2 of src
1079      * to pixel n-2 of dst, but only for the FAST_BILINEAR mode otherwise do
1080      * correct scaling.
1081      * n-2 is the last chrominance sample available.
1082      * This is not perfect, but no one should notice the difference, the more
1083      * correct variant would be like the vertical one, but that would require
1084      * some special code for the first and last pixel */
1085     if (flags & SWS_FAST_BILINEAR) {
1086         if (c->canMMXEXTBeUsed) {
1087             c->lumXInc += 20;
1088             c->chrXInc += 20;
1089         }
1090         // we don't use the x86 asm scaler if MMX is available
1091         else if (INLINE_MMX(cpu_flags)) {
1092             c->lumXInc = ((int64_t)(srcW       - 2) << 16) / (dstW       - 2) - 20;
1093             c->chrXInc = ((int64_t)(c->chrSrcW - 2) << 16) / (c->chrDstW - 2) - 20;
1094         }
1095     }
1096
1097 #define USE_MMAP (HAVE_MMAP && HAVE_MPROTECT && defined MAP_ANONYMOUS)
1098
1099     /* precalculate horizontal scaler filter coefficients */
1100     {
1101 #if HAVE_MMXEXT_INLINE
1102 // can't downscale !!!
1103         if (c->canMMXEXTBeUsed && (flags & SWS_FAST_BILINEAR)) {
1104             c->lumMmxextFilterCodeSize = init_hscaler_mmxext(dstW, c->lumXInc, NULL,
1105                                                              NULL, NULL, 8);
1106             c->chrMmxextFilterCodeSize = init_hscaler_mmxext(c->chrDstW, c->chrXInc,
1107                                                              NULL, NULL, NULL, 4);
1108
1109 #if USE_MMAP
1110             c->lumMmxextFilterCode = mmap(NULL, c->lumMmxextFilterCodeSize,
1111                                           PROT_READ | PROT_WRITE,
1112                                           MAP_PRIVATE | MAP_ANONYMOUS,
1113                                           -1, 0);
1114             c->chrMmxextFilterCode = mmap(NULL, c->chrMmxextFilterCodeSize,
1115                                           PROT_READ | PROT_WRITE,
1116                                           MAP_PRIVATE | MAP_ANONYMOUS,
1117                                           -1, 0);
1118 #elif HAVE_VIRTUALALLOC
1119             c->lumMmxextFilterCode = VirtualAlloc(NULL,
1120                                                   c->lumMmxextFilterCodeSize,
1121                                                   MEM_COMMIT,
1122                                                   PAGE_EXECUTE_READWRITE);
1123             c->chrMmxextFilterCode = VirtualAlloc(NULL,
1124                                                   c->chrMmxextFilterCodeSize,
1125                                                   MEM_COMMIT,
1126                                                   PAGE_EXECUTE_READWRITE);
1127 #else
1128             c->lumMmxextFilterCode = av_malloc(c->lumMmxextFilterCodeSize);
1129             c->chrMmxextFilterCode = av_malloc(c->chrMmxextFilterCodeSize);
1130 #endif
1131
1132             if (!c->lumMmxextFilterCode || !c->chrMmxextFilterCode)
1133                 return AVERROR(ENOMEM);
1134             FF_ALLOCZ_OR_GOTO(c, c->hLumFilter,    (dstW           / 8 + 8) * sizeof(int16_t), fail);
1135             FF_ALLOCZ_OR_GOTO(c, c->hChrFilter,    (c->chrDstW     / 4 + 8) * sizeof(int16_t), fail);
1136             FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW       / 2 / 8 + 8) * sizeof(int32_t), fail);
1137             FF_ALLOCZ_OR_GOTO(c, c->hChrFilterPos, (c->chrDstW / 2 / 4 + 8) * sizeof(int32_t), fail);
1138
1139             init_hscaler_mmxext(dstW, c->lumXInc, c->lumMmxextFilterCode,
1140                                 c->hLumFilter, c->hLumFilterPos, 8);
1141             init_hscaler_mmxext(c->chrDstW, c->chrXInc, c->chrMmxextFilterCode,
1142                                 c->hChrFilter, c->hChrFilterPos, 4);
1143
1144 #if USE_MMAP
1145             mprotect(c->lumMmxextFilterCode, c->lumMmxextFilterCodeSize, PROT_EXEC | PROT_READ);
1146             mprotect(c->chrMmxextFilterCode, c->chrMmxextFilterCodeSize, PROT_EXEC | PROT_READ);
1147 #endif
1148         } else
1149 #endif /* HAVE_MMXEXT_INLINE */
1150         {
1151             const int filterAlign = X86_MMX(cpu_flags)     ? 4 :
1152                                     PPC_ALTIVEC(cpu_flags) ? 8 : 1;
1153
1154             if (initFilter(&c->hLumFilter, &c->hLumFilterPos,
1155                            &c->hLumFilterSize, c->lumXInc,
1156                            srcW, dstW, filterAlign, 1 << 14,
1157                            (flags & SWS_BICUBLIN) ? (flags | SWS_BICUBIC) : flags,
1158                            cpu_flags, srcFilter->lumH, dstFilter->lumH,
1159                            c->param, 1) < 0)
1160                 goto fail;
1161             if (initFilter(&c->hChrFilter, &c->hChrFilterPos,
1162                            &c->hChrFilterSize, c->chrXInc,
1163                            c->chrSrcW, c->chrDstW, filterAlign, 1 << 14,
1164                            (flags & SWS_BICUBLIN) ? (flags | SWS_BILINEAR) : flags,
1165                            cpu_flags, srcFilter->chrH, dstFilter->chrH,
1166                            c->param, 1) < 0)
1167                 goto fail;
1168         }
1169     } // initialize horizontal stuff
1170
1171     /* precalculate vertical scaler filter coefficients */
1172     {
1173         const int filterAlign = X86_MMX(cpu_flags)     ? 2 :
1174                                 PPC_ALTIVEC(cpu_flags) ? 8 : 1;
1175
1176         if (initFilter(&c->vLumFilter, &c->vLumFilterPos, &c->vLumFilterSize,
1177                        c->lumYInc, srcH, dstH, filterAlign, (1 << 12),
1178                        (flags & SWS_BICUBLIN) ? (flags | SWS_BICUBIC) : flags,
1179                        cpu_flags, srcFilter->lumV, dstFilter->lumV,
1180                        c->param, 0) < 0)
1181             goto fail;
1182         if (initFilter(&c->vChrFilter, &c->vChrFilterPos, &c->vChrFilterSize,
1183                        c->chrYInc, c->chrSrcH, c->chrDstH,
1184                        filterAlign, (1 << 12),
1185                        (flags & SWS_BICUBLIN) ? (flags | SWS_BILINEAR) : flags,
1186                        cpu_flags, srcFilter->chrV, dstFilter->chrV,
1187                        c->param, 0) < 0)
1188             goto fail;
1189
1190 #if HAVE_ALTIVEC
1191         FF_ALLOC_OR_GOTO(c, c->vYCoeffsBank, sizeof(vector signed short) * c->vLumFilterSize * c->dstH,    fail);
1192         FF_ALLOC_OR_GOTO(c, c->vCCoeffsBank, sizeof(vector signed short) * c->vChrFilterSize * c->chrDstH, fail);
1193
1194         for (i = 0; i < c->vLumFilterSize * c->dstH; i++) {
1195             int j;
1196             short *p = (short *)&c->vYCoeffsBank[i];
1197             for (j = 0; j < 8; j++)
1198                 p[j] = c->vLumFilter[i];
1199         }
1200
1201         for (i = 0; i < c->vChrFilterSize * c->chrDstH; i++) {
1202             int j;
1203             short *p = (short *)&c->vCCoeffsBank[i];
1204             for (j = 0; j < 8; j++)
1205                 p[j] = c->vChrFilter[i];
1206         }
1207 #endif
1208     }
1209
1210     // calculate buffer sizes so that they won't run out while handling these damn slices
1211     c->vLumBufSize = c->vLumFilterSize;
1212     c->vChrBufSize = c->vChrFilterSize;
1213     for (i = 0; i < dstH; i++) {
1214         int chrI      = (int64_t)i * c->chrDstH / dstH;
1215         int nextSlice = FFMAX(c->vLumFilterPos[i] + c->vLumFilterSize - 1,
1216                               ((c->vChrFilterPos[chrI] + c->vChrFilterSize - 1)
1217                                << c->chrSrcVSubSample));
1218
1219         nextSlice >>= c->chrSrcVSubSample;
1220         nextSlice <<= c->chrSrcVSubSample;
1221         if (c->vLumFilterPos[i] + c->vLumBufSize < nextSlice)
1222             c->vLumBufSize = nextSlice - c->vLumFilterPos[i];
1223         if (c->vChrFilterPos[chrI] + c->vChrBufSize <
1224             (nextSlice >> c->chrSrcVSubSample))
1225             c->vChrBufSize = (nextSlice >> c->chrSrcVSubSample) -
1226                              c->vChrFilterPos[chrI];
1227     }
1228
1229     /* Allocate pixbufs (we use dynamic allocation because otherwise we would
1230      * need to allocate several megabytes to handle all possible cases) */
1231     FF_ALLOC_OR_GOTO(c, c->lumPixBuf,  c->vLumBufSize * 3 * sizeof(int16_t *), fail);
1232     FF_ALLOC_OR_GOTO(c, c->chrUPixBuf, c->vChrBufSize * 3 * sizeof(int16_t *), fail);
1233     FF_ALLOC_OR_GOTO(c, c->chrVPixBuf, c->vChrBufSize * 3 * sizeof(int16_t *), fail);
1234     if (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat) && isALPHA(c->dstFormat))
1235         FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf, c->vLumBufSize * 3 * sizeof(int16_t *), fail);
1236     /* Note we need at least one pixel more at the end because of the MMX code
1237      * (just in case someone wants to replace the 4000/8000). */
1238     /* align at 16 bytes for AltiVec */
1239     for (i = 0; i < c->vLumBufSize; i++) {
1240         FF_ALLOCZ_OR_GOTO(c, c->lumPixBuf[i + c->vLumBufSize],
1241                           dst_stride + 16, fail);
1242         c->lumPixBuf[i] = c->lumPixBuf[i + c->vLumBufSize];
1243     }
1244     // 64 / (c->dstBpc & ~7) is the same as 16 / sizeof(scaling_intermediate)
1245     c->uv_off_px   = dst_stride_px + 64 / (c->dstBpc & ~7);
1246     c->uv_off_byte = dst_stride + 16;
1247     for (i = 0; i < c->vChrBufSize; i++) {
1248         FF_ALLOC_OR_GOTO(c, c->chrUPixBuf[i + c->vChrBufSize],
1249                          dst_stride * 2 + 32, fail);
1250         c->chrUPixBuf[i] = c->chrUPixBuf[i + c->vChrBufSize];
1251         c->chrVPixBuf[i] = c->chrVPixBuf[i + c->vChrBufSize]
1252                          = c->chrUPixBuf[i] + (dst_stride >> 1) + 8;
1253     }
1254     if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
1255         for (i = 0; i < c->vLumBufSize; i++) {
1256             FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf[i + c->vLumBufSize],
1257                               dst_stride + 16, fail);
1258             c->alpPixBuf[i] = c->alpPixBuf[i + c->vLumBufSize];
1259         }
1260
1261     // try to avoid drawing green stuff between the right end and the stride end
1262     for (i = 0; i < c->vChrBufSize; i++)
1263         memset(c->chrUPixBuf[i], 64, dst_stride * 2 + 1);
1264
1265     assert(c->chrDstH <= dstH);
1266
1267     if (flags & SWS_PRINT_INFO) {
1268         if (flags & SWS_FAST_BILINEAR)
1269             av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, ");
1270         else if (flags & SWS_BILINEAR)
1271             av_log(c, AV_LOG_INFO, "BILINEAR scaler, ");
1272         else if (flags & SWS_BICUBIC)
1273             av_log(c, AV_LOG_INFO, "BICUBIC scaler, ");
1274         else if (flags & SWS_X)
1275             av_log(c, AV_LOG_INFO, "Experimental scaler, ");
1276         else if (flags & SWS_POINT)
1277             av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, ");
1278         else if (flags & SWS_AREA)
1279             av_log(c, AV_LOG_INFO, "Area Averaging scaler, ");
1280         else if (flags & SWS_BICUBLIN)
1281             av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, ");
1282         else if (flags & SWS_GAUSS)
1283             av_log(c, AV_LOG_INFO, "Gaussian scaler, ");
1284         else if (flags & SWS_SINC)
1285             av_log(c, AV_LOG_INFO, "Sinc scaler, ");
1286         else if (flags & SWS_LANCZOS)
1287             av_log(c, AV_LOG_INFO, "Lanczos scaler, ");
1288         else if (flags & SWS_SPLINE)
1289             av_log(c, AV_LOG_INFO, "Bicubic spline scaler, ");
1290         else
1291             av_log(c, AV_LOG_INFO, "ehh flags invalid?! ");
1292
1293         av_log(c, AV_LOG_INFO, "from %s to %s%s ",
1294                sws_format_name(srcFormat),
1295 #ifdef DITHER1XBPP
1296                dstFormat == AV_PIX_FMT_BGR555   || dstFormat == AV_PIX_FMT_BGR565   ||
1297                dstFormat == AV_PIX_FMT_RGB444BE || dstFormat == AV_PIX_FMT_RGB444LE ||
1298                dstFormat == AV_PIX_FMT_BGR444BE || dstFormat == AV_PIX_FMT_BGR444LE ?
1299                                                              "dithered " : "",
1300 #else
1301                "",
1302 #endif
1303                sws_format_name(dstFormat));
1304
1305         if (INLINE_MMXEXT(cpu_flags))
1306             av_log(c, AV_LOG_INFO, "using MMXEXT\n");
1307         else if (INLINE_AMD3DNOW(cpu_flags))
1308             av_log(c, AV_LOG_INFO, "using 3DNOW\n");
1309         else if (INLINE_MMX(cpu_flags))
1310             av_log(c, AV_LOG_INFO, "using MMX\n");
1311         else if (PPC_ALTIVEC(cpu_flags))
1312             av_log(c, AV_LOG_INFO, "using AltiVec\n");
1313         else
1314             av_log(c, AV_LOG_INFO, "using C\n");
1315
1316         av_log(c, AV_LOG_VERBOSE, "%dx%d -> %dx%d\n", srcW, srcH, dstW, dstH);
1317         av_log(c, AV_LOG_DEBUG,
1318                "lum srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",
1319                c->srcW, c->srcH, c->dstW, c->dstH, c->lumXInc, c->lumYInc);
1320         av_log(c, AV_LOG_DEBUG,
1321                "chr srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",
1322                c->chrSrcW, c->chrSrcH, c->chrDstW, c->chrDstH,
1323                c->chrXInc, c->chrYInc);
1324     }
1325
1326     c->swscale = ff_getSwsFunc(c);
1327     return 0;
1328 fail: // FIXME replace things by appropriate error codes
1329     return -1;
1330 }
1331
1332 SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat,
1333                            int dstW, int dstH, enum AVPixelFormat dstFormat,
1334                            int flags, SwsFilter *srcFilter,
1335                            SwsFilter *dstFilter, const double *param)
1336 {
1337     SwsContext *c;
1338
1339     if (!(c = sws_alloc_context()))
1340         return NULL;
1341
1342     c->flags     = flags;
1343     c->srcW      = srcW;
1344     c->srcH      = srcH;
1345     c->dstW      = dstW;
1346     c->dstH      = dstH;
1347     c->srcRange  = handle_jpeg(&srcFormat);
1348     c->dstRange  = handle_jpeg(&dstFormat);
1349     c->srcFormat = srcFormat;
1350     c->dstFormat = dstFormat;
1351
1352     if (param) {
1353         c->param[0] = param[0];
1354         c->param[1] = param[1];
1355     }
1356     sws_setColorspaceDetails(c, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], c->srcRange,
1357                              ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/,
1358                              c->dstRange, 0, 1 << 16, 1 << 16);
1359
1360     if (sws_init_context(c, srcFilter, dstFilter) < 0) {
1361         sws_freeContext(c);
1362         return NULL;
1363     }
1364
1365     return c;
1366 }
1367
1368 SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur,
1369                                 float lumaSharpen, float chromaSharpen,
1370                                 float chromaHShift, float chromaVShift,
1371                                 int verbose)
1372 {
1373     SwsFilter *filter = av_malloc(sizeof(SwsFilter));
1374     if (!filter)
1375         return NULL;
1376
1377     if (lumaGBlur != 0.0) {
1378         filter->lumH = sws_getGaussianVec(lumaGBlur, 3.0);
1379         filter->lumV = sws_getGaussianVec(lumaGBlur, 3.0);
1380     } else {
1381         filter->lumH = sws_getIdentityVec();
1382         filter->lumV = sws_getIdentityVec();
1383     }
1384
1385     if (chromaGBlur != 0.0) {
1386         filter->chrH = sws_getGaussianVec(chromaGBlur, 3.0);
1387         filter->chrV = sws_getGaussianVec(chromaGBlur, 3.0);
1388     } else {
1389         filter->chrH = sws_getIdentityVec();
1390         filter->chrV = sws_getIdentityVec();
1391     }
1392
1393     if (!filter->lumH || !filter->lumV || !filter->chrH || !filter->chrV)
1394         goto fail;
1395
1396     if (chromaSharpen != 0.0) {
1397         SwsVector *id = sws_getIdentityVec();
1398         if (!id)
1399             goto fail;
1400         sws_scaleVec(filter->chrH, -chromaSharpen);
1401         sws_scaleVec(filter->chrV, -chromaSharpen);
1402         sws_addVec(filter->chrH, id);
1403         sws_addVec(filter->chrV, id);
1404         sws_freeVec(id);
1405     }
1406
1407     if (lumaSharpen != 0.0) {
1408         SwsVector *id = sws_getIdentityVec();
1409         if (!id)
1410             goto fail;
1411         sws_scaleVec(filter->lumH, -lumaSharpen);
1412         sws_scaleVec(filter->lumV, -lumaSharpen);
1413         sws_addVec(filter->lumH, id);
1414         sws_addVec(filter->lumV, id);
1415         sws_freeVec(id);
1416     }
1417
1418     if (chromaHShift != 0.0)
1419         sws_shiftVec(filter->chrH, (int)(chromaHShift + 0.5));
1420
1421     if (chromaVShift != 0.0)
1422         sws_shiftVec(filter->chrV, (int)(chromaVShift + 0.5));
1423
1424     sws_normalizeVec(filter->chrH, 1.0);
1425     sws_normalizeVec(filter->chrV, 1.0);
1426     sws_normalizeVec(filter->lumH, 1.0);
1427     sws_normalizeVec(filter->lumV, 1.0);
1428
1429     if (verbose)
1430         sws_printVec2(filter->chrH, NULL, AV_LOG_DEBUG);
1431     if (verbose)
1432         sws_printVec2(filter->lumH, NULL, AV_LOG_DEBUG);
1433
1434     return filter;
1435
1436 fail:
1437     sws_freeVec(filter->lumH);
1438     sws_freeVec(filter->lumV);
1439     sws_freeVec(filter->chrH);
1440     sws_freeVec(filter->chrV);
1441     av_freep(&filter);
1442     return NULL;
1443 }
1444
1445 SwsVector *sws_allocVec(int length)
1446 {
1447     SwsVector *vec = av_malloc(sizeof(SwsVector));
1448     if (!vec)
1449         return NULL;
1450     vec->length = length;
1451     vec->coeff  = av_malloc(sizeof(double) * length);
1452     if (!vec->coeff)
1453         av_freep(&vec);
1454     return vec;
1455 }
1456
1457 SwsVector *sws_getGaussianVec(double variance, double quality)
1458 {
1459     const int length = (int)(variance * quality + 0.5) | 1;
1460     int i;
1461     double middle  = (length - 1) * 0.5;
1462     SwsVector *vec = sws_allocVec(length);
1463
1464     if (!vec)
1465         return NULL;
1466
1467     for (i = 0; i < length; i++) {
1468         double dist = i - middle;
1469         vec->coeff[i] = exp(-dist * dist / (2 * variance * variance)) /
1470                         sqrt(2 * variance * M_PI);
1471     }
1472
1473     sws_normalizeVec(vec, 1.0);
1474
1475     return vec;
1476 }
1477
1478 SwsVector *sws_getConstVec(double c, int length)
1479 {
1480     int i;
1481     SwsVector *vec = sws_allocVec(length);
1482
1483     if (!vec)
1484         return NULL;
1485
1486     for (i = 0; i < length; i++)
1487         vec->coeff[i] = c;
1488
1489     return vec;
1490 }
1491
1492 SwsVector *sws_getIdentityVec(void)
1493 {
1494     return sws_getConstVec(1.0, 1);
1495 }
1496
1497 static double sws_dcVec(SwsVector *a)
1498 {
1499     int i;
1500     double sum = 0;
1501
1502     for (i = 0; i < a->length; i++)
1503         sum += a->coeff[i];
1504
1505     return sum;
1506 }
1507
1508 void sws_scaleVec(SwsVector *a, double scalar)
1509 {
1510     int i;
1511
1512     for (i = 0; i < a->length; i++)
1513         a->coeff[i] *= scalar;
1514 }
1515
1516 void sws_normalizeVec(SwsVector *a, double height)
1517 {
1518     sws_scaleVec(a, height / sws_dcVec(a));
1519 }
1520
1521 static SwsVector *sws_getConvVec(SwsVector *a, SwsVector *b)
1522 {
1523     int length = a->length + b->length - 1;
1524     int i, j;
1525     SwsVector *vec = sws_getConstVec(0.0, length);
1526
1527     if (!vec)
1528         return NULL;
1529
1530     for (i = 0; i < a->length; i++) {
1531         for (j = 0; j < b->length; j++) {
1532             vec->coeff[i + j] += a->coeff[i] * b->coeff[j];
1533         }
1534     }
1535
1536     return vec;
1537 }
1538
1539 static SwsVector *sws_sumVec(SwsVector *a, SwsVector *b)
1540 {
1541     int length = FFMAX(a->length, b->length);
1542     int i;
1543     SwsVector *vec = sws_getConstVec(0.0, length);
1544
1545     if (!vec)
1546         return NULL;
1547
1548     for (i = 0; i < a->length; i++)
1549         vec->coeff[i + (length - 1) / 2 - (a->length - 1) / 2] += a->coeff[i];
1550     for (i = 0; i < b->length; i++)
1551         vec->coeff[i + (length - 1) / 2 - (b->length - 1) / 2] += b->coeff[i];
1552
1553     return vec;
1554 }
1555
1556 static SwsVector *sws_diffVec(SwsVector *a, SwsVector *b)
1557 {
1558     int length = FFMAX(a->length, b->length);
1559     int i;
1560     SwsVector *vec = sws_getConstVec(0.0, length);
1561
1562     if (!vec)
1563         return NULL;
1564
1565     for (i = 0; i < a->length; i++)
1566         vec->coeff[i + (length - 1) / 2 - (a->length - 1) / 2] += a->coeff[i];
1567     for (i = 0; i < b->length; i++)
1568         vec->coeff[i + (length - 1) / 2 - (b->length - 1) / 2] -= b->coeff[i];
1569
1570     return vec;
1571 }
1572
1573 /* shift left / or right if "shift" is negative */
1574 static SwsVector *sws_getShiftedVec(SwsVector *a, int shift)
1575 {
1576     int length = a->length + FFABS(shift) * 2;
1577     int i;
1578     SwsVector *vec = sws_getConstVec(0.0, length);
1579
1580     if (!vec)
1581         return NULL;
1582
1583     for (i = 0; i < a->length; i++) {
1584         vec->coeff[i + (length    - 1) / 2 -
1585                        (a->length - 1) / 2 - shift] = a->coeff[i];
1586     }
1587
1588     return vec;
1589 }
1590
1591 void sws_shiftVec(SwsVector *a, int shift)
1592 {
1593     SwsVector *shifted = sws_getShiftedVec(a, shift);
1594     av_free(a->coeff);
1595     a->coeff  = shifted->coeff;
1596     a->length = shifted->length;
1597     av_free(shifted);
1598 }
1599
1600 void sws_addVec(SwsVector *a, SwsVector *b)
1601 {
1602     SwsVector *sum = sws_sumVec(a, b);
1603     av_free(a->coeff);
1604     a->coeff  = sum->coeff;
1605     a->length = sum->length;
1606     av_free(sum);
1607 }
1608
1609 void sws_subVec(SwsVector *a, SwsVector *b)
1610 {
1611     SwsVector *diff = sws_diffVec(a, b);
1612     av_free(a->coeff);
1613     a->coeff  = diff->coeff;
1614     a->length = diff->length;
1615     av_free(diff);
1616 }
1617
1618 void sws_convVec(SwsVector *a, SwsVector *b)
1619 {
1620     SwsVector *conv = sws_getConvVec(a, b);
1621     av_free(a->coeff);
1622     a->coeff  = conv->coeff;
1623     a->length = conv->length;
1624     av_free(conv);
1625 }
1626
1627 SwsVector *sws_cloneVec(SwsVector *a)
1628 {
1629     int i;
1630     SwsVector *vec = sws_allocVec(a->length);
1631
1632     if (!vec)
1633         return NULL;
1634
1635     for (i = 0; i < a->length; i++)
1636         vec->coeff[i] = a->coeff[i];
1637
1638     return vec;
1639 }
1640
1641 void sws_printVec2(SwsVector *a, AVClass *log_ctx, int log_level)
1642 {
1643     int i;
1644     double max = 0;
1645     double min = 0;
1646     double range;
1647
1648     for (i = 0; i < a->length; i++)
1649         if (a->coeff[i] > max)
1650             max = a->coeff[i];
1651
1652     for (i = 0; i < a->length; i++)
1653         if (a->coeff[i] < min)
1654             min = a->coeff[i];
1655
1656     range = max - min;
1657
1658     for (i = 0; i < a->length; i++) {
1659         int x = (int)((a->coeff[i] - min) * 60.0 / range + 0.5);
1660         av_log(log_ctx, log_level, "%1.3f ", a->coeff[i]);
1661         for (; x > 0; x--)
1662             av_log(log_ctx, log_level, " ");
1663         av_log(log_ctx, log_level, "|\n");
1664     }
1665 }
1666
1667 void sws_freeVec(SwsVector *a)
1668 {
1669     if (!a)
1670         return;
1671     av_freep(&a->coeff);
1672     a->length = 0;
1673     av_free(a);
1674 }
1675
1676 void sws_freeFilter(SwsFilter *filter)
1677 {
1678     if (!filter)
1679         return;
1680
1681     if (filter->lumH)
1682         sws_freeVec(filter->lumH);
1683     if (filter->lumV)
1684         sws_freeVec(filter->lumV);
1685     if (filter->chrH)
1686         sws_freeVec(filter->chrH);
1687     if (filter->chrV)
1688         sws_freeVec(filter->chrV);
1689     av_free(filter);
1690 }
1691
1692 void sws_freeContext(SwsContext *c)
1693 {
1694     int i;
1695     if (!c)
1696         return;
1697
1698     if (c->lumPixBuf) {
1699         for (i = 0; i < c->vLumBufSize; i++)
1700             av_freep(&c->lumPixBuf[i]);
1701         av_freep(&c->lumPixBuf);
1702     }
1703
1704     if (c->chrUPixBuf) {
1705         for (i = 0; i < c->vChrBufSize; i++)
1706             av_freep(&c->chrUPixBuf[i]);
1707         av_freep(&c->chrUPixBuf);
1708         av_freep(&c->chrVPixBuf);
1709     }
1710
1711     if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
1712         for (i = 0; i < c->vLumBufSize; i++)
1713             av_freep(&c->alpPixBuf[i]);
1714         av_freep(&c->alpPixBuf);
1715     }
1716
1717     av_freep(&c->vLumFilter);
1718     av_freep(&c->vChrFilter);
1719     av_freep(&c->hLumFilter);
1720     av_freep(&c->hChrFilter);
1721 #if HAVE_ALTIVEC
1722     av_freep(&c->vYCoeffsBank);
1723     av_freep(&c->vCCoeffsBank);
1724 #endif
1725
1726     av_freep(&c->vLumFilterPos);
1727     av_freep(&c->vChrFilterPos);
1728     av_freep(&c->hLumFilterPos);
1729     av_freep(&c->hChrFilterPos);
1730
1731 #if HAVE_MMX_INLINE
1732 #if USE_MMAP
1733     if (c->lumMmxextFilterCode)
1734         munmap(c->lumMmxextFilterCode, c->lumMmxextFilterCodeSize);
1735     if (c->chrMmxextFilterCode)
1736         munmap(c->chrMmxextFilterCode, c->chrMmxextFilterCodeSize);
1737 #elif HAVE_VIRTUALALLOC
1738     if (c->lumMmxextFilterCode)
1739         VirtualFree(c->lumMmxextFilterCode, 0, MEM_RELEASE);
1740     if (c->chrMmxextFilterCode)
1741         VirtualFree(c->chrMmxextFilterCode, 0, MEM_RELEASE);
1742 #else
1743     av_free(c->lumMmxextFilterCode);
1744     av_free(c->chrMmxextFilterCode);
1745 #endif
1746     c->lumMmxextFilterCode = NULL;
1747     c->chrMmxextFilterCode = NULL;
1748 #endif /* HAVE_MMX_INLINE */
1749
1750     av_freep(&c->yuvTable);
1751     av_free(c->formatConvBuffer);
1752
1753     av_free(c);
1754 }
1755
1756 struct SwsContext *sws_getCachedContext(struct SwsContext *context, int srcW,
1757                                         int srcH, enum AVPixelFormat srcFormat,
1758                                         int dstW, int dstH,
1759                                         enum AVPixelFormat dstFormat, int flags,
1760                                         SwsFilter *srcFilter,
1761                                         SwsFilter *dstFilter,
1762                                         const double *param)
1763 {
1764     static const double default_param[2] = { SWS_PARAM_DEFAULT,
1765                                              SWS_PARAM_DEFAULT };
1766
1767     if (!param)
1768         param = default_param;
1769
1770     if (context &&
1771         (context->srcW      != srcW      ||
1772          context->srcH      != srcH      ||
1773          context->srcFormat != srcFormat ||
1774          context->dstW      != dstW      ||
1775          context->dstH      != dstH      ||
1776          context->dstFormat != dstFormat ||
1777          context->flags     != flags     ||
1778          context->param[0]  != param[0]  ||
1779          context->param[1]  != param[1])) {
1780         sws_freeContext(context);
1781         context = NULL;
1782     }
1783
1784     if (!context) {
1785         if (!(context = sws_alloc_context()))
1786             return NULL;
1787         context->srcW      = srcW;
1788         context->srcH      = srcH;
1789         context->srcRange  = handle_jpeg(&srcFormat);
1790         context->srcFormat = srcFormat;
1791         context->dstW      = dstW;
1792         context->dstH      = dstH;
1793         context->dstRange  = handle_jpeg(&dstFormat);
1794         context->dstFormat = dstFormat;
1795         context->flags     = flags;
1796         context->param[0]  = param[0];
1797         context->param[1]  = param[1];
1798         sws_setColorspaceDetails(context, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT],
1799                                  context->srcRange,
1800                                  ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/,
1801                                  context->dstRange, 0, 1 << 16, 1 << 16);
1802         if (sws_init_context(context, srcFilter, dstFilter) < 0) {
1803             sws_freeContext(context);
1804             return NULL;
1805         }
1806     }
1807     return context;
1808 }