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