resample: remove an unneeded context variable
[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
1d9c2dc8 22#include "libavutil/common.h"
c8af852b
JR
23#include "libavutil/libm.h"
24#include "libavutil/log.h"
25#include "internal.h"
4d68269d 26#include "resample.h"
c8af852b
JR
27#include "audio_data.h"
28
c8af852b
JR
29struct ResampleContext {
30 AVAudioResampleContext *avr;
31 AudioData *buffer;
64103976 32 uint8_t *filter_bank;
c8af852b
JR
33 int filter_length;
34 int ideal_dst_incr;
35 int dst_incr;
be394968 36 unsigned int index;
c8af852b
JR
37 int frac;
38 int src_incr;
39 int compensation_distance;
40 int phase_shift;
41 int phase_mask;
42 int linear;
372647ae
JR
43 enum AVResampleFilterType filter_type;
44 int kaiser_beta;
64103976 45 void (*set_filter)(void *filter, double *tab, int phase, int tap_count);
f20892eb 46 void (*resample_one)(struct ResampleContext *c, void *dst0,
be394968
AK
47 int dst_index, const void *src0,
48 unsigned int index, int frac);
f20892eb 49 void (*resample_nearest)(void *dst0, int dst_index,
be394968 50 const void *src0, unsigned int index);
b9dea237 51 int padding_size;
be394968
AK
52 int initial_padding_filled;
53 int initial_padding_samples;
f7c5fd81
AK
54 int final_padding_filled;
55 int final_padding_samples;
c8af852b
JR
56};
57
64103976
JR
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
3aa696e8 78/* 0th order modified bessel function of the first kind. */
c8af852b
JR
79static 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
3aa696e8 95/* Build a polyphase filterbank. */
21d8f4da 96static int build_filter(ResampleContext *c, double factor)
c8af852b
JR
97{
98 int ph, i;
21d8f4da 99 double x, y, w;
c8af852b 100 double *tab;
64103976
JR
101 int tap_count = c->filter_length;
102 int phase_count = 1 << c->phase_shift;
c8af852b
JR
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
c8af852b
JR
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;
64103976 115 switch (c->filter_type) {
372647ae 116 case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
c8af852b
JR
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 }
372647ae 123 case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
c8af852b
JR
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;
372647ae 129 case AV_RESAMPLE_FILTER_TYPE_KAISER:
c8af852b 130 w = 2.0 * x / (factor * tap_count * M_PI);
64103976 131 y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
c8af852b
JR
132 break;
133 }
134
135 tab[i] = y;
136 norm += y;
137 }
c8af852b 138 /* normalize so that an uniform color remains the same */
64103976
JR
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);
c8af852b
JR
143 }
144
145 av_free(tab);
146 return 0;
147}
148
149ResampleContext *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;
64103976 156 int felem_size;
c8af852b 157
64103976
JR
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) {
c8af852b
JR
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;
c8af852b 175 c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
372647ae
JR
176 c->filter_type = avr->filter_type;
177 c->kaiser_beta = avr->kaiser_beta;
c8af852b 178
64103976
JR
179 switch (avr->internal_sample_fmt) {
180 case AV_SAMPLE_FMT_DBLP:
254c95cd 181 c->resample_one = c->linear ? resample_linear_dbl : resample_one_dbl;
f20892eb 182 c->resample_nearest = resample_nearest_dbl;
64103976
JR
183 c->set_filter = set_filter_dbl;
184 break;
185 case AV_SAMPLE_FMT_FLTP:
254c95cd 186 c->resample_one = c->linear ? resample_linear_flt : resample_one_flt;
f20892eb 187 c->resample_nearest = resample_nearest_flt;
64103976
JR
188 c->set_filter = set_filter_flt;
189 break;
190 case AV_SAMPLE_FMT_S32P:
254c95cd 191 c->resample_one = c->linear ? resample_linear_s32 : resample_one_s32;
f20892eb 192 c->resample_nearest = resample_nearest_s32;
64103976
JR
193 c->set_filter = set_filter_s32;
194 break;
195 case AV_SAMPLE_FMT_S16P:
254c95cd 196 c->resample_one = c->linear ? resample_linear_s16 : resample_one_s16;
f20892eb 197 c->resample_nearest = resample_nearest_s16;
64103976
JR
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);
c8af852b
JR
204 if (!c->filter_bank)
205 goto error;
206
21d8f4da 207 if (build_filter(c, factor) < 0)
c8af852b
JR
208 goto error;
209
64103976
JR
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);
c8af852b
JR
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
b9dea237 221 c->padding_size = (c->filter_length - 1) / 2;
be394968
AK
222 c->initial_padding_filled = 0;
223 c->index = 0;
c8af852b
JR
224 c->frac = 0;
225
226 /* allocate internal buffer */
be394968 227 c->buffer = ff_audio_data_alloc(avr->resample_channels, c->padding_size,
c8af852b
JR
228 avr->internal_sample_fmt,
229 "resample buffer");
230 if (!c->buffer)
231 goto error;
be394968
AK
232 c->buffer->nb_samples = c->padding_size;
233 c->initial_padding_samples = c->padding_size;
c8af852b
JR
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
241error:
242 ff_audio_data_free(&c->buffer);
243 av_free(c->filter_bank);
244 av_free(c);
245 return NULL;
246}
247
248void 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
257int 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
c8af852b 269 if (!avr->resample_needed) {
f1c2915c
JR
270#if FF_API_RESAMPLE_CLOSE_OPEN
271 /* if resampling was not enabled previously, re-initialize the
272 AVAudioResampleContext and force resampling */
c8af852b 273 int fifo_samples;
f322b207 274 int restore_matrix = 0;
c8af852b
JR
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 */
f322b207
JR
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 }
c8af852b
JR
296
297 /* close the AVAudioResampleContext */
298 avresample_close(avr);
299
300 avr->force_resampling = 1;
301
302 /* restore the channel mixing matrix */
f322b207
JR
303 if (restore_matrix) {
304 ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
305 if (ret < 0)
306 goto reinit_fail;
307 }
c8af852b
JR
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 }
f1c2915c
JR
322#else
323 av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
324 return AVERROR(EINVAL);
325#endif
c8af852b
JR
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
337reinit_fail:
338 ff_audio_data_free(&fifo_buf);
339 return ret;
340}
341
64103976 342static int resample(ResampleContext *c, void *dst, const void *src,
f20892eb
AK
343 int *consumed, int src_size, int dst_size, int update_ctx,
344 int nearest_neighbour)
c8af852b 345{
64103976 346 int dst_index;
be394968 347 unsigned int index = c->index;
c8af852b
JR
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
f20892eb 356 if (nearest_neighbour) {
be394968 357 uint64_t index2 = ((uint64_t)index) << 32;
c8af852b
JR
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++) {
f20892eb 365 c->resample_nearest(dst, dst_index, src, index2 >> 32);
c8af852b
JR
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++) {
c8af852b
JR
376 int sample_index = index >> c->phase_shift;
377
be394968 378 if (sample_index + c->filter_length > src_size)
c8af852b
JR
379 break;
380
64103976 381 if (dst)
be394968 382 c->resample_one(c, dst, dst_index, src, index, frac);
c8af852b
JR
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)
be394968 398 *consumed = index >> c->phase_shift;
c8af852b
JR
399
400 if (update_ctx) {
be394968 401 index &= c->phase_mask;
c8af852b
JR
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
1d86aa8b 417int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
c8af852b 418{
1d86aa8b 419 int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
c8af852b 420 int ret = AVERROR(EINVAL);
f20892eb
AK
421 int nearest_neighbour = (c->compensation_distance == 0 &&
422 c->filter_length == 1 &&
423 c->phase_shift == 0);
c8af852b
JR
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;
f7c5fd81 433 } else if (in_leftover <= c->final_padding_samples) {
c8af852b
JR
434 /* no remaining samples to flush */
435 return 0;
c8af852b
JR
436 }
437
be394968
AK
438 if (!c->initial_padding_filled) {
439 int bps = av_get_bytes_per_sample(c->avr->internal_sample_fmt);
440 int i;
441
f7c5fd81 442 if (src && c->buffer->nb_samples < 2 * c->padding_size)
be394968
AK
443 return 0;
444
445 for (i = 0; i < c->padding_size; i++)
f7c5fd81
AK
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 }
be394968
AK
454 c->initial_padding_filled = 1;
455 }
456
f7c5fd81
AK
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
c8af852b
JR
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,
f20892eb 488 INT_MAX, 0, nearest_neighbour);
c8af852b
JR
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++) {
64103976 498 out_samples = resample(c, (void *)dst->data[ch],
1d86aa8b 499 (const void *)c->buffer->data[ch], &consumed,
c8af852b 500 c->buffer->nb_samples, dst->allocated_samples,
f20892eb 501 ch + 1 == c->buffer->channels, nearest_neighbour);
c8af852b
JR
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 */
1d86aa8b 509 ff_audio_data_drain(c->buffer, consumed);
be394968 510 c->initial_padding_samples = FFMAX(c->initial_padding_samples - consumed, 0);
c8af852b
JR
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
519int avresample_get_delay(AVAudioResampleContext *avr)
520{
b9dea237
AK
521 ResampleContext *c = avr->resample;
522
c8af852b
JR
523 if (!avr->resample_needed || !avr->resample)
524 return 0;
525
b9dea237 526 return FFMAX(c->buffer->nb_samples - c->padding_size, 0);
c8af852b 527}