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