]> git.sesse.net Git - ffmpeg/blob - libswscale/utils.c
fate: add tests for lagarith lossless video codec.
[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_cpu.h"
49 #include "rgb2rgb.h"
50 #include "swscale.h"
51 #include "swscale_internal.h"
52
53 unsigned swscale_version(void)
54 {
55     return LIBSWSCALE_VERSION_INT;
56 }
57
58 const char *swscale_configuration(void)
59 {
60     return LIBAV_CONFIGURATION;
61 }
62
63 const char *swscale_license(void)
64 {
65 #define LICENSE_PREFIX "libswscale license: "
66     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
67 }
68
69 #define RET 0xC3 // near return opcode for x86
70
71 typedef struct FormatEntry {
72     int is_supported_in, is_supported_out;
73 } FormatEntry;
74
75 static const FormatEntry format_entries[PIX_FMT_NB] = {
76     [PIX_FMT_YUV420P]     = { 1, 1 },
77     [PIX_FMT_YUYV422]     = { 1, 1 },
78     [PIX_FMT_RGB24]       = { 1, 1 },
79     [PIX_FMT_BGR24]       = { 1, 1 },
80     [PIX_FMT_YUV422P]     = { 1, 1 },
81     [PIX_FMT_YUV444P]     = { 1, 1 },
82     [PIX_FMT_YUV410P]     = { 1, 1 },
83     [PIX_FMT_YUV411P]     = { 1, 1 },
84     [PIX_FMT_GRAY8]       = { 1, 1 },
85     [PIX_FMT_MONOWHITE]   = { 1, 1 },
86     [PIX_FMT_MONOBLACK]   = { 1, 1 },
87     [PIX_FMT_PAL8]        = { 1, 0 },
88     [PIX_FMT_YUVJ420P]    = { 1, 1 },
89     [PIX_FMT_YUVJ422P]    = { 1, 1 },
90     [PIX_FMT_YUVJ444P]    = { 1, 1 },
91     [PIX_FMT_UYVY422]     = { 1, 1 },
92     [PIX_FMT_UYYVYY411]   = { 0, 0 },
93     [PIX_FMT_BGR8]        = { 1, 1 },
94     [PIX_FMT_BGR4]        = { 0, 1 },
95     [PIX_FMT_BGR4_BYTE]   = { 1, 1 },
96     [PIX_FMT_RGB8]        = { 1, 1 },
97     [PIX_FMT_RGB4]        = { 0, 1 },
98     [PIX_FMT_RGB4_BYTE]   = { 1, 1 },
99     [PIX_FMT_NV12]        = { 1, 1 },
100     [PIX_FMT_NV21]        = { 1, 1 },
101     [PIX_FMT_ARGB]        = { 1, 1 },
102     [PIX_FMT_RGBA]        = { 1, 1 },
103     [PIX_FMT_ABGR]        = { 1, 1 },
104     [PIX_FMT_BGRA]        = { 1, 1 },
105     [PIX_FMT_GRAY16BE]    = { 1, 1 },
106     [PIX_FMT_GRAY16LE]    = { 1, 1 },
107     [PIX_FMT_YUV440P]     = { 1, 1 },
108     [PIX_FMT_YUVJ440P]    = { 1, 1 },
109     [PIX_FMT_YUVA420P]    = { 1, 1 },
110     [PIX_FMT_RGB48BE]     = { 1, 1 },
111     [PIX_FMT_RGB48LE]     = { 1, 1 },
112     [PIX_FMT_RGB565BE]    = { 1, 1 },
113     [PIX_FMT_RGB565LE]    = { 1, 1 },
114     [PIX_FMT_RGB555BE]    = { 1, 1 },
115     [PIX_FMT_RGB555LE]    = { 1, 1 },
116     [PIX_FMT_BGR565BE]    = { 1, 1 },
117     [PIX_FMT_BGR565LE]    = { 1, 1 },
118     [PIX_FMT_BGR555BE]    = { 1, 1 },
119     [PIX_FMT_BGR555LE]    = { 1, 1 },
120     [PIX_FMT_YUV420P16LE] = { 1, 1 },
121     [PIX_FMT_YUV420P16BE] = { 1, 1 },
122     [PIX_FMT_YUV422P16LE] = { 1, 1 },
123     [PIX_FMT_YUV422P16BE] = { 1, 1 },
124     [PIX_FMT_YUV444P16LE] = { 1, 1 },
125     [PIX_FMT_YUV444P16BE] = { 1, 1 },
126     [PIX_FMT_RGB444LE]    = { 1, 1 },
127     [PIX_FMT_RGB444BE]    = { 1, 1 },
128     [PIX_FMT_BGR444LE]    = { 1, 1 },
129     [PIX_FMT_BGR444BE]    = { 1, 1 },
130     [PIX_FMT_Y400A]       = { 1, 0 },
131     [PIX_FMT_BGR48BE]     = { 1, 1 },
132     [PIX_FMT_BGR48LE]     = { 1, 1 },
133     [PIX_FMT_YUV420P9BE]  = { 1, 1 },
134     [PIX_FMT_YUV420P9LE]  = { 1, 1 },
135     [PIX_FMT_YUV420P10BE] = { 1, 1 },
136     [PIX_FMT_YUV420P10LE] = { 1, 1 },
137     [PIX_FMT_YUV422P9BE]  = { 1, 1 },
138     [PIX_FMT_YUV422P9LE]  = { 1, 1 },
139     [PIX_FMT_YUV422P10BE] = { 1, 1 },
140     [PIX_FMT_YUV422P10LE] = { 1, 1 },
141     [PIX_FMT_YUV444P9BE]  = { 1, 1 },
142     [PIX_FMT_YUV444P9LE]  = { 1, 1 },
143     [PIX_FMT_YUV444P10BE] = { 1, 1 },
144     [PIX_FMT_YUV444P10LE] = { 1, 1 },
145     [PIX_FMT_GBRP]        = { 1, 0 },
146     [PIX_FMT_GBRP9LE]     = { 1, 0 },
147     [PIX_FMT_GBRP9BE]     = { 1, 0 },
148     [PIX_FMT_GBRP10LE]    = { 1, 0 },
149     [PIX_FMT_GBRP10BE]    = { 1, 0 },
150     [PIX_FMT_GBRP16LE]    = { 1, 0 },
151     [PIX_FMT_GBRP16BE]    = { 1, 0 },
152 };
153
154 int sws_isSupportedInput(enum PixelFormat pix_fmt)
155 {
156     return (unsigned)pix_fmt < PIX_FMT_NB ?
157            format_entries[pix_fmt].is_supported_in : 0;
158 }
159
160 int sws_isSupportedOutput(enum PixelFormat pix_fmt)
161 {
162     return (unsigned)pix_fmt < PIX_FMT_NB ?
163            format_entries[pix_fmt].is_supported_out : 0;
164 }
165
166 extern const int32_t ff_yuv2rgb_coeffs[8][4];
167
168 const char *sws_format_name(enum PixelFormat format)
169 {
170     if ((unsigned)format < PIX_FMT_NB && av_pix_fmt_descriptors[format].name)
171         return av_pix_fmt_descriptors[format].name;
172     else
173         return "Unknown format";
174 }
175
176 static double getSplineCoeff(double a, double b, double c, double d,
177                              double dist)
178 {
179     if (dist <= 1.0)
180         return ((d * dist + c) * dist + b) * dist + a;
181     else
182         return getSplineCoeff(0.0,
183                                b + 2.0 * c + 3.0 * d,
184                                c + 3.0 * d,
185                               -b - 3.0 * c - 6.0 * d,
186                               dist - 1.0);
187 }
188
189 static int initFilter(int16_t **outFilter, int32_t **filterPos,
190                       int *outFilterSize, int xInc, int srcW, int dstW,
191                       int filterAlign, int one, int flags, int cpu_flags,
192                       SwsVector *srcFilter, SwsVector *dstFilter,
193                       double param[2], int is_horizontal)
194 {
195     int i;
196     int filterSize;
197     int filter2Size;
198     int minFilterSize;
199     int64_t *filter    = NULL;
200     int64_t *filter2   = NULL;
201     const int64_t fone = 1LL << 54;
202     int ret            = -1;
203
204     emms_c(); // FIXME should not be required but IS (even for non-MMX versions)
205
206     // NOTE: the +3 is for the MMX(+1) / SSE(+3) scaler which reads over the end
207     FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW + 3) * sizeof(**filterPos), fail);
208
209     if (FFABS(xInc - 0x10000) < 10) { // unscaled
210         int i;
211         filterSize = 1;
212         FF_ALLOCZ_OR_GOTO(NULL, filter,
213                           dstW * sizeof(*filter) * filterSize, fail);
214
215         for (i = 0; i < dstW; i++) {
216             filter[i * filterSize] = fone;
217             (*filterPos)[i]        = i;
218         }
219     } else if (flags & SWS_POINT) { // lame looking point sampling mode
220         int i;
221         int xDstInSrc;
222         filterSize = 1;
223         FF_ALLOC_OR_GOTO(NULL, filter,
224                          dstW * sizeof(*filter) * filterSize, fail);
225
226         xDstInSrc = xInc / 2 - 0x8000;
227         for (i = 0; i < dstW; i++) {
228             int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;
229
230             (*filterPos)[i] = xx;
231             filter[i]       = fone;
232             xDstInSrc      += xInc;
233         }
234     } else if ((xInc <= (1 << 16) && (flags & SWS_AREA)) ||
235                (flags & SWS_FAST_BILINEAR)) { // bilinear upscale
236         int i;
237         int xDstInSrc;
238         filterSize = 2;
239         FF_ALLOC_OR_GOTO(NULL, filter,
240                          dstW * sizeof(*filter) * filterSize, fail);
241
242         xDstInSrc = xInc / 2 - 0x8000;
243         for (i = 0; i < dstW; i++) {
244             int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;
245             int j;
246
247             (*filterPos)[i] = xx;
248             // bilinear upscale / linear interpolate / area averaging
249             for (j = 0; j < filterSize; j++) {
250                 int64_t coeff = fone - FFABS((xx << 16) - xDstInSrc) *
251                                 (fone >> 16);
252                 if (coeff < 0)
253                     coeff = 0;
254                 filter[i * filterSize + j] = coeff;
255                 xx++;
256             }
257             xDstInSrc += xInc;
258         }
259     } else {
260         int64_t xDstInSrc;
261         int sizeFactor;
262
263         if (flags & SWS_BICUBIC)
264             sizeFactor = 4;
265         else if (flags & SWS_X)
266             sizeFactor = 8;
267         else if (flags & SWS_AREA)
268             sizeFactor = 1;     // downscale only, for upscale it is bilinear
269         else if (flags & SWS_GAUSS)
270             sizeFactor = 8;     // infinite ;)
271         else if (flags & SWS_LANCZOS)
272             sizeFactor = param[0] != SWS_PARAM_DEFAULT ? ceil(2 * param[0]) : 6;
273         else if (flags & SWS_SINC)
274             sizeFactor = 20;    // infinite ;)
275         else if (flags & SWS_SPLINE)
276             sizeFactor = 20;    // infinite ;)
277         else if (flags & SWS_BILINEAR)
278             sizeFactor = 2;
279         else {
280             sizeFactor = 0;     // GCC warning killer
281             assert(0);
282         }
283
284         if (xInc <= 1 << 16)
285             filterSize = 1 + sizeFactor;    // upscale
286         else
287             filterSize = 1 + (sizeFactor * srcW + dstW - 1) / dstW;
288
289         filterSize = FFMIN(filterSize, srcW - 2);
290         filterSize = FFMAX(filterSize, 1);
291
292         FF_ALLOC_OR_GOTO(NULL, filter,
293                          dstW * sizeof(*filter) * filterSize, fail);
294
295         xDstInSrc = xInc - 0x10000;
296         for (i = 0; i < dstW; i++) {
297             int xx = (xDstInSrc - ((filterSize - 2) << 16)) / (1 << 17);
298             int j;
299             (*filterPos)[i] = xx;
300             for (j = 0; j < filterSize; j++) {
301                 int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;
302                 double floatd;
303                 int64_t coeff;
304
305                 if (xInc > 1 << 16)
306                     d = d * dstW / srcW;
307                 floatd = d * (1.0 / (1 << 30));
308
309                 if (flags & SWS_BICUBIC) {
310                     int64_t B = (param[0] != SWS_PARAM_DEFAULT ? param[0] :   0) * (1 << 24);
311                     int64_t C = (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1 << 24);
312
313                     if (d >= 1LL << 31) {
314                         coeff = 0.0;
315                     } else {
316                         int64_t dd  = (d  * d) >> 30;
317                         int64_t ddd = (dd * d) >> 30;
318
319                         if (d < 1LL << 30)
320                             coeff =  (12 * (1 << 24) -  9 * B - 6 * C) * ddd +
321                                     (-18 * (1 << 24) + 12 * B + 6 * C) *  dd +
322                                       (6 * (1 << 24) -  2 * B)         * (1 << 30);
323                         else
324                             coeff =      (-B -  6 * C) * ddd +
325                                       (6 * B + 30 * C) * dd  +
326                                     (-12 * B - 48 * C) * d   +
327                                       (8 * B + 24 * C) * (1 << 30);
328                     }
329                     coeff *= fone >> (30 + 24);
330                 }
331 #if 0
332                 else if (flags & SWS_X) {
333                     double p  = param ? param * 0.01 : 0.3;
334                     coeff     = d ? sin(d * M_PI) / (d * M_PI) : 1.0;
335                     coeff    *= pow(2.0, -p * d * d);
336                 }
337 #endif
338                 else if (flags & SWS_X) {
339                     double A = param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;
340                     double c;
341
342                     if (floatd < 1.0)
343                         c = cos(floatd * M_PI);
344                     else
345                         c = -1.0;
346                     if (c < 0.0)
347                         c = -pow(-c, A);
348                     else
349                         c = pow(c, A);
350                     coeff = (c * 0.5 + 0.5) * fone;
351                 } else if (flags & SWS_AREA) {
352                     int64_t d2 = d - (1 << 29);
353                     if (d2 * xInc < -(1LL << (29 + 16)))
354                         coeff = 1.0 * (1LL << (30 + 16));
355                     else if (d2 * xInc < (1LL << (29 + 16)))
356                         coeff = -d2 * xInc + (1LL << (29 + 16));
357                     else
358                         coeff = 0.0;
359                     coeff *= fone >> (30 + 16);
360                 } else if (flags & SWS_GAUSS) {
361                     double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
362                     coeff = (pow(2.0, -p * floatd * floatd)) * fone;
363                 } else if (flags & SWS_SINC) {
364                     coeff = (d ? sin(floatd * M_PI) / (floatd * M_PI) : 1.0) * fone;
365                 } else if (flags & SWS_LANCZOS) {
366                     double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
367                     coeff = (d ? sin(floatd * M_PI) * sin(floatd * M_PI / p) /
368                              (floatd * floatd * M_PI * M_PI / p) : 1.0) * fone;
369                     if (floatd > p)
370                         coeff = 0;
371                 } else if (flags & SWS_BILINEAR) {
372                     coeff = (1 << 30) - d;
373                     if (coeff < 0)
374                         coeff = 0;
375                     coeff *= fone >> 30;
376                 } else if (flags & SWS_SPLINE) {
377                     double p = -2.196152422706632;
378                     coeff = getSplineCoeff(1.0, 0.0, p, -p - 1.0, floatd) * fone;
379                 } else {
380                     coeff = 0.0; // GCC warning killer
381                     assert(0);
382                 }
383
384                 filter[i * filterSize + j] = coeff;
385                 xx++;
386             }
387             xDstInSrc += 2 * xInc;
388         }
389     }
390
391     /* apply src & dst Filter to filter -> filter2
392      * av_free(filter);
393      */
394     assert(filterSize > 0);
395     filter2Size = filterSize;
396     if (srcFilter)
397         filter2Size += srcFilter->length - 1;
398     if (dstFilter)
399         filter2Size += dstFilter->length - 1;
400     assert(filter2Size > 0);
401     FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size * dstW * sizeof(*filter2), fail);
402
403     for (i = 0; i < dstW; i++) {
404         int j, k;
405
406         if (srcFilter) {
407             for (k = 0; k < srcFilter->length; k++) {
408                 for (j = 0; j < filterSize; j++)
409                     filter2[i * filter2Size + k + j] +=
410                         srcFilter->coeff[k] * filter[i * filterSize + j];
411             }
412         } else {
413             for (j = 0; j < filterSize; j++)
414                 filter2[i * filter2Size + j] = filter[i * filterSize + j];
415         }
416         // FIXME dstFilter
417
418         (*filterPos)[i] += (filterSize - 1) / 2 - (filter2Size - 1) / 2;
419     }
420     av_freep(&filter);
421
422     /* try to reduce the filter-size (step1 find size and shift left) */
423     // Assume it is near normalized (*0.5 or *2.0 is OK but * 0.001 is not).
424     minFilterSize = 0;
425     for (i = dstW - 1; i >= 0; i--) {
426         int min = filter2Size;
427         int j;
428         int64_t cutOff = 0.0;
429
430         /* get rid of near zero elements on the left by shifting left */
431         for (j = 0; j < filter2Size; j++) {
432             int k;
433             cutOff += FFABS(filter2[i * filter2Size]);
434
435             if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)
436                 break;
437
438             /* preserve monotonicity because the core can't handle the
439              * filter otherwise */
440             if (i < dstW - 1 && (*filterPos)[i] >= (*filterPos)[i + 1])
441                 break;
442
443             // move filter coefficients left
444             for (k = 1; k < filter2Size; k++)
445                 filter2[i * filter2Size + k - 1] = filter2[i * filter2Size + k];
446             filter2[i * filter2Size + k - 1] = 0;
447             (*filterPos)[i]++;
448         }
449
450         cutOff = 0;
451         /* count near zeros on the right */
452         for (j = filter2Size - 1; j > 0; j--) {
453             cutOff += FFABS(filter2[i * filter2Size + j]);
454
455             if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)
456                 break;
457             min--;
458         }
459
460         if (min > minFilterSize)
461             minFilterSize = min;
462     }
463
464     if (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) {
465         // we can handle the special case 4, so we don't want to go the full 8
466         if (minFilterSize < 5)
467             filterAlign = 4;
468
469         /* We really don't want to waste our time doing useless computation, so
470          * fall back on the scalar C code for very small filters.
471          * Vectorizing is worth it only if you have a decent-sized vector. */
472         if (minFilterSize < 3)
473             filterAlign = 1;
474     }
475
476     if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX) {
477         // special case for unscaled vertical filtering
478         if (minFilterSize == 1 && filterAlign == 2)
479             filterAlign = 1;
480     }
481
482     assert(minFilterSize > 0);
483     filterSize = (minFilterSize + (filterAlign - 1)) & (~(filterAlign - 1));
484     assert(filterSize > 0);
485     filter = av_malloc(filterSize * dstW * sizeof(*filter));
486     if (filterSize >= MAX_FILTER_SIZE * 16 /
487                       ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)
488         goto fail;
489     *outFilterSize = filterSize;
490
491     if (flags & SWS_PRINT_INFO)
492         av_log(NULL, AV_LOG_VERBOSE,
493                "SwScaler: reducing / aligning filtersize %d -> %d\n",
494                filter2Size, filterSize);
495     /* try to reduce the filter-size (step2 reduce it) */
496     for (i = 0; i < dstW; i++) {
497         int j;
498
499         for (j = 0; j < filterSize; j++) {
500             if (j >= filter2Size)
501                 filter[i * filterSize + j] = 0;
502             else
503                 filter[i * filterSize + j] = filter2[i * filter2Size + j];
504             if ((flags & SWS_BITEXACT) && j >= minFilterSize)
505                 filter[i * filterSize + j] = 0;
506         }
507     }
508
509     // FIXME try to align filterPos if possible
510
511     // fix borders
512     if (is_horizontal) {
513         for (i = 0; i < dstW; i++) {
514             int j;
515             if ((*filterPos)[i] < 0) {
516                 // move filter coefficients left to compensate for filterPos
517                 for (j = 1; j < filterSize; j++) {
518                     int left = FFMAX(j + (*filterPos)[i], 0);
519                     filter[i * filterSize + left] += filter[i * filterSize + j];
520                     filter[i * filterSize + j]     = 0;
521                 }
522                 (*filterPos)[i] = 0;
523             }
524
525             if ((*filterPos)[i] + filterSize > srcW) {
526                 int shift = (*filterPos)[i] + filterSize - srcW;
527                 // move filter coefficients right to compensate for filterPos
528                 for (j = filterSize - 2; j >= 0; j--) {
529                     int right = FFMIN(j + shift, filterSize - 1);
530                     filter[i * filterSize + right] += filter[i * filterSize + j];
531                     filter[i * filterSize + j]      = 0;
532                 }
533                 (*filterPos)[i] = srcW - filterSize;
534             }
535         }
536     }
537
538     // Note the +1 is for the MMX scaler which reads over the end
539     /* align at 16 for AltiVec (needed by hScale_altivec_real) */
540     FF_ALLOCZ_OR_GOTO(NULL, *outFilter,
541                       *outFilterSize * (dstW + 3) * sizeof(int16_t), fail);
542
543     /* normalize & store in outFilter */
544     for (i = 0; i < dstW; i++) {
545         int j;
546         int64_t error = 0;
547         int64_t sum   = 0;
548
549         for (j = 0; j < filterSize; j++) {
550             sum += filter[i * filterSize + j];
551         }
552         sum = (sum + one / 2) / one;
553         for (j = 0; j < *outFilterSize; j++) {
554             int64_t v = filter[i * filterSize + j] + error;
555             int intV  = ROUNDED_DIV(v, sum);
556             (*outFilter)[i * (*outFilterSize) + j] = intV;
557             error                                  = v - intV * sum;
558         }
559     }
560
561     (*filterPos)[dstW + 0] =
562     (*filterPos)[dstW + 1] =
563     (*filterPos)[dstW + 2] = (*filterPos)[dstW - 1]; /* the MMX/SSE scaler will
564                                                       * read over the end */
565     for (i = 0; i < *outFilterSize; i++) {
566         int k = (dstW - 1) * (*outFilterSize) + i;
567         (*outFilter)[k + 1 * (*outFilterSize)] =
568         (*outFilter)[k + 2 * (*outFilterSize)] =
569         (*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];
570     }
571
572     ret = 0;
573
574 fail:
575     av_free(filter);
576     av_free(filter2);
577     return ret;
578 }
579
580 #if HAVE_MMXEXT && HAVE_INLINE_ASM
581 static int initMMX2HScaler(int dstW, int xInc, uint8_t *filterCode,
582                            int16_t *filter, int32_t *filterPos, int numSplits)
583 {
584     uint8_t *fragmentA;
585     x86_reg imm8OfPShufW1A;
586     x86_reg imm8OfPShufW2A;
587     x86_reg fragmentLengthA;
588     uint8_t *fragmentB;
589     x86_reg imm8OfPShufW1B;
590     x86_reg imm8OfPShufW2B;
591     x86_reg fragmentLengthB;
592     int fragmentPos;
593
594     int xpos, i;
595
596     // create an optimized horizontal scaling routine
597     /* This scaler is made of runtime-generated MMX2 code using specially tuned
598      * pshufw instructions. For every four output pixels, if four input pixels
599      * are enough for the fast bilinear scaling, then a chunk of fragmentB is
600      * used. If five input pixels are needed, then a chunk of fragmentA is used.
601      */
602
603     // code fragment
604
605     __asm__ volatile (
606         "jmp                         9f                 \n\t"
607         // Begin
608         "0:                                             \n\t"
609         "movq    (%%"REG_d", %%"REG_a"), %%mm3          \n\t"
610         "movd    (%%"REG_c", %%"REG_S"), %%mm0          \n\t"
611         "movd   1(%%"REG_c", %%"REG_S"), %%mm1          \n\t"
612         "punpcklbw                %%mm7, %%mm1          \n\t"
613         "punpcklbw                %%mm7, %%mm0          \n\t"
614         "pshufw                   $0xFF, %%mm1, %%mm1   \n\t"
615         "1:                                             \n\t"
616         "pshufw                   $0xFF, %%mm0, %%mm0   \n\t"
617         "2:                                             \n\t"
618         "psubw                    %%mm1, %%mm0          \n\t"
619         "movl   8(%%"REG_b", %%"REG_a"), %%esi          \n\t"
620         "pmullw                   %%mm3, %%mm0          \n\t"
621         "psllw                       $7, %%mm1          \n\t"
622         "paddw                    %%mm1, %%mm0          \n\t"
623
624         "movq                     %%mm0, (%%"REG_D", %%"REG_a") \n\t"
625
626         "add                         $8, %%"REG_a"      \n\t"
627         // End
628         "9:                                             \n\t"
629         // "int $3                                         \n\t"
630         "lea       " LOCAL_MANGLE(0b) ", %0             \n\t"
631         "lea       " LOCAL_MANGLE(1b) ", %1             \n\t"
632         "lea       " LOCAL_MANGLE(2b) ", %2             \n\t"
633         "dec                         %1                 \n\t"
634         "dec                         %2                 \n\t"
635         "sub                         %0, %1             \n\t"
636         "sub                         %0, %2             \n\t"
637         "lea       " LOCAL_MANGLE(9b) ", %3             \n\t"
638         "sub                         %0, %3             \n\t"
639
640
641         : "=r" (fragmentA), "=r" (imm8OfPShufW1A), "=r" (imm8OfPShufW2A),
642           "=r" (fragmentLengthA)
643         );
644
645     __asm__ volatile (
646         "jmp                         9f                 \n\t"
647         // Begin
648         "0:                                             \n\t"
649         "movq    (%%"REG_d", %%"REG_a"), %%mm3          \n\t"
650         "movd    (%%"REG_c", %%"REG_S"), %%mm0          \n\t"
651         "punpcklbw                %%mm7, %%mm0          \n\t"
652         "pshufw                   $0xFF, %%mm0, %%mm1   \n\t"
653         "1:                                             \n\t"
654         "pshufw                   $0xFF, %%mm0, %%mm0   \n\t"
655         "2:                                             \n\t"
656         "psubw                    %%mm1, %%mm0          \n\t"
657         "movl   8(%%"REG_b", %%"REG_a"), %%esi          \n\t"
658         "pmullw                   %%mm3, %%mm0          \n\t"
659         "psllw                       $7, %%mm1          \n\t"
660         "paddw                    %%mm1, %%mm0          \n\t"
661
662         "movq                     %%mm0, (%%"REG_D", %%"REG_a") \n\t"
663
664         "add                         $8, %%"REG_a"      \n\t"
665         // End
666         "9:                                             \n\t"
667         // "int                       $3                   \n\t"
668         "lea       " LOCAL_MANGLE(0b) ", %0             \n\t"
669         "lea       " LOCAL_MANGLE(1b) ", %1             \n\t"
670         "lea       " LOCAL_MANGLE(2b) ", %2             \n\t"
671         "dec                         %1                 \n\t"
672         "dec                         %2                 \n\t"
673         "sub                         %0, %1             \n\t"
674         "sub                         %0, %2             \n\t"
675         "lea       " LOCAL_MANGLE(9b) ", %3             \n\t"
676         "sub                         %0, %3             \n\t"
677
678
679         : "=r" (fragmentB), "=r" (imm8OfPShufW1B), "=r" (imm8OfPShufW2B),
680           "=r" (fragmentLengthB)
681         );
682
683     xpos        = 0; // lumXInc/2 - 0x8000; // difference between pixel centers
684     fragmentPos = 0;
685
686     for (i = 0; i < dstW / numSplits; i++) {
687         int xx = xpos >> 16;
688
689         if ((i & 3) == 0) {
690             int a                  = 0;
691             int b                  = ((xpos + xInc) >> 16) - xx;
692             int c                  = ((xpos + xInc * 2) >> 16) - xx;
693             int d                  = ((xpos + xInc * 3) >> 16) - xx;
694             int inc                = (d + 1 < 4);
695             uint8_t *fragment      = (d + 1 < 4) ? fragmentB : fragmentA;
696             x86_reg imm8OfPShufW1  = (d + 1 < 4) ? imm8OfPShufW1B : imm8OfPShufW1A;
697             x86_reg imm8OfPShufW2  = (d + 1 < 4) ? imm8OfPShufW2B : imm8OfPShufW2A;
698             x86_reg fragmentLength = (d + 1 < 4) ? fragmentLengthB : fragmentLengthA;
699             int maxShift           = 3 - (d + inc);
700             int shift              = 0;
701
702             if (filterCode) {
703                 filter[i]        = ((xpos              & 0xFFFF) ^ 0xFFFF) >> 9;
704                 filter[i + 1]    = (((xpos + xInc)     & 0xFFFF) ^ 0xFFFF) >> 9;
705                 filter[i + 2]    = (((xpos + xInc * 2) & 0xFFFF) ^ 0xFFFF) >> 9;
706                 filter[i + 3]    = (((xpos + xInc * 3) & 0xFFFF) ^ 0xFFFF) >> 9;
707                 filterPos[i / 2] = xx;
708
709                 memcpy(filterCode + fragmentPos, fragment, fragmentLength);
710
711                 filterCode[fragmentPos + imm8OfPShufW1] =  (a + inc)       |
712                                                           ((b + inc) << 2) |
713                                                           ((c + inc) << 4) |
714                                                           ((d + inc) << 6);
715                 filterCode[fragmentPos + imm8OfPShufW2] =  a | (b << 2) |
716                                                                (c << 4) |
717                                                                (d << 6);
718
719                 if (i + 4 - inc >= dstW)
720                     shift = maxShift;               // avoid overread
721                 else if ((filterPos[i / 2] & 3) <= maxShift)
722                     shift = filterPos[i / 2] & 3;   // align
723
724                 if (shift && i >= shift) {
725                     filterCode[fragmentPos + imm8OfPShufW1] += 0x55 * shift;
726                     filterCode[fragmentPos + imm8OfPShufW2] += 0x55 * shift;
727                     filterPos[i / 2]                        -= shift;
728                 }
729             }
730
731             fragmentPos += fragmentLength;
732
733             if (filterCode)
734                 filterCode[fragmentPos] = RET;
735         }
736         xpos += xInc;
737     }
738     if (filterCode)
739         filterPos[((i / 2) + 1) & (~1)] = xpos >> 16;  // needed to jump to the next part
740
741     return fragmentPos + 1;
742 }
743 #endif /* HAVE_MMXEXT && HAVE_INLINE_ASM */
744
745 static void getSubSampleFactors(int *h, int *v, enum PixelFormat format)
746 {
747     *h = av_pix_fmt_descriptors[format].log2_chroma_w;
748     *v = av_pix_fmt_descriptors[format].log2_chroma_h;
749 }
750
751 int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4],
752                              int srcRange, const int table[4], int dstRange,
753                              int brightness, int contrast, int saturation)
754 {
755     memcpy(c->srcColorspaceTable, inv_table, sizeof(int) * 4);
756     memcpy(c->dstColorspaceTable, table, sizeof(int) * 4);
757
758     c->brightness = brightness;
759     c->contrast   = contrast;
760     c->saturation = saturation;
761     c->srcRange   = srcRange;
762     c->dstRange   = dstRange;
763     if (isYUV(c->dstFormat) || isGray(c->dstFormat))
764         return -1;
765
766     c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[c->dstFormat]);
767     c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[c->srcFormat]);
768
769     ff_yuv2rgb_c_init_tables(c, inv_table, srcRange, brightness,
770                              contrast, saturation);
771     // FIXME factorize
772
773     if (HAVE_ALTIVEC && av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC)
774         ff_yuv2rgb_init_tables_altivec(c, inv_table, brightness,
775                                        contrast, saturation);
776     return 0;
777 }
778
779 int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table,
780                              int *srcRange, int **table, int *dstRange,
781                              int *brightness, int *contrast, int *saturation)
782 {
783     if (isYUV(c->dstFormat) || isGray(c->dstFormat))
784         return -1;
785
786     *inv_table  = c->srcColorspaceTable;
787     *table      = c->dstColorspaceTable;
788     *srcRange   = c->srcRange;
789     *dstRange   = c->dstRange;
790     *brightness = c->brightness;
791     *contrast   = c->contrast;
792     *saturation = c->saturation;
793
794     return 0;
795 }
796
797 static int handle_jpeg(enum PixelFormat *format)
798 {
799     switch (*format) {
800     case PIX_FMT_YUVJ420P:
801         *format = PIX_FMT_YUV420P;
802         return 1;
803     case PIX_FMT_YUVJ422P:
804         *format = PIX_FMT_YUV422P;
805         return 1;
806     case PIX_FMT_YUVJ444P:
807         *format = PIX_FMT_YUV444P;
808         return 1;
809     case PIX_FMT_YUVJ440P:
810         *format = PIX_FMT_YUV440P;
811         return 1;
812     default:
813         return 0;
814     }
815 }
816
817 SwsContext *sws_alloc_context(void)
818 {
819     SwsContext *c = av_mallocz(sizeof(SwsContext));
820
821     c->av_class = &sws_context_class;
822     av_opt_set_defaults(c);
823
824     return c;
825 }
826
827 av_cold int sws_init_context(SwsContext *c, SwsFilter *srcFilter,
828                              SwsFilter *dstFilter)
829 {
830     int i;
831     int usesVFilter, usesHFilter;
832     int unscaled;
833     SwsFilter dummyFilter = { NULL, NULL, NULL, NULL };
834     int srcW              = c->srcW;
835     int srcH              = c->srcH;
836     int dstW              = c->dstW;
837     int dstH              = c->dstH;
838     int dst_stride        = FFALIGN(dstW * sizeof(int16_t) + 16, 16);
839     int dst_stride_px     = dst_stride >> 1;
840     int flags, cpu_flags;
841     enum PixelFormat srcFormat = c->srcFormat;
842     enum PixelFormat dstFormat = c->dstFormat;
843
844     cpu_flags = av_get_cpu_flags();
845     flags     = c->flags;
846     emms_c();
847     if (!rgb15to16)
848         sws_rgb2rgb_init();
849
850     unscaled = (srcW == dstW && srcH == dstH);
851
852     if (!sws_isSupportedInput(srcFormat)) {
853         av_log(c, AV_LOG_ERROR, "%s is not supported as input pixel format\n",
854                sws_format_name(srcFormat));
855         return AVERROR(EINVAL);
856     }
857     if (!sws_isSupportedOutput(dstFormat)) {
858         av_log(c, AV_LOG_ERROR, "%s is not supported as output pixel format\n",
859                sws_format_name(dstFormat));
860         return AVERROR(EINVAL);
861     }
862
863     i = flags & (SWS_POINT         |
864                  SWS_AREA          |
865                  SWS_BILINEAR      |
866                  SWS_FAST_BILINEAR |
867                  SWS_BICUBIC       |
868                  SWS_X             |
869                  SWS_GAUSS         |
870                  SWS_LANCZOS       |
871                  SWS_SINC          |
872                  SWS_SPLINE        |
873                  SWS_BICUBLIN);
874     if (!i || (i & (i - 1))) {
875         av_log(c, AV_LOG_ERROR,
876                "Exactly one scaler algorithm must be chosen\n");
877         return AVERROR(EINVAL);
878     }
879     /* sanity check */
880     if (srcW < 4 || srcH < 1 || dstW < 8 || dstH < 1) {
881         /* FIXME check if these are enough and try to lower them after
882          * fixing the relevant parts of the code */
883         av_log(c, AV_LOG_ERROR, "%dx%d -> %dx%d is invalid scaling dimension\n",
884                srcW, srcH, dstW, dstH);
885         return AVERROR(EINVAL);
886     }
887
888     if (!dstFilter)
889         dstFilter = &dummyFilter;
890     if (!srcFilter)
891         srcFilter = &dummyFilter;
892
893     c->lumXInc      = (((int64_t)srcW << 16) + (dstW >> 1)) / dstW;
894     c->lumYInc      = (((int64_t)srcH << 16) + (dstH >> 1)) / dstH;
895     c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[dstFormat]);
896     c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[srcFormat]);
897     c->vRounder     = 4 * 0x0001000100010001ULL;
898
899     usesVFilter = (srcFilter->lumV && srcFilter->lumV->length > 1) ||
900                   (srcFilter->chrV && srcFilter->chrV->length > 1) ||
901                   (dstFilter->lumV && dstFilter->lumV->length > 1) ||
902                   (dstFilter->chrV && dstFilter->chrV->length > 1);
903     usesHFilter = (srcFilter->lumH && srcFilter->lumH->length > 1) ||
904                   (srcFilter->chrH && srcFilter->chrH->length > 1) ||
905                   (dstFilter->lumH && dstFilter->lumH->length > 1) ||
906                   (dstFilter->chrH && dstFilter->chrH->length > 1);
907
908     getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat);
909     getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat);
910
911     /* reuse chroma for 2 pixels RGB/BGR unless user wants full
912      * chroma interpolation */
913     if (flags & SWS_FULL_CHR_H_INT &&
914         isAnyRGB(dstFormat)        &&
915         dstFormat != PIX_FMT_RGBA  &&
916         dstFormat != PIX_FMT_ARGB  &&
917         dstFormat != PIX_FMT_BGRA  &&
918         dstFormat != PIX_FMT_ABGR  &&
919         dstFormat != PIX_FMT_RGB24 &&
920         dstFormat != PIX_FMT_BGR24) {
921         av_log(c, AV_LOG_ERROR,
922                "full chroma interpolation for destination format '%s' not yet implemented\n",
923                sws_format_name(dstFormat));
924         flags   &= ~SWS_FULL_CHR_H_INT;
925         c->flags = flags;
926     }
927     if (isAnyRGB(dstFormat) && !(flags & SWS_FULL_CHR_H_INT))
928         c->chrDstHSubSample = 1;
929
930     // drop some chroma lines if the user wants it
931     c->vChrDrop          = (flags & SWS_SRC_V_CHR_DROP_MASK) >>
932                            SWS_SRC_V_CHR_DROP_SHIFT;
933     c->chrSrcVSubSample += c->vChrDrop;
934
935     /* drop every other pixel for chroma calculation unless user
936      * wants full chroma */
937     if (isAnyRGB(srcFormat) && !(flags & SWS_FULL_CHR_H_INP)   &&
938         srcFormat != PIX_FMT_RGB8 && srcFormat != PIX_FMT_BGR8 &&
939         srcFormat != PIX_FMT_RGB4 && srcFormat != PIX_FMT_BGR4 &&
940         srcFormat != PIX_FMT_RGB4_BYTE && srcFormat != PIX_FMT_BGR4_BYTE &&
941         ((dstW >> c->chrDstHSubSample) <= (srcW >> 1) ||
942          (flags & SWS_FAST_BILINEAR)))
943         c->chrSrcHSubSample = 1;
944
945     // Note the -((-x)>>y) is so that we always round toward +inf.
946     c->chrSrcW = -((-srcW) >> c->chrSrcHSubSample);
947     c->chrSrcH = -((-srcH) >> c->chrSrcVSubSample);
948     c->chrDstW = -((-dstW) >> c->chrDstHSubSample);
949     c->chrDstH = -((-dstH) >> c->chrDstVSubSample);
950
951     /* unscaled special cases */
952     if (unscaled && !usesHFilter && !usesVFilter &&
953         (c->srcRange == c->dstRange || isAnyRGB(dstFormat))) {
954         ff_get_unscaled_swscale(c);
955
956         if (c->swScale) {
957             if (flags & SWS_PRINT_INFO)
958                 av_log(c, AV_LOG_INFO,
959                        "using unscaled %s -> %s special converter\n",
960                        sws_format_name(srcFormat), sws_format_name(dstFormat));
961             return 0;
962         }
963     }
964
965     c->srcBpc = 1 + av_pix_fmt_descriptors[srcFormat].comp[0].depth_minus1;
966     if (c->srcBpc < 8)
967         c->srcBpc = 8;
968     c->dstBpc = 1 + av_pix_fmt_descriptors[dstFormat].comp[0].depth_minus1;
969     if (c->dstBpc < 8)
970         c->dstBpc = 8;
971     if (c->dstBpc == 16)
972         dst_stride <<= 1;
973     FF_ALLOC_OR_GOTO(c, c->formatConvBuffer,
974                      (FFALIGN(srcW, 16) * 2 * FFALIGN(c->srcBpc, 8) >> 3) + 16,
975                      fail);
976     if (HAVE_MMXEXT && HAVE_INLINE_ASM && cpu_flags & AV_CPU_FLAG_MMXEXT &&
977         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 (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX) {
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 && HAVE_INLINE_ASM
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 && HAVE_INLINE_ASM */
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 (HAVE_MMXEXT && cpu_flags & AV_CPU_FLAG_MMXEXT)
1212             av_log(c, AV_LOG_INFO, "using MMX2\n");
1213         else if (HAVE_AMD3DNOW && cpu_flags & AV_CPU_FLAG_3DNOW)
1214             av_log(c, AV_LOG_INFO, "using 3DNOW\n");
1215         else if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX)
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
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 */
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 }