38284a19f563e44f6eb7a8c5520878f468c4f9e9
[ffmpeg.git] / postproc / swscale.c
1 /*
2     Copyright (C) 2001-2003 Michael Niedermayer <michaelni@gmx.at>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18
19 /*
20   supported Input formats: YV12, I420/IYUV, YUY2, UYVY, BGR32, BGR24, BGR16, BGR15, RGB32, RGB24, Y8/Y800, YVU9/IF09
21   supported output formats: YV12, I420/IYUV, YUY2, UYVY, {BGR,RGB}{1,4,8,15,16,24,32}, Y8/Y800, YVU9/IF09
22   {BGR,RGB}{1,4,8,15,16} support dithering
23   
24   unscaled special converters (YV12=I420=IYUV, Y800=Y8)
25   YV12 -> {BGR,RGB}{1,4,8,15,16,24,32}
26   x -> x
27   YUV9 -> YV12
28   YUV9/YV12 -> Y800
29   Y800 -> YUV9/YV12
30   BGR24 -> BGR32 & RGB24 -> RGB32
31   BGR32 -> BGR24 & RGB32 -> RGB24
32   BGR15 -> BGR16
33 */
34
35 /* 
36 tested special converters (most are tested actually but i didnt write it down ...)
37  YV12 -> BGR16
38  YV12 -> YV12
39  BGR15 -> BGR16
40  BGR16 -> BGR16
41  YVU9 -> YV12
42
43 untested special converters
44   YV12/I420 -> BGR15/BGR24/BGR32 (its the yuv2rgb stuff, so it should be ok)
45   YV12/I420 -> YV12/I420
46   YUY2/BGR15/BGR24/BGR32/RGB24/RGB32 -> same format
47   BGR24 -> BGR32 & RGB24 -> RGB32
48   BGR32 -> BGR24 & RGB32 -> RGB24
49   BGR24 -> YV12
50 */
51
52 #include <inttypes.h>
53 #include <string.h>
54 #include <math.h>
55 #include <stdio.h>
56 #include "../config.h"
57 #include "../mangle.h"
58 #include <assert.h>
59 #ifdef HAVE_MALLOC_H
60 #include <malloc.h>
61 #else
62 #include <stdlib.h>
63 #endif
64 #ifdef HAVE_ALTIVEC_H
65 #include <altivec.h>
66 #endif
67 #include "swscale.h"
68 #include "swscale_internal.h"
69 #include "../cpudetect.h"
70 #include "../bswap.h"
71 #include "../libvo/img_format.h"
72 #include "rgb2rgb.h"
73 #include "../libvo/fastmemcpy.h"
74
75 #undef MOVNTQ
76 #undef PAVGB
77
78 //#undef HAVE_MMX2
79 //#define HAVE_3DNOW
80 //#undef HAVE_MMX
81 //#undef ARCH_X86
82 //#define WORDS_BIGENDIAN
83 #define DITHER1XBPP
84
85 #define FAST_BGR2YV12 // use 7 bit coeffs instead of 15bit
86
87 #define RET 0xC3 //near return opcode for X86
88
89 #ifdef MP_DEBUG
90 #define ASSERT(x) assert(x);
91 #else
92 #define ASSERT(x) ;
93 #endif
94
95 #ifdef M_PI
96 #define PI M_PI
97 #else
98 #define PI 3.14159265358979323846
99 #endif
100
101 //FIXME replace this with something faster
102 #define isPlanarYUV(x) ((x)==IMGFMT_YV12 || (x)==IMGFMT_YVU9 \
103                         || (x)==IMGFMT_444P || (x)==IMGFMT_422P || (x)==IMGFMT_411P)
104 #define isYUV(x)       ((x)==IMGFMT_UYVY || (x)==IMGFMT_YUY2 || isPlanarYUV(x))
105 #define isGray(x)      ((x)==IMGFMT_Y800)
106 #define isRGB(x)       (((x)&IMGFMT_RGB_MASK)==IMGFMT_RGB)
107 #define isBGR(x)       (((x)&IMGFMT_BGR_MASK)==IMGFMT_BGR)
108 #define isSupportedIn(x)  ((x)==IMGFMT_YV12 || (x)==IMGFMT_YUY2 || (x)==IMGFMT_UYVY\
109                         || (x)==IMGFMT_BGR32|| (x)==IMGFMT_BGR24|| (x)==IMGFMT_BGR16|| (x)==IMGFMT_BGR15\
110                         || (x)==IMGFMT_RGB32|| (x)==IMGFMT_RGB24\
111                         || (x)==IMGFMT_Y800 || (x)==IMGFMT_YVU9\
112                         || (x)==IMGFMT_444P || (x)==IMGFMT_422P || (x)==IMGFMT_411P)
113 #define isSupportedOut(x) ((x)==IMGFMT_YV12 || (x)==IMGFMT_YUY2 || (x)==IMGFMT_UYVY\
114                         || (x)==IMGFMT_444P || (x)==IMGFMT_422P || (x)==IMGFMT_411P\
115                         || isRGB(x) || isBGR(x)\
116                         || (x)==IMGFMT_Y800 || (x)==IMGFMT_YVU9)
117 #define isPacked(x)    ((x)==IMGFMT_YUY2 || (x)==IMGFMT_UYVY ||isRGB(x) || isBGR(x))
118
119 #define RGB2YUV_SHIFT 16
120 #define BY ((int)( 0.098*(1<<RGB2YUV_SHIFT)+0.5))
121 #define BV ((int)(-0.071*(1<<RGB2YUV_SHIFT)+0.5))
122 #define BU ((int)( 0.439*(1<<RGB2YUV_SHIFT)+0.5))
123 #define GY ((int)( 0.504*(1<<RGB2YUV_SHIFT)+0.5))
124 #define GV ((int)(-0.368*(1<<RGB2YUV_SHIFT)+0.5))
125 #define GU ((int)(-0.291*(1<<RGB2YUV_SHIFT)+0.5))
126 #define RY ((int)( 0.257*(1<<RGB2YUV_SHIFT)+0.5))
127 #define RV ((int)( 0.439*(1<<RGB2YUV_SHIFT)+0.5))
128 #define RU ((int)(-0.148*(1<<RGB2YUV_SHIFT)+0.5))
129
130 extern const int32_t Inverse_Table_6_9[8][4];
131
132 /*
133 NOTES
134 Special versions: fast Y 1:1 scaling (no interpolation in y direction)
135
136 TODO
137 more intelligent missalignment avoidance for the horizontal scaler
138 write special vertical cubic upscale version
139 Optimize C code (yv12 / minmax)
140 add support for packed pixel yuv input & output
141 add support for Y8 output
142 optimize bgr24 & bgr32
143 add BGR4 output support
144 write special BGR->BGR scaler
145 */
146
147 #define ABS(a) ((a) > 0 ? (a) : (-(a)))
148 #define MIN(a,b) ((a) > (b) ? (b) : (a))
149 #define MAX(a,b) ((a) < (b) ? (b) : (a))
150
151 #ifdef ARCH_X86
152 static uint64_t __attribute__((aligned(8))) bF8=       0xF8F8F8F8F8F8F8F8LL;
153 static uint64_t __attribute__((aligned(8))) bFC=       0xFCFCFCFCFCFCFCFCLL;
154 static uint64_t __attribute__((aligned(8))) w10=       0x0010001000100010LL;
155 static uint64_t __attribute__((aligned(8))) w02=       0x0002000200020002LL;
156 static uint64_t __attribute__((aligned(8))) bm00001111=0x00000000FFFFFFFFLL;
157 static uint64_t __attribute__((aligned(8))) bm00000111=0x0000000000FFFFFFLL;
158 static uint64_t __attribute__((aligned(8))) bm11111000=0xFFFFFFFFFF000000LL;
159 static uint64_t __attribute__((aligned(8))) bm01010101=0x00FF00FF00FF00FFLL;
160
161 static volatile uint64_t __attribute__((aligned(8))) b5Dither;
162 static volatile uint64_t __attribute__((aligned(8))) g5Dither;
163 static volatile uint64_t __attribute__((aligned(8))) g6Dither;
164 static volatile uint64_t __attribute__((aligned(8))) r5Dither;
165
166 static uint64_t __attribute__((aligned(8))) dither4[2]={
167         0x0103010301030103LL,
168         0x0200020002000200LL,};
169
170 static uint64_t __attribute__((aligned(8))) dither8[2]={
171         0x0602060206020602LL,
172         0x0004000400040004LL,};
173
174 static uint64_t __attribute__((aligned(8))) b16Mask=   0x001F001F001F001FLL;
175 static uint64_t __attribute__((aligned(8))) g16Mask=   0x07E007E007E007E0LL;
176 static uint64_t __attribute__((aligned(8))) r16Mask=   0xF800F800F800F800LL;
177 static uint64_t __attribute__((aligned(8))) b15Mask=   0x001F001F001F001FLL;
178 static uint64_t __attribute__((aligned(8))) g15Mask=   0x03E003E003E003E0LL;
179 static uint64_t __attribute__((aligned(8))) r15Mask=   0x7C007C007C007C00LL;
180
181 static uint64_t __attribute__((aligned(8))) M24A=   0x00FF0000FF0000FFLL;
182 static uint64_t __attribute__((aligned(8))) M24B=   0xFF0000FF0000FF00LL;
183 static uint64_t __attribute__((aligned(8))) M24C=   0x0000FF0000FF0000LL;
184
185 #ifdef FAST_BGR2YV12
186 static const uint64_t bgr2YCoeff  __attribute__((aligned(8))) = 0x000000210041000DULL;
187 static const uint64_t bgr2UCoeff  __attribute__((aligned(8))) = 0x0000FFEEFFDC0038ULL;
188 static const uint64_t bgr2VCoeff  __attribute__((aligned(8))) = 0x00000038FFD2FFF8ULL;
189 #else
190 static const uint64_t bgr2YCoeff  __attribute__((aligned(8))) = 0x000020E540830C8BULL;
191 static const uint64_t bgr2UCoeff  __attribute__((aligned(8))) = 0x0000ED0FDAC23831ULL;
192 static const uint64_t bgr2VCoeff  __attribute__((aligned(8))) = 0x00003831D0E6F6EAULL;
193 #endif
194 static const uint64_t bgr2YOffset __attribute__((aligned(8))) = 0x1010101010101010ULL;
195 static const uint64_t bgr2UVOffset __attribute__((aligned(8)))= 0x8080808080808080ULL;
196 static const uint64_t w1111       __attribute__((aligned(8))) = 0x0001000100010001ULL;
197 #endif
198
199 // clipping helper table for C implementations:
200 static unsigned char clip_table[768];
201
202 static SwsVector *sws_getConvVec(SwsVector *a, SwsVector *b);
203                   
204 extern const uint8_t dither_2x2_4[2][8];
205 extern const uint8_t dither_2x2_8[2][8];
206 extern const uint8_t dither_8x8_32[8][8];
207 extern const uint8_t dither_8x8_73[8][8];
208 extern const uint8_t dither_8x8_220[8][8];
209
210 #ifdef ARCH_X86
211 void in_asm_used_var_warning_killer()
212 {
213  volatile int i= bF8+bFC+w10+
214  bm00001111+bm00000111+bm11111000+b16Mask+g16Mask+r16Mask+b15Mask+g15Mask+r15Mask+
215  M24A+M24B+M24C+w02 + b5Dither+g5Dither+r5Dither+g6Dither+dither4[0]+dither8[0]+bm01010101;
216  if(i) i=0;
217 }
218 #endif
219
220 static inline void yuv2yuvXinC(int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,
221                                     int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,
222                                     uint8_t *dest, uint8_t *uDest, uint8_t *vDest, int dstW, int chrDstW)
223 {
224         //FIXME Optimize (just quickly writen not opti..)
225         int i;
226         for(i=0; i<dstW; i++)
227         {
228                 int val=1<<18;
229                 int j;
230                 for(j=0; j<lumFilterSize; j++)
231                         val += lumSrc[j][i] * lumFilter[j];
232
233                 dest[i]= MIN(MAX(val>>19, 0), 255);
234         }
235
236         if(uDest != NULL)
237                 for(i=0; i<chrDstW; i++)
238                 {
239                         int u=1<<18;
240                         int v=1<<18;
241                         int j;
242                         for(j=0; j<chrFilterSize; j++)
243                         {
244                                 u += chrSrc[j][i] * chrFilter[j];
245                                 v += chrSrc[j][i + 2048] * chrFilter[j];
246                         }
247
248                         uDest[i]= MIN(MAX(u>>19, 0), 255);
249                         vDest[i]= MIN(MAX(v>>19, 0), 255);
250                 }
251 }
252
253
254 #define YSCALE_YUV_2_PACKEDX_C(type) \
255                 for(i=0; i<(dstW>>1); i++){\
256                         int j;\
257                         int Y1=1<<18;\
258                         int Y2=1<<18;\
259                         int U=1<<18;\
260                         int V=1<<18;\
261                         type *r, *b, *g;\
262                         const int i2= 2*i;\
263                         \
264                         for(j=0; j<lumFilterSize; j++)\
265                         {\
266                                 Y1 += lumSrc[j][i2] * lumFilter[j];\
267                                 Y2 += lumSrc[j][i2+1] * lumFilter[j];\
268                         }\
269                         for(j=0; j<chrFilterSize; j++)\
270                         {\
271                                 U += chrSrc[j][i] * chrFilter[j];\
272                                 V += chrSrc[j][i+2048] * chrFilter[j];\
273                         }\
274                         Y1>>=19;\
275                         Y2>>=19;\
276                         U >>=19;\
277                         V >>=19;\
278                         if((Y1|Y2|U|V)&256)\
279                         {\
280                                 if(Y1>255)   Y1=255;\
281                                 else if(Y1<0)Y1=0;\
282                                 if(Y2>255)   Y2=255;\
283                                 else if(Y2<0)Y2=0;\
284                                 if(U>255)    U=255;\
285                                 else if(U<0) U=0;\
286                                 if(V>255)    V=255;\
287                                 else if(V<0) V=0;\
288                         }
289                         
290 #define YSCALE_YUV_2_RGBX_C(type) \
291                         YSCALE_YUV_2_PACKEDX_C(type)\
292                         r = c->table_rV[V];\
293                         g = c->table_gU[U] + c->table_gV[V];\
294                         b = c->table_bU[U];\
295
296 #define YSCALE_YUV_2_PACKED2_C \
297                 for(i=0; i<(dstW>>1); i++){\
298                         const int i2= 2*i;\
299                         int Y1= (buf0[i2  ]*yalpha1+buf1[i2  ]*yalpha)>>19;\
300                         int Y2= (buf0[i2+1]*yalpha1+buf1[i2+1]*yalpha)>>19;\
301                         int U= (uvbuf0[i     ]*uvalpha1+uvbuf1[i     ]*uvalpha)>>19;\
302                         int V= (uvbuf0[i+2048]*uvalpha1+uvbuf1[i+2048]*uvalpha)>>19;\
303
304 #define YSCALE_YUV_2_RGB2_C(type) \
305                         YSCALE_YUV_2_PACKED2_C\
306                         type *r, *b, *g;\
307                         r = c->table_rV[V];\
308                         g = c->table_gU[U] + c->table_gV[V];\
309                         b = c->table_bU[U];\
310
311 #define YSCALE_YUV_2_PACKED1_C \
312                 for(i=0; i<(dstW>>1); i++){\
313                         const int i2= 2*i;\
314                         int Y1= buf0[i2  ]>>7;\
315                         int Y2= buf0[i2+1]>>7;\
316                         int U= (uvbuf1[i     ])>>7;\
317                         int V= (uvbuf1[i+2048])>>7;\
318
319 #define YSCALE_YUV_2_RGB1_C(type) \
320                         YSCALE_YUV_2_PACKED1_C\
321                         type *r, *b, *g;\
322                         r = c->table_rV[V];\
323                         g = c->table_gU[U] + c->table_gV[V];\
324                         b = c->table_bU[U];\
325
326 #define YSCALE_YUV_2_PACKED1B_C \
327                 for(i=0; i<(dstW>>1); i++){\
328                         const int i2= 2*i;\
329                         int Y1= buf0[i2  ]>>7;\
330                         int Y2= buf0[i2+1]>>7;\
331                         int U= (uvbuf0[i     ] + uvbuf1[i     ])>>8;\
332                         int V= (uvbuf0[i+2048] + uvbuf1[i+2048])>>8;\
333
334 #define YSCALE_YUV_2_RGB1B_C(type) \
335                         YSCALE_YUV_2_PACKED1B_C\
336                         type *r, *b, *g;\
337                         r = c->table_rV[V];\
338                         g = c->table_gU[U] + c->table_gV[V];\
339                         b = c->table_bU[U];\
340
341 #define YSCALE_YUV_2_ANYRGB_C(func, func2)\
342         switch(c->dstFormat)\
343         {\
344         case IMGFMT_BGR32:\
345         case IMGFMT_RGB32:\
346                 func(uint32_t)\
347                         ((uint32_t*)dest)[i2+0]= r[Y1] + g[Y1] + b[Y1];\
348                         ((uint32_t*)dest)[i2+1]= r[Y2] + g[Y2] + b[Y2];\
349                 }               \
350                 break;\
351         case IMGFMT_RGB24:\
352                 func(uint8_t)\
353                         ((uint8_t*)dest)[0]= r[Y1];\
354                         ((uint8_t*)dest)[1]= g[Y1];\
355                         ((uint8_t*)dest)[2]= b[Y1];\
356                         ((uint8_t*)dest)[3]= r[Y2];\
357                         ((uint8_t*)dest)[4]= g[Y2];\
358                         ((uint8_t*)dest)[5]= b[Y2];\
359                         ((uint8_t*)dest)+=6;\
360                 }\
361                 break;\
362         case IMGFMT_BGR24:\
363                 func(uint8_t)\
364                         ((uint8_t*)dest)[0]= b[Y1];\
365                         ((uint8_t*)dest)[1]= g[Y1];\
366                         ((uint8_t*)dest)[2]= r[Y1];\
367                         ((uint8_t*)dest)[3]= b[Y2];\
368                         ((uint8_t*)dest)[4]= g[Y2];\
369                         ((uint8_t*)dest)[5]= r[Y2];\
370                         ((uint8_t*)dest)+=6;\
371                 }\
372                 break;\
373         case IMGFMT_RGB16:\
374         case IMGFMT_BGR16:\
375                 {\
376                         const int dr1= dither_2x2_8[y&1    ][0];\
377                         const int dg1= dither_2x2_4[y&1    ][0];\
378                         const int db1= dither_2x2_8[(y&1)^1][0];\
379                         const int dr2= dither_2x2_8[y&1    ][1];\
380                         const int dg2= dither_2x2_4[y&1    ][1];\
381                         const int db2= dither_2x2_8[(y&1)^1][1];\
382                         func(uint16_t)\
383                                 ((uint16_t*)dest)[i2+0]= r[Y1+dr1] + g[Y1+dg1] + b[Y1+db1];\
384                                 ((uint16_t*)dest)[i2+1]= r[Y2+dr2] + g[Y2+dg2] + b[Y2+db2];\
385                         }\
386                 }\
387                 break;\
388         case IMGFMT_RGB15:\
389         case IMGFMT_BGR15:\
390                 {\
391                         const int dr1= dither_2x2_8[y&1    ][0];\
392                         const int dg1= dither_2x2_8[y&1    ][1];\
393                         const int db1= dither_2x2_8[(y&1)^1][0];\
394                         const int dr2= dither_2x2_8[y&1    ][1];\
395                         const int dg2= dither_2x2_8[y&1    ][0];\
396                         const int db2= dither_2x2_8[(y&1)^1][1];\
397                         func(uint16_t)\
398                                 ((uint16_t*)dest)[i2+0]= r[Y1+dr1] + g[Y1+dg1] + b[Y1+db1];\
399                                 ((uint16_t*)dest)[i2+1]= r[Y2+dr2] + g[Y2+dg2] + b[Y2+db2];\
400                         }\
401                 }\
402                 break;\
403         case IMGFMT_RGB8:\
404         case IMGFMT_BGR8:\
405                 {\
406                         const uint8_t * const d64= dither_8x8_73[y&7];\
407                         const uint8_t * const d32= dither_8x8_32[y&7];\
408                         func(uint8_t)\
409                                 ((uint8_t*)dest)[i2+0]= r[Y1+d32[(i2+0)&7]] + g[Y1+d32[(i2+0)&7]] + b[Y1+d64[(i2+0)&7]];\
410                                 ((uint8_t*)dest)[i2+1]= r[Y2+d32[(i2+1)&7]] + g[Y2+d32[(i2+1)&7]] + b[Y2+d64[(i2+1)&7]];\
411                         }\
412                 }\
413                 break;\
414         case IMGFMT_RGB4:\
415         case IMGFMT_BGR4:\
416                 {\
417                         const uint8_t * const d64= dither_8x8_73 [y&7];\
418                         const uint8_t * const d128=dither_8x8_220[y&7];\
419                         func(uint8_t)\
420                                 ((uint8_t*)dest)[i]= r[Y1+d128[(i2+0)&7]] + g[Y1+d64[(i2+0)&7]] + b[Y1+d128[(i2+0)&7]]\
421                                                  + ((r[Y2+d128[(i2+1)&7]] + g[Y2+d64[(i2+1)&7]] + b[Y2+d128[(i2+1)&7]])<<4);\
422                         }\
423                 }\
424                 break;\
425         case IMGFMT_RG4B:\
426         case IMGFMT_BG4B:\
427                 {\
428                         const uint8_t * const d64= dither_8x8_73 [y&7];\
429                         const uint8_t * const d128=dither_8x8_220[y&7];\
430                         func(uint8_t)\
431                                 ((uint8_t*)dest)[i2+0]= r[Y1+d128[(i2+0)&7]] + g[Y1+d64[(i2+0)&7]] + b[Y1+d128[(i2+0)&7]];\
432                                 ((uint8_t*)dest)[i2+1]= r[Y2+d128[(i2+1)&7]] + g[Y2+d64[(i2+1)&7]] + b[Y2+d128[(i2+1)&7]];\
433                         }\
434                 }\
435                 break;\
436         case IMGFMT_RGB1:\
437         case IMGFMT_BGR1:\
438                 {\
439                         const uint8_t * const d128=dither_8x8_220[y&7];\
440                         uint8_t *g= c->table_gU[128] + c->table_gV[128];\
441                         for(i=0; i<dstW-7; i+=8){\
442                                 int acc;\
443                                 acc =       g[((buf0[i  ]*yalpha1+buf1[i  ]*yalpha)>>19) + d128[0]];\
444                                 acc+= acc + g[((buf0[i+1]*yalpha1+buf1[i+1]*yalpha)>>19) + d128[1]];\
445                                 acc+= acc + g[((buf0[i+2]*yalpha1+buf1[i+2]*yalpha)>>19) + d128[2]];\
446                                 acc+= acc + g[((buf0[i+3]*yalpha1+buf1[i+3]*yalpha)>>19) + d128[3]];\
447                                 acc+= acc + g[((buf0[i+4]*yalpha1+buf1[i+4]*yalpha)>>19) + d128[4]];\
448                                 acc+= acc + g[((buf0[i+5]*yalpha1+buf1[i+5]*yalpha)>>19) + d128[5]];\
449                                 acc+= acc + g[((buf0[i+6]*yalpha1+buf1[i+6]*yalpha)>>19) + d128[6]];\
450                                 acc+= acc + g[((buf0[i+7]*yalpha1+buf1[i+7]*yalpha)>>19) + d128[7]];\
451                                 ((uint8_t*)dest)[0]= acc;\
452                                 ((uint8_t*)dest)++;\
453                         }\
454 \
455 /*\
456 ((uint8_t*)dest)-= dstW>>4;\
457 {\
458                         int acc=0;\
459                         int left=0;\
460                         static int top[1024];\
461                         static int last_new[1024][1024];\
462                         static int last_in3[1024][1024];\
463                         static int drift[1024][1024];\
464                         int topLeft=0;\
465                         int shift=0;\
466                         int count=0;\
467                         const uint8_t * const d128=dither_8x8_220[y&7];\
468                         int error_new=0;\
469                         int error_in3=0;\
470                         int f=0;\
471                         \
472                         for(i=dstW>>1; i<dstW; i++){\
473                                 int in= ((buf0[i  ]*yalpha1+buf1[i  ]*yalpha)>>19);\
474                                 int in2 = (76309 * (in - 16) + 32768) >> 16;\
475                                 int in3 = (in2 < 0) ? 0 : ((in2 > 255) ? 255 : in2);\
476                                 int old= (left*7 + topLeft + top[i]*5 + top[i+1]*3)/20 + in3\
477                                         + (last_new[y][i] - in3)*f/256;\
478                                 int new= old> 128 ? 255 : 0;\
479 \
480                                 error_new+= ABS(last_new[y][i] - new);\
481                                 error_in3+= ABS(last_in3[y][i] - in3);\
482                                 f= error_new - error_in3*4;\
483                                 if(f<0) f=0;\
484                                 if(f>256) f=256;\
485 \
486                                 topLeft= top[i];\
487                                 left= top[i]= old - new;\
488                                 last_new[y][i]= new;\
489                                 last_in3[y][i]= in3;\
490 \
491                                 acc+= acc + (new&1);\
492                                 if((i&7)==6){\
493                                         ((uint8_t*)dest)[0]= acc;\
494                                         ((uint8_t*)dest)++;\
495                                 }\
496                         }\
497 }\
498 */\
499                 }\
500                 break;\
501         case IMGFMT_YUY2:\
502                 func2\
503                         ((uint8_t*)dest)[2*i2+0]= Y1;\
504                         ((uint8_t*)dest)[2*i2+1]= U;\
505                         ((uint8_t*)dest)[2*i2+2]= Y2;\
506                         ((uint8_t*)dest)[2*i2+3]= V;\
507                 }               \
508                 break;\
509         case IMGFMT_UYVY:\
510                 func2\
511                         ((uint8_t*)dest)[2*i2+0]= U;\
512                         ((uint8_t*)dest)[2*i2+1]= Y1;\
513                         ((uint8_t*)dest)[2*i2+2]= V;\
514                         ((uint8_t*)dest)[2*i2+3]= Y2;\
515                 }               \
516                 break;\
517         }\
518
519
520 static inline void yuv2packedXinC(SwsContext *c, int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,
521                                     int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,
522                                     uint8_t *dest, int dstW, int y)
523 {
524         int i;
525         switch(c->dstFormat)
526         {
527         case IMGFMT_RGB32:
528         case IMGFMT_BGR32:
529                 YSCALE_YUV_2_RGBX_C(uint32_t)
530                         ((uint32_t*)dest)[i2+0]= r[Y1] + g[Y1] + b[Y1];
531                         ((uint32_t*)dest)[i2+1]= r[Y2] + g[Y2] + b[Y2];
532                 }
533                 break;
534         case IMGFMT_RGB24:
535                 YSCALE_YUV_2_RGBX_C(uint8_t)
536                         ((uint8_t*)dest)[0]= r[Y1];
537                         ((uint8_t*)dest)[1]= g[Y1];
538                         ((uint8_t*)dest)[2]= b[Y1];
539                         ((uint8_t*)dest)[3]= r[Y2];
540                         ((uint8_t*)dest)[4]= g[Y2];
541                         ((uint8_t*)dest)[5]= b[Y2];
542                         ((uint8_t*)dest)+=6;
543                 }
544                 break;
545         case IMGFMT_BGR24:
546                 YSCALE_YUV_2_RGBX_C(uint8_t)
547                         ((uint8_t*)dest)[0]= b[Y1];
548                         ((uint8_t*)dest)[1]= g[Y1];
549                         ((uint8_t*)dest)[2]= r[Y1];
550                         ((uint8_t*)dest)[3]= b[Y2];
551                         ((uint8_t*)dest)[4]= g[Y2];
552                         ((uint8_t*)dest)[5]= r[Y2];
553                         ((uint8_t*)dest)+=6;
554                 }
555                 break;
556         case IMGFMT_RGB16:
557         case IMGFMT_BGR16:
558                 {
559                         const int dr1= dither_2x2_8[y&1    ][0];
560                         const int dg1= dither_2x2_4[y&1    ][0];
561                         const int db1= dither_2x2_8[(y&1)^1][0];
562                         const int dr2= dither_2x2_8[y&1    ][1];
563                         const int dg2= dither_2x2_4[y&1    ][1];
564                         const int db2= dither_2x2_8[(y&1)^1][1];
565                         YSCALE_YUV_2_RGBX_C(uint16_t)
566                                 ((uint16_t*)dest)[i2+0]= r[Y1+dr1] + g[Y1+dg1] + b[Y1+db1];
567                                 ((uint16_t*)dest)[i2+1]= r[Y2+dr2] + g[Y2+dg2] + b[Y2+db2];
568                         }
569                 }
570                 break;
571         case IMGFMT_RGB15:
572         case IMGFMT_BGR15:
573                 {
574                         const int dr1= dither_2x2_8[y&1    ][0];
575                         const int dg1= dither_2x2_8[y&1    ][1];
576                         const int db1= dither_2x2_8[(y&1)^1][0];
577                         const int dr2= dither_2x2_8[y&1    ][1];
578                         const int dg2= dither_2x2_8[y&1    ][0];
579                         const int db2= dither_2x2_8[(y&1)^1][1];
580                         YSCALE_YUV_2_RGBX_C(uint16_t)
581                                 ((uint16_t*)dest)[i2+0]= r[Y1+dr1] + g[Y1+dg1] + b[Y1+db1];
582                                 ((uint16_t*)dest)[i2+1]= r[Y2+dr2] + g[Y2+dg2] + b[Y2+db2];
583                         }
584                 }
585                 break;
586         case IMGFMT_RGB8:
587         case IMGFMT_BGR8:
588                 {
589                         const uint8_t * const d64= dither_8x8_73[y&7];
590                         const uint8_t * const d32= dither_8x8_32[y&7];
591                         YSCALE_YUV_2_RGBX_C(uint8_t)
592                                 ((uint8_t*)dest)[i2+0]= r[Y1+d32[(i2+0)&7]] + g[Y1+d32[(i2+0)&7]] + b[Y1+d64[(i2+0)&7]];
593                                 ((uint8_t*)dest)[i2+1]= r[Y2+d32[(i2+1)&7]] + g[Y2+d32[(i2+1)&7]] + b[Y2+d64[(i2+1)&7]];
594                         }
595                 }
596                 break;
597         case IMGFMT_RGB4:
598         case IMGFMT_BGR4:
599                 {
600                         const uint8_t * const d64= dither_8x8_73 [y&7];
601                         const uint8_t * const d128=dither_8x8_220[y&7];
602                         YSCALE_YUV_2_RGBX_C(uint8_t)
603                                 ((uint8_t*)dest)[i]= r[Y1+d128[(i2+0)&7]] + g[Y1+d64[(i2+0)&7]] + b[Y1+d128[(i2+0)&7]]
604                                                   +((r[Y2+d128[(i2+1)&7]] + g[Y2+d64[(i2+1)&7]] + b[Y2+d128[(i2+1)&7]])<<4);
605                         }
606                 }
607                 break;
608         case IMGFMT_RG4B:
609         case IMGFMT_BG4B:
610                 {
611                         const uint8_t * const d64= dither_8x8_73 [y&7];
612                         const uint8_t * const d128=dither_8x8_220[y&7];
613                         YSCALE_YUV_2_RGBX_C(uint8_t)
614                                 ((uint8_t*)dest)[i2+0]= r[Y1+d128[(i2+0)&7]] + g[Y1+d64[(i2+0)&7]] + b[Y1+d128[(i2+0)&7]];
615                                 ((uint8_t*)dest)[i2+1]= r[Y2+d128[(i2+1)&7]] + g[Y2+d64[(i2+1)&7]] + b[Y2+d128[(i2+1)&7]];
616                         }
617                 }
618                 break;
619         case IMGFMT_RGB1:
620         case IMGFMT_BGR1:
621                 {
622                         const uint8_t * const d128=dither_8x8_220[y&7];
623                         uint8_t *g= c->table_gU[128] + c->table_gV[128];
624                         int acc=0;
625                         for(i=0; i<dstW-1; i+=2){
626                                 int j;
627                                 int Y1=1<<18;
628                                 int Y2=1<<18;
629
630                                 for(j=0; j<lumFilterSize; j++)
631                                 {
632                                         Y1 += lumSrc[j][i] * lumFilter[j];
633                                         Y2 += lumSrc[j][i+1] * lumFilter[j];
634                                 }
635                                 Y1>>=19;
636                                 Y2>>=19;
637                                 if((Y1|Y2)&256)
638                                 {
639                                         if(Y1>255)   Y1=255;
640                                         else if(Y1<0)Y1=0;
641                                         if(Y2>255)   Y2=255;
642                                         else if(Y2<0)Y2=0;
643                                 }
644                                 acc+= acc + g[Y1+d128[(i+0)&7]];
645                                 acc+= acc + g[Y2+d128[(i+1)&7]];
646                                 if((i&7)==6){
647                                         ((uint8_t*)dest)[0]= acc;
648                                         ((uint8_t*)dest)++;
649                                 }
650                         }
651                 }
652                 break;
653         case IMGFMT_YUY2:
654                 YSCALE_YUV_2_PACKEDX_C(void)
655                         ((uint8_t*)dest)[2*i2+0]= Y1;
656                         ((uint8_t*)dest)[2*i2+1]= U;
657                         ((uint8_t*)dest)[2*i2+2]= Y2;
658                         ((uint8_t*)dest)[2*i2+3]= V;
659                 }
660                 break;
661         case IMGFMT_UYVY:
662                 YSCALE_YUV_2_PACKEDX_C(void)
663                         ((uint8_t*)dest)[2*i2+0]= U;
664                         ((uint8_t*)dest)[2*i2+1]= Y1;
665                         ((uint8_t*)dest)[2*i2+2]= V;
666                         ((uint8_t*)dest)[2*i2+3]= Y2;
667                 }
668                 break;
669         }
670 }
671
672
673 //Note: we have C, X86, MMX, MMX2, 3DNOW version therse no 3DNOW+MMX2 one
674 //Plain C versions
675 #if !defined (HAVE_MMX) || defined (RUNTIME_CPUDETECT)
676 #define COMPILE_C
677 #endif
678
679 #ifdef ARCH_POWERPC
680 #ifdef HAVE_ALTIVEC
681 #define COMPILE_ALTIVEC
682 #endif //HAVE_ALTIVEC
683 #endif //ARCH_POWERPC
684
685 #ifdef ARCH_X86
686
687 #if (defined (HAVE_MMX) && !defined (HAVE_3DNOW) && !defined (HAVE_MMX2)) || defined (RUNTIME_CPUDETECT)
688 #define COMPILE_MMX
689 #endif
690
691 #if defined (HAVE_MMX2) || defined (RUNTIME_CPUDETECT)
692 #define COMPILE_MMX2
693 #endif
694
695 #if (defined (HAVE_3DNOW) && !defined (HAVE_MMX2)) || defined (RUNTIME_CPUDETECT)
696 #define COMPILE_3DNOW
697 #endif
698 #endif //ARCH_X86
699
700 #undef HAVE_MMX
701 #undef HAVE_MMX2
702 #undef HAVE_3DNOW
703
704 #ifdef COMPILE_C
705 #undef HAVE_MMX
706 #undef HAVE_MMX2
707 #undef HAVE_3DNOW
708 #undef HAVE_ALTIVEC
709 #define RENAME(a) a ## _C
710 #include "swscale_template.c"
711 #endif
712
713 #ifdef ARCH_POWERPC
714 #ifdef COMPILE_ALTIVEC
715 #undef RENAME
716 #define HAVE_ALTIVEC
717 #define RENAME(a) a ## _altivec
718 #include "swscale_template.c"
719 #endif
720 #endif //ARCH_POWERPC
721
722 #ifdef ARCH_X86
723
724 //X86 versions
725 /*
726 #undef RENAME
727 #undef HAVE_MMX
728 #undef HAVE_MMX2
729 #undef HAVE_3DNOW
730 #define ARCH_X86
731 #define RENAME(a) a ## _X86
732 #include "swscale_template.c"
733 */
734 //MMX versions
735 #ifdef COMPILE_MMX
736 #undef RENAME
737 #define HAVE_MMX
738 #undef HAVE_MMX2
739 #undef HAVE_3DNOW
740 #define RENAME(a) a ## _MMX
741 #include "swscale_template.c"
742 #endif
743
744 //MMX2 versions
745 #ifdef COMPILE_MMX2
746 #undef RENAME
747 #define HAVE_MMX
748 #define HAVE_MMX2
749 #undef HAVE_3DNOW
750 #define RENAME(a) a ## _MMX2
751 #include "swscale_template.c"
752 #endif
753
754 //3DNOW versions
755 #ifdef COMPILE_3DNOW
756 #undef RENAME
757 #define HAVE_MMX
758 #undef HAVE_MMX2
759 #define HAVE_3DNOW
760 #define RENAME(a) a ## _3DNow
761 #include "swscale_template.c"
762 #endif
763
764 #endif //ARCH_X86
765
766 // minor note: the HAVE_xyz is messed up after that line so don't use it
767
768 static double getSplineCoeff(double a, double b, double c, double d, double dist)
769 {
770 //      printf("%f %f %f %f %f\n", a,b,c,d,dist);
771         if(dist<=1.0)   return ((d*dist + c)*dist + b)*dist +a;
772         else            return getSplineCoeff(  0.0, 
773                                                  b+ 2.0*c + 3.0*d,
774                                                         c + 3.0*d,
775                                                 -b- 3.0*c - 6.0*d,
776                                                 dist-1.0);
777 }
778
779 static inline void initFilter(int16_t **outFilter, int16_t **filterPos, int *outFilterSize, int xInc,
780                               int srcW, int dstW, int filterAlign, int one, int flags,
781                               SwsVector *srcFilter, SwsVector *dstFilter)
782 {
783         int i;
784         int filterSize;
785         int filter2Size;
786         int minFilterSize;
787         double *filter=NULL;
788         double *filter2=NULL;
789 #ifdef ARCH_X86
790         if(flags & SWS_CPU_CAPS_MMX)
791                 asm volatile("emms\n\t"::: "memory"); //FIXME this shouldnt be required but it IS (even for non mmx versions)
792 #endif
793
794         // Note the +1 is for the MMXscaler which reads over the end
795         *filterPos = (int16_t*)memalign(8, (dstW+1)*sizeof(int16_t));
796
797         if(ABS(xInc - 0x10000) <10) // unscaled
798         {
799                 int i;
800                 filterSize= 1;
801                 filter= (double*)memalign(8, dstW*sizeof(double)*filterSize);
802                 for(i=0; i<dstW*filterSize; i++) filter[i]=0;
803
804                 for(i=0; i<dstW; i++)
805                 {
806                         filter[i*filterSize]=1;
807                         (*filterPos)[i]=i;
808                 }
809
810         }
811         else if(flags&SWS_POINT) // lame looking point sampling mode
812         {
813                 int i;
814                 int xDstInSrc;
815                 filterSize= 1;
816                 filter= (double*)memalign(8, dstW*sizeof(double)*filterSize);
817                 
818                 xDstInSrc= xInc/2 - 0x8000;
819                 for(i=0; i<dstW; i++)
820                 {
821                         int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
822
823                         (*filterPos)[i]= xx;
824                         filter[i]= 1.0;
825                         xDstInSrc+= xInc;
826                 }
827         }
828         else if((xInc <= (1<<16) && (flags&SWS_AREA)) || (flags&SWS_FAST_BILINEAR)) // bilinear upscale
829         {
830                 int i;
831                 int xDstInSrc;
832                 if     (flags&SWS_BICUBIC) filterSize= 4;
833                 else if(flags&SWS_X      ) filterSize= 4;
834                 else                       filterSize= 2; // SWS_BILINEAR / SWS_AREA 
835                 filter= (double*)memalign(8, dstW*sizeof(double)*filterSize);
836
837                 xDstInSrc= xInc/2 - 0x8000;
838                 for(i=0; i<dstW; i++)
839                 {
840                         int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
841                         int j;
842
843                         (*filterPos)[i]= xx;
844                                 //Bilinear upscale / linear interpolate / Area averaging
845                                 for(j=0; j<filterSize; j++)
846                                 {
847                                         double d= ABS((xx<<16) - xDstInSrc)/(double)(1<<16);
848                                         double coeff= 1.0 - d;
849                                         if(coeff<0) coeff=0;
850                                         filter[i*filterSize + j]= coeff;
851                                         xx++;
852                                 }
853                         xDstInSrc+= xInc;
854                 }
855         }
856         else
857         {
858                 double xDstInSrc;
859                 double sizeFactor, filterSizeInSrc;
860                 const double xInc1= (double)xInc / (double)(1<<16);
861                 int param= (flags&SWS_PARAM_MASK)>>SWS_PARAM_SHIFT;
862
863                 if     (flags&SWS_BICUBIC)      sizeFactor= 4.0;
864                 else if(flags&SWS_X)            sizeFactor= 8.0;
865                 else if(flags&SWS_AREA)         sizeFactor= 1.0; //downscale only, for upscale it is bilinear
866                 else if(flags&SWS_GAUSS)        sizeFactor= 8.0;   // infinite ;)
867                 else if(flags&SWS_LANCZOS)      sizeFactor= param ? 2.0*param : 6.0;
868                 else if(flags&SWS_SINC)         sizeFactor= 20.0; // infinite ;)
869                 else if(flags&SWS_SPLINE)       sizeFactor= 20.0;  // infinite ;)
870                 else if(flags&SWS_BILINEAR)     sizeFactor= 2.0;
871                 else {
872                         sizeFactor= 0.0; //GCC warning killer
873                         ASSERT(0)
874                 }
875                 
876                 if(xInc1 <= 1.0)        filterSizeInSrc= sizeFactor; // upscale
877                 else                    filterSizeInSrc= sizeFactor*srcW / (double)dstW;
878
879                 filterSize= (int)ceil(1 + filterSizeInSrc); // will be reduced later if possible
880                 if(filterSize > srcW-2) filterSize=srcW-2;
881
882                 filter= (double*)memalign(16, dstW*sizeof(double)*filterSize);
883
884                 xDstInSrc= xInc1 / 2.0 - 0.5;
885                 for(i=0; i<dstW; i++)
886                 {
887                         int xx= (int)(xDstInSrc - (filterSize-1)*0.5 + 0.5);
888                         int j;
889                         (*filterPos)[i]= xx;
890                         for(j=0; j<filterSize; j++)
891                         {
892                                 double d= ABS(xx - xDstInSrc)/filterSizeInSrc*sizeFactor;
893                                 double coeff;
894                                 if(flags & SWS_BICUBIC)
895                                 {
896                                         double A= param ? -param*0.01 : -0.60;
897                                         
898                                         // Equation is from VirtualDub
899                                         if(d<1.0)
900                                                 coeff = (1.0 - (A+3.0)*d*d + (A+2.0)*d*d*d);
901                                         else if(d<2.0)
902                                                 coeff = (-4.0*A + 8.0*A*d - 5.0*A*d*d + A*d*d*d);
903                                         else
904                                                 coeff=0.0;
905                                 }
906 /*                              else if(flags & SWS_X)
907                                 {
908                                         double p= param ? param*0.01 : 0.3;
909                                         coeff = d ? sin(d*PI)/(d*PI) : 1.0;
910                                         coeff*= pow(2.0, - p*d*d);
911                                 }*/
912                                 else if(flags & SWS_X)
913                                 {
914                                         double A= param ? param*0.1 : 1.0;
915                                         
916                                         if(d<1.0)
917                                                 coeff = cos(d*PI);
918                                         else
919                                                 coeff=-1.0;
920                                         if(coeff<0.0)   coeff= -pow(-coeff, A);
921                                         else            coeff=  pow( coeff, A);
922                                         coeff= coeff*0.5 + 0.5;
923                                 }
924                                 else if(flags & SWS_AREA)
925                                 {
926                                         double srcPixelSize= 1.0/xInc1;
927                                         if(d + srcPixelSize/2 < 0.5) coeff= 1.0;
928                                         else if(d - srcPixelSize/2 < 0.5) coeff= (0.5-d)/srcPixelSize + 0.5;
929                                         else coeff=0.0;
930                                 }
931                                 else if(flags & SWS_GAUSS)
932                                 {
933                                         double p= param ? param*0.1 : 3.0;
934                                         coeff = pow(2.0, - p*d*d);
935                                 }
936                                 else if(flags & SWS_SINC)
937                                 {
938                                         coeff = d ? sin(d*PI)/(d*PI) : 1.0;
939                                 }
940                                 else if(flags & SWS_LANCZOS)
941                                 {
942                                         double p= param ? param : 3.0; 
943                                         coeff = d ? sin(d*PI)*sin(d*PI/p)/(d*d*PI*PI/p) : 1.0;
944                                         if(d>p) coeff=0;
945                                 }
946                                 else if(flags & SWS_BILINEAR)
947                                 {
948                                         coeff= 1.0 - d;
949                                         if(coeff<0) coeff=0;
950                                 }
951                                 else if(flags & SWS_SPLINE)
952                                 {
953                                         double p=-2.196152422706632;
954                                         coeff = getSplineCoeff(1.0, 0.0, p, -p-1.0, d);
955                                 }
956                                 else {
957                                         coeff= 0.0; //GCC warning killer
958                                         ASSERT(0)
959                                 }
960
961                                 filter[i*filterSize + j]= coeff;
962                                 xx++;
963                         }
964                         xDstInSrc+= xInc1;
965                 }
966         }
967
968         /* apply src & dst Filter to filter -> filter2
969            free(filter);
970         */
971         ASSERT(filterSize>0)
972         filter2Size= filterSize;
973         if(srcFilter) filter2Size+= srcFilter->length - 1;
974         if(dstFilter) filter2Size+= dstFilter->length - 1;
975         ASSERT(filter2Size>0)
976         filter2= (double*)memalign(8, filter2Size*dstW*sizeof(double));
977
978         for(i=0; i<dstW; i++)
979         {
980                 int j;
981                 SwsVector scaleFilter;
982                 SwsVector *outVec;
983
984                 scaleFilter.coeff= filter + i*filterSize;
985                 scaleFilter.length= filterSize;
986
987                 if(srcFilter) outVec= sws_getConvVec(srcFilter, &scaleFilter);
988                 else          outVec= &scaleFilter;
989
990                 ASSERT(outVec->length == filter2Size)
991                 //FIXME dstFilter
992
993                 for(j=0; j<outVec->length; j++)
994                 {
995                         filter2[i*filter2Size + j]= outVec->coeff[j];
996                 }
997
998                 (*filterPos)[i]+= (filterSize-1)/2 - (filter2Size-1)/2;
999
1000                 if(outVec != &scaleFilter) sws_freeVec(outVec);
1001         }
1002         free(filter); filter=NULL;
1003
1004         /* try to reduce the filter-size (step1 find size and shift left) */
1005         // Assume its near normalized (*0.5 or *2.0 is ok but * 0.001 is not)
1006         minFilterSize= 0;
1007         for(i=dstW-1; i>=0; i--)
1008         {
1009                 int min= filter2Size;
1010                 int j;
1011                 double cutOff=0.0;
1012
1013                 /* get rid off near zero elements on the left by shifting left */
1014                 for(j=0; j<filter2Size; j++)
1015                 {
1016                         int k;
1017                         cutOff += ABS(filter2[i*filter2Size]);
1018
1019                         if(cutOff > SWS_MAX_REDUCE_CUTOFF) break;
1020
1021                         /* preserve Monotonicity because the core can't handle the filter otherwise */
1022                         if(i<dstW-1 && (*filterPos)[i] >= (*filterPos)[i+1]) break;
1023
1024                         // Move filter coeffs left
1025                         for(k=1; k<filter2Size; k++)
1026                                 filter2[i*filter2Size + k - 1]= filter2[i*filter2Size + k];
1027                         filter2[i*filter2Size + k - 1]= 0.0;
1028                         (*filterPos)[i]++;
1029                 }
1030
1031                 cutOff=0.0;
1032                 /* count near zeros on the right */
1033                 for(j=filter2Size-1; j>0; j--)
1034                 {
1035                         cutOff += ABS(filter2[i*filter2Size + j]);
1036
1037                         if(cutOff > SWS_MAX_REDUCE_CUTOFF) break;
1038                         min--;
1039                 }
1040
1041                 if(min>minFilterSize) minFilterSize= min;
1042         }
1043
1044         ASSERT(minFilterSize > 0)
1045         filterSize= (minFilterSize +(filterAlign-1)) & (~(filterAlign-1));
1046         ASSERT(filterSize > 0)
1047         filter= (double*)memalign(8, filterSize*dstW*sizeof(double));
1048         *outFilterSize= filterSize;
1049
1050         if(flags&SWS_PRINT_INFO)
1051                 MSG_INFO("SwScaler: reducing / aligning filtersize %d -> %d\n", filter2Size, filterSize);
1052         /* try to reduce the filter-size (step2 reduce it) */
1053         for(i=0; i<dstW; i++)
1054         {
1055                 int j;
1056
1057                 for(j=0; j<filterSize; j++)
1058                 {
1059                         if(j>=filter2Size) filter[i*filterSize + j]= 0.0;
1060                         else               filter[i*filterSize + j]= filter2[i*filter2Size + j];
1061                 }
1062         }
1063         free(filter2); filter2=NULL;
1064         
1065
1066         //FIXME try to align filterpos if possible
1067
1068         //fix borders
1069         for(i=0; i<dstW; i++)
1070         {
1071                 int j;
1072                 if((*filterPos)[i] < 0)
1073                 {
1074                         // Move filter coeffs left to compensate for filterPos
1075                         for(j=1; j<filterSize; j++)
1076                         {
1077                                 int left= MAX(j + (*filterPos)[i], 0);
1078                                 filter[i*filterSize + left] += filter[i*filterSize + j];
1079                                 filter[i*filterSize + j]=0;
1080                         }
1081                         (*filterPos)[i]= 0;
1082                 }
1083
1084                 if((*filterPos)[i] + filterSize > srcW)
1085                 {
1086                         int shift= (*filterPos)[i] + filterSize - srcW;
1087                         // Move filter coeffs right to compensate for filterPos
1088                         for(j=filterSize-2; j>=0; j--)
1089                         {
1090                                 int right= MIN(j + shift, filterSize-1);
1091                                 filter[i*filterSize +right] += filter[i*filterSize +j];
1092                                 filter[i*filterSize +j]=0;
1093                         }
1094                         (*filterPos)[i]= srcW - filterSize;
1095                 }
1096         }
1097
1098         // Note the +1 is for the MMXscaler which reads over the end
1099         *outFilter= (int16_t*)memalign(8, *outFilterSize*(dstW+1)*sizeof(int16_t));
1100         memset(*outFilter, 0, *outFilterSize*(dstW+1)*sizeof(int16_t));
1101
1102         /* Normalize & Store in outFilter */
1103         for(i=0; i<dstW; i++)
1104         {
1105                 int j;
1106                 double error=0;
1107                 double sum=0;
1108                 double scale= one;
1109
1110                 for(j=0; j<filterSize; j++)
1111                 {
1112                         sum+= filter[i*filterSize + j];
1113                 }
1114                 scale/= sum;
1115                 for(j=0; j<*outFilterSize; j++)
1116                 {
1117                         double v= filter[i*filterSize + j]*scale + error;
1118                         int intV= floor(v + 0.5);
1119                         (*outFilter)[i*(*outFilterSize) + j]= intV;
1120                         error = v - intV;
1121                 }
1122         }
1123         
1124         (*filterPos)[dstW]= (*filterPos)[dstW-1]; // the MMX scaler will read over the end
1125         for(i=0; i<*outFilterSize; i++)
1126         {
1127                 int j= dstW*(*outFilterSize);
1128                 (*outFilter)[j + i]= (*outFilter)[j + i - (*outFilterSize)];
1129         }
1130
1131         free(filter);
1132 }
1133
1134 #ifdef ARCH_X86
1135 static void initMMX2HScaler(int dstW, int xInc, uint8_t *funnyCode, int16_t *filter, int32_t *filterPos, int numSplits)
1136 {
1137         uint8_t *fragmentA;
1138         int imm8OfPShufW1A;
1139         int imm8OfPShufW2A;
1140         int fragmentLengthA;
1141         uint8_t *fragmentB;
1142         int imm8OfPShufW1B;
1143         int imm8OfPShufW2B;
1144         int fragmentLengthB;
1145         int fragmentPos;
1146
1147         int xpos, i;
1148
1149         // create an optimized horizontal scaling routine
1150
1151         //code fragment
1152
1153         asm volatile(
1154                 "jmp 9f                         \n\t"
1155         // Begin
1156                 "0:                             \n\t"
1157                 "movq (%%edx, %%eax), %%mm3     \n\t" 
1158                 "movd (%%ecx, %%esi), %%mm0     \n\t" 
1159                 "movd 1(%%ecx, %%esi), %%mm1    \n\t"
1160                 "punpcklbw %%mm7, %%mm1         \n\t"
1161                 "punpcklbw %%mm7, %%mm0         \n\t"
1162                 "pshufw $0xFF, %%mm1, %%mm1     \n\t"
1163                 "1:                             \n\t"
1164                 "pshufw $0xFF, %%mm0, %%mm0     \n\t"
1165                 "2:                             \n\t"
1166                 "psubw %%mm1, %%mm0             \n\t"
1167                 "movl 8(%%ebx, %%eax), %%esi    \n\t"
1168                 "pmullw %%mm3, %%mm0            \n\t"
1169                 "psllw $7, %%mm1                \n\t"
1170                 "paddw %%mm1, %%mm0             \n\t"
1171
1172                 "movq %%mm0, (%%edi, %%eax)     \n\t"
1173
1174                 "addl $8, %%eax                 \n\t"
1175         // End
1176                 "9:                             \n\t"
1177 //              "int $3\n\t"
1178                 "leal 0b, %0                    \n\t"
1179                 "leal 1b, %1                    \n\t"
1180                 "leal 2b, %2                    \n\t"
1181                 "decl %1                        \n\t"
1182                 "decl %2                        \n\t"
1183                 "subl %0, %1                    \n\t"
1184                 "subl %0, %2                    \n\t"
1185                 "leal 9b, %3                    \n\t"
1186                 "subl %0, %3                    \n\t"
1187
1188
1189                 :"=r" (fragmentA), "=r" (imm8OfPShufW1A), "=r" (imm8OfPShufW2A),
1190                 "=r" (fragmentLengthA)
1191         );
1192
1193         asm volatile(
1194                 "jmp 9f                         \n\t"
1195         // Begin
1196                 "0:                             \n\t"
1197                 "movq (%%edx, %%eax), %%mm3     \n\t" 
1198                 "movd (%%ecx, %%esi), %%mm0     \n\t" 
1199                 "punpcklbw %%mm7, %%mm0         \n\t"
1200                 "pshufw $0xFF, %%mm0, %%mm1     \n\t"
1201                 "1:                             \n\t"
1202                 "pshufw $0xFF, %%mm0, %%mm0     \n\t"
1203                 "2:                             \n\t"
1204                 "psubw %%mm1, %%mm0             \n\t"
1205                 "movl 8(%%ebx, %%eax), %%esi    \n\t"
1206                 "pmullw %%mm3, %%mm0            \n\t"
1207                 "psllw $7, %%mm1                \n\t"
1208                 "paddw %%mm1, %%mm0             \n\t"
1209
1210                 "movq %%mm0, (%%edi, %%eax)     \n\t"
1211
1212                 "addl $8, %%eax                 \n\t"
1213         // End
1214                 "9:                             \n\t"
1215 //              "int $3\n\t"
1216                 "leal 0b, %0                    \n\t"
1217                 "leal 1b, %1                    \n\t"
1218                 "leal 2b, %2                    \n\t"
1219                 "decl %1                        \n\t"
1220                 "decl %2                        \n\t"
1221                 "subl %0, %1                    \n\t"
1222                 "subl %0, %2                    \n\t"
1223                 "leal 9b, %3                    \n\t"
1224                 "subl %0, %3                    \n\t"
1225
1226
1227                 :"=r" (fragmentB), "=r" (imm8OfPShufW1B), "=r" (imm8OfPShufW2B),
1228                 "=r" (fragmentLengthB)
1229         );
1230
1231         xpos= 0; //lumXInc/2 - 0x8000; // difference between pixel centers
1232         fragmentPos=0;
1233         
1234         for(i=0; i<dstW/numSplits; i++)
1235         {
1236                 int xx=xpos>>16;
1237
1238                 if((i&3) == 0)
1239                 {
1240                         int a=0;
1241                         int b=((xpos+xInc)>>16) - xx;
1242                         int c=((xpos+xInc*2)>>16) - xx;
1243                         int d=((xpos+xInc*3)>>16) - xx;
1244
1245                         filter[i  ] = (( xpos         & 0xFFFF) ^ 0xFFFF)>>9;
1246                         filter[i+1] = (((xpos+xInc  ) & 0xFFFF) ^ 0xFFFF)>>9;
1247                         filter[i+2] = (((xpos+xInc*2) & 0xFFFF) ^ 0xFFFF)>>9;
1248                         filter[i+3] = (((xpos+xInc*3) & 0xFFFF) ^ 0xFFFF)>>9;
1249                         filterPos[i/2]= xx;
1250
1251                         if(d+1<4)
1252                         {
1253                                 int maxShift= 3-(d+1);
1254                                 int shift=0;
1255
1256                                 memcpy(funnyCode + fragmentPos, fragmentB, fragmentLengthB);
1257
1258                                 funnyCode[fragmentPos + imm8OfPShufW1B]=
1259                                         (a+1) | ((b+1)<<2) | ((c+1)<<4) | ((d+1)<<6);
1260                                 funnyCode[fragmentPos + imm8OfPShufW2B]=
1261                                         a | (b<<2) | (c<<4) | (d<<6);
1262
1263                                 if(i+3>=dstW) shift=maxShift; //avoid overread
1264                                 else if((filterPos[i/2]&3) <= maxShift) shift=filterPos[i/2]&3; //Align
1265
1266                                 if(shift && i>=shift)
1267                                 {
1268                                         funnyCode[fragmentPos + imm8OfPShufW1B]+= 0x55*shift;
1269                                         funnyCode[fragmentPos + imm8OfPShufW2B]+= 0x55*shift;
1270                                         filterPos[i/2]-=shift;
1271                                 }
1272
1273                                 fragmentPos+= fragmentLengthB;
1274                         }
1275                         else
1276                         {
1277                                 int maxShift= 3-d;
1278                                 int shift=0;
1279
1280                                 memcpy(funnyCode + fragmentPos, fragmentA, fragmentLengthA);
1281
1282                                 funnyCode[fragmentPos + imm8OfPShufW1A]=
1283                                 funnyCode[fragmentPos + imm8OfPShufW2A]=
1284                                         a | (b<<2) | (c<<4) | (d<<6);
1285
1286                                 if(i+4>=dstW) shift=maxShift; //avoid overread
1287                                 else if((filterPos[i/2]&3) <= maxShift) shift=filterPos[i/2]&3; //partial align
1288
1289                                 if(shift && i>=shift)
1290                                 {
1291                                         funnyCode[fragmentPos + imm8OfPShufW1A]+= 0x55*shift;
1292                                         funnyCode[fragmentPos + imm8OfPShufW2A]+= 0x55*shift;
1293                                         filterPos[i/2]-=shift;
1294                                 }
1295
1296                                 fragmentPos+= fragmentLengthA;
1297                         }
1298
1299                         funnyCode[fragmentPos]= RET;
1300                 }
1301                 xpos+=xInc;
1302         }
1303         filterPos[i/2]= xpos>>16; // needed to jump to the next part
1304 }
1305 #endif // ARCH_X86
1306
1307 static void globalInit(){
1308     // generating tables:
1309     int i;
1310     for(i=0; i<768; i++){
1311         int c= MIN(MAX(i-256, 0), 255);
1312         clip_table[i]=c;
1313     }
1314 }
1315
1316 static SwsFunc getSwsFunc(int flags){
1317     
1318 #ifdef RUNTIME_CPUDETECT
1319 #ifdef ARCH_X86
1320         // ordered per speed fasterst first
1321         if(flags & SWS_CPU_CAPS_MMX2)
1322                 return swScale_MMX2;
1323         else if(flags & SWS_CPU_CAPS_3DNOW)
1324                 return swScale_3DNow;
1325         else if(flags & SWS_CPU_CAPS_MMX)
1326                 return swScale_MMX;
1327         else
1328                 return swScale_C;
1329
1330 #else
1331 #ifdef ARCH_POWERPC
1332         if(flags & SWS_CPU_CAPS_ALTIVEC)
1333           return swScale_altivec;
1334         else
1335           return swScale_C;
1336 #endif
1337         return swScale_C;
1338 #endif
1339 #else //RUNTIME_CPUDETECT
1340 #ifdef HAVE_MMX2
1341         return swScale_MMX2;
1342 #elif defined (HAVE_3DNOW)
1343         return swScale_3DNow;
1344 #elif defined (HAVE_MMX)
1345         return swScale_MMX;
1346 #elif defined (HAVE_ALTIVEC)
1347         return swScale_altivec;
1348 #else
1349         return swScale_C;
1350 #endif
1351 #endif //!RUNTIME_CPUDETECT
1352 }
1353
1354 static int PlanarToNV12Wrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1355              int srcSliceH, uint8_t* dstParam[], int dstStride[]){
1356         uint8_t *dst=dstParam[0] + dstStride[0]*srcSliceY;
1357         /* Copy Y plane */
1358         if(dstStride[0]==srcStride[0])
1359                 memcpy(dst, src[0], srcSliceH*dstStride[0]);
1360         else
1361         {
1362                 int i;
1363                 uint8_t *srcPtr= src[0];
1364                 uint8_t *dstPtr= dst;
1365                 for(i=0; i<srcSliceH; i++)
1366                 {
1367                         memcpy(dstPtr, srcPtr, srcStride[0]);
1368                         srcPtr+= srcStride[0];
1369                         dstPtr+= dstStride[0];
1370                 }
1371         }
1372         dst = dstParam[1] + dstStride[1]*srcSliceY;
1373         interleaveBytes( src[1],src[2],dst,c->srcW,srcSliceH,srcStride[1],srcStride[2],dstStride[0] );
1374
1375         return srcSliceH;
1376 }
1377
1378 static int PlanarToYuy2Wrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1379              int srcSliceH, uint8_t* dstParam[], int dstStride[]){
1380         uint8_t *dst=dstParam[0] + dstStride[0]*srcSliceY;
1381
1382         yv12toyuy2( src[0],src[1],src[2],dst,c->srcW,srcSliceH,srcStride[0],srcStride[1],dstStride[0] );
1383
1384         return srcSliceH;
1385 }
1386
1387 static int PlanarToUyvyWrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1388              int srcSliceH, uint8_t* dstParam[], int dstStride[]){
1389         uint8_t *dst=dstParam[0] + dstStride[0]*srcSliceY;
1390
1391         yv12touyvy( src[0],src[1],src[2],dst,c->srcW,srcSliceH,srcStride[0],srcStride[1],dstStride[0] );
1392
1393         return srcSliceH;
1394 }
1395
1396 /* {RGB,BGR}{15,16,24,32} -> {RGB,BGR}{15,16,24,32} */
1397 static int rgb2rgbWrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1398                            int srcSliceH, uint8_t* dst[], int dstStride[]){
1399         const int srcFormat= c->srcFormat;
1400         const int dstFormat= c->dstFormat;
1401         const int srcBpp= ((srcFormat&0xFF) + 7)>>3;
1402         const int dstBpp= ((dstFormat&0xFF) + 7)>>3;
1403         const int srcId= (srcFormat&0xFF)>>2; // 1:0, 4:1, 8:2, 15:3, 16:4, 24:6, 32:8 
1404         const int dstId= (dstFormat&0xFF)>>2;
1405         void (*conv)(const uint8_t *src, uint8_t *dst, unsigned src_size)=NULL;
1406
1407         /* BGR -> BGR */
1408         if(   (isBGR(srcFormat) && isBGR(dstFormat))
1409            || (isRGB(srcFormat) && isRGB(dstFormat))){
1410                 switch(srcId | (dstId<<4)){
1411                 case 0x34: conv= rgb16to15; break;
1412                 case 0x36: conv= rgb24to15; break;
1413                 case 0x38: conv= rgb32to15; break;
1414                 case 0x43: conv= rgb15to16; break;
1415                 case 0x46: conv= rgb24to16; break;
1416                 case 0x48: conv= rgb32to16; break;
1417                 case 0x63: conv= rgb15to24; break;
1418                 case 0x64: conv= rgb16to24; break;
1419                 case 0x68: conv= rgb32to24; break;
1420                 case 0x83: conv= rgb15to32; break;
1421                 case 0x84: conv= rgb16to32; break;
1422                 case 0x86: conv= rgb24to32; break;
1423                 default: MSG_ERR("swScaler: internal error %s -> %s converter\n", 
1424                                  vo_format_name(srcFormat), vo_format_name(dstFormat)); break;
1425                 }
1426         }else if(   (isBGR(srcFormat) && isRGB(dstFormat))
1427                  || (isRGB(srcFormat) && isBGR(dstFormat))){
1428                 switch(srcId | (dstId<<4)){
1429                 case 0x33: conv= rgb15tobgr15; break;
1430                 case 0x34: conv= rgb16tobgr15; break;
1431                 case 0x36: conv= rgb24tobgr15; break;
1432                 case 0x38: conv= rgb32tobgr15; break;
1433                 case 0x43: conv= rgb15tobgr16; break;
1434                 case 0x44: conv= rgb16tobgr16; break;
1435                 case 0x46: conv= rgb24tobgr16; break;
1436                 case 0x48: conv= rgb32tobgr16; break;
1437                 case 0x63: conv= rgb15tobgr24; break;
1438                 case 0x64: conv= rgb16tobgr24; break;
1439                 case 0x66: conv= rgb24tobgr24; break;
1440                 case 0x68: conv= rgb32tobgr24; break;
1441                 case 0x83: conv= rgb15tobgr32; break;
1442                 case 0x84: conv= rgb16tobgr32; break;
1443                 case 0x86: conv= rgb24tobgr32; break;
1444                 case 0x88: conv= rgb32tobgr32; break;
1445                 default: MSG_ERR("swScaler: internal error %s -> %s converter\n", 
1446                                  vo_format_name(srcFormat), vo_format_name(dstFormat)); break;
1447                 }
1448         }else{
1449                 MSG_ERR("swScaler: internal error %s -> %s converter\n", 
1450                          vo_format_name(srcFormat), vo_format_name(dstFormat));
1451         }
1452
1453         if(dstStride[0]*srcBpp == srcStride[0]*dstBpp)
1454                 conv(src[0], dst[0] + dstStride[0]*srcSliceY, srcSliceH*srcStride[0]);
1455         else
1456         {
1457                 int i;
1458                 uint8_t *srcPtr= src[0];
1459                 uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;
1460
1461                 for(i=0; i<srcSliceH; i++)
1462                 {
1463                         conv(srcPtr, dstPtr, c->srcW*srcBpp);
1464                         srcPtr+= srcStride[0];
1465                         dstPtr+= dstStride[0];
1466                 }
1467         }     
1468         return srcSliceH;
1469 }
1470
1471 static int bgr24toyv12Wrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1472              int srcSliceH, uint8_t* dst[], int dstStride[]){
1473
1474         rgb24toyv12(
1475                 src[0], 
1476                 dst[0]+ srcSliceY    *dstStride[0], 
1477                 dst[1]+(srcSliceY>>1)*dstStride[1], 
1478                 dst[2]+(srcSliceY>>1)*dstStride[2],
1479                 c->srcW, srcSliceH, 
1480                 dstStride[0], dstStride[1], srcStride[0]);
1481         return srcSliceH;
1482 }
1483
1484 static int yvu9toyv12Wrapper(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1485              int srcSliceH, uint8_t* dst[], int dstStride[]){
1486         int i;
1487
1488         /* copy Y */
1489         if(srcStride[0]==dstStride[0]) 
1490                 memcpy(dst[0]+ srcSliceY*dstStride[0], src[0], srcStride[0]*srcSliceH);
1491         else{
1492                 uint8_t *srcPtr= src[0];
1493                 uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;
1494
1495                 for(i=0; i<srcSliceH; i++)
1496                 {
1497                         memcpy(dstPtr, srcPtr, c->srcW);
1498                         srcPtr+= srcStride[0];
1499                         dstPtr+= dstStride[0];
1500                 }
1501         }
1502
1503         if(c->dstFormat==IMGFMT_YV12){
1504                 planar2x(src[1], dst[1], c->chrSrcW, c->chrSrcH, srcStride[1], dstStride[1]);
1505                 planar2x(src[2], dst[2], c->chrSrcW, c->chrSrcH, srcStride[2], dstStride[2]);
1506         }else{
1507                 planar2x(src[1], dst[2], c->chrSrcW, c->chrSrcH, srcStride[1], dstStride[2]);
1508                 planar2x(src[2], dst[1], c->chrSrcW, c->chrSrcH, srcStride[2], dstStride[1]);
1509         }
1510         return srcSliceH;
1511 }
1512
1513 /**
1514  * bring pointers in YUV order instead of YVU
1515  */
1516 static inline void sws_orderYUV(int format, uint8_t * sortedP[], int sortedStride[], uint8_t * p[], int stride[]){
1517         if(format == IMGFMT_YV12 || format == IMGFMT_YVU9
1518            || format == IMGFMT_444P || format == IMGFMT_422P || format == IMGFMT_411P){
1519                 sortedP[0]= p[0];
1520                 sortedP[1]= p[2];
1521                 sortedP[2]= p[1];
1522                 sortedStride[0]= stride[0];
1523                 sortedStride[1]= stride[2];
1524                 sortedStride[2]= stride[1];
1525         }
1526         else if(isPacked(format) || isGray(format) || format == IMGFMT_Y8)
1527         {
1528                 sortedP[0]= p[0];
1529                 sortedP[1]= 
1530                 sortedP[2]= NULL;
1531                 sortedStride[0]= stride[0];
1532                 sortedStride[1]= 
1533                 sortedStride[2]= 0;
1534         }
1535         else if(format == IMGFMT_I420 || format == IMGFMT_IYUV)
1536         {
1537                 sortedP[0]= p[0];
1538                 sortedP[1]= p[1];
1539                 sortedP[2]= p[2];
1540                 sortedStride[0]= stride[0];
1541                 sortedStride[1]= stride[1];
1542                 sortedStride[2]= stride[2];
1543         }else{
1544                 MSG_ERR("internal error in orderYUV\n");
1545         }
1546 }
1547
1548 /* unscaled copy like stuff (assumes nearly identical formats) */
1549 static int simpleCopy(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
1550              int srcSliceH, uint8_t* dst[], int dstStride[]){
1551
1552         if(isPacked(c->srcFormat))
1553         {
1554                 if(dstStride[0]==srcStride[0])
1555                         memcpy(dst[0] + dstStride[0]*srcSliceY, src[0], srcSliceH*dstStride[0]);
1556                 else
1557                 {
1558                         int i;
1559                         uint8_t *srcPtr= src[0];
1560                         uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;
1561                         int length=0;
1562
1563                         /* universal length finder */
1564                         while(length+c->srcW <= ABS(dstStride[0]) 
1565                            && length+c->srcW <= ABS(srcStride[0])) length+= c->srcW;
1566                         ASSERT(length!=0);
1567
1568                         for(i=0; i<srcSliceH; i++)
1569                         {
1570                                 memcpy(dstPtr, srcPtr, length);
1571                                 srcPtr+= srcStride[0];
1572                                 dstPtr+= dstStride[0];
1573                         }
1574                 }
1575         }
1576         else 
1577         { /* Planar YUV or gray */
1578                 int plane;
1579                 for(plane=0; plane<3; plane++)
1580                 {
1581                         int length= plane==0 ? c->srcW  : -((-c->srcW  )>>c->chrDstHSubSample);
1582                         int y=      plane==0 ? srcSliceY: -((-srcSliceY)>>c->chrDstVSubSample);
1583                         int height= plane==0 ? srcSliceH: -((-srcSliceH)>>c->chrDstVSubSample);
1584
1585                         if((isGray(c->srcFormat) || isGray(c->dstFormat)) && plane>0)
1586                         {
1587                                 if(!isGray(c->dstFormat))
1588                                         memset(dst[plane], 128, dstStride[plane]*height);
1589                         }
1590                         else
1591                         {
1592                                 if(dstStride[plane]==srcStride[plane])
1593                                         memcpy(dst[plane] + dstStride[plane]*y, src[plane], height*dstStride[plane]);
1594                                 else
1595                                 {
1596                                         int i;
1597                                         uint8_t *srcPtr= src[plane];
1598                                         uint8_t *dstPtr= dst[plane] + dstStride[plane]*y;
1599                                         for(i=0; i<height; i++)
1600                                         {
1601                                                 memcpy(dstPtr, srcPtr, length);
1602                                                 srcPtr+= srcStride[plane];
1603                                                 dstPtr+= dstStride[plane];
1604                                         }
1605                                 }
1606                         }
1607                 }
1608         }
1609         return srcSliceH;
1610 }
1611
1612 static int remove_dup_fourcc(int fourcc)
1613 {
1614         switch(fourcc)
1615         {
1616             case IMGFMT_I420:
1617             case IMGFMT_IYUV: return IMGFMT_YV12;
1618             case IMGFMT_Y8  : return IMGFMT_Y800;
1619             case IMGFMT_IF09: return IMGFMT_YVU9;
1620             default: return fourcc;
1621         }
1622 }
1623
1624 static void getSubSampleFactors(int *h, int *v, int format){
1625         switch(format){
1626         case IMGFMT_UYVY:
1627         case IMGFMT_YUY2:
1628                 *h=1;
1629                 *v=0;
1630                 break;
1631         case IMGFMT_YV12:
1632         case IMGFMT_Y800: //FIXME remove after different subsamplings are fully implemented
1633                 *h=1;
1634                 *v=1;
1635                 break;
1636         case IMGFMT_YVU9:
1637                 *h=2;
1638                 *v=2;
1639                 break;
1640         case IMGFMT_444P:
1641                 *h=0;
1642                 *v=0;
1643                 break;
1644         case IMGFMT_422P:
1645                 *h=1;
1646                 *v=0;
1647                 break;
1648         case IMGFMT_411P:
1649                 *h=2;
1650                 *v=0;
1651                 break;
1652         default:
1653                 *h=0;
1654                 *v=0;
1655                 break;
1656         }
1657 }
1658
1659 static uint16_t roundToInt16(int64_t f){
1660         int r= (f + (1<<15))>>16;
1661              if(r<-0x7FFF) return 0x8000;
1662         else if(r> 0x7FFF) return 0x7FFF;
1663         else               return r;
1664 }
1665
1666 /**
1667  * @param inv_table the yuv2rgb coeffs, normally Inverse_Table_6_9[x]
1668  * @param fullRange if 1 then the luma range is 0..255 if 0 its 16..235
1669  * @return -1 if not supported
1670  */
1671 int sws_setColorspaceDetails(SwsContext *c, const int inv_table[4], int srcRange, const int table[4], int dstRange, int brightness, int contrast, int saturation){
1672         int64_t crv =  inv_table[0];
1673         int64_t cbu =  inv_table[1];
1674         int64_t cgu = -inv_table[2];
1675         int64_t cgv = -inv_table[3];
1676         int64_t cy  = 1<<16;
1677         int64_t oy  = 0;
1678
1679         if(isYUV(c->dstFormat) || isGray(c->dstFormat)) return -1;
1680         memcpy(c->srcColorspaceTable, inv_table, sizeof(int)*4);
1681         memcpy(c->dstColorspaceTable,     table, sizeof(int)*4);
1682
1683         c->brightness= brightness;
1684         c->contrast  = contrast;
1685         c->saturation= saturation;
1686         c->srcRange  = srcRange;
1687         c->dstRange  = dstRange;
1688
1689         c->uOffset=   0x0400040004000400LL;
1690         c->vOffset=   0x0400040004000400LL;
1691
1692         if(!srcRange){
1693                 cy= (cy*255) / 219;
1694                 oy= 16<<16;
1695         }
1696
1697         cy = (cy *contrast             )>>16;
1698         crv= (crv*contrast * saturation)>>32;
1699         cbu= (cbu*contrast * saturation)>>32;
1700         cgu= (cgu*contrast * saturation)>>32;
1701         cgv= (cgv*contrast * saturation)>>32;
1702
1703         oy -= 256*brightness;
1704
1705         c->yCoeff=    roundToInt16(cy *8192) * 0x0001000100010001ULL;
1706         c->vrCoeff=   roundToInt16(crv*8192) * 0x0001000100010001ULL;
1707         c->ubCoeff=   roundToInt16(cbu*8192) * 0x0001000100010001ULL;
1708         c->vgCoeff=   roundToInt16(cgv*8192) * 0x0001000100010001ULL;
1709         c->ugCoeff=   roundToInt16(cgu*8192) * 0x0001000100010001ULL;
1710         c->yOffset=   roundToInt16(oy *   8) * 0x0001000100010001ULL;
1711
1712         yuv2rgb_c_init_tables(c, inv_table, srcRange, brightness, contrast, saturation);
1713         //FIXME factorize
1714         
1715         return 0;
1716 }
1717
1718 /**
1719  * @return -1 if not supported
1720  */
1721 int sws_getColorspaceDetails(SwsContext *c, int **inv_table, int *srcRange, int **table, int *dstRange, int *brightness, int *contrast, int *saturation){
1722         if(isYUV(c->dstFormat) || isGray(c->dstFormat)) return -1;
1723
1724         *inv_table = c->srcColorspaceTable;
1725         *table     = c->dstColorspaceTable;
1726         *srcRange  = c->srcRange;
1727         *dstRange  = c->dstRange;
1728         *brightness= c->brightness;
1729         *contrast  = c->contrast;
1730         *saturation= c->saturation;
1731         
1732         return 0;       
1733 }
1734
1735 SwsContext *sws_getContext(int srcW, int srcH, int origSrcFormat, int dstW, int dstH, int origDstFormat, int flags,
1736                          SwsFilter *srcFilter, SwsFilter *dstFilter){
1737
1738         SwsContext *c;
1739         int i;
1740         int usesVFilter, usesHFilter;
1741         int unscaled, needsDither;
1742         int srcFormat, dstFormat;
1743         SwsFilter dummyFilter= {NULL, NULL, NULL, NULL};
1744 #ifdef ARCH_X86
1745         if(flags & SWS_CPU_CAPS_MMX)
1746                 asm volatile("emms\n\t"::: "memory");
1747 #endif
1748
1749 #ifndef RUNTIME_CPUDETECT //ensure that the flags match the compiled variant if cpudetect is off
1750         flags &= ~(SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2|SWS_CPU_CAPS_3DNOW|SWS_CPU_CAPS_ALTIVEC);
1751 #ifdef HAVE_MMX2
1752         flags |= SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2;
1753 #elif defined (HAVE_3DNOW)
1754         flags |= SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_3DNOW;
1755 #elif defined (HAVE_MMX)
1756         flags |= SWS_CPU_CAPS_MMX;
1757 #elif defined (HAVE_ALTIVEC)
1758         flags |= SWS_CPU_CAPS_ALTIVEC;
1759 #endif
1760 #endif
1761         if(clip_table[512] != 255) globalInit();
1762         if(rgb15to16 == NULL) sws_rgb2rgb_init(flags);
1763
1764         /* avoid duplicate Formats, so we don't need to check to much */
1765         srcFormat = remove_dup_fourcc(origSrcFormat);
1766         dstFormat = remove_dup_fourcc(origDstFormat);
1767
1768         unscaled = (srcW == dstW && srcH == dstH);
1769         needsDither= (isBGR(dstFormat) || isRGB(dstFormat)) 
1770                      && (dstFormat&0xFF)<24
1771                      && ((dstFormat&0xFF)<(srcFormat&0xFF) || (!(isRGB(srcFormat) || isBGR(srcFormat))));
1772
1773         if(!isSupportedIn(srcFormat)) 
1774         {
1775                 MSG_ERR("swScaler: %s is not supported as input format\n", vo_format_name(srcFormat));
1776                 return NULL;
1777         }
1778         if(!isSupportedOut(dstFormat))
1779         {
1780                 MSG_ERR("swScaler: %s is not supported as output format\n", vo_format_name(dstFormat));
1781                 return NULL;
1782         }
1783
1784         /* sanity check */
1785         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
1786         {
1787                  MSG_ERR("swScaler: %dx%d -> %dx%d is invalid scaling dimension\n", 
1788                         srcW, srcH, dstW, dstH);
1789                 return NULL;
1790         }
1791
1792         if(!dstFilter) dstFilter= &dummyFilter;
1793         if(!srcFilter) srcFilter= &dummyFilter;
1794
1795         c= memalign(64, sizeof(SwsContext));
1796         memset(c, 0, sizeof(SwsContext));
1797
1798         c->srcW= srcW;
1799         c->srcH= srcH;
1800         c->dstW= dstW;
1801         c->dstH= dstH;
1802         c->lumXInc= ((srcW<<16) + (dstW>>1))/dstW;
1803         c->lumYInc= ((srcH<<16) + (dstH>>1))/dstH;
1804         c->flags= flags;
1805         c->dstFormat= dstFormat;
1806         c->srcFormat= srcFormat;
1807         c->origDstFormat= origDstFormat;
1808         c->origSrcFormat= origSrcFormat;
1809         c->vRounder= 4* 0x0001000100010001ULL;
1810
1811         usesHFilter= usesVFilter= 0;
1812         if(dstFilter->lumV!=NULL && dstFilter->lumV->length>1) usesVFilter=1;
1813         if(dstFilter->lumH!=NULL && dstFilter->lumH->length>1) usesHFilter=1;
1814         if(dstFilter->chrV!=NULL && dstFilter->chrV->length>1) usesVFilter=1;
1815         if(dstFilter->chrH!=NULL && dstFilter->chrH->length>1) usesHFilter=1;
1816         if(srcFilter->lumV!=NULL && srcFilter->lumV->length>1) usesVFilter=1;
1817         if(srcFilter->lumH!=NULL && srcFilter->lumH->length>1) usesHFilter=1;
1818         if(srcFilter->chrV!=NULL && srcFilter->chrV->length>1) usesVFilter=1;
1819         if(srcFilter->chrH!=NULL && srcFilter->chrH->length>1) usesHFilter=1;
1820
1821         getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat);
1822         getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat);
1823
1824         // reuse chroma for 2 pixles rgb/bgr unless user wants full chroma interpolation
1825         if((isBGR(dstFormat) || isRGB(dstFormat)) && !(flags&SWS_FULL_CHR_H_INT)) c->chrDstHSubSample=1;
1826
1827         // drop some chroma lines if the user wants it
1828         c->vChrDrop= (flags&SWS_SRC_V_CHR_DROP_MASK)>>SWS_SRC_V_CHR_DROP_SHIFT;
1829         c->chrSrcVSubSample+= c->vChrDrop;
1830
1831         // drop every 2. pixel for chroma calculation unless user wants full chroma
1832         if((isBGR(srcFormat) || isRGB(srcFormat)) && !(flags&SWS_FULL_CHR_H_INP)) 
1833                 c->chrSrcHSubSample=1;
1834
1835         c->chrIntHSubSample= c->chrDstHSubSample;
1836         c->chrIntVSubSample= c->chrSrcVSubSample;
1837
1838         // note the -((-x)>>y) is so that we allways round toward +inf
1839         c->chrSrcW= -((-srcW) >> c->chrSrcHSubSample);
1840         c->chrSrcH= -((-srcH) >> c->chrSrcVSubSample);
1841         c->chrDstW= -((-dstW) >> c->chrDstHSubSample);
1842         c->chrDstH= -((-dstH) >> c->chrDstVSubSample);
1843
1844         sws_setColorspaceDetails(c, Inverse_Table_6_9[SWS_CS_DEFAULT], 0, Inverse_Table_6_9[SWS_CS_DEFAULT] /* FIXME*/, 0, 0, 1<<16, 1<<16); 
1845
1846         /* unscaled special Cases */
1847         if(unscaled && !usesHFilter && !usesVFilter)
1848         {
1849                 /* yv12_to_nv12 */
1850                 if(srcFormat == IMGFMT_YV12 && dstFormat == IMGFMT_NV12)
1851                 {
1852                         c->swScale= PlanarToNV12Wrapper;
1853                 }
1854                 /* yuv2bgr */
1855                 if((srcFormat==IMGFMT_YV12 || srcFormat==IMGFMT_422P) && (isBGR(dstFormat) || isRGB(dstFormat)))
1856                 {
1857                         c->swScale= yuv2rgb_get_func_ptr(c);
1858                 }
1859                 
1860                 if( srcFormat==IMGFMT_YVU9 && dstFormat==IMGFMT_YV12 )
1861                 {
1862                         c->swScale= yvu9toyv12Wrapper;
1863                 }
1864
1865                 /* bgr24toYV12 */
1866                 if(srcFormat==IMGFMT_BGR24 && dstFormat==IMGFMT_YV12)
1867                         c->swScale= bgr24toyv12Wrapper;
1868                 
1869                 /* rgb/bgr -> rgb/bgr (no dither needed forms) */
1870                 if(   (isBGR(srcFormat) || isRGB(srcFormat))
1871                    && (isBGR(dstFormat) || isRGB(dstFormat)) 
1872                    && !needsDither)
1873                         c->swScale= rgb2rgbWrapper;
1874
1875                 /* LQ converters if -sws 0 or -sws 4*/
1876                 if(c->flags&(SWS_FAST_BILINEAR|SWS_POINT)){
1877                         /* rgb/bgr -> rgb/bgr (dither needed forms) */
1878                         if(  (isBGR(srcFormat) || isRGB(srcFormat))
1879                           && (isBGR(dstFormat) || isRGB(dstFormat)) 
1880                           && needsDither)
1881                                 c->swScale= rgb2rgbWrapper;
1882
1883                         /* yv12_to_yuy2 */
1884                         if(srcFormat == IMGFMT_YV12 && 
1885                             (dstFormat == IMGFMT_YUY2 || dstFormat == IMGFMT_UYVY))
1886                         {
1887                                 if (dstFormat == IMGFMT_YUY2)
1888                                     c->swScale= PlanarToYuy2Wrapper;
1889                                 else
1890                                     c->swScale= PlanarToUyvyWrapper;
1891                         }
1892                 }
1893
1894                 /* simple copy */
1895                 if(   srcFormat == dstFormat
1896                    || (isPlanarYUV(srcFormat) && isGray(dstFormat))
1897                    || (isPlanarYUV(dstFormat) && isGray(srcFormat))
1898                   )
1899                 {
1900                         c->swScale= simpleCopy;
1901                 }
1902
1903                 if(c->swScale){
1904                         if(flags&SWS_PRINT_INFO)
1905                                 MSG_INFO("SwScaler: using unscaled %s -> %s special converter\n", 
1906                                         vo_format_name(srcFormat), vo_format_name(dstFormat));
1907                         return c;
1908                 }
1909         }
1910
1911         if(flags & SWS_CPU_CAPS_MMX2)
1912         {
1913                 c->canMMX2BeUsed= (dstW >=srcW && (dstW&31)==0 && (srcW&15)==0) ? 1 : 0;
1914                 if(!c->canMMX2BeUsed && dstW >=srcW && (srcW&15)==0 && (flags&SWS_FAST_BILINEAR))
1915                 {
1916                         if(flags&SWS_PRINT_INFO)
1917                                 MSG_INFO("SwScaler: output Width is not a multiple of 32 -> no MMX2 scaler\n");
1918                 }
1919                 if(usesHFilter) c->canMMX2BeUsed=0;
1920         }
1921         else
1922                 c->canMMX2BeUsed=0;
1923
1924         c->chrXInc= ((c->chrSrcW<<16) + (c->chrDstW>>1))/c->chrDstW;
1925         c->chrYInc= ((c->chrSrcH<<16) + (c->chrDstH>>1))/c->chrDstH;
1926
1927         // match pixel 0 of the src to pixel 0 of dst and match pixel n-2 of src to pixel n-2 of dst
1928         // but only for the FAST_BILINEAR mode otherwise do correct scaling
1929         // n-2 is the last chrominance sample available
1930         // this is not perfect, but noone shuld notice the difference, the more correct variant
1931         // would be like the vertical one, but that would require some special code for the
1932         // first and last pixel
1933         if(flags&SWS_FAST_BILINEAR)
1934         {
1935                 if(c->canMMX2BeUsed)
1936                 {
1937                         c->lumXInc+= 20;
1938                         c->chrXInc+= 20;
1939                 }
1940                 //we don't use the x86asm scaler if mmx is available
1941                 else if(flags & SWS_CPU_CAPS_MMX)
1942                 {
1943                         c->lumXInc = ((srcW-2)<<16)/(dstW-2) - 20;
1944                         c->chrXInc = ((c->chrSrcW-2)<<16)/(c->chrDstW-2) - 20;
1945                 }
1946         }
1947
1948         /* precalculate horizontal scaler filter coefficients */
1949         {
1950                 const int filterAlign= (flags & SWS_CPU_CAPS_MMX) ? 4 : 1;
1951
1952                 initFilter(&c->hLumFilter, &c->hLumFilterPos, &c->hLumFilterSize, c->lumXInc,
1953                                  srcW      ,       dstW, filterAlign, 1<<14,
1954                                  (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags,
1955                                  srcFilter->lumH, dstFilter->lumH);
1956                 initFilter(&c->hChrFilter, &c->hChrFilterPos, &c->hChrFilterSize, c->chrXInc,
1957                                  c->chrSrcW, c->chrDstW, filterAlign, 1<<14,
1958                                  (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags,
1959                                  srcFilter->chrH, dstFilter->chrH);
1960
1961 #ifdef ARCH_X86
1962 // can't downscale !!!
1963                 if(c->canMMX2BeUsed && (flags & SWS_FAST_BILINEAR))
1964                 {
1965                         c->lumMmx2Filter   = (int16_t*)memalign(8, (dstW        /8+8)*sizeof(int16_t));
1966                         c->chrMmx2Filter   = (int16_t*)memalign(8, (c->chrDstW  /4+8)*sizeof(int16_t));
1967                         c->lumMmx2FilterPos= (int32_t*)memalign(8, (dstW      /2/8+8)*sizeof(int32_t));
1968                         c->chrMmx2FilterPos= (int32_t*)memalign(8, (c->chrDstW/2/4+8)*sizeof(int32_t));
1969
1970                         initMMX2HScaler(      dstW, c->lumXInc, c->funnyYCode , c->lumMmx2Filter, c->lumMmx2FilterPos, 8);
1971                         initMMX2HScaler(c->chrDstW, c->chrXInc, c->funnyUVCode, c->chrMmx2Filter, c->chrMmx2FilterPos, 4);
1972                 }
1973 #endif
1974         } // Init Horizontal stuff
1975
1976
1977
1978         /* precalculate vertical scaler filter coefficients */
1979         initFilter(&c->vLumFilter, &c->vLumFilterPos, &c->vLumFilterSize, c->lumYInc,
1980                         srcH      ,        dstH, 1, (1<<12)-4,
1981                         (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags,
1982                         srcFilter->lumV, dstFilter->lumV);
1983         initFilter(&c->vChrFilter, &c->vChrFilterPos, &c->vChrFilterSize, c->chrYInc,
1984                         c->chrSrcH, c->chrDstH, 1, (1<<12)-4,
1985                         (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags,
1986                         srcFilter->chrV, dstFilter->chrV);
1987
1988         // Calculate Buffer Sizes so that they won't run out while handling these damn slices
1989         c->vLumBufSize= c->vLumFilterSize;
1990         c->vChrBufSize= c->vChrFilterSize;
1991         for(i=0; i<dstH; i++)
1992         {
1993                 int chrI= i*c->chrDstH / dstH;
1994                 int nextSlice= MAX(c->vLumFilterPos[i   ] + c->vLumFilterSize - 1,
1995                                  ((c->vChrFilterPos[chrI] + c->vChrFilterSize - 1)<<c->chrSrcVSubSample));
1996
1997                 nextSlice>>= c->chrSrcVSubSample;
1998                 nextSlice<<= c->chrSrcVSubSample;
1999                 if(c->vLumFilterPos[i   ] + c->vLumBufSize < nextSlice)
2000                         c->vLumBufSize= nextSlice - c->vLumFilterPos[i   ];
2001                 if(c->vChrFilterPos[chrI] + c->vChrBufSize < (nextSlice>>c->chrSrcVSubSample))
2002                         c->vChrBufSize= (nextSlice>>c->chrSrcVSubSample) - c->vChrFilterPos[chrI];
2003         }
2004
2005         // allocate pixbufs (we use dynamic allocation because otherwise we would need to
2006         c->lumPixBuf= (int16_t**)memalign(4, c->vLumBufSize*2*sizeof(int16_t*));
2007         c->chrPixBuf= (int16_t**)memalign(4, c->vChrBufSize*2*sizeof(int16_t*));
2008         //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)
2009         for(i=0; i<c->vLumBufSize; i++)
2010                 c->lumPixBuf[i]= c->lumPixBuf[i+c->vLumBufSize]= (uint16_t*)memalign(8, 4000);
2011         for(i=0; i<c->vChrBufSize; i++)
2012                 c->chrPixBuf[i]= c->chrPixBuf[i+c->vChrBufSize]= (uint16_t*)memalign(8, 8000);
2013
2014         //try to avoid drawing green stuff between the right end and the stride end
2015         for(i=0; i<c->vLumBufSize; i++) memset(c->lumPixBuf[i], 0, 4000);
2016         for(i=0; i<c->vChrBufSize; i++) memset(c->chrPixBuf[i], 64, 8000);
2017
2018         ASSERT(c->chrDstH <= dstH)
2019
2020         if(flags&SWS_PRINT_INFO)
2021         {
2022 #ifdef DITHER1XBPP
2023                 char *dither= " dithered";
2024 #else
2025                 char *dither= "";
2026 #endif
2027                 if(flags&SWS_FAST_BILINEAR)
2028                         MSG_INFO("\nSwScaler: FAST_BILINEAR scaler, ");
2029                 else if(flags&SWS_BILINEAR)
2030                         MSG_INFO("\nSwScaler: BILINEAR scaler, ");
2031                 else if(flags&SWS_BICUBIC)
2032                         MSG_INFO("\nSwScaler: BICUBIC scaler, ");
2033                 else if(flags&SWS_X)
2034                         MSG_INFO("\nSwScaler: Experimental scaler, ");
2035                 else if(flags&SWS_POINT)
2036                         MSG_INFO("\nSwScaler: Nearest Neighbor / POINT scaler, ");
2037                 else if(flags&SWS_AREA)
2038                         MSG_INFO("\nSwScaler: Area Averageing scaler, ");
2039                 else if(flags&SWS_BICUBLIN)
2040                         MSG_INFO("\nSwScaler: luma BICUBIC / chroma BILINEAR scaler, ");
2041                 else if(flags&SWS_GAUSS)
2042                         MSG_INFO("\nSwScaler: Gaussian scaler, ");
2043                 else if(flags&SWS_SINC)
2044                         MSG_INFO("\nSwScaler: Sinc scaler, ");
2045                 else if(flags&SWS_LANCZOS)
2046                         MSG_INFO("\nSwScaler: Lanczos scaler, ");
2047                 else if(flags&SWS_SPLINE)
2048                         MSG_INFO("\nSwScaler: Bicubic spline scaler, ");
2049                 else
2050                         MSG_INFO("\nSwScaler: ehh flags invalid?! ");
2051
2052                 if(dstFormat==IMGFMT_BGR15 || dstFormat==IMGFMT_BGR16)
2053                         MSG_INFO("from %s to%s %s ", 
2054                                 vo_format_name(srcFormat), dither, vo_format_name(dstFormat));
2055                 else
2056                         MSG_INFO("from %s to %s ", 
2057                                 vo_format_name(srcFormat), vo_format_name(dstFormat));
2058
2059                 if(flags & SWS_CPU_CAPS_MMX2)
2060                         MSG_INFO("using MMX2\n");
2061                 else if(flags & SWS_CPU_CAPS_3DNOW)
2062                         MSG_INFO("using 3DNOW\n");
2063                 else if(flags & SWS_CPU_CAPS_MMX)
2064                         MSG_INFO("using MMX\n");
2065                 else if(flags & SWS_CPU_CAPS_ALTIVEC)
2066                         MSG_INFO("using AltiVec\n");
2067                 else 
2068                         MSG_INFO("using C\n");
2069         }
2070
2071         if(flags & SWS_PRINT_INFO)
2072         {
2073                 if(flags & SWS_CPU_CAPS_MMX)
2074                 {
2075                         if(c->canMMX2BeUsed && (flags&SWS_FAST_BILINEAR))
2076                                 MSG_V("SwScaler: using FAST_BILINEAR MMX2 scaler for horizontal scaling\n");
2077                         else
2078                         {
2079                                 if(c->hLumFilterSize==4)
2080                                         MSG_V("SwScaler: using 4-tap MMX scaler for horizontal luminance scaling\n");
2081                                 else if(c->hLumFilterSize==8)
2082                                         MSG_V("SwScaler: using 8-tap MMX scaler for horizontal luminance scaling\n");
2083                                 else
2084                                         MSG_V("SwScaler: using n-tap MMX scaler for horizontal luminance scaling\n");
2085
2086                                 if(c->hChrFilterSize==4)
2087                                         MSG_V("SwScaler: using 4-tap MMX scaler for horizontal chrominance scaling\n");
2088                                 else if(c->hChrFilterSize==8)
2089                                         MSG_V("SwScaler: using 8-tap MMX scaler for horizontal chrominance scaling\n");
2090                                 else
2091                                         MSG_V("SwScaler: using n-tap MMX scaler for horizontal chrominance scaling\n");
2092                         }
2093                 }
2094                 else
2095                 {
2096 #ifdef ARCH_X86
2097                         MSG_V("SwScaler: using X86-Asm scaler for horizontal scaling\n");
2098 #else
2099                         if(flags & SWS_FAST_BILINEAR)
2100                                 MSG_V("SwScaler: using FAST_BILINEAR C scaler for horizontal scaling\n");
2101                         else
2102                                 MSG_V("SwScaler: using C scaler for horizontal scaling\n");
2103 #endif
2104                 }
2105                 if(isPlanarYUV(dstFormat))
2106                 {
2107                         if(c->vLumFilterSize==1)
2108                                 MSG_V("SwScaler: using 1-tap %s \"scaler\" for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2109                         else
2110                                 MSG_V("SwScaler: using n-tap %s scaler for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2111                 }
2112                 else
2113                 {
2114                         if(c->vLumFilterSize==1 && c->vChrFilterSize==2)
2115                                 MSG_V("SwScaler: using 1-tap %s \"scaler\" for vertical luminance scaling (BGR)\n"
2116                                        "SwScaler:       2-tap scaler for vertical chrominance scaling (BGR)\n",(flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2117                         else if(c->vLumFilterSize==2 && c->vChrFilterSize==2)
2118                                 MSG_V("SwScaler: using 2-tap linear %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2119                         else
2120                                 MSG_V("SwScaler: using n-tap %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2121                 }
2122
2123                 if(dstFormat==IMGFMT_BGR24)
2124                         MSG_V("SwScaler: using %s YV12->BGR24 Converter\n",
2125                                 (flags & SWS_CPU_CAPS_MMX2) ? "MMX2" : ((flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"));
2126                 else if(dstFormat==IMGFMT_BGR32)
2127                         MSG_V("SwScaler: using %s YV12->BGR32 Converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2128                 else if(dstFormat==IMGFMT_BGR16)
2129                         MSG_V("SwScaler: using %s YV12->BGR16 Converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2130                 else if(dstFormat==IMGFMT_BGR15)
2131                         MSG_V("SwScaler: using %s YV12->BGR15 Converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");
2132
2133                 MSG_V("SwScaler: %dx%d -> %dx%d\n", srcW, srcH, dstW, dstH);
2134         }
2135         if(flags & SWS_PRINT_INFO)
2136         {
2137                 MSG_DBG2("SwScaler:Lum srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",
2138                         c->srcW, c->srcH, c->dstW, c->dstH, c->lumXInc, c->lumYInc);
2139                 MSG_DBG2("SwScaler:Chr srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",
2140                         c->chrSrcW, c->chrSrcH, c->chrDstW, c->chrDstH, c->chrXInc, c->chrYInc);
2141         }
2142
2143         c->swScale= getSwsFunc(flags);
2144         return c;
2145 }
2146
2147 /**
2148  * swscale warper, so we don't need to export the SwsContext.
2149  * assumes planar YUV to be in YUV order instead of YVU
2150  */
2151 int sws_scale_ordered(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
2152                            int srcSliceH, uint8_t* dst[], int dstStride[]){
2153         //copy strides, so they can safely be modified
2154         int srcStride2[3]= {srcStride[0], srcStride[1], srcStride[2]};
2155         int dstStride2[3]= {dstStride[0], dstStride[1], dstStride[2]};
2156         return c->swScale(c, src, srcStride2, srcSliceY, srcSliceH, dst, dstStride2);
2157 }
2158
2159 /**
2160  * swscale warper, so we don't need to export the SwsContext
2161  */
2162 int sws_scale(SwsContext *c, uint8_t* srcParam[], int srcStrideParam[], int srcSliceY,
2163                            int srcSliceH, uint8_t* dstParam[], int dstStrideParam[]){
2164         int srcStride[3];
2165         int dstStride[3];
2166         uint8_t *src[3];
2167         uint8_t *dst[3];
2168         sws_orderYUV(c->origSrcFormat, src, srcStride, srcParam, srcStrideParam);
2169         sws_orderYUV(c->origDstFormat, dst, dstStride, dstParam, dstStrideParam);
2170 //printf("sws: slice %d %d\n", srcSliceY, srcSliceH);
2171
2172         return c->swScale(c, src, srcStride, srcSliceY, srcSliceH, dst, dstStride);
2173 }
2174
2175 SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur, 
2176                                 float lumaSharpen, float chromaSharpen,
2177                                 float chromaHShift, float chromaVShift,
2178                                 int verbose)
2179 {
2180         SwsFilter *filter= malloc(sizeof(SwsFilter));
2181
2182         if(lumaGBlur!=0.0){
2183                 filter->lumH= sws_getGaussianVec(lumaGBlur, 3.0);
2184                 filter->lumV= sws_getGaussianVec(lumaGBlur, 3.0);
2185         }else{
2186                 filter->lumH= sws_getIdentityVec();
2187                 filter->lumV= sws_getIdentityVec();
2188         }
2189
2190         if(chromaGBlur!=0.0){
2191                 filter->chrH= sws_getGaussianVec(chromaGBlur, 3.0);
2192                 filter->chrV= sws_getGaussianVec(chromaGBlur, 3.0);
2193         }else{
2194                 filter->chrH= sws_getIdentityVec();
2195                 filter->chrV= sws_getIdentityVec();
2196         }
2197
2198         if(chromaSharpen!=0.0){
2199                 SwsVector *g= sws_getConstVec(-1.0, 3);
2200                 SwsVector *id= sws_getConstVec(10.0/chromaSharpen, 1);
2201                 g->coeff[1]=2.0;
2202                 sws_addVec(id, g);
2203                 sws_convVec(filter->chrH, id);
2204                 sws_convVec(filter->chrV, id);
2205                 sws_freeVec(g);
2206                 sws_freeVec(id);
2207         }
2208
2209         if(lumaSharpen!=0.0){
2210                 SwsVector *g= sws_getConstVec(-1.0, 3);
2211                 SwsVector *id= sws_getConstVec(10.0/lumaSharpen, 1);
2212                 g->coeff[1]=2.0;
2213                 sws_addVec(id, g);
2214                 sws_convVec(filter->lumH, id);
2215                 sws_convVec(filter->lumV, id);
2216                 sws_freeVec(g);
2217                 sws_freeVec(id);
2218         }
2219
2220         if(chromaHShift != 0.0)
2221                 sws_shiftVec(filter->chrH, (int)(chromaHShift+0.5));
2222
2223         if(chromaVShift != 0.0)
2224                 sws_shiftVec(filter->chrV, (int)(chromaVShift+0.5));
2225
2226         sws_normalizeVec(filter->chrH, 1.0);
2227         sws_normalizeVec(filter->chrV, 1.0);
2228         sws_normalizeVec(filter->lumH, 1.0);
2229         sws_normalizeVec(filter->lumV, 1.0);
2230
2231         if(verbose) sws_printVec(filter->chrH);
2232         if(verbose) sws_printVec(filter->lumH);
2233
2234         return filter;
2235 }
2236
2237 /**
2238  * returns a normalized gaussian curve used to filter stuff
2239  * quality=3 is high quality, lowwer is lowwer quality
2240  */
2241 SwsVector *sws_getGaussianVec(double variance, double quality){
2242         const int length= (int)(variance*quality + 0.5) | 1;
2243         int i;
2244         double *coeff= memalign(sizeof(double), length*sizeof(double));
2245         double middle= (length-1)*0.5;
2246         SwsVector *vec= malloc(sizeof(SwsVector));
2247
2248         vec->coeff= coeff;
2249         vec->length= length;
2250
2251         for(i=0; i<length; i++)
2252         {
2253                 double dist= i-middle;
2254                 coeff[i]= exp( -dist*dist/(2*variance*variance) ) / sqrt(2*variance*PI);
2255         }
2256
2257         sws_normalizeVec(vec, 1.0);
2258
2259         return vec;
2260 }
2261
2262 SwsVector *sws_getConstVec(double c, int length){
2263         int i;
2264         double *coeff= memalign(sizeof(double), length*sizeof(double));
2265         SwsVector *vec= malloc(sizeof(SwsVector));
2266
2267         vec->coeff= coeff;
2268         vec->length= length;
2269
2270         for(i=0; i<length; i++)
2271                 coeff[i]= c;
2272
2273         return vec;
2274 }
2275
2276
2277 SwsVector *sws_getIdentityVec(void){
2278         double *coeff= memalign(sizeof(double), sizeof(double));
2279         SwsVector *vec= malloc(sizeof(SwsVector));
2280         coeff[0]= 1.0;
2281
2282         vec->coeff= coeff;
2283         vec->length= 1;
2284
2285         return vec;
2286 }
2287
2288 void sws_normalizeVec(SwsVector *a, double height){
2289         int i;
2290         double sum=0;
2291         double inv;
2292
2293         for(i=0; i<a->length; i++)
2294                 sum+= a->coeff[i];
2295
2296         inv= height/sum;
2297
2298         for(i=0; i<a->length; i++)
2299                 a->coeff[i]*= inv;
2300 }
2301
2302 void sws_scaleVec(SwsVector *a, double scalar){
2303         int i;
2304
2305         for(i=0; i<a->length; i++)
2306                 a->coeff[i]*= scalar;
2307 }
2308
2309 static SwsVector *sws_getConvVec(SwsVector *a, SwsVector *b){
2310         int length= a->length + b->length - 1;
2311         double *coeff= memalign(sizeof(double), length*sizeof(double));
2312         int i, j;
2313         SwsVector *vec= malloc(sizeof(SwsVector));
2314
2315         vec->coeff= coeff;
2316         vec->length= length;
2317
2318         for(i=0; i<length; i++) coeff[i]= 0.0;
2319
2320         for(i=0; i<a->length; i++)
2321         {
2322                 for(j=0; j<b->length; j++)
2323                 {
2324                         coeff[i+j]+= a->coeff[i]*b->coeff[j];
2325                 }
2326         }
2327
2328         return vec;
2329 }
2330
2331 static SwsVector *sws_sumVec(SwsVector *a, SwsVector *b){
2332         int length= MAX(a->length, b->length);
2333         double *coeff= memalign(sizeof(double), length*sizeof(double));
2334         int i;
2335         SwsVector *vec= malloc(sizeof(SwsVector));
2336
2337         vec->coeff= coeff;
2338         vec->length= length;
2339
2340         for(i=0; i<length; i++) coeff[i]= 0.0;
2341
2342         for(i=0; i<a->length; i++) coeff[i + (length-1)/2 - (a->length-1)/2]+= a->coeff[i];
2343         for(i=0; i<b->length; i++) coeff[i + (length-1)/2 - (b->length-1)/2]+= b->coeff[i];
2344
2345         return vec;
2346 }
2347
2348 static SwsVector *sws_diffVec(SwsVector *a, SwsVector *b){
2349         int length= MAX(a->length, b->length);
2350         double *coeff= memalign(sizeof(double), length*sizeof(double));
2351         int i;
2352         SwsVector *vec= malloc(sizeof(SwsVector));
2353
2354         vec->coeff= coeff;
2355         vec->length= length;
2356
2357         for(i=0; i<length; i++) coeff[i]= 0.0;
2358
2359         for(i=0; i<a->length; i++) coeff[i + (length-1)/2 - (a->length-1)/2]+= a->coeff[i];
2360         for(i=0; i<b->length; i++) coeff[i + (length-1)/2 - (b->length-1)/2]-= b->coeff[i];
2361
2362         return vec;
2363 }
2364
2365 /* shift left / or right if "shift" is negative */
2366 static SwsVector *sws_getShiftedVec(SwsVector *a, int shift){
2367         int length= a->length + ABS(shift)*2;
2368         double *coeff= memalign(sizeof(double), length*sizeof(double));
2369         int i;
2370         SwsVector *vec= malloc(sizeof(SwsVector));
2371
2372         vec->coeff= coeff;
2373         vec->length= length;
2374
2375         for(i=0; i<length; i++) coeff[i]= 0.0;
2376
2377         for(i=0; i<a->length; i++)
2378         {
2379                 coeff[i + (length-1)/2 - (a->length-1)/2 - shift]= a->coeff[i];
2380         }
2381
2382         return vec;
2383 }
2384
2385 void sws_shiftVec(SwsVector *a, int shift){
2386         SwsVector *shifted= sws_getShiftedVec(a, shift);
2387         free(a->coeff);
2388         a->coeff= shifted->coeff;
2389         a->length= shifted->length;
2390         free(shifted);
2391 }
2392
2393 void sws_addVec(SwsVector *a, SwsVector *b){
2394         SwsVector *sum= sws_sumVec(a, b);
2395         free(a->coeff);
2396         a->coeff= sum->coeff;
2397         a->length= sum->length;
2398         free(sum);
2399 }
2400
2401 void sws_subVec(SwsVector *a, SwsVector *b){
2402         SwsVector *diff= sws_diffVec(a, b);
2403         free(a->coeff);
2404         a->coeff= diff->coeff;
2405         a->length= diff->length;
2406         free(diff);
2407 }
2408
2409 void sws_convVec(SwsVector *a, SwsVector *b){
2410         SwsVector *conv= sws_getConvVec(a, b);
2411         free(a->coeff);  
2412         a->coeff= conv->coeff;
2413         a->length= conv->length;
2414         free(conv);
2415 }
2416
2417 SwsVector *sws_cloneVec(SwsVector *a){
2418         double *coeff= memalign(sizeof(double), a->length*sizeof(double));
2419         int i;
2420         SwsVector *vec= malloc(sizeof(SwsVector));
2421
2422         vec->coeff= coeff;
2423         vec->length= a->length;
2424
2425         for(i=0; i<a->length; i++) coeff[i]= a->coeff[i];
2426
2427         return vec;
2428 }
2429
2430 void sws_printVec(SwsVector *a){
2431         int i;
2432         double max=0;
2433         double min=0;
2434         double range;
2435
2436         for(i=0; i<a->length; i++)
2437                 if(a->coeff[i]>max) max= a->coeff[i];
2438
2439         for(i=0; i<a->length; i++)
2440                 if(a->coeff[i]<min) min= a->coeff[i];
2441
2442         range= max - min;
2443
2444         for(i=0; i<a->length; i++)
2445         {
2446                 int x= (int)((a->coeff[i]-min)*60.0/range +0.5);
2447                 MSG_DBG2("%1.3f ", a->coeff[i]);
2448                 for(;x>0; x--) MSG_DBG2(" ");
2449                 MSG_DBG2("|\n");
2450         }
2451 }
2452
2453 void sws_freeVec(SwsVector *a){
2454         if(!a) return;
2455         if(a->coeff) free(a->coeff);
2456         a->coeff=NULL;
2457         a->length=0;
2458         free(a);
2459 }
2460
2461 void sws_freeFilter(SwsFilter *filter){
2462         if(!filter) return;
2463
2464         if(filter->lumH) sws_freeVec(filter->lumH);
2465         if(filter->lumV) sws_freeVec(filter->lumV);
2466         if(filter->chrH) sws_freeVec(filter->chrH);
2467         if(filter->chrV) sws_freeVec(filter->chrV);
2468         free(filter);
2469 }
2470
2471
2472 void sws_freeContext(SwsContext *c){
2473         int i;
2474         if(!c) return;
2475
2476         if(c->lumPixBuf)
2477         {
2478                 for(i=0; i<c->vLumBufSize; i++)
2479                 {
2480                         if(c->lumPixBuf[i]) free(c->lumPixBuf[i]);
2481                         c->lumPixBuf[i]=NULL;
2482                 }
2483                 free(c->lumPixBuf);
2484                 c->lumPixBuf=NULL;
2485         }
2486
2487         if(c->chrPixBuf)
2488         {
2489                 for(i=0; i<c->vChrBufSize; i++)
2490                 {
2491                         if(c->chrPixBuf[i]) free(c->chrPixBuf[i]);
2492                         c->chrPixBuf[i]=NULL;
2493                 }
2494                 free(c->chrPixBuf);
2495                 c->chrPixBuf=NULL;
2496         }
2497
2498         if(c->vLumFilter) free(c->vLumFilter);
2499         c->vLumFilter = NULL;
2500         if(c->vChrFilter) free(c->vChrFilter);
2501         c->vChrFilter = NULL;
2502         if(c->hLumFilter) free(c->hLumFilter);
2503         c->hLumFilter = NULL;
2504         if(c->hChrFilter) free(c->hChrFilter);
2505         c->hChrFilter = NULL;
2506
2507         if(c->vLumFilterPos) free(c->vLumFilterPos);
2508         c->vLumFilterPos = NULL;
2509         if(c->vChrFilterPos) free(c->vChrFilterPos);
2510         c->vChrFilterPos = NULL;
2511         if(c->hLumFilterPos) free(c->hLumFilterPos);
2512         c->hLumFilterPos = NULL;
2513         if(c->hChrFilterPos) free(c->hChrFilterPos);
2514         c->hChrFilterPos = NULL;
2515
2516         if(c->lumMmx2Filter) free(c->lumMmx2Filter);
2517         c->lumMmx2Filter=NULL;
2518         if(c->chrMmx2Filter) free(c->chrMmx2Filter);
2519         c->chrMmx2Filter=NULL;
2520         if(c->lumMmx2FilterPos) free(c->lumMmx2FilterPos);
2521         c->lumMmx2FilterPos=NULL;
2522         if(c->chrMmx2FilterPos) free(c->chrMmx2FilterPos);
2523         c->chrMmx2FilterPos=NULL;
2524         if(c->yuvTable) free(c->yuvTable);
2525         c->yuvTable=NULL;
2526
2527         free(c);
2528 }
2529