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