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