Add libavresample
[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
33#define WINDOW_TYPE 24
34#elifdef CONFIG_RESAMPLE_S32
35/* s32 template */
36#define FILTER_SHIFT 30
37#define FELEM int32_t
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
43#else
44/* s16 template */
45#define FILTER_SHIFT 15
46#define FELEM int16_t
47#define FELEM2 int32_t
48#define FELEML int64_t
49#define FELEM_MAX INT16_MAX
50#define FELEM_MIN INT16_MIN
51#define WINDOW_TYPE 9
52#endif
53
54struct ResampleContext {
55 AVAudioResampleContext *avr;
56 AudioData *buffer;
57 FELEM *filter_bank;
58 int filter_length;
59 int ideal_dst_incr;
60 int dst_incr;
61 int index;
62 int frac;
63 int src_incr;
64 int compensation_distance;
65 int phase_shift;
66 int phase_mask;
67 int linear;
68 double factor;
69};
70
71/**
72 * 0th order modified bessel function of the first kind.
73 */
74static double bessel(double x)
75{
76 double v = 1;
77 double lastv = 0;
78 double t = 1;
79 int i;
80
81 x = x * x / 4;
82 for (i = 1; v != lastv; i++) {
83 lastv = v;
84 t *= x / (i * i);
85 v += t;
86 }
87 return v;
88}
89
90/**
91 * Build a polyphase filterbank.
92 *
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
102 */
103static int build_filter(FELEM *filter, double factor, int tap_count,
104 int phase_count, int scale, int type)
105{
106 int ph, i;
107 double x, y, w;
108 double *tab;
109 const int center = (tap_count - 1) / 2;
110
111 tab = av_malloc(tap_count * sizeof(*tab));
112 if (!tab)
113 return AVERROR(ENOMEM);
114
115 /* if upsampling, only need to interpolate, no filter */
116 if (factor > 1.0)
117 factor = 1.0;
118
119 for (ph = 0; ph < phase_count; ph++) {
120 double norm = 0;
121 for (i = 0; i < tap_count; i++) {
122 x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
123 if (x == 0) y = 1.0;
124 else y = sin(x) / x;
125 switch (type) {
126 case 0: {
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);
131 break;
132 }
133 case 1:
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);
138 break;
139 default:
140 w = 2.0 * x / (factor * tap_count * M_PI);
141 y *= bessel(type * sqrt(FFMAX(1 - w * w, 0)));
142 break;
143 }
144
145 tab[i] = y;
146 norm += y;
147 }
148
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;
153#else
154 filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm),
155 FELEM_MIN, FELEM_MAX);
156#endif
157 }
158 }
159
160 av_free(tab);
161 return 0;
162}
163
164ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
165{
166 ResampleContext *c;
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;
171
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 "
175 "resampling: %s\n",
176 av_get_sample_fmt_name(avr->internal_sample_fmt));
177 return NULL;
178 }
179 c = av_mallocz(sizeof(*c));
180 if (!c)
181 return NULL;
182
183 c->avr = avr;
184 c->phase_shift = avr->phase_shift;
185 c->phase_mask = phase_count - 1;
186 c->linear = avr->linear_interp;
187 c->factor = factor;
188 c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
189
190 c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * sizeof(FELEM));
191 if (!c->filter_bank)
192 goto error;
193
194 if (build_filter(c->filter_bank, factor, c->filter_length, phase_count,
195 1 << FILTER_SHIFT, WINDOW_TYPE) < 0)
196 goto error;
197
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];
201
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))
205 goto error;
206 c->ideal_dst_incr = c->dst_incr;
207
208 c->index = -phase_count * ((c->filter_length - 1) / 2);
209 c->frac = 0;
210
211 /* allocate internal buffer */
212 c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
213 avr->internal_sample_fmt,
214 "resample buffer");
215 if (!c->buffer)
216 goto error;
217
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);
221
222 return c;
223
224error:
225 ff_audio_data_free(&c->buffer);
226 av_free(c->filter_bank);
227 av_free(c);
228 return NULL;
229}
230
231void ff_audio_resample_free(ResampleContext **c)
232{
233 if (!*c)
234 return;
235 ff_audio_data_free(&(*c)->buffer);
236 av_free((*c)->filter_bank);
237 av_freep(c);
238}
239
240int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
241 int compensation_distance)
242{
243 ResampleContext *c;
244 AudioData *fifo_buf = NULL;
245 int ret = 0;
246
247 if (compensation_distance < 0)
248 return AVERROR(EINVAL);
249 if (!compensation_distance && sample_delta)
250 return AVERROR(EINVAL);
251
252 /* if resampling was not enabled previously, re-initialize the
253 AVAudioResampleContext and force resampling */
254 if (!avr->resample_needed) {
255 int fifo_samples;
256 double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
257
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);
263 if (!fifo_buf)
264 return AVERROR(EINVAL);
265 ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
266 fifo_samples);
267 if (ret < 0)
268 goto reinit_fail;
269 }
270 /* save the channel mixing matrix */
271 ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
272 if (ret < 0)
273 goto reinit_fail;
274
275 /* close the AVAudioResampleContext */
276 avresample_close(avr);
277
278 avr->force_resampling = 1;
279
280 /* restore the channel mixing matrix */
281 ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
282 if (ret < 0)
283 goto reinit_fail;
284
285 /* re-open the AVAudioResampleContext */
286 ret = avresample_open(avr);
287 if (ret < 0)
288 goto reinit_fail;
289
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,
293 fifo_samples);
294 if (ret < 0)
295 goto reinit_fail;
296 ff_audio_data_free(&fifo_buf);
297 }
298 }
299 c = avr->resample;
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;
304 } else {
305 c->dst_incr = c->ideal_dst_incr;
306 }
307 return 0;
308
309reinit_fail:
310 ff_audio_data_free(&fifo_buf);
311 return ret;
312}
313
314static int resample(ResampleContext *c, int16_t *dst, const int16_t *src,
315 int *consumed, int src_size, int dst_size, int update_ctx)
316{
317 int dst_index, i;
318 int index = c->index;
319 int frac = c->frac;
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;
323
324 if (!dst != !src)
325 return AVERROR(EINVAL);
326
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 /
333 c->dst_incr);
334
335 if (dst) {
336 for(dst_index = 0; dst_index < dst_size; dst_index++) {
337 dst[dst_index] = src[index2 >> 32];
338 index2 += incr;
339 }
340 } else {
341 dst_index = dst_size;
342 }
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;
346 } else {
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;
351
352 if (!dst && (sample_index + c->filter_length > src_size ||
353 -sample_index >= src_size))
354 break;
355
356 if (dst) {
357 FELEM2 val = 0;
358
359 if (sample_index < 0) {
360 for (i = 0; i < c->filter_length; i++)
361 val += src[FFABS(sample_index + i) % src_size] *
362 (FELEM2)filter[i];
363 } else if (sample_index + c->filter_length > src_size) {
364 break;
365 } else if (c->linear) {
366 FELEM2 v2 = 0;
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];
370 }
371 val += (v2 - val) * (FELEML)frac / c->src_incr;
372 } else {
373 for (i = 0; i < c->filter_length; i++)
374 val += src[sample_index + i] * (FELEM2)filter[i];
375 }
376
377#ifdef CONFIG_RESAMPLE_FLT
378 dst[dst_index] = av_clip_int16(lrintf(val));
379#else
380 val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
381 dst[dst_index] = av_clip_int16(val);
382#endif
383 }
384
385 frac += dst_incr_frac;
386 index += dst_incr;
387 if (frac >= c->src_incr) {
388 frac -= c->src_incr;
389 index++;
390 }
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;
395 }
396 }
397 }
398 if (consumed)
399 *consumed = FFMAX(index, 0) >> c->phase_shift;
400
401 if (update_ctx) {
402 if (index >= 0)
403 index &= c->phase_mask;
404
405 if (compensation_distance) {
406 compensation_distance -= dst_index;
407 if (compensation_distance <= 0)
408 return AVERROR_BUG;
409 }
410 c->frac = frac;
411 c->index = index;
412 c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
413 c->compensation_distance = compensation_distance;
414 }
415
416 return dst_index;
417}
418
419int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
420 int *consumed)
421{
422 int ch, in_samples, in_leftover, out_samples = 0;
423 int ret = AVERROR(EINVAL);
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) {
434 /* no remaining samples to flush */
435 return 0;
436 } else {
437 /* TODO: pad buffer to flush completely */
438 }
439
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,
444 INT_MAX, 0);
445 ret = ff_audio_data_realloc(dst, out_samples);
446 if (ret < 0) {
447 av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
448 return ret;
449 }
450 }
451
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);
458 }
459 if (out_samples < 0) {
460 av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
461 return out_samples;
462 }
463
464 /* drain consumed samples from the internal buffer */
465 ff_audio_data_drain(c->buffer, *consumed);
466
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);
469
470 dst->nb_samples = out_samples;
471 return 0;
472}
473
474int avresample_get_delay(AVAudioResampleContext *avr)
475{
476 if (!avr->resample_needed || !avr->resample)
477 return 0;
478
479 return avr->resample->buffer->nb_samples;
480}