]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_asyncts.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / af_asyncts.c
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"
21 #include "libavutil/common.h"
22 #include "libavutil/mathematics.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/samplefmt.h"
25
26 #include "audio.h"
27 #include "avfilter.h"
28 #include "internal.h"
29
30 typedef 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     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
39
40     /* options */
41     int resample;
42     float min_delta_sec;
43     int max_comp;
44
45     /* set by filter_frame() to signal an output frame to request_frame() */
46     int got_output;
47 } ASyncContext;
48
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 },
58     { NULL },
59 };
60
61 AVFILTER_DEFINE_CLASS(asyncts);
62
63 static int init(AVFilterContext *ctx, const char *args)
64 {
65     ASyncContext *s = ctx->priv;
66     int ret;
67
68     s->class = &asyncts_class;
69     av_opt_set_defaults(s);
70
71     if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
72         return ret;
73     av_opt_free(s);
74
75     s->pts         = AV_NOPTS_VALUE;
76     s->first_frame = 1;
77
78     return 0;
79 }
80
81 static 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
91 static 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
119 /* get amount of data currently buffered, in samples */
120 static int64_t get_delay(ASyncContext *s)
121 {
122     return avresample_available(s->avr) + avresample_get_delay(s->avr);
123 }
124
125 static void handle_trimming(AVFilterContext *ctx)
126 {
127     ASyncContext *s = ctx->priv;
128
129     if (s->pts < s->first_pts) {
130         int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
131         av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
132                delta);
133         avresample_read(s->avr, NULL, delta);
134         s->pts += delta;
135     } else if (s->first_frame)
136         s->pts = s->first_pts;
137 }
138
139 static int request_frame(AVFilterLink *link)
140 {
141     AVFilterContext *ctx = link->src;
142     ASyncContext      *s = ctx->priv;
143     int ret = 0;
144     int nb_samples;
145
146     s->got_output = 0;
147     while (ret >= 0 && !s->got_output)
148         ret = ff_request_frame(ctx->inputs[0]);
149
150     /* flush the fifo */
151     if (ret == AVERROR_EOF) {
152         if (s->first_pts != AV_NOPTS_VALUE)
153             handle_trimming(ctx);
154
155         if (nb_samples = get_delay(s)) {
156             AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
157             if (!buf)
158                 return AVERROR(ENOMEM);
159             ret = avresample_convert(s->avr, buf->extended_data,
160                                      buf->linesize[0], nb_samples, NULL, 0, 0);
161             if (ret <= 0) {
162                 av_frame_free(&buf);
163                 return (ret < 0) ? ret : AVERROR_EOF;
164             }
165
166             buf->pts = s->pts;
167             return ff_filter_frame(link, buf);
168         }
169     }
170
171     return ret;
172 }
173
174 static int write_to_fifo(ASyncContext *s, AVFrame *buf)
175 {
176     int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
177                                  buf->linesize[0], buf->nb_samples);
178     av_frame_free(&buf);
179     return ret;
180 }
181
182 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
183 {
184     AVFilterContext  *ctx = inlink->dst;
185     ASyncContext       *s = ctx->priv;
186     AVFilterLink *outlink = ctx->outputs[0];
187     int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
188     int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
189                   av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
190     int out_size, ret;
191     int64_t delta;
192     int64_t new_pts;
193
194     /* buffer data until we get the next timestamp */
195     if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
196         if (pts != AV_NOPTS_VALUE) {
197             s->pts = pts - get_delay(s);
198         }
199         return write_to_fifo(s, buf);
200     }
201
202     if (s->first_pts != AV_NOPTS_VALUE) {
203         handle_trimming(ctx);
204         if (!avresample_available(s->avr))
205             return write_to_fifo(s, buf);
206     }
207
208     /* when we have two timestamps, compute how many samples would we have
209      * to add/remove to get proper sync between data and timestamps */
210     delta    = pts - s->pts - get_delay(s);
211     out_size = avresample_available(s->avr);
212
213     if (labs(delta) > s->min_delta ||
214         (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
215         av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
216         out_size = av_clipl_int32((int64_t)out_size + delta);
217     } else {
218         if (s->resample) {
219             // adjust the compensation if delta is non-zero
220             int delay = get_delay(s);
221             int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
222                                          -s->max_comp, s->max_comp);
223             if (comp != s->comp) {
224                 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
225                 if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
226                     s->comp = comp;
227                 }
228             }
229         }
230         // adjust PTS to avoid monotonicity errors with input PTS jitter
231         pts -= delta;
232         delta = 0;
233     }
234
235     if (out_size > 0) {
236         AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
237         if (!buf_out) {
238             ret = AVERROR(ENOMEM);
239             goto fail;
240         }
241
242         if (s->first_frame && delta > 0) {
243             int ch;
244
245             av_samples_set_silence(buf_out->extended_data, 0, delta,
246                                    nb_channels, buf->format);
247
248             for (ch = 0; ch < nb_channels; ch++)
249                 buf_out->extended_data[ch] += delta;
250
251             avresample_read(s->avr, buf_out->extended_data, out_size);
252
253             for (ch = 0; ch < nb_channels; ch++)
254                 buf_out->extended_data[ch] -= delta;
255         } else {
256             avresample_read(s->avr, buf_out->extended_data, out_size);
257
258             if (delta > 0) {
259                 av_samples_set_silence(buf_out->extended_data, out_size - delta,
260                                        delta, nb_channels, buf->format);
261             }
262         }
263         buf_out->pts = s->pts;
264         ret = ff_filter_frame(outlink, buf_out);
265         if (ret < 0)
266             goto fail;
267         s->got_output = 1;
268     } else if (avresample_available(s->avr)) {
269         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
270                "whole buffer.\n");
271     }
272
273     /* drain any remaining buffered data */
274     avresample_read(s->avr, NULL, avresample_available(s->avr));
275
276     new_pts = pts - avresample_get_delay(s->avr);
277     /* check for s->pts monotonicity */
278     if (new_pts > s->pts) {
279         s->pts = new_pts;
280         ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
281                                  buf->linesize[0], buf->nb_samples);
282     } else {
283         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
284                "whole buffer.\n");
285         ret = 0;
286     }
287
288     s->first_frame = 0;
289 fail:
290     av_frame_free(&buf);
291
292     return ret;
293 }
294
295 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
296     {
297         .name           = "default",
298         .type           = AVMEDIA_TYPE_AUDIO,
299         .filter_frame   = filter_frame
300     },
301     { NULL }
302 };
303
304 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
305     {
306         .name          = "default",
307         .type          = AVMEDIA_TYPE_AUDIO,
308         .config_props  = config_props,
309         .request_frame = request_frame
310     },
311     { NULL }
312 };
313
314 AVFilter avfilter_af_asyncts = {
315     .name        = "asyncts",
316     .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
317
318     .init        = init,
319     .uninit      = uninit,
320
321     .priv_size   = sizeof(ASyncContext),
322
323     .inputs      = avfilter_af_asyncts_inputs,
324     .outputs     = avfilter_af_asyncts_outputs,
325     .priv_class = &asyncts_class,
326 };