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