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