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