2 * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
3 * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
5 * This file is part of Libav.
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.
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.
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
22 #include "libavutil/libm.h"
23 #include "libavutil/log.h"
25 #include "audio_data.h"
27 #ifdef CONFIG_RESAMPLE_FLT
29 #define FILTER_SHIFT 0
33 #define WINDOW_TYPE 24
34 #elifdef CONFIG_RESAMPLE_S32
36 #define FILTER_SHIFT 30
38 #define FELEM2 int64_t
39 #define FELEML int64_t
40 #define FELEM_MAX INT32_MAX
41 #define FELEM_MIN INT32_MIN
42 #define WINDOW_TYPE 12
45 #define FILTER_SHIFT 15
47 #define FELEM2 int32_t
48 #define FELEML int64_t
49 #define FELEM_MAX INT16_MAX
50 #define FELEM_MIN INT16_MIN
54 struct ResampleContext {
55 AVAudioResampleContext *avr;
64 int compensation_distance;
72 * 0th order modified bessel function of the first kind.
74 static double bessel(double x)
82 for (i = 1; v != lastv; i++) {
91 * Build a polyphase filterbank.
93 * @param[out] filter filter coefficients
94 * @param factor resampling factor
95 * @param tap_count tap count
96 * @param phase_count phase count
97 * @param scale wanted sum of coefficients for each filter
98 * @param type 0->cubic
99 * 1->blackman nuttall windowed sinc
100 * 2..16->kaiser windowed sinc beta=2..16
101 * @return 0 on success, negative AVERROR code on failure
103 static int build_filter(FELEM *filter, double factor, int tap_count,
104 int phase_count, int scale, int type)
109 const int center = (tap_count - 1) / 2;
111 tab = av_malloc(tap_count * sizeof(*tab));
113 return AVERROR(ENOMEM);
115 /* if upsampling, only need to interpolate, no filter */
119 for (ph = 0; ph < phase_count; ph++) {
121 for (i = 0; i < tap_count; i++) {
122 x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
127 const float d = -0.5; //first order derivative = -0.5
128 x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
129 if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * ( -x*x + x*x*x);
130 else y = d * (-4 + 8 * x - 5 * x*x + x*x*x);
134 w = 2.0 * x / (factor * tap_count) + M_PI;
135 y *= 0.3635819 - 0.4891775 * cos( w) +
136 0.1365995 * cos(2 * w) -
137 0.0106411 * cos(3 * w);
140 w = 2.0 * x / (factor * tap_count * M_PI);
141 y *= bessel(type * sqrt(FFMAX(1 - w * w, 0)));
149 /* normalize so that an uniform color remains the same */
150 for (i = 0; i < tap_count; i++) {
151 #ifdef CONFIG_RESAMPLE_FLT
152 filter[ph * tap_count + i] = tab[i] / norm;
154 filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm),
155 FELEM_MIN, FELEM_MAX);
164 ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
167 int out_rate = avr->out_sample_rate;
168 int in_rate = avr->in_sample_rate;
169 double factor = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
170 int phase_count = 1 << avr->phase_shift;
172 /* TODO: add support for s32 and float internal formats */
173 if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P) {
174 av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
176 av_get_sample_fmt_name(avr->internal_sample_fmt));
179 c = av_mallocz(sizeof(*c));
184 c->phase_shift = avr->phase_shift;
185 c->phase_mask = phase_count - 1;
186 c->linear = avr->linear_interp;
188 c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
190 c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * sizeof(FELEM));
194 if (build_filter(c->filter_bank, factor, c->filter_length, phase_count,
195 1 << FILTER_SHIFT, WINDOW_TYPE) < 0)
198 memcpy(&c->filter_bank[c->filter_length * phase_count + 1],
199 c->filter_bank, (c->filter_length - 1) * sizeof(FELEM));
200 c->filter_bank[c->filter_length * phase_count] = c->filter_bank[c->filter_length - 1];
202 c->compensation_distance = 0;
203 if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
204 in_rate * (int64_t)phase_count, INT32_MAX / 2))
206 c->ideal_dst_incr = c->dst_incr;
208 c->index = -phase_count * ((c->filter_length - 1) / 2);
211 /* allocate internal buffer */
212 c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
213 avr->internal_sample_fmt,
218 av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
219 av_get_sample_fmt_name(avr->internal_sample_fmt),
220 avr->in_sample_rate, avr->out_sample_rate);
225 ff_audio_data_free(&c->buffer);
226 av_free(c->filter_bank);
231 void ff_audio_resample_free(ResampleContext **c)
235 ff_audio_data_free(&(*c)->buffer);
236 av_free((*c)->filter_bank);
240 int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
241 int compensation_distance)
244 AudioData *fifo_buf = NULL;
247 if (compensation_distance < 0)
248 return AVERROR(EINVAL);
249 if (!compensation_distance && sample_delta)
250 return AVERROR(EINVAL);
252 /* if resampling was not enabled previously, re-initialize the
253 AVAudioResampleContext and force resampling */
254 if (!avr->resample_needed) {
256 double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
258 /* buffer any remaining samples in the output FIFO before closing */
259 fifo_samples = av_audio_fifo_size(avr->out_fifo);
260 if (fifo_samples > 0) {
261 fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
262 avr->out_sample_fmt, NULL);
264 return AVERROR(EINVAL);
265 ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
270 /* save the channel mixing matrix */
271 ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
275 /* close the AVAudioResampleContext */
276 avresample_close(avr);
278 avr->force_resampling = 1;
280 /* restore the channel mixing matrix */
281 ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
285 /* re-open the AVAudioResampleContext */
286 ret = avresample_open(avr);
290 /* restore buffered samples to the output FIFO */
291 if (fifo_samples > 0) {
292 ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
296 ff_audio_data_free(&fifo_buf);
300 c->compensation_distance = compensation_distance;
301 if (compensation_distance) {
302 c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
303 (int64_t)sample_delta / compensation_distance;
305 c->dst_incr = c->ideal_dst_incr;
310 ff_audio_data_free(&fifo_buf);
314 static int resample(ResampleContext *c, int16_t *dst, const int16_t *src,
315 int *consumed, int src_size, int dst_size, int update_ctx)
318 int index = c->index;
320 int dst_incr_frac = c->dst_incr % c->src_incr;
321 int dst_incr = c->dst_incr / c->src_incr;
322 int compensation_distance = c->compensation_distance;
325 return AVERROR(EINVAL);
327 if (compensation_distance == 0 && c->filter_length == 1 &&
328 c->phase_shift == 0) {
329 int64_t index2 = ((int64_t)index) << 32;
330 int64_t incr = (1LL << 32) * c->dst_incr / c->src_incr;
331 dst_size = FFMIN(dst_size,
332 (src_size-1-index) * (int64_t)c->src_incr /
336 for(dst_index = 0; dst_index < dst_size; dst_index++) {
337 dst[dst_index] = src[index2 >> 32];
341 dst_index = dst_size;
343 index += dst_index * dst_incr;
344 index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
345 frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
347 for (dst_index = 0; dst_index < dst_size; dst_index++) {
348 FELEM *filter = c->filter_bank +
349 c->filter_length * (index & c->phase_mask);
350 int sample_index = index >> c->phase_shift;
352 if (!dst && (sample_index + c->filter_length > src_size ||
353 -sample_index >= src_size))
359 if (sample_index < 0) {
360 for (i = 0; i < c->filter_length; i++)
361 val += src[FFABS(sample_index + i) % src_size] *
363 } else if (sample_index + c->filter_length > src_size) {
365 } else if (c->linear) {
367 for (i = 0; i < c->filter_length; i++) {
368 val += src[abs(sample_index + i)] * (FELEM2)filter[i];
369 v2 += src[abs(sample_index + i)] * (FELEM2)filter[i + c->filter_length];
371 val += (v2 - val) * (FELEML)frac / c->src_incr;
373 for (i = 0; i < c->filter_length; i++)
374 val += src[sample_index + i] * (FELEM2)filter[i];
377 #ifdef CONFIG_RESAMPLE_FLT
378 dst[dst_index] = av_clip_int16(lrintf(val));
380 val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
381 dst[dst_index] = av_clip_int16(val);
385 frac += dst_incr_frac;
387 if (frac >= c->src_incr) {
391 if (dst_index + 1 == compensation_distance) {
392 compensation_distance = 0;
393 dst_incr_frac = c->ideal_dst_incr % c->src_incr;
394 dst_incr = c->ideal_dst_incr / c->src_incr;
399 *consumed = FFMAX(index, 0) >> c->phase_shift;
403 index &= c->phase_mask;
405 if (compensation_distance) {
406 compensation_distance -= dst_index;
407 if (compensation_distance <= 0)
412 c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
413 c->compensation_distance = compensation_distance;
419 int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
422 int ch, in_samples, in_leftover, out_samples = 0;
423 int ret = AVERROR(EINVAL);
425 in_samples = src ? src->nb_samples : 0;
426 in_leftover = c->buffer->nb_samples;
428 /* add input samples to the internal buffer */
430 ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
433 } else if (!in_leftover) {
434 /* no remaining samples to flush */
437 /* TODO: pad buffer to flush completely */
440 /* calculate output size and reallocate output buffer if needed */
441 /* TODO: try to calculate this without the dummy resample() run */
442 if (!dst->read_only && dst->allow_realloc) {
443 out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
445 ret = ff_audio_data_realloc(dst, out_samples);
447 av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
452 /* resample each channel plane */
453 for (ch = 0; ch < c->buffer->channels; ch++) {
454 out_samples = resample(c, (int16_t *)dst->data[ch],
455 (const int16_t *)c->buffer->data[ch], consumed,
456 c->buffer->nb_samples, dst->allocated_samples,
457 ch + 1 == c->buffer->channels);
459 if (out_samples < 0) {
460 av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
464 /* drain consumed samples from the internal buffer */
465 ff_audio_data_drain(c->buffer, *consumed);
467 av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
468 in_samples, in_leftover, out_samples, c->buffer->nb_samples);
470 dst->nb_samples = out_samples;
474 int avresample_get_delay(AVAudioResampleContext *avr)
476 if (!avr->resample_needed || !avr->resample)
479 return avr->resample->buffer->nb_samples;