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