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