]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_asyncts.c
x86: Move some conditional code around to avoid unused variable warnings
[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 static const AVOption options[] = {
52     { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample),      AV_OPT_TYPE_INT,   { .i64 = 0 },   0, 1,       A },
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 },
55     { "max_comp",   "Maximum compensation in samples per second.",              OFFSET(max_comp),      AV_OPT_TYPE_INT,   { .i64 = 500 }, 0, INT_MAX, A },
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 },
57     { NULL },
58 };
59
60 static const AVClass async_class = {
61     .class_name = "asyncts filter",
62     .item_name  = av_default_item_name,
63     .option     = options,
64     .version    = LIBAVUTIL_VERSION_INT,
65 };
66
67 static int init(AVFilterContext *ctx)
68 {
69     ASyncContext *s = ctx->priv;
70
71     s->pts         = AV_NOPTS_VALUE;
72     s->first_frame = 1;
73
74     return 0;
75 }
76
77 static void uninit(AVFilterContext *ctx)
78 {
79     ASyncContext *s = ctx->priv;
80
81     if (s->avr) {
82         avresample_close(s->avr);
83         avresample_free(&s->avr);
84     }
85 }
86
87 static int config_props(AVFilterLink *link)
88 {
89     ASyncContext *s = link->src->priv;
90     int ret;
91
92     s->min_delta = s->min_delta_sec * link->sample_rate;
93     link->time_base = (AVRational){1, link->sample_rate};
94
95     s->avr = avresample_alloc_context();
96     if (!s->avr)
97         return AVERROR(ENOMEM);
98
99     av_opt_set_int(s->avr,  "in_channel_layout", link->channel_layout, 0);
100     av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
101     av_opt_set_int(s->avr,  "in_sample_fmt",     link->format,         0);
102     av_opt_set_int(s->avr, "out_sample_fmt",     link->format,         0);
103     av_opt_set_int(s->avr,  "in_sample_rate",    link->sample_rate,    0);
104     av_opt_set_int(s->avr, "out_sample_rate",    link->sample_rate,    0);
105
106     if (s->resample)
107         av_opt_set_int(s->avr, "force_resampling", 1, 0);
108
109     if ((ret = avresample_open(s->avr)) < 0)
110         return ret;
111
112     return 0;
113 }
114
115 /* get amount of data currently buffered, in samples */
116 static int64_t get_delay(ASyncContext *s)
117 {
118     return avresample_available(s->avr) + avresample_get_delay(s->avr);
119 }
120
121 static void handle_trimming(AVFilterContext *ctx)
122 {
123     ASyncContext *s = ctx->priv;
124
125     if (s->pts < s->first_pts) {
126         int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
127         av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
128                delta);
129         avresample_read(s->avr, NULL, delta);
130         s->pts += delta;
131     } else if (s->first_frame)
132         s->pts = s->first_pts;
133 }
134
135 static int request_frame(AVFilterLink *link)
136 {
137     AVFilterContext *ctx = link->src;
138     ASyncContext      *s = ctx->priv;
139     int ret = 0;
140     int nb_samples;
141
142     s->got_output = 0;
143     while (ret >= 0 && !s->got_output)
144         ret = ff_request_frame(ctx->inputs[0]);
145
146     /* flush the fifo */
147     if (ret == AVERROR_EOF) {
148         if (s->first_pts != AV_NOPTS_VALUE)
149             handle_trimming(ctx);
150
151         if (nb_samples = get_delay(s)) {
152             AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
153             if (!buf)
154                 return AVERROR(ENOMEM);
155             ret = avresample_convert(s->avr, buf->extended_data,
156                                      buf->linesize[0], nb_samples, NULL, 0, 0);
157             if (ret <= 0) {
158                 av_frame_free(&buf);
159                 return (ret < 0) ? ret : AVERROR_EOF;
160             }
161
162             buf->pts = s->pts;
163             return ff_filter_frame(link, buf);
164         }
165     }
166
167     return ret;
168 }
169
170 static int write_to_fifo(ASyncContext *s, AVFrame *buf)
171 {
172     int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
173                                  buf->linesize[0], buf->nb_samples);
174     av_frame_free(&buf);
175     return ret;
176 }
177
178 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
179 {
180     AVFilterContext  *ctx = inlink->dst;
181     ASyncContext       *s = ctx->priv;
182     AVFilterLink *outlink = ctx->outputs[0];
183     int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
184     int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
185                   av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
186     int out_size, ret;
187     int64_t delta;
188     int64_t new_pts;
189
190     /* buffer data until we get the next timestamp */
191     if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
192         if (pts != AV_NOPTS_VALUE) {
193             s->pts = pts - get_delay(s);
194         }
195         return write_to_fifo(s, buf);
196     }
197
198     if (s->first_pts != AV_NOPTS_VALUE) {
199         handle_trimming(ctx);
200         if (!avresample_available(s->avr))
201             return write_to_fifo(s, buf);
202     }
203
204     /* when we have two timestamps, compute how many samples would we have
205      * to add/remove to get proper sync between data and timestamps */
206     delta    = pts - s->pts - get_delay(s);
207     out_size = avresample_available(s->avr);
208
209     if (labs(delta) > s->min_delta ||
210         (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
211         av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
212         out_size = av_clipl_int32((int64_t)out_size + delta);
213     } else {
214         if (s->resample) {
215             // adjust the compensation if delta is non-zero
216             int delay = get_delay(s);
217             int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
218                                          -s->max_comp, s->max_comp);
219             if (comp != s->comp) {
220                 av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
221                 if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
222                     s->comp = comp;
223                 }
224             }
225         }
226         // adjust PTS to avoid monotonicity errors with input PTS jitter
227         pts -= delta;
228         delta = 0;
229     }
230
231     if (out_size > 0) {
232         AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
233         if (!buf_out) {
234             ret = AVERROR(ENOMEM);
235             goto fail;
236         }
237
238         if (s->first_frame && delta > 0) {
239             int ch;
240
241             av_samples_set_silence(buf_out->extended_data, 0, delta,
242                                    nb_channels, buf->format);
243
244             for (ch = 0; ch < nb_channels; ch++)
245                 buf_out->extended_data[ch] += delta;
246
247             avresample_read(s->avr, buf_out->extended_data, out_size);
248
249             for (ch = 0; ch < nb_channels; ch++)
250                 buf_out->extended_data[ch] -= delta;
251         } else {
252             avresample_read(s->avr, buf_out->extended_data, out_size);
253
254             if (delta > 0) {
255                 av_samples_set_silence(buf_out->extended_data, out_size - delta,
256                                        delta, nb_channels, buf->format);
257             }
258         }
259         buf_out->pts = s->pts;
260         ret = ff_filter_frame(outlink, buf_out);
261         if (ret < 0)
262             goto fail;
263         s->got_output = 1;
264     } else if (avresample_available(s->avr)) {
265         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
266                "whole buffer.\n");
267     }
268
269     /* drain any remaining buffered data */
270     avresample_read(s->avr, NULL, avresample_available(s->avr));
271
272     new_pts = pts - avresample_get_delay(s->avr);
273     /* check for s->pts monotonicity */
274     if (new_pts > s->pts) {
275         s->pts = new_pts;
276         ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
277                                  buf->linesize[0], buf->nb_samples);
278     } else {
279         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
280                "whole buffer.\n");
281         ret = 0;
282     }
283
284     s->first_frame = 0;
285 fail:
286     av_frame_free(&buf);
287
288     return ret;
289 }
290
291 static const AVFilterPad avfilter_af_asyncts_inputs[] = {
292     {
293         .name           = "default",
294         .type           = AVMEDIA_TYPE_AUDIO,
295         .filter_frame   = filter_frame,
296     },
297     { NULL }
298 };
299
300 static const AVFilterPad avfilter_af_asyncts_outputs[] = {
301     {
302         .name          = "default",
303         .type          = AVMEDIA_TYPE_AUDIO,
304         .config_props  = config_props,
305         .request_frame = request_frame
306     },
307     { NULL }
308 };
309
310 AVFilter avfilter_af_asyncts = {
311     .name        = "asyncts",
312     .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
313
314     .init        = init,
315     .uninit      = uninit,
316
317     .priv_size   = sizeof(ASyncContext),
318     .priv_class  = &async_class,
319
320     .inputs      = avfilter_af_asyncts_inputs,
321     .outputs     = avfilter_af_asyncts_outputs,
322 };