2 * This file is part of Libav.
4 * Libav is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * Libav is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with Libav; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #include "libavresample/avresample.h"
20 #include "libavutil/attributes.h"
21 #include "libavutil/audio_fifo.h"
22 #include "libavutil/common.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/samplefmt.h"
31 typedef struct ASyncContext {
34 AVAudioResampleContext *avr;
35 int64_t pts; ///< timestamp in samples of the first sample in fifo
36 int min_delta; ///< pad/trim min threshold in samples
37 int first_frame; ///< 1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE
38 int64_t first_pts; ///< user-specified first expected pts, in samples
39 int comp; ///< current resample compensation
46 /* set by filter_frame() to signal an output frame to request_frame() */
50 #define OFFSET(x) offsetof(ASyncContext, x)
51 #define A AV_OPT_FLAG_AUDIO_PARAM
52 static const AVOption options[] = {
53 { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
54 { "min_delta", "Minimum difference between timestamps and audio data "
55 "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
56 { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
57 { "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 },
61 static const AVClass async_class = {
62 .class_name = "asyncts filter",
63 .item_name = av_default_item_name,
65 .version = LIBAVUTIL_VERSION_INT,
68 static av_cold int init(AVFilterContext *ctx)
70 ASyncContext *s = ctx->priv;
72 s->pts = AV_NOPTS_VALUE;
78 static av_cold void uninit(AVFilterContext *ctx)
80 ASyncContext *s = ctx->priv;
83 avresample_close(s->avr);
84 avresample_free(&s->avr);
88 static int config_props(AVFilterLink *link)
90 ASyncContext *s = link->src->priv;
93 s->min_delta = s->min_delta_sec * link->sample_rate;
94 link->time_base = (AVRational){1, link->sample_rate};
96 s->avr = avresample_alloc_context();
98 return AVERROR(ENOMEM);
100 av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
101 av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
102 av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
103 av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
104 av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
105 av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
108 av_opt_set_int(s->avr, "force_resampling", 1, 0);
110 if ((ret = avresample_open(s->avr)) < 0)
116 /* get amount of data currently buffered, in samples */
117 static int64_t get_delay(ASyncContext *s)
119 return avresample_available(s->avr) + avresample_get_delay(s->avr);
122 static void handle_trimming(AVFilterContext *ctx)
124 ASyncContext *s = ctx->priv;
126 if (s->pts < s->first_pts) {
127 int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
128 av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
130 avresample_read(s->avr, NULL, delta);
132 } else if (s->first_frame)
133 s->pts = s->first_pts;
136 static int request_frame(AVFilterLink *link)
138 AVFilterContext *ctx = link->src;
139 ASyncContext *s = ctx->priv;
144 while (ret >= 0 && !s->got_output)
145 ret = ff_request_frame(ctx->inputs[0]);
148 if (ret == AVERROR_EOF) {
149 if (s->first_pts != AV_NOPTS_VALUE)
150 handle_trimming(ctx);
152 if (nb_samples = get_delay(s)) {
153 AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
155 return AVERROR(ENOMEM);
156 ret = avresample_convert(s->avr, buf->extended_data,
157 buf->linesize[0], nb_samples, NULL, 0, 0);
160 return (ret < 0) ? ret : AVERROR_EOF;
164 return ff_filter_frame(link, buf);
171 static int write_to_fifo(ASyncContext *s, AVFrame *buf)
173 int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
174 buf->linesize[0], buf->nb_samples);
179 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
181 AVFilterContext *ctx = inlink->dst;
182 ASyncContext *s = ctx->priv;
183 AVFilterLink *outlink = ctx->outputs[0];
184 int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
185 int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
186 av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
191 /* buffer data until we get the next timestamp */
192 if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
193 if (pts != AV_NOPTS_VALUE) {
194 s->pts = pts - get_delay(s);
196 return write_to_fifo(s, buf);
199 if (s->first_pts != AV_NOPTS_VALUE) {
200 handle_trimming(ctx);
201 if (!avresample_available(s->avr))
202 return write_to_fifo(s, buf);
205 /* when we have two timestamps, compute how many samples would we have
206 * to add/remove to get proper sync between data and timestamps */
207 delta = pts - s->pts - get_delay(s);
208 out_size = avresample_available(s->avr);
210 if (labs(delta) > s->min_delta ||
211 (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
212 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
213 out_size = av_clipl_int32((int64_t)out_size + delta);
216 // adjust the compensation if delta is non-zero
217 int delay = get_delay(s);
218 int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
219 -s->max_comp, s->max_comp);
220 if (comp != s->comp) {
221 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
222 if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
227 // adjust PTS to avoid monotonicity errors with input PTS jitter
233 AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
235 ret = AVERROR(ENOMEM);
239 if (s->first_frame && delta > 0) {
240 int planar = av_sample_fmt_is_planar(buf_out->format);
241 int planes = planar ? nb_channels : 1;
242 int block_size = av_get_bytes_per_sample(buf_out->format) *
243 (planar ? 1 : nb_channels);
247 av_samples_set_silence(buf_out->extended_data, 0, delta,
248 nb_channels, buf->format);
250 for (ch = 0; ch < planes; ch++)
251 buf_out->extended_data[ch] += delta * block_size;
253 avresample_read(s->avr, buf_out->extended_data, out_size);
255 for (ch = 0; ch < planes; ch++)
256 buf_out->extended_data[ch] -= delta * block_size;
258 avresample_read(s->avr, buf_out->extended_data, out_size);
261 av_samples_set_silence(buf_out->extended_data, out_size - delta,
262 delta, nb_channels, buf->format);
265 buf_out->pts = s->pts;
266 ret = ff_filter_frame(outlink, buf_out);
270 } else if (avresample_available(s->avr)) {
271 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
275 /* drain any remaining buffered data */
276 avresample_read(s->avr, NULL, avresample_available(s->avr));
278 new_pts = pts - avresample_get_delay(s->avr);
279 /* check for s->pts monotonicity */
280 if (new_pts > s->pts) {
282 ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
283 buf->linesize[0], buf->nb_samples);
285 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
297 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
300 .type = AVMEDIA_TYPE_AUDIO,
301 .filter_frame = filter_frame,
306 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
309 .type = AVMEDIA_TYPE_AUDIO,
310 .config_props = config_props,
311 .request_frame = request_frame
316 AVFilter avfilter_af_asyncts = {
318 .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
323 .priv_size = sizeof(ASyncContext),
324 .priv_class = &async_class,
326 .inputs = avfilter_af_asyncts_inputs,
327 .outputs = avfilter_af_asyncts_outputs,