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