FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
af_asyncts.c
Go to the documentation of this file.
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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; ///< timestamp in samples of the first sample in fifo
38  int min_delta; ///< pad/trim min threshold in samples
39  int first_frame; ///< 1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE
40  int64_t first_pts; ///< user-specified first expected pts, in samples
41  int comp; ///< current resample compensation
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 #define F AV_OPT_FLAG_FILTERING_PARAM
55 static const AVOption asyncts_options[] = {
56  { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, A|F },
57  { "min_delta", "Minimum difference between timestamps and audio data "
58  "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A|F },
59  { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A|F },
60  { "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|F },
61  { NULL }
62 };
63 
64 AVFILTER_DEFINE_CLASS(asyncts);
65 
67 {
68  ASyncContext *s = ctx->priv;
69 
70  s->pts = AV_NOPTS_VALUE;
71  s->first_frame = 1;
72 
73  return 0;
74 }
75 
77 {
78  ASyncContext *s = ctx->priv;
79 
80  if (s->avr) {
82  avresample_free(&s->avr);
83  }
84 }
85 
86 static int config_props(AVFilterLink *link)
87 {
88  ASyncContext *s = link->src->priv;
89  int ret;
90 
91  s->min_delta = s->min_delta_sec * link->sample_rate;
92  link->time_base = (AVRational){1, link->sample_rate};
93 
95  if (!s->avr)
96  return AVERROR(ENOMEM);
97 
98  av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
99  av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
100  av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
101  av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
102  av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
103  av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
104 
105  if (s->resample)
106  av_opt_set_int(s->avr, "force_resampling", 1, 0);
107 
108  if ((ret = avresample_open(s->avr)) < 0)
109  return ret;
110 
111  return 0;
112 }
113 
114 /* get amount of data currently buffered, in samples */
115 static int64_t get_delay(ASyncContext *s)
116 {
118 }
119 
121 {
122  ASyncContext *s = ctx->priv;
123 
124  if (s->pts < s->first_pts) {
125  int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
126  av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
127  delta);
128  avresample_read(s->avr, NULL, delta);
129  s->pts += delta;
130  } else if (s->first_frame)
131  s->pts = s->first_pts;
132 }
133 
134 static int request_frame(AVFilterLink *link)
135 {
136  AVFilterContext *ctx = link->src;
137  ASyncContext *s = ctx->priv;
138  int ret = 0;
139  int nb_samples;
140 
141  s->got_output = 0;
142  ret = ff_request_frame(ctx->inputs[0]);
143 
144  /* flush the fifo */
145  if (ret == AVERROR_EOF) {
146  if (s->first_pts != AV_NOPTS_VALUE)
147  handle_trimming(ctx);
148 
149  if (nb_samples = get_delay(s)) {
150  AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
151  if (!buf)
152  return AVERROR(ENOMEM);
153  ret = avresample_convert(s->avr, buf->extended_data,
154  buf->linesize[0], nb_samples, NULL, 0, 0);
155  if (ret <= 0) {
156  av_frame_free(&buf);
157  return (ret < 0) ? ret : AVERROR_EOF;
158  }
159 
160  buf->pts = s->pts;
161  return ff_filter_frame(link, buf);
162  }
163  }
164 
165  return ret;
166 }
167 
169 {
170  int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
171  buf->linesize[0], buf->nb_samples);
172  av_frame_free(&buf);
173  return ret;
174 }
175 
176 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
177 {
178  AVFilterContext *ctx = inlink->dst;
179  ASyncContext *s = ctx->priv;
180  AVFilterLink *outlink = ctx->outputs[0];
182  int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
183  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
184  int out_size, ret;
185  int64_t delta;
186  int64_t new_pts;
187 
188  /* buffer data until we get the next timestamp */
189  if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
190  if (pts != AV_NOPTS_VALUE) {
191  s->pts = pts - get_delay(s);
192  }
193  return write_to_fifo(s, buf);
194  }
195 
196  if (s->first_pts != AV_NOPTS_VALUE) {
197  handle_trimming(ctx);
198  if (!avresample_available(s->avr))
199  return write_to_fifo(s, buf);
200  }
201 
202  /* when we have two timestamps, compute how many samples would we have
203  * to add/remove to get proper sync between data and timestamps */
204  delta = pts - s->pts - get_delay(s);
205  out_size = avresample_available(s->avr);
206 
207  if (llabs(delta) > s->min_delta ||
208  (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
209  av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
210  out_size = av_clipl_int32((int64_t)out_size + delta);
211  } else {
212  if (s->resample) {
213  // adjust the compensation if delta is non-zero
214  int delay = get_delay(s);
215  int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
216  -s->max_comp, s->max_comp);
217  if (comp != s->comp) {
218  av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
219  if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
220  s->comp = comp;
221  }
222  }
223  }
224  // adjust PTS to avoid monotonicity errors with input PTS jitter
225  pts -= delta;
226  delta = 0;
227  }
228 
229  if (out_size > 0) {
230  AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
231  if (!buf_out) {
232  ret = AVERROR(ENOMEM);
233  goto fail;
234  }
235 
236  if (s->first_frame && delta > 0) {
237  int planar = av_sample_fmt_is_planar(buf_out->format);
238  int planes = planar ? nb_channels : 1;
239  int block_size = av_get_bytes_per_sample(buf_out->format) *
240  (planar ? 1 : nb_channels);
241 
242  int ch;
243 
244  av_samples_set_silence(buf_out->extended_data, 0, delta,
245  nb_channels, buf->format);
246 
247  for (ch = 0; ch < planes; ch++)
248  buf_out->extended_data[ch] += delta * block_size;
249 
250  avresample_read(s->avr, buf_out->extended_data, out_size);
251 
252  for (ch = 0; ch < planes; ch++)
253  buf_out->extended_data[ch] -= delta * block_size;
254  } else {
255  avresample_read(s->avr, buf_out->extended_data, out_size);
256 
257  if (delta > 0) {
258  av_samples_set_silence(buf_out->extended_data, out_size - delta,
259  delta, nb_channels, buf->format);
260  }
261  }
262  buf_out->pts = s->pts;
263  ret = ff_filter_frame(outlink, buf_out);
264  if (ret < 0)
265  goto fail;
266  s->got_output = 1;
267  } else if (avresample_available(s->avr)) {
268  av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
269  "whole buffer.\n");
270  }
271 
272  /* drain any remaining buffered data */
274 
275  new_pts = pts - avresample_get_delay(s->avr);
276  /* check for s->pts monotonicity */
277  if (new_pts > s->pts) {
278  s->pts = new_pts;
279  ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
280  buf->linesize[0], buf->nb_samples);
281  } else {
282  av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
283  "whole buffer.\n");
284  ret = 0;
285  }
286 
287  s->first_frame = 0;
288 fail:
289  av_frame_free(&buf);
290 
291  return ret;
292 }
293 
295  {
296  .name = "default",
297  .type = AVMEDIA_TYPE_AUDIO,
298  .filter_frame = filter_frame
299  },
300  { NULL }
301 };
302 
304  {
305  .name = "default",
306  .type = AVMEDIA_TYPE_AUDIO,
307  .config_props = config_props,
308  .request_frame = request_frame
309  },
310  { NULL }
311 };
312 
314  .name = "asyncts",
315  .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps."),
316  .init = init,
317  .uninit = uninit,
318  .priv_size = sizeof(ASyncContext),
319  .priv_class = &asyncts_class,
320  .inputs = avfilter_af_asyncts_inputs,
321  .outputs = avfilter_af_asyncts_outputs,
322 };
#define NULL
Definition: coverity.c:32
const char * s
Definition: avisynth_c.h:631
This structure describes decoded (raw) audio or video data.
Definition: frame.h:184
static const AVFilterPad avfilter_af_asyncts_inputs[]
Definition: af_asyncts.c:294
AVOption.
Definition: opt.h:245
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:182
int avresample_convert(AVAudioResampleContext *avr, uint8_t **output, int out_plane_size, int out_samples, uint8_t *const *input, int in_plane_size, int in_samples)
Convert input samples and write them to the output FIFO.
Definition: utils.c:330
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:772
int out_size
Definition: movenc.c:55
static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
Definition: af_asyncts.c:176
int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta, int compensation_distance)
Set compensation for resampling.
Definition: resample.c:233
void avresample_free(AVAudioResampleContext **avr)
Free AVAudioResampleContext and associated AVOption values.
Definition: utils.c:278
Macro definitions for various function/variable attributes.
int av_get_channel_layout_nb_channels(uint64_t channel_layout)
Return the number of channels in the channel layout.
static av_cold int init(AVFilterContext *ctx)
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, int nearest_neighbour)
Definition: resample.c:259
const char * name
Pad name.
Definition: internal.h:59
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:313
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1180
#define av_cold
Definition: attributes.h:82
float delta
AVOptions.
static av_cold void uninit(AVFilterContext *ctx)
Definition: af_asyncts.c:76
#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:268
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
#define av_log(a,...)
void avresample_close(AVAudioResampleContext *avr)
Close AVAudioResampleContext.
Definition: utils.c:262
static int request_frame(AVFilterLink *link)
Definition: af_asyncts.c:134
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition: samplefmt.c:110
A filter pad used for either input or output.
Definition: internal.h:53
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
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:235
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:65
#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:153
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
int comp
current resample compensation
Definition: af_asyncts.c:41
void * priv
private data for use by the filter
Definition: avfilter.h:320
int64_t pts
timestamp in samples of the first sample in fifo
Definition: af_asyncts.c:37
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:539
#define fail()
Definition: checkasm.h:81
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:349
static int config_props(AVFilterLink *link)
Definition: af_asyncts.c:86
external API header
#define FFMIN(a, b)
Definition: common.h:96
static const AVOption asyncts_options[]
Definition: af_asyncts.c:55
AVAudioResampleContext * avr
Definition: af_asyncts.c:36
AVFormatContext * ctx
Definition: movenc.c:48
int first_frame
1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE ...
Definition: af_asyncts.c:39
AVFILTER_DEFINE_CLASS(asyncts)
static const AVFilterPad outputs[]
Definition: af_afftfilt.c:386
int64_t first_pts
user-specified first expected pts, in samples
Definition: af_asyncts.c:40
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:248
int avresample_get_delay(AVAudioResampleContext *avr)
Return the number of samples currently in the resampling delay buffer.
Definition: resample.c:438
int avresample_available(AVAudioResampleContext *avr)
Return the number of available samples in the output FIFO.
Definition: utils.c:748
static const AVFilterPad inputs[]
Definition: af_afftfilt.c:376
#define F
Definition: af_asyncts.c:54
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:215
#define A
Definition: af_asyncts.c:53
void * buf
Definition: avisynth_c.h:553
static int write_to_fifo(ASyncContext *s, AVFrame *buf)
Definition: af_asyncts.c:168
Describe the class of an AVClass context structure.
Definition: log.h:67
Filter definition.
Definition: avfilter.h:142
rational number numerator/denominator
Definition: rational.h:43
const char * name
Filter name.
Definition: avfilter.h:146
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:317
AVFilter ff_af_asyncts
Definition: af_asyncts.c:313
static int64_t get_delay(ASyncContext *s)
Definition: af_asyncts.c:115
static int64_t pts
Global timestamp for the audio frames.
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:104
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:120
int got_output
Definition: af_asyncts.c:49
Audio FIFO Buffer.
An instance of a filter.
Definition: avfilter.h:305
static const AVFilterPad avfilter_af_asyncts_outputs[]
Definition: af_asyncts.c:303
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:369
int nb_channels
internal API functions
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:231
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:241
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240