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/audio_fifo.h"
21 #include "libavutil/common.h"
22 #include "libavutil/mathematics.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/samplefmt.h"
30 typedef struct ASyncContext {
33 AVAudioResampleContext *avr;
34 int64_t pts; ///< timestamp in samples of the first sample in fifo
35 int min_delta; ///< pad/trim min threshold in samples
36 int first_frame; ///< 1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE
37 int64_t first_pts; ///< user-specified first expected pts, in samples
38 int comp; ///< current resample compensation
45 /* set by filter_frame() to signal an output frame to request_frame() */
49 #define OFFSET(x) offsetof(ASyncContext, x)
50 #define A AV_OPT_FLAG_AUDIO_PARAM
51 #define F AV_OPT_FLAG_FILTERING_PARAM
52 static const AVOption asyncts_options[] = {
53 { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A|F },
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|F },
56 { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A|F },
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|F },
61 AVFILTER_DEFINE_CLASS(asyncts);
63 static int init(AVFilterContext *ctx, const char *args)
65 ASyncContext *s = ctx->priv;
67 s->pts = AV_NOPTS_VALUE;
73 static void uninit(AVFilterContext *ctx)
75 ASyncContext *s = ctx->priv;
78 avresample_close(s->avr);
79 avresample_free(&s->avr);
83 static int config_props(AVFilterLink *link)
85 ASyncContext *s = link->src->priv;
88 s->min_delta = s->min_delta_sec * link->sample_rate;
89 link->time_base = (AVRational){1, link->sample_rate};
91 s->avr = avresample_alloc_context();
93 return AVERROR(ENOMEM);
95 av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
96 av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
97 av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
98 av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
99 av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
100 av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
103 av_opt_set_int(s->avr, "force_resampling", 1, 0);
105 if ((ret = avresample_open(s->avr)) < 0)
111 /* get amount of data currently buffered, in samples */
112 static int64_t get_delay(ASyncContext *s)
114 return avresample_available(s->avr) + avresample_get_delay(s->avr);
117 static void handle_trimming(AVFilterContext *ctx)
119 ASyncContext *s = ctx->priv;
121 if (s->pts < s->first_pts) {
122 int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
123 av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
125 avresample_read(s->avr, NULL, delta);
127 } else if (s->first_frame)
128 s->pts = s->first_pts;
131 static int request_frame(AVFilterLink *link)
133 AVFilterContext *ctx = link->src;
134 ASyncContext *s = ctx->priv;
139 while (ret >= 0 && !s->got_output)
140 ret = ff_request_frame(ctx->inputs[0]);
143 if (ret == AVERROR_EOF) {
144 if (s->first_pts != AV_NOPTS_VALUE)
145 handle_trimming(ctx);
147 if (nb_samples = get_delay(s)) {
148 AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
150 return AVERROR(ENOMEM);
151 ret = avresample_convert(s->avr, buf->extended_data,
152 buf->linesize[0], nb_samples, NULL, 0, 0);
155 return (ret < 0) ? ret : AVERROR_EOF;
159 return ff_filter_frame(link, buf);
166 static int write_to_fifo(ASyncContext *s, AVFrame *buf)
168 int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
169 buf->linesize[0], buf->nb_samples);
174 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
176 AVFilterContext *ctx = inlink->dst;
177 ASyncContext *s = ctx->priv;
178 AVFilterLink *outlink = ctx->outputs[0];
179 int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
180 int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
181 av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
186 /* buffer data until we get the next timestamp */
187 if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
188 if (pts != AV_NOPTS_VALUE) {
189 s->pts = pts - get_delay(s);
191 return write_to_fifo(s, buf);
194 if (s->first_pts != AV_NOPTS_VALUE) {
195 handle_trimming(ctx);
196 if (!avresample_available(s->avr))
197 return write_to_fifo(s, buf);
200 /* when we have two timestamps, compute how many samples would we have
201 * to add/remove to get proper sync between data and timestamps */
202 delta = pts - s->pts - get_delay(s);
203 out_size = avresample_available(s->avr);
205 if (labs(delta) > s->min_delta ||
206 (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
207 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
208 out_size = av_clipl_int32((int64_t)out_size + delta);
211 // adjust the compensation if delta is non-zero
212 int delay = get_delay(s);
213 int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
214 -s->max_comp, s->max_comp);
215 if (comp != s->comp) {
216 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
217 if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
222 // adjust PTS to avoid monotonicity errors with input PTS jitter
228 AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
230 ret = AVERROR(ENOMEM);
234 if (s->first_frame && delta > 0) {
237 av_samples_set_silence(buf_out->extended_data, 0, delta,
238 nb_channels, buf->format);
240 for (ch = 0; ch < nb_channels; ch++)
241 buf_out->extended_data[ch] += delta;
243 avresample_read(s->avr, buf_out->extended_data, out_size);
245 for (ch = 0; ch < nb_channels; ch++)
246 buf_out->extended_data[ch] -= delta;
248 avresample_read(s->avr, buf_out->extended_data, out_size);
251 av_samples_set_silence(buf_out->extended_data, out_size - delta,
252 delta, nb_channels, buf->format);
255 buf_out->pts = s->pts;
256 ret = ff_filter_frame(outlink, buf_out);
260 } else if (avresample_available(s->avr)) {
261 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
265 /* drain any remaining buffered data */
266 avresample_read(s->avr, NULL, avresample_available(s->avr));
268 new_pts = pts - avresample_get_delay(s->avr);
269 /* check for s->pts monotonicity */
270 if (new_pts > s->pts) {
272 ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
273 buf->linesize[0], buf->nb_samples);
275 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
287 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
290 .type = AVMEDIA_TYPE_AUDIO,
291 .filter_frame = filter_frame
296 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
299 .type = AVMEDIA_TYPE_AUDIO,
300 .config_props = config_props,
301 .request_frame = request_frame
306 AVFilter avfilter_af_asyncts = {
308 .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
313 .priv_size = sizeof(ASyncContext),
314 .priv_class = &asyncts_class,
316 .inputs = avfilter_af_asyncts_inputs,
317 .outputs = avfilter_af_asyncts_outputs,