af_asyncts.c 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * 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
 */

19 20
#include <stdint.h>

21
#include "libavresample/avresample.h"
22
#include "libavutil/attributes.h"
23
#include "libavutil/audio_fifo.h"
24
#include "libavutil/common.h"
25 26 27 28 29 30
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/samplefmt.h"

#include "audio.h"
#include "avfilter.h"
31
#include "internal.h"
32 33 34 35 36 37 38

typedef struct ASyncContext {
    const AVClass *class;

    AVAudioResampleContext *avr;
    int64_t pts;            ///< timestamp in samples of the first sample in fifo
    int min_delta;          ///< pad/trim min threshold in samples
39 40
    int first_frame;        ///< 1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE
    int64_t first_pts;      ///< user-specified first expected pts, in samples
41
    int comp;               ///< current resample compensation
42 43 44 45 46

    /* options */
    int resample;
    float min_delta_sec;
    int max_comp;
47

48
    /* set by filter_frame() to signal an output frame to request_frame() */
49
    int got_output;
50 51 52 53 54
} ASyncContext;

#define OFFSET(x) offsetof(ASyncContext, x)
#define A AV_OPT_FLAG_AUDIO_PARAM
static const AVOption options[] = {
55
    { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample),      AV_OPT_TYPE_INT,   { .i64 = 0 },   0, 1,       A },
56
    { "min_delta",  "Minimum difference between timestamps and audio data "
57
                    "(in seconds) to trigger padding/trimmin the data.",        OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
58
    { "max_comp",   "Maximum compensation in samples per second.",              OFFSET(max_comp),      AV_OPT_TYPE_INT,   { .i64 = 500 }, 0, INT_MAX, A },
59
    { "first_pts",  "Assume the first pts should be this value.",               OFFSET(first_pts),     AV_OPT_TYPE_INT64, { .i64 = AV_NOPTS_VALUE }, INT64_MIN, INT64_MAX, A },
60 61 62 63 64 65 66 67 68 69
    { NULL },
};

static const AVClass async_class = {
    .class_name = "asyncts filter",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

70
static av_cold int init(AVFilterContext *ctx)
71 72 73
{
    ASyncContext *s = ctx->priv;

74 75 76
    s->pts         = AV_NOPTS_VALUE;
    s->first_frame = 1;

77 78 79
    return 0;
}

80
static av_cold void uninit(AVFilterContext *ctx)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
{
    ASyncContext *s = ctx->priv;

    if (s->avr) {
        avresample_close(s->avr);
        avresample_free(&s->avr);
    }
}

static int config_props(AVFilterLink *link)
{
    ASyncContext *s = link->src->priv;
    int ret;

    s->min_delta = s->min_delta_sec * link->sample_rate;
    link->time_base = (AVRational){1, link->sample_rate};

    s->avr = avresample_alloc_context();
    if (!s->avr)
        return AVERROR(ENOMEM);

    av_opt_set_int(s->avr,  "in_channel_layout", link->channel_layout, 0);
    av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
    av_opt_set_int(s->avr,  "in_sample_fmt",     link->format,         0);
    av_opt_set_int(s->avr, "out_sample_fmt",     link->format,         0);
    av_opt_set_int(s->avr,  "in_sample_rate",    link->sample_rate,    0);
    av_opt_set_int(s->avr, "out_sample_rate",    link->sample_rate,    0);

    if (s->resample)
        av_opt_set_int(s->avr, "force_resampling", 1, 0);

    if ((ret = avresample_open(s->avr)) < 0)
        return ret;

    return 0;
}

118 119 120 121 122 123
/* get amount of data currently buffered, in samples */
static int64_t get_delay(ASyncContext *s)
{
    return avresample_available(s->avr) + avresample_get_delay(s->avr);
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137
static void handle_trimming(AVFilterContext *ctx)
{
    ASyncContext *s = ctx->priv;

    if (s->pts < s->first_pts) {
        int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
        av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
               delta);
        avresample_read(s->avr, NULL, delta);
        s->pts += delta;
    } else if (s->first_frame)
        s->pts = s->first_pts;
}

138 139 140 141
static int request_frame(AVFilterLink *link)
{
    AVFilterContext *ctx = link->src;
    ASyncContext      *s = ctx->priv;
142
    int ret = 0;
143 144
    int nb_samples;

145 146 147 148
    s->got_output = 0;
    while (ret >= 0 && !s->got_output)
        ret = ff_request_frame(ctx->inputs[0]);

149
    /* flush the fifo */
150 151 152 153 154
    if (ret == AVERROR_EOF) {
        if (s->first_pts != AV_NOPTS_VALUE)
            handle_trimming(ctx);

        if (nb_samples = get_delay(s)) {
155
            AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
156 157 158 159 160
            if (!buf)
                return AVERROR(ENOMEM);
            ret = avresample_convert(s->avr, buf->extended_data,
                                     buf->linesize[0], nb_samples, NULL, 0, 0);
            if (ret <= 0) {
161
                av_frame_free(&buf);
162 163 164 165 166
                return (ret < 0) ? ret : AVERROR_EOF;
            }

            buf->pts = s->pts;
            return ff_filter_frame(link, buf);
167
        }
168 169 170 171 172
    }

    return ret;
}

173
static int write_to_fifo(ASyncContext *s, AVFrame *buf)
174
{
175
    int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
176 177
                                 buf->linesize[0], buf->nb_samples);
    av_frame_free(&buf);
178
    return ret;
179 180
}

181
static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
182 183 184 185
{
    AVFilterContext  *ctx = inlink->dst;
    ASyncContext       *s = ctx->priv;
    AVFilterLink *outlink = ctx->outputs[0];
186
    int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
187 188
    int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
                  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
189
    int out_size, ret;
190
    int64_t delta;
191
    int64_t new_pts;
192

193 194
    /* buffer data until we get the next timestamp */
    if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
195 196 197
        if (pts != AV_NOPTS_VALUE) {
            s->pts = pts - get_delay(s);
        }
198
        return write_to_fifo(s, buf);
199 200
    }

201 202 203 204 205 206
    if (s->first_pts != AV_NOPTS_VALUE) {
        handle_trimming(ctx);
        if (!avresample_available(s->avr))
            return write_to_fifo(s, buf);
    }

207 208 209 210 211
    /* when we have two timestamps, compute how many samples would we have
     * to add/remove to get proper sync between data and timestamps */
    delta    = pts - s->pts - get_delay(s);
    out_size = avresample_available(s->avr);

212 213
    if (labs(delta) > s->min_delta ||
        (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
214
        av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
215
        out_size = av_clipl_int32((int64_t)out_size + delta);
216 217
    } else {
        if (s->resample) {
218 219 220 221 222 223 224 225 226 227
            // adjust the compensation if delta is non-zero
            int delay = get_delay(s);
            int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
                                         -s->max_comp, s->max_comp);
            if (comp != s->comp) {
                av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
                if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
                    s->comp = comp;
                }
            }
228
        }
229 230
        // adjust PTS to avoid monotonicity errors with input PTS jitter
        pts -= delta;
231
        delta = 0;
232 233 234
    }

    if (out_size > 0) {
235
        AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
236 237 238 239
        if (!buf_out) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
240

241
        if (s->first_frame && delta > 0) {
242 243 244 245 246
            int planar = av_sample_fmt_is_planar(buf_out->format);
            int planes = planar ?  nb_channels : 1;
            int block_size = av_get_bytes_per_sample(buf_out->format) *
                             (planar ? 1 : nb_channels);

247 248 249 250 251
            int ch;

            av_samples_set_silence(buf_out->extended_data, 0, delta,
                                   nb_channels, buf->format);

252 253
            for (ch = 0; ch < planes; ch++)
                buf_out->extended_data[ch] += delta * block_size;
254

255 256
            avresample_read(s->avr, buf_out->extended_data, out_size);

257 258
            for (ch = 0; ch < planes; ch++)
                buf_out->extended_data[ch] -= delta * block_size;
259 260 261 262 263 264 265
        } else {
            avresample_read(s->avr, buf_out->extended_data, out_size);

            if (delta > 0) {
                av_samples_set_silence(buf_out->extended_data, out_size - delta,
                                       delta, nb_channels, buf->format);
            }
266
        }
267
        buf_out->pts = s->pts;
268
        ret = ff_filter_frame(outlink, buf_out);
269 270
        if (ret < 0)
            goto fail;
271
        s->got_output = 1;
272
    } else if (avresample_available(s->avr)) {
273 274 275 276 277 278 279
        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
               "whole buffer.\n");
    }

    /* drain any remaining buffered data */
    avresample_read(s->avr, NULL, avresample_available(s->avr));

280 281 282 283 284 285 286 287 288 289 290
    new_pts = pts - avresample_get_delay(s->avr);
    /* check for s->pts monotonicity */
    if (new_pts > s->pts) {
        s->pts = new_pts;
        ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
                                 buf->linesize[0], buf->nb_samples);
    } else {
        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
               "whole buffer.\n");
        ret = 0;
    }
291

292
    s->first_frame = 0;
293
fail:
294
    av_frame_free(&buf);
295 296

    return ret;
297 298
}

299 300 301 302
static const AVFilterPad avfilter_af_asyncts_inputs[] = {
    {
        .name           = "default",
        .type           = AVMEDIA_TYPE_AUDIO,
303
        .filter_frame   = filter_frame,
304 305 306 307 308 309 310 311 312 313 314 315 316 317
    },
    { NULL }
};

static const AVFilterPad avfilter_af_asyncts_outputs[] = {
    {
        .name          = "default",
        .type          = AVMEDIA_TYPE_AUDIO,
        .config_props  = config_props,
        .request_frame = request_frame
    },
    { NULL }
};

318
AVFilter ff_af_asyncts = {
319 320 321 322 323 324 325
    .name        = "asyncts",
    .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),

    .init        = init,
    .uninit      = uninit,

    .priv_size   = sizeof(ASyncContext),
326
    .priv_class  = &async_class,
327

328 329
    .inputs      = avfilter_af_asyncts_inputs,
    .outputs     = avfilter_af_asyncts_outputs,
330
};