doc: improve documentation for the asyncts filter first_pts option
[libav.git] / libavfilter / af_asyncts.c
CommitLineData
9f26421b
AK
1/*
2 * This file is part of Libav.
3 *
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.
8 *
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.
13 *
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
17 */
18
19#include "libavresample/avresample.h"
20#include "libavutil/audio_fifo.h"
1d9c2dc8 21#include "libavutil/common.h"
9f26421b
AK
22#include "libavutil/mathematics.h"
23#include "libavutil/opt.h"
24#include "libavutil/samplefmt.h"
25
26#include "audio.h"
27#include "avfilter.h"
803391f7 28#include "internal.h"
9f26421b
AK
29
30typedef struct ASyncContext {
31 const AVClass *class;
32
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
c143de40
JR
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
9f26421b
AK
38
39 /* options */
40 int resample;
41 float min_delta_sec;
42 int max_comp;
6f834293 43
565e4993 44 /* set by filter_frame() to signal an output frame to request_frame() */
6f834293 45 int got_output;
9f26421b
AK
46} ASyncContext;
47
48#define OFFSET(x) offsetof(ASyncContext, x)
49#define A AV_OPT_FLAG_AUDIO_PARAM
50static const AVOption options[] = {
e6153f17 51 { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
9f26421b 52 { "min_delta", "Minimum difference between timestamps and audio data "
c7b610aa 53 "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
e6153f17 54 { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
c143de40 55 { "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 },
9f26421b
AK
56 { NULL },
57};
58
59static const AVClass async_class = {
60 .class_name = "asyncts filter",
61 .item_name = av_default_item_name,
62 .option = options,
63 .version = LIBAVUTIL_VERSION_INT,
64};
65
a5e8c41c 66static int init(AVFilterContext *ctx, const char *args)
9f26421b
AK
67{
68 ASyncContext *s = ctx->priv;
69 int ret;
70
71 s->class = &async_class;
72 av_opt_set_defaults(s);
73
74 if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
75 av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
76 return ret;
77 }
78 av_opt_free(s);
79
c143de40
JR
80 s->pts = AV_NOPTS_VALUE;
81 s->first_frame = 1;
82
9f26421b
AK
83 return 0;
84}
85
86static void uninit(AVFilterContext *ctx)
87{
88 ASyncContext *s = ctx->priv;
89
90 if (s->avr) {
91 avresample_close(s->avr);
92 avresample_free(&s->avr);
93 }
94}
95
96static int config_props(AVFilterLink *link)
97{
98 ASyncContext *s = link->src->priv;
99 int ret;
100
101 s->min_delta = s->min_delta_sec * link->sample_rate;
102 link->time_base = (AVRational){1, link->sample_rate};
103
104 s->avr = avresample_alloc_context();
105 if (!s->avr)
106 return AVERROR(ENOMEM);
107
108 av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
109 av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
110 av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
111 av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
112 av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
113 av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
114
115 if (s->resample)
116 av_opt_set_int(s->avr, "force_resampling", 1, 0);
117
118 if ((ret = avresample_open(s->avr)) < 0)
119 return ret;
120
121 return 0;
122}
123
f266486b
JR
124/* get amount of data currently buffered, in samples */
125static int64_t get_delay(ASyncContext *s)
126{
127 return avresample_available(s->avr) + avresample_get_delay(s->avr);
128}
129
c143de40
JR
130static void handle_trimming(AVFilterContext *ctx)
131{
132 ASyncContext *s = ctx->priv;
133
134 if (s->pts < s->first_pts) {
135 int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
136 av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
137 delta);
138 avresample_read(s->avr, NULL, delta);
139 s->pts += delta;
140 } else if (s->first_frame)
141 s->pts = s->first_pts;
142}
143
9f26421b
AK
144static int request_frame(AVFilterLink *link)
145{
146 AVFilterContext *ctx = link->src;
147 ASyncContext *s = ctx->priv;
6f834293 148 int ret = 0;
9f26421b
AK
149 int nb_samples;
150
6f834293
AK
151 s->got_output = 0;
152 while (ret >= 0 && !s->got_output)
153 ret = ff_request_frame(ctx->inputs[0]);
154
9f26421b 155 /* flush the fifo */
c143de40
JR
156 if (ret == AVERROR_EOF) {
157 if (s->first_pts != AV_NOPTS_VALUE)
158 handle_trimming(ctx);
159
160 if (nb_samples = get_delay(s)) {
9f26421b
AK
161 AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
162 nb_samples);
163 if (!buf)
164 return AVERROR(ENOMEM);
e7ba5b1d 165 ret = avresample_convert(s->avr, buf->extended_data,
91a84a52
AK
166 buf->linesize[0], nb_samples, NULL, 0, 0);
167 if (ret <= 0) {
168 avfilter_unref_bufferp(&buf);
169 return (ret < 0) ? ret : AVERROR_EOF;
170 }
171
9f26421b 172 buf->pts = s->pts;
565e4993 173 return ff_filter_frame(link, buf);
c143de40 174 }
9f26421b
AK
175 }
176
177 return ret;
178}
179
cd991462 180static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
9f26421b 181{
e7ba5b1d 182 int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
cd991462 183 buf->linesize[0], buf->audio->nb_samples);
9f26421b 184 avfilter_unref_buffer(buf);
cd991462 185 return ret;
9f26421b
AK
186}
187
565e4993 188static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
9f26421b
AK
189{
190 AVFilterContext *ctx = inlink->dst;
191 ASyncContext *s = ctx->priv;
192 AVFilterLink *outlink = ctx->outputs[0];
193 int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
194 int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
195 av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
cd991462 196 int out_size, ret;
9f26421b
AK
197 int64_t delta;
198
199 /* buffer data until we get the first timestamp */
200 if (s->pts == AV_NOPTS_VALUE) {
201 if (pts != AV_NOPTS_VALUE) {
202 s->pts = pts - get_delay(s);
203 }
cd991462 204 return write_to_fifo(s, buf);
9f26421b
AK
205 }
206
207 /* now wait for the next timestamp */
208 if (pts == AV_NOPTS_VALUE) {
cd991462 209 return write_to_fifo(s, buf);
9f26421b
AK
210 }
211
c143de40
JR
212 if (s->first_pts != AV_NOPTS_VALUE) {
213 handle_trimming(ctx);
214 if (!avresample_available(s->avr))
215 return write_to_fifo(s, buf);
216 }
217
9f26421b
AK
218 /* when we have two timestamps, compute how many samples would we have
219 * to add/remove to get proper sync between data and timestamps */
220 delta = pts - s->pts - get_delay(s);
221 out_size = avresample_available(s->avr);
222
c143de40 223 if (labs(delta) > s->min_delta || (s->first_frame && delta)) {
9f26421b 224 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
be51e589 225 out_size = av_clipl_int32((int64_t)out_size + delta);
f297dd38
AK
226 } else {
227 if (s->resample) {
228 int comp = av_clip(delta, -s->max_comp, s->max_comp);
229 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
8083332c 230 avresample_set_compensation(s->avr, comp, inlink->sample_rate);
f297dd38
AK
231 }
232 delta = 0;
9f26421b
AK
233 }
234
235 if (out_size > 0) {
236 AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
237 out_size);
cd991462
AK
238 if (!buf_out) {
239 ret = AVERROR(ENOMEM);
240 goto fail;
241 }
9f26421b 242
c143de40
JR
243 if (s->first_frame && delta > 0) {
244 int ch;
245
246 av_samples_set_silence(buf_out->extended_data, 0, delta,
247 nb_channels, buf->format);
248
249 for (ch = 0; ch < nb_channels; ch++)
250 buf_out->extended_data[ch] += delta;
9f26421b 251
c143de40
JR
252 avresample_read(s->avr, buf_out->extended_data, out_size);
253
254 for (ch = 0; ch < nb_channels; ch++)
255 buf_out->extended_data[ch] -= delta;
256 } else {
257 avresample_read(s->avr, buf_out->extended_data, out_size);
258
259 if (delta > 0) {
260 av_samples_set_silence(buf_out->extended_data, out_size - delta,
261 delta, nb_channels, buf->format);
262 }
9f26421b 263 }
c143de40 264 buf_out->pts = s->pts;
565e4993 265 ret = ff_filter_frame(outlink, buf_out);
cd991462
AK
266 if (ret < 0)
267 goto fail;
6f834293 268 s->got_output = 1;
c143de40 269 } else if (avresample_available(s->avr)) {
9f26421b
AK
270 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
271 "whole buffer.\n");
272 }
273
274 /* drain any remaining buffered data */
275 avresample_read(s->avr, NULL, avresample_available(s->avr));
276
277 s->pts = pts - avresample_get_delay(s->avr);
e7ba5b1d 278 ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
cd991462
AK
279 buf->linesize[0], buf->audio->nb_samples);
280
c143de40 281 s->first_frame = 0;
cd991462 282fail:
9f26421b 283 avfilter_unref_buffer(buf);
cd991462
AK
284
285 return ret;
9f26421b
AK
286}
287
568c70e7
MR
288static const AVFilterPad avfilter_af_asyncts_inputs[] = {
289 {
290 .name = "default",
291 .type = AVMEDIA_TYPE_AUDIO,
565e4993 292 .filter_frame = filter_frame,
568c70e7
MR
293 },
294 { NULL }
295};
296
297static const AVFilterPad avfilter_af_asyncts_outputs[] = {
298 {
299 .name = "default",
300 .type = AVMEDIA_TYPE_AUDIO,
301 .config_props = config_props,
302 .request_frame = request_frame
303 },
304 { NULL }
305};
306
9f26421b
AK
307AVFilter avfilter_af_asyncts = {
308 .name = "asyncts",
309 .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
310
311 .init = init,
312 .uninit = uninit,
313
314 .priv_size = sizeof(ASyncContext),
315
568c70e7
MR
316 .inputs = avfilter_af_asyncts_inputs,
317 .outputs = avfilter_af_asyncts_outputs,
9f26421b 318};