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