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