asyncts: use clipped delta value when setting resample compensation
[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
36
37 /* options */
38 int resample;
39 float min_delta_sec;
40 int max_comp;
6f834293 41
565e4993 42 /* set by filter_frame() to signal an output frame to request_frame() */
6f834293 43 int got_output;
9f26421b
AK
44} ASyncContext;
45
46#define OFFSET(x) offsetof(ASyncContext, x)
47#define A AV_OPT_FLAG_AUDIO_PARAM
48static const AVOption options[] = {
e6153f17 49 { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
9f26421b 50 { "min_delta", "Minimum difference between timestamps and audio data "
c7b610aa 51 "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
e6153f17 52 { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
4d7adec8 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 },
9f26421b
AK
54 { NULL },
55};
56
57static const AVClass async_class = {
58 .class_name = "asyncts filter",
59 .item_name = av_default_item_name,
60 .option = options,
61 .version = LIBAVUTIL_VERSION_INT,
62};
63
a5e8c41c 64static int init(AVFilterContext *ctx, const char *args)
9f26421b
AK
65{
66 ASyncContext *s = ctx->priv;
67 int ret;
68
69 s->class = &async_class;
70 av_opt_set_defaults(s);
71
72 if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
73 av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
74 return ret;
75 }
76 av_opt_free(s);
77
9f26421b
AK
78 return 0;
79}
80
81static void uninit(AVFilterContext *ctx)
82{
83 ASyncContext *s = ctx->priv;
84
85 if (s->avr) {
86 avresample_close(s->avr);
87 avresample_free(&s->avr);
88 }
89}
90
91static int config_props(AVFilterLink *link)
92{
93 ASyncContext *s = link->src->priv;
94 int ret;
95
96 s->min_delta = s->min_delta_sec * link->sample_rate;
97 link->time_base = (AVRational){1, link->sample_rate};
98
99 s->avr = avresample_alloc_context();
100 if (!s->avr)
101 return AVERROR(ENOMEM);
102
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);
109
110 if (s->resample)
111 av_opt_set_int(s->avr, "force_resampling", 1, 0);
112
113 if ((ret = avresample_open(s->avr)) < 0)
114 return ret;
115
116 return 0;
117}
118
f266486b
JR
119/* get amount of data currently buffered, in samples */
120static int64_t get_delay(ASyncContext *s)
121{
122 return avresample_available(s->avr) + avresample_get_delay(s->avr);
123}
124
9f26421b
AK
125static int request_frame(AVFilterLink *link)
126{
127 AVFilterContext *ctx = link->src;
128 ASyncContext *s = ctx->priv;
6f834293 129 int ret = 0;
9f26421b
AK
130 int nb_samples;
131
6f834293
AK
132 s->got_output = 0;
133 while (ret >= 0 && !s->got_output)
134 ret = ff_request_frame(ctx->inputs[0]);
135
9f26421b 136 /* flush the fifo */
f266486b 137 if (ret == AVERROR_EOF && (nb_samples = get_delay(s))) {
9f26421b
AK
138 AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
139 nb_samples);
140 if (!buf)
141 return AVERROR(ENOMEM);
e7ba5b1d 142 ret = avresample_convert(s->avr, buf->extended_data,
91a84a52
AK
143 buf->linesize[0], nb_samples, NULL, 0, 0);
144 if (ret <= 0) {
145 avfilter_unref_bufferp(&buf);
146 return (ret < 0) ? ret : AVERROR_EOF;
147 }
148
9f26421b 149 buf->pts = s->pts;
565e4993 150 return ff_filter_frame(link, buf);
9f26421b
AK
151 }
152
153 return ret;
154}
155
cd991462 156static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
9f26421b 157{
e7ba5b1d 158 int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
cd991462 159 buf->linesize[0], buf->audio->nb_samples);
9f26421b 160 avfilter_unref_buffer(buf);
cd991462 161 return ret;
9f26421b
AK
162}
163
565e4993 164static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
9f26421b
AK
165{
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);
cd991462 172 int out_size, ret;
9f26421b
AK
173 int64_t delta;
174
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);
179 }
cd991462 180 return write_to_fifo(s, buf);
9f26421b
AK
181 }
182
183 /* now wait for the next timestamp */
184 if (pts == AV_NOPTS_VALUE) {
cd991462 185 return write_to_fifo(s, buf);
9f26421b
AK
186 }
187
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);
192
193 if (labs(delta) > s->min_delta) {
194 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
be51e589 195 out_size = av_clipl_int32((int64_t)out_size + delta);
f297dd38
AK
196 } else {
197 if (s->resample) {
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);
8083332c 200 avresample_set_compensation(s->avr, comp, inlink->sample_rate);
f297dd38
AK
201 }
202 delta = 0;
9f26421b
AK
203 }
204
205 if (out_size > 0) {
206 AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
207 out_size);
cd991462
AK
208 if (!buf_out) {
209 ret = AVERROR(ENOMEM);
210 goto fail;
211 }
9f26421b 212
e7ba5b1d 213 avresample_read(s->avr, buf_out->extended_data, out_size);
9f26421b
AK
214 buf_out->pts = s->pts;
215
216 if (delta > 0) {
217 av_samples_set_silence(buf_out->extended_data, out_size - delta,
218 delta, nb_channels, buf->format);
219 }
565e4993 220 ret = ff_filter_frame(outlink, buf_out);
cd991462
AK
221 if (ret < 0)
222 goto fail;
6f834293 223 s->got_output = 1;
9f26421b
AK
224 } else {
225 av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
226 "whole buffer.\n");
227 }
228
229 /* drain any remaining buffered data */
230 avresample_read(s->avr, NULL, avresample_available(s->avr));
231
232 s->pts = pts - avresample_get_delay(s->avr);
e7ba5b1d 233 ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
cd991462
AK
234 buf->linesize[0], buf->audio->nb_samples);
235
236fail:
9f26421b 237 avfilter_unref_buffer(buf);
cd991462
AK
238
239 return ret;
9f26421b
AK
240}
241
568c70e7
MR
242static const AVFilterPad avfilter_af_asyncts_inputs[] = {
243 {
244 .name = "default",
245 .type = AVMEDIA_TYPE_AUDIO,
565e4993 246 .filter_frame = filter_frame,
568c70e7
MR
247 },
248 { NULL }
249};
250
251static const AVFilterPad avfilter_af_asyncts_outputs[] = {
252 {
253 .name = "default",
254 .type = AVMEDIA_TYPE_AUDIO,
255 .config_props = config_props,
256 .request_frame = request_frame
257 },
258 { NULL }
259};
260
9f26421b
AK
261AVFilter avfilter_af_asyncts = {
262 .name = "asyncts",
263 .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
264
265 .init = init,
266 .uninit = uninit,
267
268 .priv_size = sizeof(ASyncContext),
269
568c70e7
MR
270 .inputs = avfilter_af_asyncts_inputs,
271 .outputs = avfilter_af_asyncts_outputs,
9f26421b 272};