af_asyncts.c
Go to the documentation of this file.
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 
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 
34  int64_t pts;
35  int min_delta;
37  int64_t first_pts;
38 
39  /* options */
40  int resample;
42  int max_comp;
43 
44  /* set by filter_frame() to signal an output frame to request_frame() */
46 } ASyncContext;
47 
48 #define OFFSET(x) offsetof(ASyncContext, x)
49 #define A AV_OPT_FLAG_AUDIO_PARAM
50 static const AVOption options[] = {
51  { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
52  { "min_delta", "Minimum difference between timestamps and audio data "
53  "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
54  { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
55  { "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 },
56  { NULL },
57 };
58 
59 static const AVClass async_class = {
60  .class_name = "asyncts filter",
61  .item_name = av_default_item_name,
62  .option = options,
63  .version = LIBAVUTIL_VERSION_INT,
64 };
65 
66 static int init(AVFilterContext *ctx, const char *args)
67 {
68  ASyncContext *s = ctx->priv;
69  int ret;
70 
71  s->class = &async_class;
73 
74  if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
75  av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
76  return ret;
77  }
78  av_opt_free(s);
79 
80  s->pts = AV_NOPTS_VALUE;
81  s->first_frame = 1;
82 
83  return 0;
84 }
85 
86 static void uninit(AVFilterContext *ctx)
87 {
88  ASyncContext *s = ctx->priv;
89 
90  if (s->avr) {
92  avresample_free(&s->avr);
93  }
94 }
95 
96 static int config_props(AVFilterLink *link)
97 {
98  ASyncContext *s = link->src->priv;
99  int ret;
100 
101  s->min_delta = s->min_delta_sec * link->sample_rate;
102  link->time_base = (AVRational){1, link->sample_rate};
103 
105  if (!s->avr)
106  return AVERROR(ENOMEM);
107 
108  av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
109  av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
110  av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
111  av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
112  av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
113  av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
114 
115  if (s->resample)
116  av_opt_set_int(s->avr, "force_resampling", 1, 0);
117 
118  if ((ret = avresample_open(s->avr)) < 0)
119  return ret;
120 
121  return 0;
122 }
123 
124 /* get amount of data currently buffered, in samples */
125 static int64_t get_delay(ASyncContext *s)
126 {
128 }
129 
131 {
132  ASyncContext *s = ctx->priv;
133 
134  if (s->pts < s->first_pts) {
135  int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
136  av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
137  delta);
138  avresample_read(s->avr, NULL, delta);
139  s->pts += delta;
140  } else if (s->first_frame)
141  s->pts = s->first_pts;
142 }
143 
144 static int request_frame(AVFilterLink *link)
145 {
146  AVFilterContext *ctx = link->src;
147  ASyncContext *s = ctx->priv;
148  int ret = 0;
149  int nb_samples;
150 
151  s->got_output = 0;
152  while (ret >= 0 && !s->got_output)
153  ret = ff_request_frame(ctx->inputs[0]);
154 
155  /* flush the fifo */
156  if (ret == AVERROR_EOF) {
157  if (s->first_pts != AV_NOPTS_VALUE)
158  handle_trimming(ctx);
159 
160  if (nb_samples = get_delay(s)) {
162  nb_samples);
163  if (!buf)
164  return AVERROR(ENOMEM);
165  ret = avresample_convert(s->avr, buf->extended_data,
166  buf->linesize[0], nb_samples, NULL, 0, 0);
167  if (ret <= 0) {
169  return (ret < 0) ? ret : AVERROR_EOF;
170  }
171 
172  buf->pts = s->pts;
173  return ff_filter_frame(link, buf);
174  }
175  }
176 
177  return ret;
178 }
179 
181 {
182  int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
183  buf->linesize[0], buf->audio->nb_samples);
185  return ret;
186 }
187 
188 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
189 {
190  AVFilterContext *ctx = inlink->dst;
191  ASyncContext *s = ctx->priv;
192  AVFilterLink *outlink = ctx->outputs[0];
194  int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
195  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
196  int out_size, ret;
197  int64_t delta;
198 
199  /* buffer data until we get the next timestamp */
200  if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
201  if (pts != AV_NOPTS_VALUE) {
202  s->pts = pts - get_delay(s);
203  }
204  return write_to_fifo(s, buf);
205  }
206 
207  if (s->first_pts != AV_NOPTS_VALUE) {
208  handle_trimming(ctx);
209  if (!avresample_available(s->avr))
210  return write_to_fifo(s, buf);
211  }
212 
213  /* when we have two timestamps, compute how many samples would we have
214  * to add/remove to get proper sync between data and timestamps */
215  delta = pts - s->pts - get_delay(s);
216  out_size = avresample_available(s->avr);
217 
218  if (labs(delta) > s->min_delta ||
219  (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
220  av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
221  out_size = av_clipl_int32((int64_t)out_size + delta);
222  } else {
223  if (s->resample) {
224  int comp = av_clip(delta, -s->max_comp, s->max_comp);
225  av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
226  avresample_set_compensation(s->avr, comp, inlink->sample_rate);
227  }
228  delta = 0;
229  }
230 
231  if (out_size > 0) {
233  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 */
277 
278  s->pts = pts - avresample_get_delay(s->avr);
279  ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
280  buf->linesize[0], buf->audio->nb_samples);
281 
282  s->first_frame = 0;
283 fail:
285 
286  return ret;
287 }
288 
290  {
291  .name = "default",
292  .type = AVMEDIA_TYPE_AUDIO,
293  .filter_frame = filter_frame,
294  },
295  { NULL }
296 };
297 
299  {
300  .name = "default",
301  .type = AVMEDIA_TYPE_AUDIO,
302  .config_props = config_props,
303  .request_frame = request_frame
304  },
305  { NULL }
306 };
307 
309  .name = "asyncts",
310  .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
311 
312  .init = init,
313  .uninit = uninit,
314 
315  .priv_size = sizeof(ASyncContext),
316 
317  .inputs = avfilter_af_asyncts_inputs,
318  .outputs = avfilter_af_asyncts_outputs,
319 };
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: avfilter.h:156
AVFilterBufferRef * ff_get_audio_buffer(AVFilterLink *link, int perms, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:63
static const AVFilterPad avfilter_af_asyncts_inputs[]
Definition: af_asyncts.c:289
int nb_samples
number of audio samples
Definition: avfilter.h:111
AVOption.
Definition: opt.h:233
AVFilterBufferRefAudioProps * audio
audio buffer specific properties
Definition: avfilter.h:160
float min_delta_sec
Definition: af_asyncts.c:41
int linesize[8]
number of bytes per line
Definition: avfilter.h:157
int min_delta
pad/trim min threshold in samples
Definition: af_asyncts.c:35
static const AVFilterPad outputs[]
Definition: af_ashowinfo.c:122
int avresample_read(AVAudioResampleContext *avr, uint8_t **output, int nb_samples)
Read samples from the output FIFO.
Definition: utils.c:476
void av_opt_set_defaults(void *s)
Set the values of all AVOption fields to their default values.
Definition: opt.c:505
int ff_filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:459
int av_set_options_string(void *ctx, const char *opts, const char *key_val_sep, const char *pairs_sep)
Parse the key/value pairs list in opts.
Definition: opt.c:587
int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta, int compensation_distance)
Set compensation for resampling.
Definition: resample.c:246
void avresample_free(AVAudioResampleContext **avr)
Free AVAudioResampleContext and associated AVOption values.
Definition: utils.c:202
void avfilter_unref_buffer(AVFilterBufferRef *ref)
Remove a reference to a buffer.
Definition: buffer.c:75
struct ASyncContext ASyncContext
const char * name
Pad name.
Definition: internal.h:39
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:38
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:426
float delta
AVOptions.
#define OFFSET(x)
Definition: af_asyncts.c:48
void avfilter_unref_bufferp(AVFilterBufferRef **ref)
Remove a reference to a buffer and set the pointer to NULL.
Definition: buffer.c:88
static int init(AVFilterContext *ctx, const char *args)
Definition: af_asyncts.c:66
static int resample(ResampleContext *c, void *dst, const void *src, int *consumed, int src_size, int dst_size, int update_ctx)
Definition: resample.c:331
static void uninit(AVFilterContext *ctx)
Definition: af_asyncts.c:86
void avresample_close(AVAudioResampleContext *avr)
Close AVAudioResampleContext.
Definition: utils.c:188
static int request_frame(AVFilterLink *link)
Definition: af_asyncts.c:144
int64_t pts
presentation timestamp.
Definition: avfilter.h:167
A filter pad used for either input or output.
Definition: internal.h:33
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:122
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
void * priv
private data for use by the filter
Definition: avfilter.h:439
int64_t pts
timestamp in samples of the first sample in fifo
Definition: af_asyncts.c:34
int av_get_channel_layout_nb_channels(uint64_t channel_layout)
Return the number of channels in the channel layout.
static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
Definition: af_asyncts.c:188
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:262
const AVClass * class
Definition: af_asyncts.c:31
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
AVFilter avfilter_af_asyncts
Definition: af_asyncts.c:308
static int config_props(AVFilterLink *link)
Definition: af_asyncts.c:96
struct AVRational AVRational
rational number numerator/denominator
external API header
int av_samples_set_silence(uint8_t **audio_data, int offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt)
Fill an audio buffer with silence.
Definition: samplefmt.c:204
AVAudioResampleContext * avr
Definition: af_asyncts.c:33
int first_frame
1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE ...
Definition: af_asyncts.c:36
int64_t first_pts
user-specified first expected pts, in samples
Definition: af_asyncts.c:37
LIBAVUTIL_VERSION_INT
Definition: eval.c:52
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:95
int avresample_get_delay(AVAudioResampleContext *avr)
Return the number of samples currently in the resampling delay buffer.
Definition: resample.c:462
A reference to an AVFilterBuffer.
Definition: avfilter.h:139
NULL
Definition: eval.c:52
int avresample_available(AVAudioResampleContext *avr)
Return the number of available samples in the output FIFO.
Definition: utils.c:471
av_default_item_name
Definition: dnxhdenc.c:43
#define A
Definition: af_asyncts.c:49
out nb_samples
Describe the class of an AVClass context structure.
Definition: log.h:33
Filter definition.
Definition: avfilter.h:371
static const AVFilterPad inputs[]
Definition: af_ashowinfo.c:110
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition: samplefmt.c:101
int avresample_convert(AVAudioResampleContext *avr, uint8_t **output, int out_plane_size, int out_samples, uint8_t **input, int in_plane_size, int in_samples)
Convert input samples and write them to the output FIFO.
Definition: utils.c:252
const char * name
filter name
Definition: avfilter.h:372
uint64_t channel_layout
channel layout of audio buffer
Definition: avfilter.h:110
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:433
static int64_t get_delay(ASyncContext *s)
Definition: af_asyncts.c:125
static const AVOption options[]
Definition: af_asyncts.c:50
static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
Definition: af_asyncts.c:180
AVAudioResampleContext * avresample_alloc_context(void)
Allocate AVAudioResampleContext and set options.
Definition: options.c:82
void av_opt_free(void *obj)
Free all string and binary options in obj.
Definition: opt.c:607
common internal and external API header
static void handle_trimming(AVFilterContext *ctx)
Definition: af_asyncts.c:130
static const AVClass async_class
Definition: af_asyncts.c:59
#define AV_PERM_WRITE
can write to the buffer
Definition: avfilter.h:98
int got_output
Definition: af_asyncts.c:45
Audio FIFO Buffer.
int format
media format
Definition: avfilter.h:170
An instance of a filter.
Definition: avfilter.h:418
static const AVFilterPad avfilter_af_asyncts_outputs[]
Definition: af_asyncts.c:298
static void comp(unsigned char *dst, int dst_stride, unsigned char *src, int src_stride, int add)
Definition: eamad.c:73
int ff_request_frame(AVFilterLink *link)
Request an input frame from the filter at the other end of the link.
Definition: avfilter.c:239
int nb_channels
internal API functions
int avresample_open(AVAudioResampleContext *avr)
Initialize AVAudioResampleContext.
Definition: utils.c:32