FFmpeg
asrc_sine.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Nicolas George
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License
8  * as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <float.h>
22 
23 #include "libavutil/avassert.h"
25 #include "libavutil/eval.h"
26 #include "libavutil/opt.h"
27 #include "audio.h"
28 #include "avfilter.h"
29 #include "internal.h"
30 
31 typedef struct SineContext {
32  const AVClass *class;
33  double frequency;
34  double beep_factor;
38  int64_t duration;
39  int16_t *sin;
40  int64_t pts;
41  uint32_t phi; ///< current phase of the sine (2pi = 1<<32)
42  uint32_t dphi; ///< phase increment between two samples
43  unsigned beep_period;
44  unsigned beep_index;
45  unsigned beep_length;
46  uint32_t phi_beep; ///< current phase of the beep
47  uint32_t dphi_beep; ///< phase increment of the beep
48 } SineContext;
49 
50 #define CONTEXT SineContext
51 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
52 
53 #define OPT_GENERIC(name, field, def, min, max, descr, type, deffield, ...) \
54  { name, descr, offsetof(CONTEXT, field), AV_OPT_TYPE_ ## type, \
55  { .deffield = def }, min, max, FLAGS, __VA_ARGS__ }
56 
57 #define OPT_INT(name, field, def, min, max, descr, ...) \
58  OPT_GENERIC(name, field, def, min, max, descr, INT, i64, __VA_ARGS__)
59 
60 #define OPT_DBL(name, field, def, min, max, descr, ...) \
61  OPT_GENERIC(name, field, def, min, max, descr, DOUBLE, dbl, __VA_ARGS__)
62 
63 #define OPT_DUR(name, field, def, min, max, descr, ...) \
64  OPT_GENERIC(name, field, def, min, max, descr, DURATION, str, __VA_ARGS__)
65 
66 #define OPT_STR(name, field, def, min, max, descr, ...) \
67  OPT_GENERIC(name, field, def, min, max, descr, STRING, str, __VA_ARGS__)
68 
69 static const AVOption sine_options[] = {
70  OPT_DBL("frequency", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
71  OPT_DBL("f", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
72  OPT_DBL("beep_factor", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
73  OPT_DBL("b", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
74  OPT_INT("sample_rate", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
75  OPT_INT("r", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
76  OPT_DUR("duration", duration, 0, 0, INT64_MAX, "set the audio duration",),
77  OPT_DUR("d", duration, 0, 0, INT64_MAX, "set the audio duration",),
78  OPT_STR("samples_per_frame", samples_per_frame, "1024", 0, 0, "set the number of samples per frame",),
79  {NULL}
80 };
81 
83 
84 #define LOG_PERIOD 15
85 #define AMPLITUDE 4095
86 #define AMPLITUDE_SHIFT 3
87 
88 static void make_sin_table(int16_t *sin)
89 {
90  unsigned half_pi = 1 << (LOG_PERIOD - 2);
91  unsigned ampls = AMPLITUDE << AMPLITUDE_SHIFT;
92  uint64_t unit2 = (uint64_t)(ampls * ampls) << 32;
93  unsigned step, i, c, s, k, new_k, n2;
94 
95  /* Principle: if u = exp(i*a1) and v = exp(i*a2), then
96  exp(i*(a1+a2)/2) = (u+v) / length(u+v) */
97  sin[0] = 0;
98  sin[half_pi] = ampls;
99  for (step = half_pi; step > 1; step /= 2) {
100  /* k = (1 << 16) * amplitude / length(u+v)
101  In exact values, k is constant at a given step */
102  k = 0x10000;
103  for (i = 0; i < half_pi / 2; i += step) {
104  s = sin[i] + sin[i + step];
105  c = sin[half_pi - i] + sin[half_pi - i - step];
106  n2 = s * s + c * c;
107  /* Newton's method to solve n² * k² = unit² */
108  while (1) {
109  new_k = (k + unit2 / ((uint64_t)k * n2) + 1) >> 1;
110  if (k == new_k)
111  break;
112  k = new_k;
113  }
114  sin[i + step / 2] = (k * s + 0x7FFF) >> 16;
115  sin[half_pi - i - step / 2] = (k * c + 0x8000) >> 16;
116  }
117  }
118  /* Unshift amplitude */
119  for (i = 0; i <= half_pi; i++)
120  sin[i] = (sin[i] + (1 << (AMPLITUDE_SHIFT - 1))) >> AMPLITUDE_SHIFT;
121  /* Use symmetries to fill the other three quarters */
122  for (i = 0; i < half_pi; i++)
123  sin[half_pi * 2 - i] = sin[i];
124  for (i = 0; i < 2 * half_pi; i++)
125  sin[i + 2 * half_pi] = -sin[i];
126 }
127 
128 static const char *const var_names[] = {
129  "n",
130  "pts",
131  "t",
132  "TB",
133  NULL
134 };
135 
136 enum {
142 };
143 
145 {
146  int ret;
147  SineContext *sine = ctx->priv;
148 
149  if (!(sine->sin = av_malloc(sizeof(*sine->sin) << LOG_PERIOD)))
150  return AVERROR(ENOMEM);
151  sine->dphi = ldexp(sine->frequency, 32) / sine->sample_rate + 0.5;
152  make_sin_table(sine->sin);
153 
154  if (sine->beep_factor) {
155  sine->beep_period = sine->sample_rate;
156  sine->beep_length = sine->beep_period / 25;
157  sine->dphi_beep = ldexp(sine->beep_factor * sine->frequency, 32) /
158  sine->sample_rate + 0.5;
159  }
160 
163  NULL, NULL, NULL, NULL, 0, sine);
164  if (ret < 0)
165  return ret;
166 
167  return 0;
168 }
169 
171 {
172  SineContext *sine = ctx->priv;
173 
176  av_freep(&sine->sin);
177 }
178 
180 {
181  SineContext *sine = ctx->priv;
182  static const int64_t chlayouts[] = { AV_CH_LAYOUT_MONO, -1 };
183  int sample_rates[] = { sine->sample_rate, -1 };
184  static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16,
188  int ret;
189 
191  if (!formats)
192  return AVERROR(ENOMEM);
194  if (ret < 0)
195  return ret;
196 
197  layouts = ff_make_format64_list(chlayouts);
198  if (!layouts)
199  return AVERROR(ENOMEM);
201  if (ret < 0)
202  return ret;
203 
205  if (!formats)
206  return AVERROR(ENOMEM);
208 }
209 
210 static av_cold int config_props(AVFilterLink *outlink)
211 {
212  SineContext *sine = outlink->src->priv;
213  sine->duration = av_rescale(sine->duration, sine->sample_rate, AV_TIME_BASE);
214  return 0;
215 }
216 
217 static int request_frame(AVFilterLink *outlink)
218 {
219  SineContext *sine = outlink->src->priv;
220  AVFrame *frame;
221  double values[VAR_VARS_NB] = {
222  [VAR_N] = outlink->frame_count_in,
223  [VAR_PTS] = sine->pts,
224  [VAR_T] = sine->pts * av_q2d(outlink->time_base),
225  [VAR_TB] = av_q2d(outlink->time_base),
226  };
227  int i, nb_samples = lrint(av_expr_eval(sine->samples_per_frame_expr, values, sine));
228  int16_t *samples;
229 
230  if (nb_samples <= 0) {
231  av_log(sine, AV_LOG_WARNING, "nb samples expression evaluated to %d, "
232  "defaulting to 1024\n", nb_samples);
233  nb_samples = 1024;
234  }
235 
236  if (sine->duration) {
237  nb_samples = FFMIN(nb_samples, sine->duration - sine->pts);
238  av_assert1(nb_samples >= 0);
239  if (!nb_samples)
240  return AVERROR_EOF;
241  }
242  if (!(frame = ff_get_audio_buffer(outlink, nb_samples)))
243  return AVERROR(ENOMEM);
244  samples = (int16_t *)frame->data[0];
245 
246  for (i = 0; i < nb_samples; i++) {
247  samples[i] = sine->sin[sine->phi >> (32 - LOG_PERIOD)];
248  sine->phi += sine->dphi;
249  if (sine->beep_index < sine->beep_length) {
250  samples[i] += sine->sin[sine->phi_beep >> (32 - LOG_PERIOD)] * 2;
251  sine->phi_beep += sine->dphi_beep;
252  }
253  if (++sine->beep_index == sine->beep_period)
254  sine->beep_index = 0;
255  }
256 
257  frame->pts = sine->pts;
258  sine->pts += nb_samples;
259  return ff_filter_frame(outlink, frame);
260 }
261 
262 static const AVFilterPad sine_outputs[] = {
263  {
264  .name = "default",
265  .type = AVMEDIA_TYPE_AUDIO,
266  .request_frame = request_frame,
267  .config_props = config_props,
268  },
269  { NULL }
270 };
271 
273  .name = "sine",
274  .description = NULL_IF_CONFIG_SMALL("Generate sine wave audio signal."),
275  .query_formats = query_formats,
276  .init = init,
277  .uninit = uninit,
278  .priv_size = sizeof(SineContext),
279  .inputs = NULL,
281  .priv_class = &sine_class,
282 };
formats
formats
Definition: signature.h:48
ff_get_audio_buffer
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:86
AVFilterChannelLayouts
A list of supported channel layouts.
Definition: formats.h:86
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
SineContext::duration
int64_t duration
Definition: asrc_sine.c:38
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
ff_make_format_list
AVFilterFormats * ff_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:286
sine_options
static const AVOption sine_options[]
Definition: asrc_sine.c:69
VAR_TB
@ VAR_TB
Definition: asrc_sine.c:140
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1096
sample_fmts
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:925
SineContext::frequency
double frequency
Definition: asrc_sine.c:33
layouts
enum MovChannelLayoutTag * layouts
Definition: mov_chan.c:434
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:55
AV_CH_LAYOUT_MONO
#define AV_CH_LAYOUT_MONO
Definition: channel_layout.h:90
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(sine)
ff_make_format64_list
AVFilterChannelLayouts * ff_make_format64_list(const int64_t *fmts)
Definition: formats.c:295
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:318
step
trying all byte sequences megabyte in length and selecting the best looking sequence will yield cases to try But a word about which is also called distortion Distortion can be quantified by almost any quality measurement one chooses the sum of squared differences is used but more complex methods that consider psychovisual effects can be used as well It makes no difference in this discussion First step
Definition: rate_distortion.txt:58
config_props
static av_cold int config_props(AVFilterLink *outlink)
Definition: asrc_sine.c:210
AVOption
AVOption.
Definition: opt.h:248
VAR_N
@ VAR_N
Definition: asrc_sine.c:137
float.h
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:149
make_sin_table
static void make_sin_table(int16_t *sin)
Definition: asrc_sine.c:88
sample_rate
sample_rate
Definition: ffmpeg_filter.c:170
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:31
AVFilterFormats
A list of supported formats for one end of a filter link.
Definition: formats.h:65
av_expr_parse
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:685
uninit
static av_cold void uninit(AVFilterContext *ctx)
Definition: asrc_sine.c:170
VAR_PTS
@ VAR_PTS
Definition: asrc_sine.c:138
AVFilterContext::priv
void * priv
private data for use by the filter
Definition: avfilter.h:356
request_frame
static int request_frame(AVFilterLink *outlink)
Definition: asrc_sine.c:217
OPT_DBL
#define OPT_DBL(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:60
av_expr_free
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:336
AVFilterPad
A filter pad used for either input or output.
Definition: internal.h:54
avassert.h
lrint
#define lrint
Definition: tablegen.h:53
av_cold
#define av_cold
Definition: attributes.h:90
ff_set_common_formats
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:587
duration
int64_t duration
Definition: movenc.c:64
VAR_T
@ VAR_T
Definition: asrc_sine.c:139
s
#define s(width, name)
Definition: cbs_vp9.c:257
AMPLITUDE_SHIFT
#define AMPLITUDE_SHIFT
Definition: asrc_sine.c:86
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
av_q2d
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
outputs
static const AVFilterPad outputs[]
Definition: af_acontrast.c:203
ctx
AVFormatContext * ctx
Definition: movenc.c:48
av_expr_eval
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:766
AVExpr
Definition: eval.c:157
var_names
static const char *const var_names[]
Definition: asrc_sine.c:128
OPT_DUR
#define OPT_DUR(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:63
SineContext::beep_index
unsigned beep_index
Definition: asrc_sine.c:44
SineContext::samples_per_frame_expr
AVExpr * samples_per_frame_expr
Definition: asrc_sine.c:36
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:67
LOG_PERIOD
#define LOG_PERIOD
Definition: asrc_sine.c:84
NULL
#define NULL
Definition: coverity.c:32
SineContext::sample_rate
int sample_rate
Definition: asrc_sine.c:37
SineContext::pts
int64_t pts
Definition: asrc_sine.c:40
inputs
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several inputs
Definition: filter_design.txt:243
SineContext::dphi_beep
uint32_t dphi_beep
phase increment of the beep
Definition: asrc_sine.c:47
SineContext
Definition: asrc_sine.c:31
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
for
for(j=16;j >0;--j)
Definition: h264pred_template.c:469
SineContext::beep_factor
double beep_factor
Definition: asrc_sine.c:34
eval.h
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
OPT_STR
#define OPT_STR(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:66
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:59
sine_outputs
static const AVFilterPad sine_outputs[]
Definition: asrc_sine.c:262
FFMIN
#define FFMIN(a, b)
Definition: common.h:105
OPT_INT
#define OPT_INT(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:57
ff_asrc_sine
AVFilter ff_asrc_sine
Definition: asrc_sine.c:272
sample_rates
sample_rates
Definition: ffmpeg_filter.c:170
internal.h
SineContext::sin
int16_t * sin
Definition: asrc_sine.c:39
i
int i
Definition: input.c:407
SineContext::phi
uint32_t phi
current phase of the sine (2pi = 1<<32)
Definition: asrc_sine.c:41
AV_TIME_BASE
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
AVSampleFormat
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:58
AV_SAMPLE_FMT_S16
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition: samplefmt.h:61
AVFilterPad::name
const char * name
Pad name.
Definition: internal.h:60
av_rescale
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:129
init
static av_cold int init(AVFilterContext *ctx)
Definition: asrc_sine.c:144
AVFilter
Filter definition.
Definition: avfilter.h:145
SineContext::beep_length
unsigned beep_length
Definition: asrc_sine.c:45
SineContext::beep_period
unsigned beep_period
Definition: asrc_sine.c:43
ret
ret
Definition: filter_design.txt:187
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
channel_layout.h
avfilter.h
SineContext::dphi
uint32_t dphi
phase increment between two samples
Definition: asrc_sine.c:42
values
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return values
Definition: filter_design.txt:263
samples
Filter the word “frame” indicates either a video frame or a group of audio samples
Definition: filter_design.txt:8
AVFilterContext
An instance of a filter.
Definition: avfilter.h:341
audio.h
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:28
ff_set_common_samplerates
int ff_set_common_samplerates(AVFilterContext *ctx, AVFilterFormats *samplerates)
Definition: formats.c:575
SineContext::phi_beep
uint32_t phi_beep
current phase of the beep
Definition: asrc_sine.c:46
AMPLITUDE
#define AMPLITUDE
Definition: asrc_sine.c:85
query_formats
static av_cold int query_formats(AVFilterContext *ctx)
Definition: asrc_sine.c:179
SineContext::samples_per_frame
char * samples_per_frame
Definition: asrc_sine.c:35
VAR_VARS_NB
@ VAR_VARS_NB
Definition: asrc_sine.c:141
ff_set_common_channel_layouts
int ff_set_common_channel_layouts(AVFilterContext *ctx, AVFilterChannelLayouts *channel_layouts)
A helper for query_formats() which sets all links to the same list of channel layouts/sample rates.
Definition: formats.c:568