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