resample: Avoid off-by-1 errors in PTS calcs.
[platform/upstream/libav.git] / libavfilter / af_resample.c
1 /*
2  *
3  * This file is part of Libav.
4  *
5  * Libav is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * Libav is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with Libav; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 /**
21  * @file
22  * sample format and channel layout conversion audio filter
23  */
24
25 #include "libavutil/avassert.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/common.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31
32 #include "libavresample/avresample.h"
33
34 #include "audio.h"
35 #include "avfilter.h"
36 #include "formats.h"
37 #include "internal.h"
38
39 typedef struct ResampleContext {
40     const AVClass *class;
41     AVAudioResampleContext *avr;
42     AVDictionary *options;
43
44     int64_t next_pts;
45     int64_t next_in_pts;
46
47     /* set by filter_frame() to signal an output frame to request_frame() */
48     int got_output;
49 } ResampleContext;
50
51 static av_cold int init(AVFilterContext *ctx, AVDictionary **opts)
52 {
53     ResampleContext *s = ctx->priv;
54     const AVClass *avr_class = avresample_get_class();
55     AVDictionaryEntry *e = NULL;
56
57     while ((e = av_dict_get(*opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
58         if (av_opt_find(&avr_class, e->key, NULL, 0,
59                         AV_OPT_SEARCH_FAKE_OBJ | AV_OPT_SEARCH_CHILDREN))
60             av_dict_set(&s->options, e->key, e->value, 0);
61     }
62
63     e = NULL;
64     while ((e = av_dict_get(s->options, "", e, AV_DICT_IGNORE_SUFFIX)))
65         av_dict_set(opts, e->key, NULL, 0);
66
67     /* do not allow the user to override basic format options */
68     av_dict_set(&s->options,  "in_channel_layout", NULL, 0);
69     av_dict_set(&s->options, "out_channel_layout", NULL, 0);
70     av_dict_set(&s->options,  "in_sample_fmt",     NULL, 0);
71     av_dict_set(&s->options, "out_sample_fmt",     NULL, 0);
72     av_dict_set(&s->options,  "in_sample_rate",    NULL, 0);
73     av_dict_set(&s->options, "out_sample_rate",    NULL, 0);
74
75     return 0;
76 }
77
78 static av_cold void uninit(AVFilterContext *ctx)
79 {
80     ResampleContext *s = ctx->priv;
81
82     if (s->avr) {
83         avresample_close(s->avr);
84         avresample_free(&s->avr);
85     }
86     av_dict_free(&s->options);
87 }
88
89 static int query_formats(AVFilterContext *ctx)
90 {
91     AVFilterLink *inlink  = ctx->inputs[0];
92     AVFilterLink *outlink = ctx->outputs[0];
93
94     AVFilterFormats        *in_formats      = ff_all_formats(AVMEDIA_TYPE_AUDIO);
95     AVFilterFormats        *out_formats     = ff_all_formats(AVMEDIA_TYPE_AUDIO);
96     AVFilterFormats        *in_samplerates  = ff_all_samplerates();
97     AVFilterFormats        *out_samplerates = ff_all_samplerates();
98     AVFilterChannelLayouts *in_layouts      = ff_all_channel_layouts();
99     AVFilterChannelLayouts *out_layouts     = ff_all_channel_layouts();
100
101     ff_formats_ref(in_formats,  &inlink->out_formats);
102     ff_formats_ref(out_formats, &outlink->in_formats);
103
104     ff_formats_ref(in_samplerates,  &inlink->out_samplerates);
105     ff_formats_ref(out_samplerates, &outlink->in_samplerates);
106
107     ff_channel_layouts_ref(in_layouts,  &inlink->out_channel_layouts);
108     ff_channel_layouts_ref(out_layouts, &outlink->in_channel_layouts);
109
110     return 0;
111 }
112
113 static int config_output(AVFilterLink *outlink)
114 {
115     AVFilterContext *ctx = outlink->src;
116     AVFilterLink *inlink = ctx->inputs[0];
117     ResampleContext   *s = ctx->priv;
118     char buf1[64], buf2[64];
119     int ret;
120
121     if (s->avr) {
122         avresample_close(s->avr);
123         avresample_free(&s->avr);
124     }
125
126     if (inlink->channel_layout == outlink->channel_layout &&
127         inlink->sample_rate    == outlink->sample_rate    &&
128         (inlink->format        == outlink->format ||
129         (av_get_channel_layout_nb_channels(inlink->channel_layout)  == 1 &&
130          av_get_channel_layout_nb_channels(outlink->channel_layout) == 1 &&
131          av_get_planar_sample_fmt(inlink->format) ==
132          av_get_planar_sample_fmt(outlink->format))))
133         return 0;
134
135     if (!(s->avr = avresample_alloc_context()))
136         return AVERROR(ENOMEM);
137
138     if (s->options) {
139         AVDictionaryEntry *e = NULL;
140         while ((e = av_dict_get(s->options, "", e, AV_DICT_IGNORE_SUFFIX)))
141             av_log(ctx, AV_LOG_VERBOSE, "lavr option: %s=%s\n", e->key, e->value);
142
143         av_opt_set_dict(s->avr, &s->options);
144     }
145
146     av_opt_set_int(s->avr,  "in_channel_layout", inlink ->channel_layout, 0);
147     av_opt_set_int(s->avr, "out_channel_layout", outlink->channel_layout, 0);
148     av_opt_set_int(s->avr,  "in_sample_fmt",     inlink ->format,         0);
149     av_opt_set_int(s->avr, "out_sample_fmt",     outlink->format,         0);
150     av_opt_set_int(s->avr,  "in_sample_rate",    inlink ->sample_rate,    0);
151     av_opt_set_int(s->avr, "out_sample_rate",    outlink->sample_rate,    0);
152
153     if ((ret = avresample_open(s->avr)) < 0)
154         return ret;
155
156     outlink->time_base = (AVRational){ 1, outlink->sample_rate };
157     s->next_pts        = AV_NOPTS_VALUE;
158     s->next_in_pts     = AV_NOPTS_VALUE;
159
160     av_get_channel_layout_string(buf1, sizeof(buf1),
161                                  -1, inlink ->channel_layout);
162     av_get_channel_layout_string(buf2, sizeof(buf2),
163                                  -1, outlink->channel_layout);
164     av_log(ctx, AV_LOG_VERBOSE,
165            "fmt:%s srate:%d cl:%s -> fmt:%s srate:%d cl:%s\n",
166            av_get_sample_fmt_name(inlink ->format), inlink ->sample_rate, buf1,
167            av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf2);
168
169     return 0;
170 }
171
172 static int request_frame(AVFilterLink *outlink)
173 {
174     AVFilterContext *ctx = outlink->src;
175     ResampleContext   *s = ctx->priv;
176     int ret = 0;
177
178     s->got_output = 0;
179     while (ret >= 0 && !s->got_output)
180         ret = ff_request_frame(ctx->inputs[0]);
181
182     /* flush the lavr delay buffer */
183     if (ret == AVERROR_EOF && s->avr) {
184         AVFrame *frame;
185         int nb_samples = avresample_get_out_samples(s->avr, 0);
186
187         if (!nb_samples)
188             return ret;
189
190         frame = ff_get_audio_buffer(outlink, nb_samples);
191         if (!frame)
192             return AVERROR(ENOMEM);
193
194         ret = avresample_convert(s->avr, frame->extended_data,
195                                  frame->linesize[0], nb_samples,
196                                  NULL, 0, 0);
197         if (ret <= 0) {
198             av_frame_free(&frame);
199             return (ret == 0) ? AVERROR_EOF : ret;
200         }
201
202         frame->pts = s->next_pts;
203         return ff_filter_frame(outlink, frame);
204     }
205     return ret;
206 }
207
208 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
209 {
210     AVFilterContext  *ctx = inlink->dst;
211     ResampleContext    *s = ctx->priv;
212     AVFilterLink *outlink = ctx->outputs[0];
213     int ret;
214
215     if (s->avr) {
216         AVFrame *out;
217         int delay, nb_samples;
218
219         /* maximum possible samples lavr can output */
220         delay      = avresample_get_delay(s->avr);
221         nb_samples = avresample_get_out_samples(s->avr, in->nb_samples);
222
223         out = ff_get_audio_buffer(outlink, nb_samples);
224         if (!out) {
225             ret = AVERROR(ENOMEM);
226             goto fail;
227         }
228
229         ret = avresample_convert(s->avr, out->extended_data, out->linesize[0],
230                                  nb_samples, in->extended_data, in->linesize[0],
231                                  in->nb_samples);
232         if (ret <= 0) {
233             av_frame_free(&out);
234             if (ret < 0)
235                 goto fail;
236         }
237
238         av_assert0(!avresample_available(s->avr));
239
240         if (s->next_pts == AV_NOPTS_VALUE) {
241             if (in->pts == AV_NOPTS_VALUE) {
242                 av_log(ctx, AV_LOG_WARNING, "First timestamp is missing, "
243                        "assuming 0.\n");
244                 s->next_pts = 0;
245             } else
246                 s->next_pts = av_rescale_q(in->pts, inlink->time_base,
247                                            outlink->time_base);
248         }
249
250         if (ret > 0) {
251             out->nb_samples = ret;
252
253             ret = av_frame_copy_props(out, in);
254             if (ret < 0) {
255                 av_frame_free(&out);
256                 goto fail;
257             }
258
259             out->sample_rate = outlink->sample_rate;
260             /* Only convert in->pts if there is a discontinuous jump.
261                This ensures that out->pts tracks the number of samples actually
262                output by the resampler in the absence of such a jump.
263                Otherwise, the rounding in av_rescale_q() and av_rescale()
264                causes off-by-1 errors. */
265             if (in->pts != AV_NOPTS_VALUE && in->pts != s->next_in_pts) {
266                 out->pts = av_rescale_q(in->pts, inlink->time_base,
267                                             outlink->time_base) -
268                                av_rescale(delay, outlink->sample_rate,
269                                           inlink->sample_rate);
270             } else
271                 out->pts = s->next_pts;
272
273             s->next_pts = out->pts + out->nb_samples;
274             s->next_in_pts = in->pts + in->nb_samples;
275
276             ret = ff_filter_frame(outlink, out);
277             s->got_output = 1;
278         }
279
280 fail:
281         av_frame_free(&in);
282     } else {
283         in->format = outlink->format;
284         ret = ff_filter_frame(outlink, in);
285         s->got_output = 1;
286     }
287
288     return ret;
289 }
290
291 static const AVClass *resample_child_class_next(const AVClass *prev)
292 {
293     return prev ? NULL : avresample_get_class();
294 }
295
296 static void *resample_child_next(void *obj, void *prev)
297 {
298     ResampleContext *s = obj;
299     return prev ? NULL : s->avr;
300 }
301
302 static const AVClass resample_class = {
303     .class_name       = "resample",
304     .item_name        = av_default_item_name,
305     .version          = LIBAVUTIL_VERSION_INT,
306     .child_class_next = resample_child_class_next,
307     .child_next       = resample_child_next,
308 };
309
310 static const AVFilterPad avfilter_af_resample_inputs[] = {
311     {
312         .name           = "default",
313         .type           = AVMEDIA_TYPE_AUDIO,
314         .filter_frame   = filter_frame,
315     },
316     { NULL }
317 };
318
319 static const AVFilterPad avfilter_af_resample_outputs[] = {
320     {
321         .name          = "default",
322         .type          = AVMEDIA_TYPE_AUDIO,
323         .config_props  = config_output,
324         .request_frame = request_frame
325     },
326     { NULL }
327 };
328
329 AVFilter ff_af_resample = {
330     .name          = "resample",
331     .description   = NULL_IF_CONFIG_SMALL("Audio resampling and conversion."),
332     .priv_size     = sizeof(ResampleContext),
333     .priv_class    = &resample_class,
334
335     .init_dict      = init,
336     .uninit         = uninit,
337     .query_formats  = query_formats,
338
339     .inputs    = avfilter_af_resample_inputs,
340     .outputs   = avfilter_af_resample_outputs,
341 };