]> git.sesse.net Git - ffmpeg/blob - libavresample/resample.c
ffmpeg: doxyfy some comments and mention the timebase used in various timestamp fields.
[ffmpeg] / libavresample / resample.c
1 /*
2  * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
3  * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/libm.h"
23 #include "libavutil/log.h"
24 #include "internal.h"
25 #include "audio_data.h"
26
27 struct ResampleContext {
28     AVAudioResampleContext *avr;
29     AudioData *buffer;
30     uint8_t *filter_bank;
31     int filter_length;
32     int ideal_dst_incr;
33     int dst_incr;
34     int index;
35     int frac;
36     int src_incr;
37     int compensation_distance;
38     int phase_shift;
39     int phase_mask;
40     int linear;
41     enum AVResampleFilterType filter_type;
42     int kaiser_beta;
43     double factor;
44     void (*set_filter)(void *filter, double *tab, int phase, int tap_count);
45     void (*resample_one)(struct ResampleContext *c, int no_filter, void *dst0,
46                          int dst_index, const void *src0, int src_size,
47                          int index, int frac);
48 };
49
50
51 /* double template */
52 #define CONFIG_RESAMPLE_DBL
53 #include "resample_template.c"
54 #undef CONFIG_RESAMPLE_DBL
55
56 /* float template */
57 #define CONFIG_RESAMPLE_FLT
58 #include "resample_template.c"
59 #undef CONFIG_RESAMPLE_FLT
60
61 /* s32 template */
62 #define CONFIG_RESAMPLE_S32
63 #include "resample_template.c"
64 #undef CONFIG_RESAMPLE_S32
65
66 /* s16 template */
67 #include "resample_template.c"
68
69
70 /**
71  * 0th order modified bessel function of the first kind.
72  */
73 static double bessel(double x)
74 {
75     double v     = 1;
76     double lastv = 0;
77     double t     = 1;
78     int i;
79
80     x = x * x / 4;
81     for (i = 1; v != lastv; i++) {
82         lastv = v;
83         t    *= x / (i * i);
84         v    += t;
85     }
86     return v;
87 }
88
89 /**
90  * Build a polyphase filterbank.
91  *
92  * @param[out] filter       filter coefficients
93  * @param      factor       resampling factor
94  * @param      tap_count    tap count
95  * @param      phase_count  phase count
96  * @param      scale        wanted sum of coefficients for each filter
97  * @param      filter_type  filter type
98  * @param      kaiser_beta  kaiser window beta
99  * @return                  0 on success, negative AVERROR code on failure
100  */
101 static int build_filter(ResampleContext *c)
102 {
103     int ph, i;
104     double x, y, w, factor;
105     double *tab;
106     int tap_count    = c->filter_length;
107     int phase_count  = 1 << c->phase_shift;
108     const int center = (tap_count - 1) / 2;
109
110     tab = av_malloc(tap_count * sizeof(*tab));
111     if (!tab)
112         return AVERROR(ENOMEM);
113
114     /* if upsampling, only need to interpolate, no filter */
115     factor = FFMIN(c->factor, 1.0);
116
117     for (ph = 0; ph < phase_count; ph++) {
118         double norm = 0;
119         for (i = 0; i < tap_count; i++) {
120             x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
121             if (x == 0) y = 1.0;
122             else        y = sin(x) / x;
123             switch (c->filter_type) {
124             case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
125                 const float d = -0.5; //first order derivative = -0.5
126                 x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
127                 if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * (                -x*x + x*x*x);
128                 else         y =                           d * (-4 + 8 * x - 5 * x*x + x*x*x);
129                 break;
130             }
131             case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
132                 w  = 2.0 * x / (factor * tap_count) + M_PI;
133                 y *= 0.3635819 - 0.4891775 * cos(    w) +
134                                  0.1365995 * cos(2 * w) -
135                                  0.0106411 * cos(3 * w);
136                 break;
137             case AV_RESAMPLE_FILTER_TYPE_KAISER:
138                 w  = 2.0 * x / (factor * tap_count * M_PI);
139                 y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
140                 break;
141             }
142
143             tab[i] = y;
144             norm  += y;
145         }
146         /* normalize so that an uniform color remains the same */
147         for (i = 0; i < tap_count; i++)
148             tab[i] = tab[i] / norm;
149
150         c->set_filter(c->filter_bank, tab, ph, tap_count);
151     }
152
153     av_free(tab);
154     return 0;
155 }
156
157 ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
158 {
159     ResampleContext *c;
160     int out_rate    = avr->out_sample_rate;
161     int in_rate     = avr->in_sample_rate;
162     double factor   = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
163     int phase_count = 1 << avr->phase_shift;
164     int felem_size;
165
166     if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&
167         avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&
168         avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&
169         avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {
170         av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
171                "resampling: %s\n",
172                av_get_sample_fmt_name(avr->internal_sample_fmt));
173         return NULL;
174     }
175     c = av_mallocz(sizeof(*c));
176     if (!c)
177         return NULL;
178
179     c->avr           = avr;
180     c->phase_shift   = avr->phase_shift;
181     c->phase_mask    = phase_count - 1;
182     c->linear        = avr->linear_interp;
183     c->factor        = factor;
184     c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
185     c->filter_type   = avr->filter_type;
186     c->kaiser_beta   = avr->kaiser_beta;
187
188     switch (avr->internal_sample_fmt) {
189     case AV_SAMPLE_FMT_DBLP:
190         c->resample_one  = resample_one_dbl;
191         c->set_filter    = set_filter_dbl;
192         break;
193     case AV_SAMPLE_FMT_FLTP:
194         c->resample_one  = resample_one_flt;
195         c->set_filter    = set_filter_flt;
196         break;
197     case AV_SAMPLE_FMT_S32P:
198         c->resample_one  = resample_one_s32;
199         c->set_filter    = set_filter_s32;
200         break;
201     case AV_SAMPLE_FMT_S16P:
202         c->resample_one  = resample_one_s16;
203         c->set_filter    = set_filter_s16;
204         break;
205     }
206
207     felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
208     c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
209     if (!c->filter_bank)
210         goto error;
211
212     if (build_filter(c) < 0)
213         goto error;
214
215     memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],
216            c->filter_bank, (c->filter_length - 1) * felem_size);
217     memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],
218            &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);
219
220     c->compensation_distance = 0;
221     if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
222                    in_rate * (int64_t)phase_count, INT32_MAX / 2))
223         goto error;
224     c->ideal_dst_incr = c->dst_incr;
225
226     c->index = -phase_count * ((c->filter_length - 1) / 2);
227     c->frac  = 0;
228
229     /* allocate internal buffer */
230     c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
231                                     avr->internal_sample_fmt,
232                                     "resample buffer");
233     if (!c->buffer)
234         goto error;
235
236     av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
237            av_get_sample_fmt_name(avr->internal_sample_fmt),
238            avr->in_sample_rate, avr->out_sample_rate);
239
240     return c;
241
242 error:
243     ff_audio_data_free(&c->buffer);
244     av_free(c->filter_bank);
245     av_free(c);
246     return NULL;
247 }
248
249 void ff_audio_resample_free(ResampleContext **c)
250 {
251     if (!*c)
252         return;
253     ff_audio_data_free(&(*c)->buffer);
254     av_free((*c)->filter_bank);
255     av_freep(c);
256 }
257
258 int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
259                                 int compensation_distance)
260 {
261     ResampleContext *c;
262     AudioData *fifo_buf = NULL;
263     int ret = 0;
264
265     if (compensation_distance < 0)
266         return AVERROR(EINVAL);
267     if (!compensation_distance && sample_delta)
268         return AVERROR(EINVAL);
269
270     /* if resampling was not enabled previously, re-initialize the
271        AVAudioResampleContext and force resampling */
272     if (!avr->resample_needed) {
273         int fifo_samples;
274         double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
275
276         /* buffer any remaining samples in the output FIFO before closing */
277         fifo_samples = av_audio_fifo_size(avr->out_fifo);
278         if (fifo_samples > 0) {
279             fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
280                                            avr->out_sample_fmt, NULL);
281             if (!fifo_buf)
282                 return AVERROR(EINVAL);
283             ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
284                                                fifo_samples);
285             if (ret < 0)
286                 goto reinit_fail;
287         }
288         /* save the channel mixing matrix */
289         ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
290         if (ret < 0)
291             goto reinit_fail;
292
293         /* close the AVAudioResampleContext */
294         avresample_close(avr);
295
296         avr->force_resampling = 1;
297
298         /* restore the channel mixing matrix */
299         ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
300         if (ret < 0)
301             goto reinit_fail;
302
303         /* re-open the AVAudioResampleContext */
304         ret = avresample_open(avr);
305         if (ret < 0)
306             goto reinit_fail;
307
308         /* restore buffered samples to the output FIFO */
309         if (fifo_samples > 0) {
310             ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
311                                             fifo_samples);
312             if (ret < 0)
313                 goto reinit_fail;
314             ff_audio_data_free(&fifo_buf);
315         }
316     }
317     c = avr->resample;
318     c->compensation_distance = compensation_distance;
319     if (compensation_distance) {
320         c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
321                       (int64_t)sample_delta / compensation_distance;
322     } else {
323         c->dst_incr = c->ideal_dst_incr;
324     }
325     return 0;
326
327 reinit_fail:
328     ff_audio_data_free(&fifo_buf);
329     return ret;
330 }
331
332 static int resample(ResampleContext *c, void *dst, const void *src,
333                     int *consumed, int src_size, int dst_size, int update_ctx)
334 {
335     int dst_index;
336     int index         = c->index;
337     int frac          = c->frac;
338     int dst_incr_frac = c->dst_incr % c->src_incr;
339     int dst_incr      = c->dst_incr / c->src_incr;
340     int compensation_distance = c->compensation_distance;
341
342     if (!dst != !src)
343         return AVERROR(EINVAL);
344
345     if (compensation_distance == 0 && c->filter_length == 1 &&
346         c->phase_shift == 0) {
347         int64_t index2 = ((int64_t)index) << 32;
348         int64_t incr   = (1LL << 32) * c->dst_incr / c->src_incr;
349         dst_size       = FFMIN(dst_size,
350                                (src_size-1-index) * (int64_t)c->src_incr /
351                                c->dst_incr);
352
353         if (dst) {
354             for(dst_index = 0; dst_index < dst_size; dst_index++) {
355                 c->resample_one(c, 1, dst, dst_index, src, 0, index2 >> 32, 0);
356                 index2 += incr;
357             }
358         } else {
359             dst_index = dst_size;
360         }
361         index += dst_index * dst_incr;
362         index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
363         frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
364     } else {
365         for (dst_index = 0; dst_index < dst_size; dst_index++) {
366             int sample_index = index >> c->phase_shift;
367
368             if (sample_index + c->filter_length > src_size ||
369                 -sample_index >= src_size)
370                 break;
371
372             if (dst)
373                 c->resample_one(c, 0, dst, dst_index, src, src_size, index, frac);
374
375             frac  += dst_incr_frac;
376             index += dst_incr;
377             if (frac >= c->src_incr) {
378                 frac -= c->src_incr;
379                 index++;
380             }
381             if (dst_index + 1 == compensation_distance) {
382                 compensation_distance = 0;
383                 dst_incr_frac = c->ideal_dst_incr % c->src_incr;
384                 dst_incr      = c->ideal_dst_incr / c->src_incr;
385             }
386         }
387     }
388     if (consumed)
389         *consumed = FFMAX(index, 0) >> c->phase_shift;
390
391     if (update_ctx) {
392         if (index >= 0)
393             index &= c->phase_mask;
394
395         if (compensation_distance) {
396             compensation_distance -= dst_index;
397             if (compensation_distance <= 0)
398                 return AVERROR_BUG;
399         }
400         c->frac     = frac;
401         c->index    = index;
402         c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
403         c->compensation_distance = compensation_distance;
404     }
405
406     return dst_index;
407 }
408
409 int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
410                       int *consumed)
411 {
412     int ch, in_samples, in_leftover, out_samples = 0;
413     int ret = AVERROR(EINVAL);
414
415     in_samples  = src ? src->nb_samples : 0;
416     in_leftover = c->buffer->nb_samples;
417
418     /* add input samples to the internal buffer */
419     if (src) {
420         ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
421         if (ret < 0)
422             return ret;
423     } else if (!in_leftover) {
424         /* no remaining samples to flush */
425         return 0;
426     } else {
427         /* TODO: pad buffer to flush completely */
428     }
429
430     /* calculate output size and reallocate output buffer if needed */
431     /* TODO: try to calculate this without the dummy resample() run */
432     if (!dst->read_only && dst->allow_realloc) {
433         out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
434                                INT_MAX, 0);
435         ret = ff_audio_data_realloc(dst, out_samples);
436         if (ret < 0) {
437             av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
438             return ret;
439         }
440     }
441
442     /* resample each channel plane */
443     for (ch = 0; ch < c->buffer->channels; ch++) {
444         out_samples = resample(c, (void *)dst->data[ch],
445                                (const void *)c->buffer->data[ch], consumed,
446                                c->buffer->nb_samples, dst->allocated_samples,
447                                ch + 1 == c->buffer->channels);
448     }
449     if (out_samples < 0) {
450         av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
451         return out_samples;
452     }
453
454     /* drain consumed samples from the internal buffer */
455     ff_audio_data_drain(c->buffer, *consumed);
456
457     av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
458             in_samples, in_leftover, out_samples, c->buffer->nb_samples);
459
460     dst->nb_samples = out_samples;
461     return 0;
462 }
463
464 int avresample_get_delay(AVAudioResampleContext *avr)
465 {
466     if (!avr->resample_needed || !avr->resample)
467         return 0;
468
469     return avr->resample->buffer->nb_samples;
470 }