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