]> git.sesse.net Git - ffmpeg/blob - libavcodec/resample2.c
Remove redundant #inclusion of common.h, avcodec.h already #includes it.
[ffmpeg] / libavcodec / resample2.c
1 /*
2  * audio resampling
3  * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  *
21  */
22
23 /**
24  * @file resample2.c
25  * audio resampling
26  * @author Michael Niedermayer <michaelni@gmx.at>
27  */
28
29 #include "avcodec.h"
30 #include "dsputil.h"
31
32 #ifndef CONFIG_RESAMPLE_HP
33 #define FILTER_SHIFT 15
34
35 #define FELEM int16_t
36 #define FELEM2 int32_t
37 #define FELEML int64_t
38 #define FELEM_MAX INT16_MAX
39 #define FELEM_MIN INT16_MIN
40 #define WINDOW_TYPE 9
41 #elif !defined(CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE)
42 #define FILTER_SHIFT 30
43
44 #define FELEM int32_t
45 #define FELEM2 int64_t
46 #define FELEML int64_t
47 #define FELEM_MAX INT32_MAX
48 #define FELEM_MIN INT32_MIN
49 #define WINDOW_TYPE 12
50 #else
51 #define FILTER_SHIFT 0
52
53 #define FELEM double
54 #define FELEM2 double
55 #define FELEML double
56 #define WINDOW_TYPE 24
57 #endif
58
59
60 typedef struct AVResampleContext{
61     FELEM *filter_bank;
62     int filter_length;
63     int ideal_dst_incr;
64     int dst_incr;
65     int index;
66     int frac;
67     int src_incr;
68     int compensation_distance;
69     int phase_shift;
70     int phase_mask;
71     int linear;
72 }AVResampleContext;
73
74 /**
75  * 0th order modified bessel function of the first kind.
76  */
77 static double bessel(double x){
78     double v=1;
79     double t=1;
80     int i;
81
82     x= x*x/4;
83     for(i=1; i<50; i++){
84         t *= x/(i*i);
85         v += t;
86     }
87     return v;
88 }
89
90 /**
91  * builds a polyphase filterbank.
92  * @param factor resampling factor
93  * @param scale wanted sum of coefficients for each filter
94  * @param type 0->cubic, 1->blackman nuttall windowed sinc, 2..16->kaiser windowed sinc beta=2..16
95  */
96 void av_build_filter(FELEM *filter, double factor, int tap_count, int phase_count, int scale, int type){
97     int ph, i;
98     double x, y, w, tab[tap_count];
99     const int center= (tap_count-1)/2;
100
101     /* if upsampling, only need to interpolate, no filter */
102     if (factor > 1.0)
103         factor = 1.0;
104
105     for(ph=0;ph<phase_count;ph++) {
106         double norm = 0;
107         for(i=0;i<tap_count;i++) {
108             x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
109             if (x == 0) y = 1.0;
110             else        y = sin(x) / x;
111             switch(type){
112             case 0:{
113                 const float d= -0.5; //first order derivative = -0.5
114                 x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
115                 if(x<1.0) y= 1 - 3*x*x + 2*x*x*x + d*(            -x*x + x*x*x);
116                 else      y=                       d*(-4 + 8*x - 5*x*x + x*x*x);
117                 break;}
118             case 1:
119                 w = 2.0*x / (factor*tap_count) + M_PI;
120                 y *= 0.3635819 - 0.4891775 * cos(w) + 0.1365995 * cos(2*w) - 0.0106411 * cos(3*w);
121                 break;
122             default:
123                 w = 2.0*x / (factor*tap_count*M_PI);
124                 y *= bessel(type*sqrt(FFMAX(1-w*w, 0)));
125                 break;
126             }
127
128             tab[i] = y;
129             norm += y;
130         }
131
132         /* normalize so that an uniform color remains the same */
133         for(i=0;i<tap_count;i++) {
134 #ifdef CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE
135             filter[ph * tap_count + i] = tab[i] / norm;
136 #else
137             filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm), FELEM_MIN, FELEM_MAX);
138 #endif
139         }
140     }
141 #if 0
142     {
143 #define LEN 1024
144         int j,k;
145         double sine[LEN + tap_count];
146         double filtered[LEN];
147         double maxff=-2, minff=2, maxsf=-2, minsf=2;
148         for(i=0; i<LEN; i++){
149             double ss=0, sf=0, ff=0;
150             for(j=0; j<LEN+tap_count; j++)
151                 sine[j]= cos(i*j*M_PI/LEN);
152             for(j=0; j<LEN; j++){
153                 double sum=0;
154                 ph=0;
155                 for(k=0; k<tap_count; k++)
156                     sum += filter[ph * tap_count + k] * sine[k+j];
157                 filtered[j]= sum / (1<<FILTER_SHIFT);
158                 ss+= sine[j + center] * sine[j + center];
159                 ff+= filtered[j] * filtered[j];
160                 sf+= sine[j + center] * filtered[j];
161             }
162             ss= sqrt(2*ss/LEN);
163             ff= sqrt(2*ff/LEN);
164             sf= 2*sf/LEN;
165             maxff= FFMAX(maxff, ff);
166             minff= FFMIN(minff, ff);
167             maxsf= FFMAX(maxsf, sf);
168             minsf= FFMIN(minsf, sf);
169             if(i%11==0){
170                 av_log(NULL, AV_LOG_ERROR, "i:%4d ss:%f ff:%13.6e-%13.6e sf:%13.6e-%13.6e\n", i, ss, maxff, minff, maxsf, minsf);
171                 minff=minsf= 2;
172                 maxff=maxsf= -2;
173             }
174         }
175     }
176 #endif
177 }
178
179 /**
180  * initalizes a audio resampler.
181  * note, if either rate is not a integer then simply scale both rates up so they are
182  */
183 AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff){
184     AVResampleContext *c= av_mallocz(sizeof(AVResampleContext));
185     double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);
186     int phase_count= 1<<phase_shift;
187
188     c->phase_shift= phase_shift;
189     c->phase_mask= phase_count-1;
190     c->linear= linear;
191
192     c->filter_length= FFMAX((int)ceil(filter_size/factor), 1);
193     c->filter_bank= av_mallocz(c->filter_length*(phase_count+1)*sizeof(FELEM));
194     av_build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, WINDOW_TYPE);
195     memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));
196     c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];
197
198     c->src_incr= out_rate;
199     c->ideal_dst_incr= c->dst_incr= in_rate * phase_count;
200     c->index= -phase_count*((c->filter_length-1)/2);
201
202     return c;
203 }
204
205 void av_resample_close(AVResampleContext *c){
206     av_freep(&c->filter_bank);
207     av_freep(&c);
208 }
209
210 /**
211  * Compensates samplerate/timestamp drift. The compensation is done by changing
212  * the resampler parameters, so no audible clicks or similar distortions ocur
213  * @param compensation_distance distance in output samples over which the compensation should be performed
214  * @param sample_delta number of output samples which should be output less
215  *
216  * example: av_resample_compensate(c, 10, 500)
217  * here instead of 510 samples only 500 samples would be output
218  *
219  * note, due to rounding the actual compensation might be slightly different,
220  * especially if the compensation_distance is large and the in_rate used during init is small
221  */
222 void av_resample_compensate(AVResampleContext *c, int sample_delta, int compensation_distance){
223 //    sample_delta += (c->ideal_dst_incr - c->dst_incr)*(int64_t)c->compensation_distance / c->ideal_dst_incr;
224     c->compensation_distance= compensation_distance;
225     c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr * (int64_t)sample_delta / compensation_distance;
226 }
227
228 /**
229  * resamples.
230  * @param src an array of unconsumed samples
231  * @param consumed the number of samples of src which have been consumed are returned here
232  * @param src_size the number of unconsumed samples available
233  * @param dst_size the amount of space in samples available in dst
234  * @param update_ctx if this is 0 then the context wont be modified, that way several channels can be resampled with the same context
235  * @return the number of samples written in dst or -1 if an error occured
236  */
237 int av_resample(AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx){
238     int dst_index, i;
239     int index= c->index;
240     int frac= c->frac;
241     int dst_incr_frac= c->dst_incr % c->src_incr;
242     int dst_incr=      c->dst_incr / c->src_incr;
243     int compensation_distance= c->compensation_distance;
244
245   if(compensation_distance == 0 && c->filter_length == 1 && c->phase_shift==0){
246         int64_t index2= ((int64_t)index)<<32;
247         int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;
248         dst_size= FFMIN(dst_size, (src_size-1-index) * (int64_t)c->src_incr / c->dst_incr);
249
250         for(dst_index=0; dst_index < dst_size; dst_index++){
251             dst[dst_index] = src[index2>>32];
252             index2 += incr;
253         }
254         frac += dst_index * dst_incr_frac;
255         index += dst_index * dst_incr;
256         index += frac / c->src_incr;
257         frac %= c->src_incr;
258   }else{
259     for(dst_index=0; dst_index < dst_size; dst_index++){
260         FELEM *filter= c->filter_bank + c->filter_length*(index & c->phase_mask);
261         int sample_index= index >> c->phase_shift;
262         FELEM2 val=0;
263
264         if(sample_index < 0){
265             for(i=0; i<c->filter_length; i++)
266                 val += src[FFABS(sample_index + i) % src_size] * filter[i];
267         }else if(sample_index + c->filter_length > src_size){
268             break;
269         }else if(c->linear){
270             FELEM2 v2=0;
271             for(i=0; i<c->filter_length; i++){
272                 val += src[sample_index + i] * (FELEM2)filter[i];
273                 v2  += src[sample_index + i] * (FELEM2)filter[i + c->filter_length];
274             }
275             val+=(v2-val)*(FELEML)frac / c->src_incr;
276         }else{
277             for(i=0; i<c->filter_length; i++){
278                 val += src[sample_index + i] * (FELEM2)filter[i];
279             }
280         }
281
282 #ifdef CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE
283         dst[dst_index] = av_clip(lrintf(val), -32768, 32767);
284 #else
285         val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
286         dst[dst_index] = (unsigned)(val + 32768) > 65535 ? (val>>31) ^ 32767 : val;
287 #endif
288
289         frac += dst_incr_frac;
290         index += dst_incr;
291         if(frac >= c->src_incr){
292             frac -= c->src_incr;
293             index++;
294         }
295
296         if(dst_index + 1 == compensation_distance){
297             compensation_distance= 0;
298             dst_incr_frac= c->ideal_dst_incr % c->src_incr;
299             dst_incr=      c->ideal_dst_incr / c->src_incr;
300         }
301     }
302   }
303     *consumed= FFMAX(index, 0) >> c->phase_shift;
304     if(index>=0) index &= c->phase_mask;
305
306     if(compensation_distance){
307         compensation_distance -= dst_index;
308         assert(compensation_distance > 0);
309     }
310     if(update_ctx){
311         c->frac= frac;
312         c->index= index;
313         c->dst_incr= dst_incr_frac + c->src_incr*dst_incr;
314         c->compensation_distance= compensation_distance;
315     }
316 #if 0
317     if(update_ctx && !c->compensation_distance){
318 #undef rand
319         av_resample_compensate(c, rand() % (8000*2) - 8000, 8000*2);
320 av_log(NULL, AV_LOG_DEBUG, "%d %d %d\n", c->dst_incr, c->ideal_dst_incr, c->compensation_distance);
321     }
322 #endif
323
324     return dst_index;
325 }