lavr: resampling: add filter type and Kaiser window beta to AVOptions
[libav.git] / libavresample / resample.c
CommitLineData
c8af852b
JR
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#ifdef CONFIG_RESAMPLE_FLT
28/* float template */
29#define FILTER_SHIFT 0
30#define FELEM float
31#define FELEM2 float
32#define FELEML float
c8af852b
JR
33#elifdef CONFIG_RESAMPLE_S32
34/* s32 template */
35#define FILTER_SHIFT 30
36#define FELEM int32_t
37#define FELEM2 int64_t
38#define FELEML int64_t
39#define FELEM_MAX INT32_MAX
40#define FELEM_MIN INT32_MIN
c8af852b
JR
41#else
42/* s16 template */
43#define FILTER_SHIFT 15
44#define FELEM int16_t
45#define FELEM2 int32_t
46#define FELEML int64_t
47#define FELEM_MAX INT16_MAX
48#define FELEM_MIN INT16_MIN
c8af852b
JR
49#endif
50
51struct ResampleContext {
52 AVAudioResampleContext *avr;
53 AudioData *buffer;
54 FELEM *filter_bank;
55 int filter_length;
56 int ideal_dst_incr;
57 int dst_incr;
58 int index;
59 int frac;
60 int src_incr;
61 int compensation_distance;
62 int phase_shift;
63 int phase_mask;
64 int linear;
372647ae
JR
65 enum AVResampleFilterType filter_type;
66 int kaiser_beta;
c8af852b
JR
67 double factor;
68};
69
70/**
71 * 0th order modified bessel function of the first kind.
72 */
73static 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
372647ae
JR
97 * @param filter_type filter type
98 * @param kaiser_beta kaiser window beta
c8af852b
JR
99 * @return 0 on success, negative AVERROR code on failure
100 */
101static int build_filter(FELEM *filter, double factor, int tap_count,
372647ae
JR
102 int phase_count, int scale, int filter_type,
103 int kaiser_beta)
c8af852b
JR
104{
105 int ph, i;
106 double x, y, w;
107 double *tab;
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 if (factor > 1.0)
116 factor = 1.0;
117
118 for (ph = 0; ph < phase_count; ph++) {
119 double norm = 0;
120 for (i = 0; i < tap_count; i++) {
121 x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
122 if (x == 0) y = 1.0;
123 else y = sin(x) / x;
372647ae
JR
124 switch (filter_type) {
125 case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
c8af852b
JR
126 const float d = -0.5; //first order derivative = -0.5
127 x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
128 if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * ( -x*x + x*x*x);
129 else y = d * (-4 + 8 * x - 5 * x*x + x*x*x);
130 break;
131 }
372647ae 132 case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
c8af852b
JR
133 w = 2.0 * x / (factor * tap_count) + M_PI;
134 y *= 0.3635819 - 0.4891775 * cos( w) +
135 0.1365995 * cos(2 * w) -
136 0.0106411 * cos(3 * w);
137 break;
372647ae 138 case AV_RESAMPLE_FILTER_TYPE_KAISER:
c8af852b 139 w = 2.0 * x / (factor * tap_count * M_PI);
372647ae 140 y *= bessel(kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
c8af852b
JR
141 break;
142 }
143
144 tab[i] = y;
145 norm += y;
146 }
147
148 /* normalize so that an uniform color remains the same */
149 for (i = 0; i < tap_count; i++) {
150#ifdef CONFIG_RESAMPLE_FLT
151 filter[ph * tap_count + i] = tab[i] / norm;
152#else
153 filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm),
154 FELEM_MIN, FELEM_MAX);
155#endif
156 }
157 }
158
159 av_free(tab);
160 return 0;
161}
162
163ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
164{
165 ResampleContext *c;
166 int out_rate = avr->out_sample_rate;
167 int in_rate = avr->in_sample_rate;
168 double factor = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
169 int phase_count = 1 << avr->phase_shift;
170
171 /* TODO: add support for s32 and float internal formats */
172 if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P) {
173 av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
174 "resampling: %s\n",
175 av_get_sample_fmt_name(avr->internal_sample_fmt));
176 return NULL;
177 }
178 c = av_mallocz(sizeof(*c));
179 if (!c)
180 return NULL;
181
182 c->avr = avr;
183 c->phase_shift = avr->phase_shift;
184 c->phase_mask = phase_count - 1;
185 c->linear = avr->linear_interp;
186 c->factor = factor;
187 c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
372647ae
JR
188 c->filter_type = avr->filter_type;
189 c->kaiser_beta = avr->kaiser_beta;
c8af852b
JR
190
191 c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * sizeof(FELEM));
192 if (!c->filter_bank)
193 goto error;
194
195 if (build_filter(c->filter_bank, factor, c->filter_length, phase_count,
372647ae 196 1 << FILTER_SHIFT, c->filter_type, c->kaiser_beta) < 0)
c8af852b
JR
197 goto error;
198
199 memcpy(&c->filter_bank[c->filter_length * phase_count + 1],
200 c->filter_bank, (c->filter_length - 1) * sizeof(FELEM));
201 c->filter_bank[c->filter_length * phase_count] = c->filter_bank[c->filter_length - 1];
202
203 c->compensation_distance = 0;
204 if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
205 in_rate * (int64_t)phase_count, INT32_MAX / 2))
206 goto error;
207 c->ideal_dst_incr = c->dst_incr;
208
209 c->index = -phase_count * ((c->filter_length - 1) / 2);
210 c->frac = 0;
211
212 /* allocate internal buffer */
213 c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
214 avr->internal_sample_fmt,
215 "resample buffer");
216 if (!c->buffer)
217 goto error;
218
219 av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
220 av_get_sample_fmt_name(avr->internal_sample_fmt),
221 avr->in_sample_rate, avr->out_sample_rate);
222
223 return c;
224
225error:
226 ff_audio_data_free(&c->buffer);
227 av_free(c->filter_bank);
228 av_free(c);
229 return NULL;
230}
231
232void ff_audio_resample_free(ResampleContext **c)
233{
234 if (!*c)
235 return;
236 ff_audio_data_free(&(*c)->buffer);
237 av_free((*c)->filter_bank);
238 av_freep(c);
239}
240
241int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
242 int compensation_distance)
243{
244 ResampleContext *c;
245 AudioData *fifo_buf = NULL;
246 int ret = 0;
247
248 if (compensation_distance < 0)
249 return AVERROR(EINVAL);
250 if (!compensation_distance && sample_delta)
251 return AVERROR(EINVAL);
252
253 /* if resampling was not enabled previously, re-initialize the
254 AVAudioResampleContext and force resampling */
255 if (!avr->resample_needed) {
256 int fifo_samples;
257 double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
258
259 /* buffer any remaining samples in the output FIFO before closing */
260 fifo_samples = av_audio_fifo_size(avr->out_fifo);
261 if (fifo_samples > 0) {
262 fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
263 avr->out_sample_fmt, NULL);
264 if (!fifo_buf)
265 return AVERROR(EINVAL);
266 ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
267 fifo_samples);
268 if (ret < 0)
269 goto reinit_fail;
270 }
271 /* save the channel mixing matrix */
272 ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
273 if (ret < 0)
274 goto reinit_fail;
275
276 /* close the AVAudioResampleContext */
277 avresample_close(avr);
278
279 avr->force_resampling = 1;
280
281 /* restore the channel mixing matrix */
282 ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
283 if (ret < 0)
284 goto reinit_fail;
285
286 /* re-open the AVAudioResampleContext */
287 ret = avresample_open(avr);
288 if (ret < 0)
289 goto reinit_fail;
290
291 /* restore buffered samples to the output FIFO */
292 if (fifo_samples > 0) {
293 ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
294 fifo_samples);
295 if (ret < 0)
296 goto reinit_fail;
297 ff_audio_data_free(&fifo_buf);
298 }
299 }
300 c = avr->resample;
301 c->compensation_distance = compensation_distance;
302 if (compensation_distance) {
303 c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
304 (int64_t)sample_delta / compensation_distance;
305 } else {
306 c->dst_incr = c->ideal_dst_incr;
307 }
308 return 0;
309
310reinit_fail:
311 ff_audio_data_free(&fifo_buf);
312 return ret;
313}
314
315static int resample(ResampleContext *c, int16_t *dst, const int16_t *src,
316 int *consumed, int src_size, int dst_size, int update_ctx)
317{
318 int dst_index, i;
319 int index = c->index;
320 int frac = c->frac;
321 int dst_incr_frac = c->dst_incr % c->src_incr;
322 int dst_incr = c->dst_incr / c->src_incr;
323 int compensation_distance = c->compensation_distance;
324
325 if (!dst != !src)
326 return AVERROR(EINVAL);
327
328 if (compensation_distance == 0 && c->filter_length == 1 &&
329 c->phase_shift == 0) {
330 int64_t index2 = ((int64_t)index) << 32;
331 int64_t incr = (1LL << 32) * c->dst_incr / c->src_incr;
332 dst_size = FFMIN(dst_size,
333 (src_size-1-index) * (int64_t)c->src_incr /
334 c->dst_incr);
335
336 if (dst) {
337 for(dst_index = 0; dst_index < dst_size; dst_index++) {
338 dst[dst_index] = src[index2 >> 32];
339 index2 += incr;
340 }
341 } else {
342 dst_index = dst_size;
343 }
344 index += dst_index * dst_incr;
345 index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
346 frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
347 } else {
348 for (dst_index = 0; dst_index < dst_size; dst_index++) {
349 FELEM *filter = c->filter_bank +
350 c->filter_length * (index & c->phase_mask);
351 int sample_index = index >> c->phase_shift;
352
353 if (!dst && (sample_index + c->filter_length > src_size ||
354 -sample_index >= src_size))
355 break;
356
357 if (dst) {
358 FELEM2 val = 0;
359
360 if (sample_index < 0) {
361 for (i = 0; i < c->filter_length; i++)
362 val += src[FFABS(sample_index + i) % src_size] *
363 (FELEM2)filter[i];
364 } else if (sample_index + c->filter_length > src_size) {
365 break;
366 } else if (c->linear) {
367 FELEM2 v2 = 0;
368 for (i = 0; i < c->filter_length; i++) {
369 val += src[abs(sample_index + i)] * (FELEM2)filter[i];
370 v2 += src[abs(sample_index + i)] * (FELEM2)filter[i + c->filter_length];
371 }
372 val += (v2 - val) * (FELEML)frac / c->src_incr;
373 } else {
374 for (i = 0; i < c->filter_length; i++)
375 val += src[sample_index + i] * (FELEM2)filter[i];
376 }
377
378#ifdef CONFIG_RESAMPLE_FLT
379 dst[dst_index] = av_clip_int16(lrintf(val));
380#else
381 val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
382 dst[dst_index] = av_clip_int16(val);
383#endif
384 }
385
386 frac += dst_incr_frac;
387 index += dst_incr;
388 if (frac >= c->src_incr) {
389 frac -= c->src_incr;
390 index++;
391 }
392 if (dst_index + 1 == compensation_distance) {
393 compensation_distance = 0;
394 dst_incr_frac = c->ideal_dst_incr % c->src_incr;
395 dst_incr = c->ideal_dst_incr / c->src_incr;
396 }
397 }
398 }
399 if (consumed)
400 *consumed = FFMAX(index, 0) >> c->phase_shift;
401
402 if (update_ctx) {
403 if (index >= 0)
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
420int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
421 int *consumed)
422{
423 int ch, in_samples, in_leftover, out_samples = 0;
424 int ret = AVERROR(EINVAL);
425
426 in_samples = src ? src->nb_samples : 0;
427 in_leftover = c->buffer->nb_samples;
428
429 /* add input samples to the internal buffer */
430 if (src) {
431 ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
432 if (ret < 0)
433 return ret;
434 } else if (!in_leftover) {
435 /* no remaining samples to flush */
436 return 0;
437 } else {
438 /* TODO: pad buffer to flush completely */
439 }
440
441 /* calculate output size and reallocate output buffer if needed */
442 /* TODO: try to calculate this without the dummy resample() run */
443 if (!dst->read_only && dst->allow_realloc) {
444 out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
445 INT_MAX, 0);
446 ret = ff_audio_data_realloc(dst, out_samples);
447 if (ret < 0) {
448 av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
449 return ret;
450 }
451 }
452
453 /* resample each channel plane */
454 for (ch = 0; ch < c->buffer->channels; ch++) {
455 out_samples = resample(c, (int16_t *)dst->data[ch],
456 (const int16_t *)c->buffer->data[ch], consumed,
457 c->buffer->nb_samples, dst->allocated_samples,
458 ch + 1 == c->buffer->channels);
459 }
460 if (out_samples < 0) {
461 av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
462 return out_samples;
463 }
464
465 /* drain consumed samples from the internal buffer */
466 ff_audio_data_drain(c->buffer, *consumed);
467
468 av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
469 in_samples, in_leftover, out_samples, c->buffer->nb_samples);
470
471 dst->nb_samples = out_samples;
472 return 0;
473}
474
475int avresample_get_delay(AVAudioResampleContext *avr)
476{
477 if (!avr->resample_needed || !avr->resample)
478 return 0;
479
480 return avr->resample->buffer->nb_samples;
481}