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