Libav
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 
19 #include <stdint.h>
20 
22 #include "libavutil/attributes.h"
23 #include "libavutil/audio_fifo.h"
24 #include "libavutil/common.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/samplefmt.h"
28 
29 #include "audio.h"
30 #include "avfilter.h"
31 #include "internal.h"
32 
33 typedef struct ASyncContext {
34  const AVClass *class;
35 
37  int64_t pts;
38  int min_delta;
40  int64_t first_pts;
41  int comp;
42 
43  /* options */
44  int resample;
46  int max_comp;
47 
48  /* set by filter_frame() to signal an output frame to request_frame() */
50 } ASyncContext;
51 
52 #define OFFSET(x) offsetof(ASyncContext, x)
53 #define A AV_OPT_FLAG_AUDIO_PARAM
54 static const AVOption options[] = {
55  { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
56  { "min_delta", "Minimum difference between timestamps and audio data "
57  "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
58  { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
59  { "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 },
60  { NULL },
61 };
62 
63 static const AVClass async_class = {
64  .class_name = "asyncts filter",
65  .item_name = av_default_item_name,
66  .option = options,
67  .version = LIBAVUTIL_VERSION_INT,
68 };
69 
70 static av_cold int init(AVFilterContext *ctx)
71 {
72  ASyncContext *s = ctx->priv;
73 
74  s->pts = AV_NOPTS_VALUE;
75  s->first_frame = 1;
76 
77  return 0;
78 }
79 
80 static av_cold void uninit(AVFilterContext *ctx)
81 {
82  ASyncContext *s = ctx->priv;
83 
84  if (s->avr) {
86  avresample_free(&s->avr);
87  }
88 }
89 
90 static int config_props(AVFilterLink *link)
91 {
92  ASyncContext *s = link->src->priv;
93  int ret;
94 
95  s->min_delta = s->min_delta_sec * link->sample_rate;
96  link->time_base = (AVRational){1, link->sample_rate};
97 
99  if (!s->avr)
100  return AVERROR(ENOMEM);
101 
102  av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
103  av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
104  av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
105  av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
106  av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
107  av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
108 
109  if (s->resample)
110  av_opt_set_int(s->avr, "force_resampling", 1, 0);
111 
112  if ((ret = avresample_open(s->avr)) < 0)
113  return ret;
114 
115  return 0;
116 }
117 
118 /* get amount of data currently buffered, in samples */
119 static int64_t get_delay(ASyncContext *s)
120 {
122 }
123 
125 {
126  ASyncContext *s = ctx->priv;
127 
128  if (s->pts < s->first_pts) {
129  int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
130  av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
131  delta);
132  avresample_read(s->avr, NULL, delta);
133  s->pts += delta;
134  } else if (s->first_frame)
135  s->pts = s->first_pts;
136 }
137 
138 static int request_frame(AVFilterLink *link)
139 {
140  AVFilterContext *ctx = link->src;
141  ASyncContext *s = ctx->priv;
142  int ret = 0;
143  int nb_samples;
144 
145  s->got_output = 0;
146  while (ret >= 0 && !s->got_output)
147  ret = ff_request_frame(ctx->inputs[0]);
148 
149  /* flush the fifo */
150  if (ret == AVERROR_EOF) {
151  if (s->first_pts != AV_NOPTS_VALUE)
152  handle_trimming(ctx);
153 
154  if (nb_samples = get_delay(s)) {
155  AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
156  if (!buf)
157  return AVERROR(ENOMEM);
158  ret = avresample_convert(s->avr, buf->extended_data,
159  buf->linesize[0], nb_samples, NULL, 0, 0);
160  if (ret <= 0) {
161  av_frame_free(&buf);
162  return (ret < 0) ? ret : AVERROR_EOF;
163  }
164 
165  buf->pts = s->pts;
166  return ff_filter_frame(link, buf);
167  }
168  }
169 
170  return ret;
171 }
172 
173 static int write_to_fifo(ASyncContext *s, AVFrame *buf)
174 {
175  int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
176  buf->linesize[0], buf->nb_samples);
177  av_frame_free(&buf);
178  return ret;
179 }
180 
181 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
182 {
183  AVFilterContext *ctx = inlink->dst;
184  ASyncContext *s = ctx->priv;
185  AVFilterLink *outlink = ctx->outputs[0];
187  int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
188  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
189  int out_size, ret;
190  int64_t delta;
191  int64_t new_pts;
192 
193  /* buffer data until we get the next timestamp */
194  if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
195  if (pts != AV_NOPTS_VALUE) {
196  s->pts = pts - get_delay(s);
197  }
198  return write_to_fifo(s, buf);
199  }
200 
201  if (s->first_pts != AV_NOPTS_VALUE) {
202  handle_trimming(ctx);
203  if (!avresample_available(s->avr))
204  return write_to_fifo(s, buf);
205  }
206 
207  /* when we have two timestamps, compute how many samples would we have
208  * to add/remove to get proper sync between data and timestamps */
209  delta = pts - s->pts - get_delay(s);
210  out_size = avresample_available(s->avr);
211 
212  if (labs(delta) > s->min_delta ||
213  (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
214  av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
215  out_size = av_clipl_int32((int64_t)out_size + delta);
216  } else {
217  if (s->resample) {
218  // adjust the compensation if delta is non-zero
219  int delay = get_delay(s);
220  int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
221  -s->max_comp, s->max_comp);
222  if (comp != s->comp) {
223  av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
224  if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
225  s->comp = comp;
226  }
227  }
228  }
229  // adjust PTS to avoid monotonicity errors with input PTS jitter
230  pts -= delta;
231  delta = 0;
232  }
233 
234  if (out_size > 0) {
235  AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
236  if (!buf_out) {
237  ret = AVERROR(ENOMEM);
238  goto fail;
239  }
240 
241  if (s->first_frame && delta > 0) {
242  int planar = av_sample_fmt_is_planar(buf_out->format);
243  int planes = planar ? nb_channels : 1;
244  int block_size = av_get_bytes_per_sample(buf_out->format) *
245  (planar ? 1 : nb_channels);
246 
247  int ch;
248 
249  av_samples_set_silence(buf_out->extended_data, 0, delta,
250  nb_channels, buf->format);
251 
252  for (ch = 0; ch < planes; ch++)
253  buf_out->extended_data[ch] += delta * block_size;
254 
255  avresample_read(s->avr, buf_out->extended_data, out_size);
256 
257  for (ch = 0; ch < planes; ch++)
258  buf_out->extended_data[ch] -= delta * block_size;
259  } else {
260  avresample_read(s->avr, buf_out->extended_data, out_size);
261 
262  if (delta > 0) {
263  av_samples_set_silence(buf_out->extended_data, out_size - delta,
264  delta, nb_channels, buf->format);
265  }
266  }
267  buf_out->pts = s->pts;
268  ret = ff_filter_frame(outlink, buf_out);
269  if (ret < 0)
270  goto fail;
271  s->got_output = 1;
272  } else if (avresample_available(s->avr)) {
273  av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
274  "whole buffer.\n");
275  }
276 
277  /* drain any remaining buffered data */
279 
280  new_pts = pts - avresample_get_delay(s->avr);
281  /* check for s->pts monotonicity */
282  if (new_pts > s->pts) {
283  s->pts = new_pts;
284  ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
285  buf->linesize[0], buf->nb_samples);
286  } else {
287  av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
288  "whole buffer.\n");
289  ret = 0;
290  }
291 
292  s->first_frame = 0;
293 fail:
294  av_frame_free(&buf);
295 
296  return ret;
297 }
298 
300  {
301  .name = "default",
302  .type = AVMEDIA_TYPE_AUDIO,
303  .filter_frame = filter_frame,
304  },
305  { NULL }
306 };
307 
309  {
310  .name = "default",
311  .type = AVMEDIA_TYPE_AUDIO,
312  .config_props = config_props,
313  .request_frame = request_frame
314  },
315  { NULL }
316 };
317 
319  .name = "asyncts",
320  .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
321 
322  .init = init,
323  .uninit = uninit,
324 
325  .priv_size = sizeof(ASyncContext),
326  .priv_class = &async_class,
327 
330 };
This structure describes decoded (raw) audio or video data.
Definition: frame.h:135
static const AVFilterPad avfilter_af_asyncts_inputs[]
Definition: af_asyncts.c:299
AVOption.
Definition: opt.h:234
float min_delta_sec
Definition: af_asyncts.c:45
int min_delta
pad/trim min threshold in samples
Definition: af_asyncts.c:38
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
static const AVFilterPad outputs[]
Definition: af_ashowinfo.c:232
Main libavfilter public API header.
int avresample_read(AVAudioResampleContext *avr, uint8_t **output, int nb_samples)
Read samples from the output FIFO.
Definition: utils.c:768
static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
Definition: af_asyncts.c:181
int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta, int compensation_distance)
Set compensation for resampling.
Definition: resample.c:231
void avresample_free(AVAudioResampleContext **avr)
Free AVAudioResampleContext and associated AVOption values.
Definition: utils.c:278
Macro definitions for various function/variable attributes.
static av_cold int init(AVFilterContext *ctx)
Definition: af_asyncts.c:70
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:571
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:733
#define av_cold
Definition: attributes.h:66
float delta
AVOptions.
static av_cold void uninit(AVFilterContext *ctx)
Definition: af_asyncts.c:80
#define OFFSET(x)
Definition: af_asyncts.c:52
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:211
#define AVERROR_EOF
End of file.
Definition: error.h:51
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:139
void avresample_close(AVAudioResampleContext *avr)
Close AVAudioResampleContext.
Definition: utils.c:262
static int request_frame(AVFilterLink *link)
Definition: af_asyncts.c:138
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition: samplefmt.c:101
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:129
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:206
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:57
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:69
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:150
int comp
current resample compensation
Definition: af_asyncts.c:41
void * priv
private data for use by the filter
Definition: avfilter.h:584
int64_t pts
timestamp in samples of the first sample in fifo
Definition: af_asyncts.c:37
int av_get_channel_layout_nb_channels(uint64_t channel_layout)
Return the number of channels in the channel layout.
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:268
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:169
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:381
static int config_props(AVFilterLink *link)
Definition: af_asyncts.c:90
external API header
#define FFMIN(a, b)
Definition: common.h:57
AVAudioResampleContext * avr
Definition: af_asyncts.c:36
int first_frame
1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE ...
Definition: af_asyncts.c:39
int64_t first_pts
user-specified first expected pts, in samples
Definition: af_asyncts.c:40
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:186
int avresample_get_delay(AVAudioResampleContext *avr)
Return the number of samples currently in the resampling delay buffer.
Definition: resample.c:493
NULL
Definition: eval.c:55
int avresample_available(AVAudioResampleContext *avr)
Return the number of available samples in the output FIFO.
Definition: utils.c:744
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:153
av_default_item_name
Definition: dnxhdenc.c:52
#define A
Definition: af_asyncts.c:53
static int write_to_fifo(ASyncContext *s, AVFrame *buf)
Definition: af_asyncts.c:173
Describe the class of an AVClass context structure.
Definition: log.h:33
Filter definition.
Definition: avfilter.h:421
static const AVFilterPad inputs[]
Definition: af_ashowinfo.c:221
rational number numerator/denominator
Definition: rational.h:43
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:330
const char * name
Filter name.
Definition: avfilter.h:425
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:578
AVFilter ff_af_asyncts
Definition: af_asyncts.c:318
static int64_t get_delay(ASyncContext *s)
Definition: af_asyncts.c:119
static const AVOption options[]
Definition: af_asyncts.c:54
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:95
AVAudioResampleContext * avresample_alloc_context(void)
Allocate AVAudioResampleContext and set options.
Definition: options.c:96
common internal and external API header
static void handle_trimming(AVFilterContext *ctx)
Definition: af_asyncts.c:124
struct AVFilterPad AVFilterPad
Definition: avfilter.h:67
static const AVClass async_class
Definition: af_asyncts.c:63
int got_output
Definition: af_asyncts.c:49
Audio FIFO Buffer.
An instance of a filter.
Definition: avfilter.h:563
static const AVFilterPad avfilter_af_asyncts_outputs[]
Definition: af_asyncts.c:308
static void comp(unsigned char *dst, int dst_stride, unsigned char *src, int src_stride, int add)
Definition: eamad.c:83
int ff_request_frame(AVFilterLink *link)
Request an input frame from the filter at the other end of the link.
Definition: avfilter.c:249
int nb_channels
internal API functions
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:169
int avresample_open(AVAudioResampleContext *avr)
Initialize AVAudioResampleContext.
Definition: utils.c:36
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:179
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:228
static int resample(ResampleContext *c, void *dst, const void *src, int *consumed, int src_size, int dst_size, int update_ctx, int nearest_neighbour)
Definition: resample.c:316