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