]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_asyncts.c
Merge commit 'fd9147f11456a7e39a998d7270684922a2a46e6d'
[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
39     /* options */
40     int resample;
41     float min_delta_sec;
42     int max_comp;
43
44     /* set by filter_frame() to signal an output frame to request_frame() */
45     int got_output;
46 } ASyncContext;
47
48 #define OFFSET(x) offsetof(ASyncContext, x)
49 #define A AV_OPT_FLAG_AUDIO_PARAM
50 #define F AV_OPT_FLAG_FILTERING_PARAM
51 static const AVOption asyncts_options[] = {
52     { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample),      AV_OPT_TYPE_INT,   { .i64 = 0 },   0, 1,       A|F },
53     { "min_delta",  "Minimum difference between timestamps and audio data "
54                     "(in seconds) to trigger padding/trimmin the data.",        OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A|F },
55     { "max_comp",   "Maximum compensation in samples per second.",              OFFSET(max_comp),      AV_OPT_TYPE_INT,   { .i64 = 500 }, 0, INT_MAX, A|F },
56     { "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 },
57     { NULL },
58 };
59
60 AVFILTER_DEFINE_CLASS(asyncts);
61
62 static int init(AVFilterContext *ctx, const char *args)
63 {
64     ASyncContext *s = ctx->priv;
65     int ret;
66
67     s->class = &asyncts_class;
68     av_opt_set_defaults(s);
69
70     if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
71         return ret;
72     av_opt_free(s);
73
74     s->pts         = AV_NOPTS_VALUE;
75     s->first_frame = 1;
76
77     return 0;
78 }
79
80 static void uninit(AVFilterContext *ctx)
81 {
82     ASyncContext *s = ctx->priv;
83
84     if (s->avr) {
85         avresample_close(s->avr);
86         avresample_free(&s->avr);
87     }
88 }
89
90 static int config_props(AVFilterLink *link)
91 {
92     ASyncContext *s = link->src->priv;
93     int ret;
94
95     s->min_delta = s->min_delta_sec * link->sample_rate;
96     link->time_base = (AVRational){1, link->sample_rate};
97
98     s->avr = avresample_alloc_context();
99     if (!s->avr)
100         return AVERROR(ENOMEM);
101
102     av_opt_set_int(s->avr,  "in_channel_layout", link->channel_layout, 0);
103     av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
104     av_opt_set_int(s->avr,  "in_sample_fmt",     link->format,         0);
105     av_opt_set_int(s->avr, "out_sample_fmt",     link->format,         0);
106     av_opt_set_int(s->avr,  "in_sample_rate",    link->sample_rate,    0);
107     av_opt_set_int(s->avr, "out_sample_rate",    link->sample_rate,    0);
108
109     if (s->resample)
110         av_opt_set_int(s->avr, "force_resampling", 1, 0);
111
112     if ((ret = avresample_open(s->avr)) < 0)
113         return ret;
114
115     return 0;
116 }
117
118 /* get amount of data currently buffered, in samples */
119 static int64_t get_delay(ASyncContext *s)
120 {
121     return avresample_available(s->avr) + avresample_get_delay(s->avr);
122 }
123
124 static void handle_trimming(AVFilterContext *ctx)
125 {
126     ASyncContext *s = ctx->priv;
127
128     if (s->pts < s->first_pts) {
129         int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
130         av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
131                delta);
132         avresample_read(s->avr, NULL, delta);
133         s->pts += delta;
134     } else if (s->first_frame)
135         s->pts = s->first_pts;
136 }
137
138 static int request_frame(AVFilterLink *link)
139 {
140     AVFilterContext *ctx = link->src;
141     ASyncContext      *s = ctx->priv;
142     int ret = 0;
143     int nb_samples;
144
145     s->got_output = 0;
146     while (ret >= 0 && !s->got_output)
147         ret = ff_request_frame(ctx->inputs[0]);
148
149     /* flush the fifo */
150     if (ret == AVERROR_EOF) {
151         if (s->first_pts != AV_NOPTS_VALUE)
152             handle_trimming(ctx);
153
154         if (nb_samples = get_delay(s)) {
155             AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
156                                                          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                 avfilter_unref_bufferp(&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, AVFilterBufferRef *buf)
175 {
176     int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
177                                  buf->linesize[0], buf->audio->nb_samples);
178     avfilter_unref_buffer(buf);
179     return ret;
180 }
181
182 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *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->audio->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
193     /* buffer data until we get the next timestamp */
194     if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
195         if (pts != AV_NOPTS_VALUE) {
196             s->pts = pts - get_delay(s);
197         }
198         return write_to_fifo(s, buf);
199     }
200
201     if (s->first_pts != AV_NOPTS_VALUE) {
202         handle_trimming(ctx);
203         if (!avresample_available(s->avr))
204             return write_to_fifo(s, buf);
205     }
206
207     /* when we have two timestamps, compute how many samples would we have
208      * to add/remove to get proper sync between data and timestamps */
209     delta    = pts - s->pts - get_delay(s);
210     out_size = avresample_available(s->avr);
211
212     if (labs(delta) > s->min_delta ||
213         (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
214         av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
215         out_size = av_clipl_int32((int64_t)out_size + delta);
216     } else {
217         if (s->resample) {
218             int comp = av_clip(delta, -s->max_comp, s->max_comp);
219             av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
220             avresample_set_compensation(s->avr, comp, inlink->sample_rate);
221         }
222         delta = 0;
223     }
224
225     if (out_size > 0) {
226         AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
227                                                          out_size);
228         if (!buf_out) {
229             ret = AVERROR(ENOMEM);
230             goto fail;
231         }
232
233         if (s->first_frame && delta > 0) {
234             int ch;
235
236             av_samples_set_silence(buf_out->extended_data, 0, delta,
237                                    nb_channels, buf->format);
238
239             for (ch = 0; ch < nb_channels; ch++)
240                 buf_out->extended_data[ch] += delta;
241
242             avresample_read(s->avr, buf_out->extended_data, out_size);
243
244             for (ch = 0; ch < nb_channels; ch++)
245                 buf_out->extended_data[ch] -= delta;
246         } else {
247             avresample_read(s->avr, buf_out->extended_data, out_size);
248
249             if (delta > 0) {
250                 av_samples_set_silence(buf_out->extended_data, out_size - delta,
251                                        delta, nb_channels, buf->format);
252             }
253         }
254         buf_out->pts = s->pts;
255         ret = ff_filter_frame(outlink, buf_out);
256         if (ret < 0)
257             goto fail;
258         s->got_output = 1;
259     } else if (avresample_available(s->avr)) {
260         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
261                "whole buffer.\n");
262     }
263
264     /* drain any remaining buffered data */
265     avresample_read(s->avr, NULL, avresample_available(s->avr));
266
267     s->pts = pts - avresample_get_delay(s->avr);
268     ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
269                              buf->linesize[0], buf->audio->nb_samples);
270
271     s->first_frame = 0;
272 fail:
273     avfilter_unref_buffer(buf);
274
275     return ret;
276 }
277
278 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
279     {
280         .name           = "default",
281         .type           = AVMEDIA_TYPE_AUDIO,
282         .filter_frame   = filter_frame
283     },
284     { NULL }
285 };
286
287 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
288     {
289         .name          = "default",
290         .type          = AVMEDIA_TYPE_AUDIO,
291         .config_props  = config_props,
292         .request_frame = request_frame
293     },
294     { NULL }
295 };
296
297 AVFilter avfilter_af_asyncts = {
298     .name        = "asyncts",
299     .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
300
301     .init        = init,
302     .uninit      = uninit,
303
304     .priv_size   = sizeof(ASyncContext),
305
306     .inputs      = avfilter_af_asyncts_inputs,
307     .outputs     = avfilter_af_asyncts_outputs,
308     .priv_class = &asyncts_class,
309 };