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
42 /* set by filter_samples() to signal an output frame to request_frame() */
46 #define OFFSET(x) offsetof(ASyncContext, x)
47 #define A AV_OPT_FLAG_AUDIO_PARAM
48 static const AVOption options[] = {
49 { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
50 { "min_delta", "Minimum difference between timestamps and audio data "
51 "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
52 { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
53 { "first_pts", "Assume the first pts should be this value.", OFFSET(pts), AV_OPT_TYPE_INT64, { .i64 = AV_NOPTS_VALUE }, INT64_MIN, INT64_MAX, A },
57 static const AVClass async_class = {
58 .class_name = "asyncts filter",
59 .item_name = av_default_item_name,
61 .version = LIBAVUTIL_VERSION_INT,
64 static int init(AVFilterContext *ctx, const char *args)
66 ASyncContext *s = ctx->priv;
69 s->class = &async_class;
70 av_opt_set_defaults(s);
72 if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
73 av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
81 static void uninit(AVFilterContext *ctx)
83 ASyncContext *s = ctx->priv;
86 avresample_close(s->avr);
87 avresample_free(&s->avr);
91 static int config_props(AVFilterLink *link)
93 ASyncContext *s = link->src->priv;
96 s->min_delta = s->min_delta_sec * link->sample_rate;
97 link->time_base = (AVRational){1, link->sample_rate};
99 s->avr = avresample_alloc_context();
101 return AVERROR(ENOMEM);
103 av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
104 av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
105 av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
106 av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
107 av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
108 av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
111 av_opt_set_int(s->avr, "force_resampling", 1, 0);
113 if ((ret = avresample_open(s->avr)) < 0)
119 static int request_frame(AVFilterLink *link)
121 AVFilterContext *ctx = link->src;
122 ASyncContext *s = ctx->priv;
127 while (ret >= 0 && !s->got_output)
128 ret = ff_request_frame(ctx->inputs[0]);
131 if (ret == AVERROR_EOF && (nb_samples = avresample_get_delay(s->avr))) {
132 AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
135 return AVERROR(ENOMEM);
136 ret = avresample_convert(s->avr, buf->extended_data,
137 buf->linesize[0], nb_samples, NULL, 0, 0);
139 avfilter_unref_bufferp(&buf);
140 return (ret < 0) ? ret : AVERROR_EOF;
144 return ff_filter_samples(link, buf);
150 static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
152 int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
153 buf->linesize[0], buf->audio->nb_samples);
154 avfilter_unref_buffer(buf);
158 /* get amount of data currently buffered, in samples */
159 static int64_t get_delay(ASyncContext *s)
161 return avresample_available(s->avr) + avresample_get_delay(s->avr);
164 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
166 AVFilterContext *ctx = inlink->dst;
167 ASyncContext *s = ctx->priv;
168 AVFilterLink *outlink = ctx->outputs[0];
169 int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
170 int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
171 av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
175 /* buffer data until we get the first timestamp */
176 if (s->pts == AV_NOPTS_VALUE) {
177 if (pts != AV_NOPTS_VALUE) {
178 s->pts = pts - get_delay(s);
180 return write_to_fifo(s, buf);
183 /* now wait for the next timestamp */
184 if (pts == AV_NOPTS_VALUE) {
185 return write_to_fifo(s, buf);
188 /* when we have two timestamps, compute how many samples would we have
189 * to add/remove to get proper sync between data and timestamps */
190 delta = pts - s->pts - get_delay(s);
191 out_size = avresample_available(s->avr);
193 if (labs(delta) > s->min_delta) {
194 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
195 out_size = av_clipl_int32((int64_t)out_size + delta);
198 int comp = av_clip(delta, -s->max_comp, s->max_comp);
199 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
200 avresample_set_compensation(s->avr, delta, inlink->sample_rate);
206 AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
209 ret = AVERROR(ENOMEM);
213 avresample_read(s->avr, buf_out->extended_data, out_size);
214 buf_out->pts = s->pts;
217 av_samples_set_silence(buf_out->extended_data, out_size - delta,
218 delta, nb_channels, buf->format);
220 ret = ff_filter_samples(outlink, buf_out);
225 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
229 /* drain any remaining buffered data */
230 avresample_read(s->avr, NULL, avresample_available(s->avr));
232 s->pts = pts - avresample_get_delay(s->avr);
233 ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
234 buf->linesize[0], buf->audio->nb_samples);
237 avfilter_unref_buffer(buf);
242 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
245 .type = AVMEDIA_TYPE_AUDIO,
246 .filter_samples = filter_samples
251 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
254 .type = AVMEDIA_TYPE_AUDIO,
255 .config_props = config_props,
256 .request_frame = request_frame
261 AVFilter avfilter_af_asyncts = {
263 .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
268 .priv_size = sizeof(ASyncContext),
270 .inputs = avfilter_af_asyncts_inputs,
271 .outputs = avfilter_af_asyncts_outputs,