]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_asyncts.c
lavfi: add audio mix filter
[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
28 typedef struct ASyncContext {
29     const AVClass *class;
30
31     AVAudioResampleContext *avr;
32     int64_t pts;            ///< timestamp in samples of the first sample in fifo
33     int min_delta;          ///< pad/trim min threshold in samples
34
35     /* options */
36     int resample;
37     float min_delta_sec;
38     int max_comp;
39 } ASyncContext;
40
41 #define OFFSET(x) offsetof(ASyncContext, x)
42 #define A AV_OPT_FLAG_AUDIO_PARAM
43 static const AVOption options[] = {
44     { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample),      AV_OPT_TYPE_INT,   { 0 },   0, 1,       A },
45     { "min_delta",  "Minimum difference between timestamps and audio data "
46                     "(in seconds) to trigger padding/trimmin the data.",        OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { 0.1 }, 0, INT_MAX, A },
47     { "max_comp",   "Maximum compensation in samples per second.",              OFFSET(max_comp),      AV_OPT_TYPE_INT,   { 500 }, 0, INT_MAX, A },
48     { NULL },
49 };
50
51 static const AVClass async_class = {
52     .class_name = "asyncts filter",
53     .item_name  = av_default_item_name,
54     .option     = options,
55     .version    = LIBAVUTIL_VERSION_INT,
56 };
57
58 static int init(AVFilterContext *ctx, const char *args, void *opaque)
59 {
60     ASyncContext *s = ctx->priv;
61     int ret;
62
63     s->class = &async_class;
64     av_opt_set_defaults(s);
65
66     if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
67         av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
68         return ret;
69     }
70     av_opt_free(s);
71
72     s->pts = AV_NOPTS_VALUE;
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 static int request_frame(AVFilterLink *link)
116 {
117     AVFilterContext *ctx = link->src;
118     ASyncContext      *s = ctx->priv;
119     int ret = avfilter_request_frame(ctx->inputs[0]);
120     int nb_samples;
121
122     /* flush the fifo */
123     if (ret == AVERROR_EOF && (nb_samples = avresample_get_delay(s->avr))) {
124         AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
125                                                      nb_samples);
126         if (!buf)
127             return AVERROR(ENOMEM);
128         avresample_convert(s->avr, (void**)buf->extended_data, buf->linesize[0],
129                            nb_samples, NULL, 0, 0);
130         buf->pts = s->pts;
131         ff_filter_samples(link, buf);
132         return 0;
133     }
134
135     return ret;
136 }
137
138 static void write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
139 {
140     avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
141                        buf->linesize[0], buf->audio->nb_samples);
142     avfilter_unref_buffer(buf);
143 }
144
145 /* get amount of data currently buffered, in samples */
146 static int64_t get_delay(ASyncContext *s)
147 {
148     return avresample_available(s->avr) + avresample_get_delay(s->avr);
149 }
150
151 static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
152 {
153     AVFilterContext  *ctx = inlink->dst;
154     ASyncContext       *s = ctx->priv;
155     AVFilterLink *outlink = ctx->outputs[0];
156     int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
157     int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
158                   av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
159     int out_size;
160     int64_t delta;
161
162     /* buffer data until we get the first timestamp */
163     if (s->pts == AV_NOPTS_VALUE) {
164         if (pts != AV_NOPTS_VALUE) {
165             s->pts = pts - get_delay(s);
166         }
167         write_to_fifo(s, buf);
168         return;
169     }
170
171     /* now wait for the next timestamp */
172     if (pts == AV_NOPTS_VALUE) {
173         write_to_fifo(s, buf);
174         return;
175     }
176
177     /* when we have two timestamps, compute how many samples would we have
178      * to add/remove to get proper sync between data and timestamps */
179     delta    = pts - s->pts - get_delay(s);
180     out_size = avresample_available(s->avr);
181
182     if (labs(delta) > s->min_delta) {
183         av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
184         out_size += delta;
185     } else {
186         if (s->resample) {
187             int comp = av_clip(delta, -s->max_comp, s->max_comp);
188             av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
189             avresample_set_compensation(s->avr, delta, inlink->sample_rate);
190         }
191         delta = 0;
192     }
193
194     if (out_size > 0) {
195         AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
196                                                          out_size);
197         if (!buf_out)
198             return;
199
200         avresample_read(s->avr, (void**)buf_out->extended_data, out_size);
201         buf_out->pts = s->pts;
202
203         if (delta > 0) {
204             av_samples_set_silence(buf_out->extended_data, out_size - delta,
205                                    delta, nb_channels, buf->format);
206         }
207         ff_filter_samples(outlink, buf_out);
208     } else {
209         av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
210                "whole buffer.\n");
211     }
212
213     /* drain any remaining buffered data */
214     avresample_read(s->avr, NULL, avresample_available(s->avr));
215
216     s->pts = pts - avresample_get_delay(s->avr);
217     avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
218                        buf->linesize[0], buf->audio->nb_samples);
219     avfilter_unref_buffer(buf);
220 }
221
222 AVFilter avfilter_af_asyncts = {
223     .name        = "asyncts",
224     .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
225
226     .init        = init,
227     .uninit      = uninit,
228
229     .priv_size   = sizeof(ASyncContext),
230
231     .inputs      = (const AVFilterPad[]) {{ .name           = "default",
232                                             .type           = AVMEDIA_TYPE_AUDIO,
233                                             .filter_samples = filter_samples },
234                                           { NULL }},
235     .outputs     = (const AVFilterPad[]) {{ .name           = "default",
236                                             .type           = AVMEDIA_TYPE_AUDIO,
237                                             .config_props   = config_props,
238                                             .request_frame  = request_frame },
239                                           { NULL }},
240 };