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