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