resample.c 16.6 KB
Newer Older
Justin Ruggles's avatar
Justin Ruggles committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
 * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
 *
 * This file is part of Libav.
 *
 * Libav is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Libav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Libav; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

22
#include "libavutil/common.h"
Justin Ruggles's avatar
Justin Ruggles committed
23 24 25
#include "libavutil/libm.h"
#include "libavutil/log.h"
#include "internal.h"
26
#include "resample.h"
Justin Ruggles's avatar
Justin Ruggles committed
27 28
#include "audio_data.h"

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

/* double template */
#define CONFIG_RESAMPLE_DBL
#include "resample_template.c"
#undef CONFIG_RESAMPLE_DBL

/* float template */
#define CONFIG_RESAMPLE_FLT
#include "resample_template.c"
#undef CONFIG_RESAMPLE_FLT

/* s32 template */
#define CONFIG_RESAMPLE_S32
#include "resample_template.c"
#undef CONFIG_RESAMPLE_S32

/* s16 template */
#include "resample_template.c"


49
/* 0th order modified bessel function of the first kind. */
Justin Ruggles's avatar
Justin Ruggles committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
static double bessel(double x)
{
    double v     = 1;
    double lastv = 0;
    double t     = 1;
    int i;

    x = x * x / 4;
    for (i = 1; v != lastv; i++) {
        lastv = v;
        t    *= x / (i * i);
        v    += t;
    }
    return v;
}

66
/* Build a polyphase filterbank. */
67
static int build_filter(ResampleContext *c, double factor)
Justin Ruggles's avatar
Justin Ruggles committed
68 69
{
    int ph, i;
70
    double x, y, w;
Justin Ruggles's avatar
Justin Ruggles committed
71
    double *tab;
72 73
    int tap_count    = c->filter_length;
    int phase_count  = 1 << c->phase_shift;
Justin Ruggles's avatar
Justin Ruggles committed
74 75 76 77 78 79 80 81 82 83 84 85
    const int center = (tap_count - 1) / 2;

    tab = av_malloc(tap_count * sizeof(*tab));
    if (!tab)
        return AVERROR(ENOMEM);

    for (ph = 0; ph < phase_count; ph++) {
        double norm = 0;
        for (i = 0; i < tap_count; i++) {
            x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
            if (x == 0) y = 1.0;
            else        y = sin(x) / x;
86
            switch (c->filter_type) {
87
            case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
Justin Ruggles's avatar
Justin Ruggles committed
88 89 90 91 92 93
                const float d = -0.5; //first order derivative = -0.5
                x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
                if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * (                -x*x + x*x*x);
                else         y =                           d * (-4 + 8 * x - 5 * x*x + x*x*x);
                break;
            }
94
            case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
Justin Ruggles's avatar
Justin Ruggles committed
95 96 97 98 99
                w  = 2.0 * x / (factor * tap_count) + M_PI;
                y *= 0.3635819 - 0.4891775 * cos(    w) +
                                 0.1365995 * cos(2 * w) -
                                 0.0106411 * cos(3 * w);
                break;
100
            case AV_RESAMPLE_FILTER_TYPE_KAISER:
Justin Ruggles's avatar
Justin Ruggles committed
101
                w  = 2.0 * x / (factor * tap_count * M_PI);
102
                y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
Justin Ruggles's avatar
Justin Ruggles committed
103 104 105 106 107 108 109
                break;
            }

            tab[i] = y;
            norm  += y;
        }
        /* normalize so that an uniform color remains the same */
110 111 112 113
        for (i = 0; i < tap_count; i++)
            tab[i] = tab[i] / norm;

        c->set_filter(c->filter_bank, tab, ph, tap_count);
Justin Ruggles's avatar
Justin Ruggles committed
114 115 116 117 118 119 120 121 122 123 124 125 126
    }

    av_free(tab);
    return 0;
}

ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
{
    ResampleContext *c;
    int out_rate    = avr->out_sample_rate;
    int in_rate     = avr->in_sample_rate;
    double factor   = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
    int phase_count = 1 << avr->phase_shift;
127
    int felem_size;
Justin Ruggles's avatar
Justin Ruggles committed
128

129 130 131 132
    if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {
Justin Ruggles's avatar
Justin Ruggles committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146
        av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
               "resampling: %s\n",
               av_get_sample_fmt_name(avr->internal_sample_fmt));
        return NULL;
    }
    c = av_mallocz(sizeof(*c));
    if (!c)
        return NULL;

    c->avr           = avr;
    c->phase_shift   = avr->phase_shift;
    c->phase_mask    = phase_count - 1;
    c->linear        = avr->linear_interp;
    c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
147 148
    c->filter_type   = avr->filter_type;
    c->kaiser_beta   = avr->kaiser_beta;
Justin Ruggles's avatar
Justin Ruggles committed
149

150 151
    switch (avr->internal_sample_fmt) {
    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 155 156
        c->set_filter    = set_filter_dbl;
        break;
    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 160 161
        c->set_filter    = set_filter_flt;
        break;
    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 165 166
        c->set_filter    = set_filter_s32;
        break;
    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 170 171 172
        c->set_filter    = set_filter_s16;
        break;
    }

173 174 175
    if (ARCH_AARCH64)
        ff_audio_resample_init_aarch64(c, avr->internal_sample_fmt);

176 177
    felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
    c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
Justin Ruggles's avatar
Justin Ruggles committed
178 179 180
    if (!c->filter_bank)
        goto error;

181
    if (build_filter(c, factor) < 0)
Justin Ruggles's avatar
Justin Ruggles committed
182 183
        goto error;

184 185 186 187
    memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],
           c->filter_bank, (c->filter_length - 1) * felem_size);
    memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],
           &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);
Justin Ruggles's avatar
Justin Ruggles committed
188 189 190 191 192 193 194

    c->compensation_distance = 0;
    if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
                   in_rate * (int64_t)phase_count, INT32_MAX / 2))
        goto error;
    c->ideal_dst_incr = c->dst_incr;

195
    c->padding_size   = (c->filter_length - 1) / 2;
196 197
    c->initial_padding_filled = 0;
    c->index = 0;
Justin Ruggles's avatar
Justin Ruggles committed
198 199 200
    c->frac  = 0;

    /* allocate internal buffer */
201
    c->buffer = ff_audio_data_alloc(avr->resample_channels, c->padding_size,
Justin Ruggles's avatar
Justin Ruggles committed
202 203 204 205
                                    avr->internal_sample_fmt,
                                    "resample buffer");
    if (!c->buffer)
        goto error;
206 207
    c->buffer->nb_samples      = c->padding_size;
    c->initial_padding_samples = c->padding_size;
Justin Ruggles's avatar
Justin Ruggles committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
           av_get_sample_fmt_name(avr->internal_sample_fmt),
           avr->in_sample_rate, avr->out_sample_rate);

    return c;

error:
    ff_audio_data_free(&c->buffer);
    av_free(c->filter_bank);
    av_free(c);
    return NULL;
}

void ff_audio_resample_free(ResampleContext **c)
{
    if (!*c)
        return;
    ff_audio_data_free(&(*c)->buffer);
    av_free((*c)->filter_bank);
    av_freep(c);
}

int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
                                int compensation_distance)
{
    ResampleContext *c;
    AudioData *fifo_buf = NULL;
    int ret = 0;

    if (compensation_distance < 0)
        return AVERROR(EINVAL);
    if (!compensation_distance && sample_delta)
        return AVERROR(EINVAL);

    if (!avr->resample_needed) {
244 245 246
#if FF_API_RESAMPLE_CLOSE_OPEN
        /* if resampling was not enabled previously, re-initialize the
           AVAudioResampleContext and force resampling */
Justin Ruggles's avatar
Justin Ruggles committed
247
        int fifo_samples;
248
        int restore_matrix = 0;
Justin Ruggles's avatar
Justin Ruggles committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };

        /* buffer any remaining samples in the output FIFO before closing */
        fifo_samples = av_audio_fifo_size(avr->out_fifo);
        if (fifo_samples > 0) {
            fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
                                           avr->out_sample_fmt, NULL);
            if (!fifo_buf)
                return AVERROR(EINVAL);
            ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
                                               fifo_samples);
            if (ret < 0)
                goto reinit_fail;
        }
        /* save the channel mixing matrix */
264 265 266 267 268 269
        if (avr->am) {
            ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
            if (ret < 0)
                goto reinit_fail;
            restore_matrix = 1;
        }
Justin Ruggles's avatar
Justin Ruggles committed
270 271 272 273 274 275 276

        /* close the AVAudioResampleContext */
        avresample_close(avr);

        avr->force_resampling = 1;

        /* restore the channel mixing matrix */
277 278 279 280 281
        if (restore_matrix) {
            ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
            if (ret < 0)
                goto reinit_fail;
        }
Justin Ruggles's avatar
Justin Ruggles committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295

        /* re-open the AVAudioResampleContext */
        ret = avresample_open(avr);
        if (ret < 0)
            goto reinit_fail;

        /* restore buffered samples to the output FIFO */
        if (fifo_samples > 0) {
            ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
                                            fifo_samples);
            if (ret < 0)
                goto reinit_fail;
            ff_audio_data_free(&fifo_buf);
        }
296 297 298 299
#else
        av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
        return AVERROR(EINVAL);
#endif
Justin Ruggles's avatar
Justin Ruggles committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    }
    c = avr->resample;
    c->compensation_distance = compensation_distance;
    if (compensation_distance) {
        c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
                      (int64_t)sample_delta / compensation_distance;
    } else {
        c->dst_incr = c->ideal_dst_incr;
    }
    return 0;

reinit_fail:
    ff_audio_data_free(&fifo_buf);
    return ret;
}

316
static int resample(ResampleContext *c, void *dst, const void *src,
317 318
                    int *consumed, int src_size, int dst_size, int update_ctx,
                    int nearest_neighbour)
Justin Ruggles's avatar
Justin Ruggles committed
319
{
320
    int dst_index;
321
    unsigned int index = c->index;
Justin Ruggles's avatar
Justin Ruggles committed
322 323 324 325 326 327 328 329
    int frac          = c->frac;
    int dst_incr_frac = c->dst_incr % c->src_incr;
    int dst_incr      = c->dst_incr / c->src_incr;
    int compensation_distance = c->compensation_distance;

    if (!dst != !src)
        return AVERROR(EINVAL);

330
    if (nearest_neighbour) {
331
        uint64_t index2 = ((uint64_t)index) << 32;
Justin Ruggles's avatar
Justin Ruggles committed
332 333 334 335 336 337 338
        int64_t incr   = (1LL << 32) * c->dst_incr / c->src_incr;
        dst_size       = FFMIN(dst_size,
                               (src_size-1-index) * (int64_t)c->src_incr /
                               c->dst_incr);

        if (dst) {
            for(dst_index = 0; dst_index < dst_size; dst_index++) {
339
                c->resample_nearest(dst, dst_index, src, index2 >> 32);
Justin Ruggles's avatar
Justin Ruggles committed
340 341 342 343 344 345 346 347 348 349 350 351
                index2 += incr;
            }
        } else {
            dst_index = dst_size;
        }
        index += dst_index * dst_incr;
        index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
        frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
    } else {
        for (dst_index = 0; dst_index < dst_size; dst_index++) {
            int sample_index = index >> c->phase_shift;

352
            if (sample_index + c->filter_length > src_size)
Justin Ruggles's avatar
Justin Ruggles committed
353 354
                break;

355
            if (dst)
356
                c->resample_one(c, dst, dst_index, src, index, frac);
Justin Ruggles's avatar
Justin Ruggles committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

            frac  += dst_incr_frac;
            index += dst_incr;
            if (frac >= c->src_incr) {
                frac -= c->src_incr;
                index++;
            }
            if (dst_index + 1 == compensation_distance) {
                compensation_distance = 0;
                dst_incr_frac = c->ideal_dst_incr % c->src_incr;
                dst_incr      = c->ideal_dst_incr / c->src_incr;
            }
        }
    }
    if (consumed)
372
        *consumed = index >> c->phase_shift;
Justin Ruggles's avatar
Justin Ruggles committed
373 374

    if (update_ctx) {
375
        index &= c->phase_mask;
Justin Ruggles's avatar
Justin Ruggles committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

        if (compensation_distance) {
            compensation_distance -= dst_index;
            if (compensation_distance <= 0)
                return AVERROR_BUG;
        }
        c->frac     = frac;
        c->index    = index;
        c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
        c->compensation_distance = compensation_distance;
    }

    return dst_index;
}

391
int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
Justin Ruggles's avatar
Justin Ruggles committed
392
{
393
    int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
Justin Ruggles's avatar
Justin Ruggles committed
394
    int ret = AVERROR(EINVAL);
395 396 397
    int nearest_neighbour = (c->compensation_distance == 0 &&
                             c->filter_length == 1 &&
                             c->phase_shift == 0);
Justin Ruggles's avatar
Justin Ruggles committed
398 399 400 401 402 403 404 405 406

    in_samples  = src ? src->nb_samples : 0;
    in_leftover = c->buffer->nb_samples;

    /* add input samples to the internal buffer */
    if (src) {
        ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
        if (ret < 0)
            return ret;
407
    } else if (in_leftover <= c->final_padding_samples) {
Justin Ruggles's avatar
Justin Ruggles committed
408 409 410 411
        /* no remaining samples to flush */
        return 0;
    }

412 413 414 415
    if (!c->initial_padding_filled) {
        int bps = av_get_bytes_per_sample(c->avr->internal_sample_fmt);
        int i;

416
        if (src && c->buffer->nb_samples < 2 * c->padding_size)
417 418 419
            return 0;

        for (i = 0; i < c->padding_size; i++)
420 421 422 423 424 425 426 427
            for (ch = 0; ch < c->buffer->channels; ch++) {
                if (c->buffer->nb_samples > 2 * c->padding_size - i) {
                    memcpy(c->buffer->data[ch] + bps * i,
                           c->buffer->data[ch] + bps * (2 * c->padding_size - i), bps);
                } else {
                    memset(c->buffer->data[ch] + bps * i, 0, bps);
                }
            }
428 429 430
        c->initial_padding_filled = 1;
    }

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    if (!src && !c->final_padding_filled) {
        int bps = av_get_bytes_per_sample(c->avr->internal_sample_fmt);
        int i;

        ret = ff_audio_data_realloc(c->buffer, in_samples + c->padding_size);
        if (ret < 0) {
            av_log(c->avr, AV_LOG_ERROR, "Error reallocating resampling buffer\n");
            return AVERROR(ENOMEM);
        }

        for (i = 0; i < c->padding_size; i++)
            for (ch = 0; ch < c->buffer->channels; ch++) {
                if (in_leftover > i) {
                    memcpy(c->buffer->data[ch] + bps * (in_leftover + i),
                           c->buffer->data[ch] + bps * (in_leftover - i - 1),
                           bps);
                } else {
                    memset(c->buffer->data[ch] + bps * (in_leftover + i),
                           0, bps);
                }
            }
        c->buffer->nb_samples   += c->padding_size;
        c->final_padding_samples = c->padding_size;
        c->final_padding_filled  = 1;
    }


Justin Ruggles's avatar
Justin Ruggles committed
458 459 460 461
    /* calculate output size and reallocate output buffer if needed */
    /* TODO: try to calculate this without the dummy resample() run */
    if (!dst->read_only && dst->allow_realloc) {
        out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
462
                               INT_MAX, 0, nearest_neighbour);
Justin Ruggles's avatar
Justin Ruggles committed
463 464 465 466 467 468 469 470 471
        ret = ff_audio_data_realloc(dst, out_samples);
        if (ret < 0) {
            av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
            return ret;
        }
    }

    /* resample each channel plane */
    for (ch = 0; ch < c->buffer->channels; ch++) {
472
        out_samples = resample(c, (void *)dst->data[ch],
473
                               (const void *)c->buffer->data[ch], &consumed,
Justin Ruggles's avatar
Justin Ruggles committed
474
                               c->buffer->nb_samples, dst->allocated_samples,
475
                               ch + 1 == c->buffer->channels, nearest_neighbour);
Justin Ruggles's avatar
Justin Ruggles committed
476 477 478 479 480 481 482
    }
    if (out_samples < 0) {
        av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
        return out_samples;
    }

    /* drain consumed samples from the internal buffer */
483
    ff_audio_data_drain(c->buffer, consumed);
484
    c->initial_padding_samples = FFMAX(c->initial_padding_samples - consumed, 0);
Justin Ruggles's avatar
Justin Ruggles committed
485 486 487 488 489 490 491 492 493 494

    av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
            in_samples, in_leftover, out_samples, c->buffer->nb_samples);

    dst->nb_samples = out_samples;
    return 0;
}

int avresample_get_delay(AVAudioResampleContext *avr)
{
495 496
    ResampleContext *c = avr->resample;

Justin Ruggles's avatar
Justin Ruggles committed
497 498 499
    if (!avr->resample_needed || !avr->resample)
        return 0;

500
    return FFMAX(c->buffer->nb_samples - c->padding_size, 0);
Justin Ruggles's avatar
Justin Ruggles committed
501
}