FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
af_aresample.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  * Copyright (c) 2011 Mina Nagy Zaki
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * resampling audio filter
25  */
26 
27 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/samplefmt.h"
31 #include "libavutil/avassert.h"
33 #include "avfilter.h"
34 #include "audio.h"
35 #include "internal.h"
36 
37 typedef struct {
38  const AVClass *class;
40  double ratio;
41  struct SwrContext *swr;
42  int64_t next_pts;
44  int more_data;
46 
48 {
49  AResampleContext *aresample = ctx->priv;
50  int ret = 0;
51 
52  aresample->next_pts = AV_NOPTS_VALUE;
53  aresample->swr = swr_alloc();
54  if (!aresample->swr) {
55  ret = AVERROR(ENOMEM);
56  goto end;
57  }
58 
59  if (opts) {
61 
62  while ((e = av_dict_get(*opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
63  if ((ret = av_opt_set(aresample->swr, e->key, e->value, 0)) < 0)
64  goto end;
65  }
66  av_dict_free(opts);
67  }
68  if (aresample->sample_rate_arg > 0)
69  av_opt_set_int(aresample->swr, "osr", aresample->sample_rate_arg, 0);
70 end:
71  return ret;
72 }
73 
74 static av_cold void uninit(AVFilterContext *ctx)
75 {
76  AResampleContext *aresample = ctx->priv;
77  swr_free(&aresample->swr);
78 }
79 
81 {
82  AResampleContext *aresample = ctx->priv;
83  enum AVSampleFormat out_format;
84  int64_t out_rate, out_layout;
85 
86  AVFilterLink *inlink = ctx->inputs[0];
87  AVFilterLink *outlink = ctx->outputs[0];
88 
89  AVFilterFormats *in_formats, *out_formats;
90  AVFilterFormats *in_samplerates, *out_samplerates;
91  AVFilterChannelLayouts *in_layouts, *out_layouts;
92 
93  av_opt_get_sample_fmt(aresample->swr, "osf", 0, &out_format);
94  av_opt_get_int(aresample->swr, "osr", 0, &out_rate);
95  av_opt_get_int(aresample->swr, "ocl", 0, &out_layout);
96 
97  in_formats = ff_all_formats(AVMEDIA_TYPE_AUDIO);
98  if (!in_formats)
99  return AVERROR(ENOMEM);
100  ff_formats_ref (in_formats, &inlink->out_formats);
101 
102  in_samplerates = ff_all_samplerates();
103  if (!in_samplerates)
104  return AVERROR(ENOMEM);
105  ff_formats_ref (in_samplerates, &inlink->out_samplerates);
106 
107  in_layouts = ff_all_channel_counts();
108  if (!in_layouts)
109  return AVERROR(ENOMEM);
110  ff_channel_layouts_ref(in_layouts, &inlink->out_channel_layouts);
111 
112  if(out_rate > 0) {
113  int ratelist[] = { out_rate, -1 };
114  out_samplerates = ff_make_format_list(ratelist);
115  } else {
116  out_samplerates = ff_all_samplerates();
117  }
118  if (!out_samplerates) {
119  av_log(ctx, AV_LOG_ERROR, "Cannot allocate output samplerates.\n");
120  return AVERROR(ENOMEM);
121  }
122 
123  ff_formats_ref(out_samplerates, &outlink->in_samplerates);
124 
125  if(out_format != AV_SAMPLE_FMT_NONE) {
126  int formatlist[] = { out_format, -1 };
127  out_formats = ff_make_format_list(formatlist);
128  } else
129  out_formats = ff_all_formats(AVMEDIA_TYPE_AUDIO);
130  ff_formats_ref(out_formats, &outlink->in_formats);
131 
132  if(out_layout) {
133  int64_t layout_list[] = { out_layout, -1 };
134  out_layouts = avfilter_make_format64_list(layout_list);
135  } else
136  out_layouts = ff_all_channel_counts();
137  ff_channel_layouts_ref(out_layouts, &outlink->in_channel_layouts);
138 
139  return 0;
140 }
141 
142 
143 static int config_output(AVFilterLink *outlink)
144 {
145  int ret;
146  AVFilterContext *ctx = outlink->src;
147  AVFilterLink *inlink = ctx->inputs[0];
148  AResampleContext *aresample = ctx->priv;
149  int64_t out_rate, out_layout;
150  enum AVSampleFormat out_format;
151  char inchl_buf[128], outchl_buf[128];
152 
153  aresample->swr = swr_alloc_set_opts(aresample->swr,
154  outlink->channel_layout, outlink->format, outlink->sample_rate,
155  inlink->channel_layout, inlink->format, inlink->sample_rate,
156  0, ctx);
157  if (!aresample->swr)
158  return AVERROR(ENOMEM);
159  if (!inlink->channel_layout)
160  av_opt_set_int(aresample->swr, "ich", inlink->channels, 0);
161  if (!outlink->channel_layout)
162  av_opt_set_int(aresample->swr, "och", outlink->channels, 0);
163 
164  ret = swr_init(aresample->swr);
165  if (ret < 0)
166  return ret;
167 
168  av_opt_get_int(aresample->swr, "osr", 0, &out_rate);
169  av_opt_get_int(aresample->swr, "ocl", 0, &out_layout);
170  av_opt_get_sample_fmt(aresample->swr, "osf", 0, &out_format);
171  outlink->time_base = (AVRational) {1, out_rate};
172 
173  av_assert0(outlink->sample_rate == out_rate);
174  av_assert0(outlink->channel_layout == out_layout || !outlink->channel_layout);
175  av_assert0(outlink->format == out_format);
176 
177  aresample->ratio = (double)outlink->sample_rate / inlink->sample_rate;
178 
179  av_get_channel_layout_string(inchl_buf, sizeof(inchl_buf), inlink ->channels, inlink ->channel_layout);
180  av_get_channel_layout_string(outchl_buf, sizeof(outchl_buf), outlink->channels, outlink->channel_layout);
181 
182  av_log(ctx, AV_LOG_VERBOSE, "ch:%d chl:%s fmt:%s r:%dHz -> ch:%d chl:%s fmt:%s r:%dHz\n",
183  inlink ->channels, inchl_buf, av_get_sample_fmt_name(inlink->format), inlink->sample_rate,
184  outlink->channels, outchl_buf, av_get_sample_fmt_name(outlink->format), outlink->sample_rate);
185  return 0;
186 }
187 
188 static int filter_frame(AVFilterLink *inlink, AVFrame *insamplesref)
189 {
190  AResampleContext *aresample = inlink->dst->priv;
191  const int n_in = insamplesref->nb_samples;
192  int64_t delay;
193  int n_out = n_in * aresample->ratio + 32;
194  AVFilterLink *const outlink = inlink->dst->outputs[0];
195  AVFrame *outsamplesref;
196  int ret;
197 
198  delay = swr_get_delay(aresample->swr, outlink->sample_rate);
199  if (delay > 0)
200  n_out += FFMIN(delay, FFMAX(4096, n_out));
201 
202  outsamplesref = ff_get_audio_buffer(outlink, n_out);
203 
204  if(!outsamplesref)
205  return AVERROR(ENOMEM);
206 
207  av_frame_copy_props(outsamplesref, insamplesref);
208  outsamplesref->format = outlink->format;
209  av_frame_set_channels(outsamplesref, outlink->channels);
210  outsamplesref->channel_layout = outlink->channel_layout;
211  outsamplesref->sample_rate = outlink->sample_rate;
212 
213  if(insamplesref->pts != AV_NOPTS_VALUE) {
214  int64_t inpts = av_rescale(insamplesref->pts, inlink->time_base.num * (int64_t)outlink->sample_rate * inlink->sample_rate, inlink->time_base.den);
215  int64_t outpts= swr_next_pts(aresample->swr, inpts);
216  aresample->next_pts =
217  outsamplesref->pts = ROUNDED_DIV(outpts, inlink->sample_rate);
218  } else {
219  outsamplesref->pts = AV_NOPTS_VALUE;
220  }
221  n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out,
222  (void *)insamplesref->extended_data, n_in);
223  if (n_out <= 0) {
224  av_frame_free(&outsamplesref);
225  av_frame_free(&insamplesref);
226  return 0;
227  }
228 
229  aresample->more_data = outsamplesref->nb_samples == n_out; // Indicate that there is probably more data in our buffers
230 
231  outsamplesref->nb_samples = n_out;
232 
233  ret = ff_filter_frame(outlink, outsamplesref);
234  aresample->req_fullfilled= 1;
235  av_frame_free(&insamplesref);
236  return ret;
237 }
238 
239 static int flush_frame(AVFilterLink *outlink, int final, AVFrame **outsamplesref_ret)
240 {
241  AVFilterContext *ctx = outlink->src;
242  AResampleContext *aresample = ctx->priv;
243  AVFilterLink *const inlink = outlink->src->inputs[0];
244  AVFrame *outsamplesref;
245  int n_out = 4096;
246  int64_t pts;
247 
248  outsamplesref = ff_get_audio_buffer(outlink, n_out);
249  *outsamplesref_ret = outsamplesref;
250  if (!outsamplesref)
251  return AVERROR(ENOMEM);
252 
253  pts = swr_next_pts(aresample->swr, INT64_MIN);
254  pts = ROUNDED_DIV(pts, inlink->sample_rate);
255 
256  n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out, final ? NULL : (void*)outsamplesref->extended_data, 0);
257  if (n_out <= 0) {
258  av_frame_free(&outsamplesref);
259  return (n_out == 0) ? AVERROR_EOF : n_out;
260  }
261 
262  outsamplesref->sample_rate = outlink->sample_rate;
263  outsamplesref->nb_samples = n_out;
264 
265  outsamplesref->pts = pts;
266 
267  return 0;
268 }
269 
270 static int request_frame(AVFilterLink *outlink)
271 {
272  AVFilterContext *ctx = outlink->src;
273  AResampleContext *aresample = ctx->priv;
274  int ret;
275 
276  // First try to get data from the internal buffers
277  if (aresample->more_data) {
278  AVFrame *outsamplesref;
279 
280  if (flush_frame(outlink, 0, &outsamplesref) >= 0) {
281  return ff_filter_frame(outlink, outsamplesref);
282  }
283  }
284  aresample->more_data = 0;
285 
286  // Second request more data from the input
287  aresample->req_fullfilled = 0;
288  do{
289  ret = ff_request_frame(ctx->inputs[0]);
290  }while(!aresample->req_fullfilled && ret>=0);
291 
292  // Third if we hit the end flush
293  if (ret == AVERROR_EOF) {
294  AVFrame *outsamplesref;
295 
296  if ((ret = flush_frame(outlink, 1, &outsamplesref)) < 0)
297  return ret;
298 
299  return ff_filter_frame(outlink, outsamplesref);
300  }
301  return ret;
302 }
303 
304 static const AVClass *resample_child_class_next(const AVClass *prev)
305 {
306  return prev ? NULL : swr_get_class();
307 }
308 
309 static void *resample_child_next(void *obj, void *prev)
310 {
311  AResampleContext *s = obj;
312  return prev ? NULL : s->swr;
313 }
314 
315 #define OFFSET(x) offsetof(AResampleContext, x)
316 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
317 
318 static const AVOption options[] = {
319  {"sample_rate", NULL, OFFSET(sample_rate_arg), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
320  {NULL}
321 };
322 
323 static const AVClass aresample_class = {
324  .class_name = "aresample",
325  .item_name = av_default_item_name,
326  .option = options,
327  .version = LIBAVUTIL_VERSION_INT,
328  .child_class_next = resample_child_class_next,
330 };
331 
332 static const AVFilterPad aresample_inputs[] = {
333  {
334  .name = "default",
335  .type = AVMEDIA_TYPE_AUDIO,
336  .filter_frame = filter_frame,
337  },
338  { NULL }
339 };
340 
341 static const AVFilterPad aresample_outputs[] = {
342  {
343  .name = "default",
344  .config_props = config_output,
345  .request_frame = request_frame,
346  .type = AVMEDIA_TYPE_AUDIO,
347  },
348  { NULL }
349 };
350 
352  .name = "aresample",
353  .description = NULL_IF_CONFIG_SMALL("Resample audio data."),
354  .init_dict = init_dict,
355  .uninit = uninit,
356  .query_formats = query_formats,
357  .priv_size = sizeof(AResampleContext),
358  .priv_class = &aresample_class,
359  .inputs = aresample_inputs,
360  .outputs = aresample_outputs,
361 };
void av_frame_set_channels(AVFrame *frame, int val)
#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:171
AVOption.
Definition: opt.h:255
static const AVFilterPad aresample_inputs[]
Definition: af_aresample.c:332
static const AVFilterPad outputs[]
Definition: af_ashowinfo.c:248
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
Main libavfilter public API header.
int num
numerator
Definition: rational.h:44
int64_t swr_next_pts(struct SwrContext *s, int64_t pts)
Convert the next timestamp from input to output timestamps are in 1/(in_sample_rate * out_sample_rate...
Definition: swresample.c:898
static const AVOption options[]
Definition: af_aresample.c:318
AVFilterFormats * ff_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:283
const char * name
Pad name.
Definition: internal.h:69
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:72
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:641
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
int ff_channel_layouts_ref(AVFilterChannelLayouts *f, AVFilterChannelLayouts **ref)
Add *ref as a new reference to f.
Definition: formats.c:417
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1158
av_cold struct SwrContext * swr_alloc(void)
Allocate SwrContext.
Definition: options.c:148
#define av_cold
Definition: attributes.h:74
AVOptions.
#define FLAGS
Definition: af_aresample.c:316
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:257
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:39
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
#define av_log(a,...)
AVFilterFormats * ff_all_formats(enum AVMediaType type)
Return a list of all formats supported by FFmpeg for the given media type.
Definition: formats.c:336
#define ROUNDED_DIV(a, b)
Definition: common.h:55
A filter pad used for either input or output.
Definition: internal.h:63
libswresample public header
static void * resample_child_next(void *obj, void *prev)
Definition: af_aresample.c:309
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:74
av_default_item_name
#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:148
The libswresample context.
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
void * priv
private data for use by the filter
Definition: avfilter.h:654
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:199
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:491
simple assert() macros that are a bit more flexible than ISO C assert().
const char * av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
Return the name of sample_fmt, or NULL if sample_fmt is not recognized.
Definition: samplefmt.c:47
int64_t swr_get_delay(struct SwrContext *s, int64_t base)
Gets the delay the next input sample will experience relative to the next output sample.
Definition: swresample.c:848
#define FFMAX(a, b)
Definition: common.h:79
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:427
int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt)
Definition: opt.c:920
audio channel layout utility functions
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:127
#define FFMIN(a, b)
Definition: common.h:81
int ff_formats_ref(AVFilterFormats *f, AVFilterFormats **ref)
Add *ref as a new reference to formats.
Definition: formats.c:422
static int flush_frame(AVFilterLink *outlink, int final, AVFrame **outsamplesref_ret)
Definition: af_aresample.c:239
static const AVClass aresample_class
Definition: af_aresample.c:323
static av_cold int init_dict(AVFilterContext *ctx, AVDictionary **opts)
Definition: af_aresample.c:47
struct SwrContext * swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx)
Allocate SwrContext if needed and set/reset common parameters.
Definition: swresample.c:59
const AVClass * swr_get_class(void)
Get the AVClass for SwrContext.
Definition: options.c:143
A list of supported channel layouts.
Definition: formats.h:85
void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout)
Return a description of a channel layout.
static av_cold void uninit(AVFilterContext *ctx)
Definition: af_aresample.c:74
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:232
int av_opt_get_int(void *obj, const char *name, int search_flags, int64_t *out_val)
Definition: opt.c:823
int64_t outpts
output PTS
AVFilterChannelLayouts * avfilter_make_format64_list(const int64_t *fmts)
Definition: formats.c:292
AVFilter ff_af_aresample
Definition: af_aresample.c:351
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:59
static const AVFilterPad aresample_outputs[]
Definition: af_aresample.c:341
av_cold void swr_free(SwrContext **ss)
Free the given SwrContext and set the pointer to NULL.
Definition: swresample.c:140
Describe the class of an AVClass context structure.
Definition: log.h:67
int sample_rate
Sample rate of the audio data.
Definition: frame.h:422
Filter definition.
Definition: avfilter.h:470
static const AVFilterPad inputs[]
Definition: af_ashowinfo.c:239
rational number numerator/denominator
Definition: rational.h:43
struct SwrContext * swr
Definition: af_aresample.c:41
const char * name
Filter name.
Definition: avfilter.h:474
int attribute_align_arg swr_convert(struct SwrContext *s, uint8_t *out_arg[SWR_CH_MAX], int out_count, const uint8_t *in_arg[SWR_CH_MAX], int in_count)
Definition: swresample.c:695
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:648
AVFilterFormats * ff_all_samplerates(void)
Definition: formats.c:379
static int64_t pts
Global timestamp for the audio frames.
static int filter_frame(AVFilterLink *inlink, AVFrame *insamplesref)
Definition: af_aresample.c:188
static const AVClass * resample_child_class_next(const AVClass *prev)
Definition: af_aresample.c:304
void *(* child_next)(void *obj, void *prev)
Return next AVOptions-enabled child or NULL.
Definition: log.h:113
char * key
Definition: dict.h:87
int den
denominator
Definition: rational.h:45
#define OFFSET(x)
Definition: af_aresample.c:315
char * value
Definition: dict.h:88
A list of supported formats for one end of a filter link.
Definition: formats.h:64
An instance of a filter.
Definition: avfilter.h:633
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
Definition: dict.h:72
int ff_request_frame(AVFilterLink *link)
Request an input frame from the filter at the other end of the link.
Definition: avfilter.c:343
internal API functions
AVFilterChannelLayouts * ff_all_channel_counts(void)
Construct an AVFilterChannelLayouts coding for any channel layout, with known or unknown disposition...
Definition: formats.c:394
static int query_formats(AVFilterContext *ctx)
Definition: af_aresample.c:80
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:215
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:369
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:225
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition: frame.c:553
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
static int request_frame(AVFilterLink *outlink)
Definition: af_aresample.c:270
av_cold int swr_init(struct SwrContext *s)
Initialize context after user parameters have been set.
Definition: swresample.c:155
static int config_output(AVFilterLink *outlink)
Definition: af_aresample.c:143