OSDN Git Service

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