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