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/mem.h"
27 #include "libavutil/opt.h"
28 #include "audio.h"
29 #include "avfilter.h"
30 #include "filters.h"
31 #include "formats.h"
32 
33 typedef struct SineContext {
34  const AVClass *class;
35  double frequency;
36  double beep_factor;
41  int16_t *sin;
43  uint32_t phi; ///< current phase of the sine (2pi = 1<<32)
44  uint32_t dphi; ///< phase increment between two samples
45  unsigned beep_period;
46  unsigned beep_index;
47  unsigned beep_length;
48  uint32_t phi_beep; ///< current phase of the beep
49  uint32_t dphi_beep; ///< phase increment of the beep
50 } SineContext;
51 
52 #define CONTEXT SineContext
53 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
54 
55 #define OPT_GENERIC(name, field, def, min, max, descr, type, deffield, ...) \
56  { name, descr, offsetof(CONTEXT, field), AV_OPT_TYPE_ ## type, \
57  { .deffield = def }, min, max, FLAGS, __VA_ARGS__ }
58 
59 #define OPT_INT(name, field, def, min, max, descr, ...) \
60  OPT_GENERIC(name, field, def, min, max, descr, INT, i64, __VA_ARGS__)
61 
62 #define OPT_DBL(name, field, def, min, max, descr, ...) \
63  OPT_GENERIC(name, field, def, min, max, descr, DOUBLE, dbl, __VA_ARGS__)
64 
65 #define OPT_DUR(name, field, def, min, max, descr, ...) \
66  OPT_GENERIC(name, field, def, min, max, descr, DURATION, str, __VA_ARGS__)
67 
68 #define OPT_STR(name, field, def, min, max, descr, ...) \
69  OPT_GENERIC(name, field, def, min, max, descr, STRING, str, __VA_ARGS__)
70 
71 static const AVOption sine_options[] = {
72  OPT_DBL("frequency", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
73  OPT_DBL("f", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
74  OPT_DBL("beep_factor", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
75  OPT_DBL("b", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
76  OPT_INT("sample_rate", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
77  OPT_INT("r", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
78  OPT_DUR("duration", duration, 0, 0, INT64_MAX, "set the audio duration",),
79  OPT_DUR("d", duration, 0, 0, INT64_MAX, "set the audio duration",),
80  OPT_STR("samples_per_frame", samples_per_frame, "1024", 0, 0, "set the number of samples per frame",),
81  {NULL}
82 };
83 
85 
86 #define LOG_PERIOD 15
87 #define AMPLITUDE 4095
88 #define AMPLITUDE_SHIFT 3
89 
90 static void make_sin_table(int16_t *sin)
91 {
92  unsigned half_pi = 1 << (LOG_PERIOD - 2);
93  unsigned ampls = AMPLITUDE << AMPLITUDE_SHIFT;
94  uint64_t unit2 = (uint64_t)(ampls * ampls) << 32;
95  unsigned step, i, c, s, k, new_k, n2;
96 
97  /* Principle: if u = exp(i*a1) and v = exp(i*a2), then
98  exp(i*(a1+a2)/2) = (u+v) / length(u+v) */
99  sin[0] = 0;
100  sin[half_pi] = ampls;
101  for (step = half_pi; step > 1; step /= 2) {
102  /* k = (1 << 16) * amplitude / length(u+v)
103  In exact values, k is constant at a given step */
104  k = 0x10000;
105  for (i = 0; i < half_pi / 2; i += step) {
106  s = sin[i] + sin[i + step];
107  c = sin[half_pi - i] + sin[half_pi - i - step];
108  n2 = s * s + c * c;
109  /* Newton's method to solve n² * k² = unit² */
110  while (1) {
111  new_k = (k + unit2 / ((uint64_t)k * n2) + 1) >> 1;
112  if (k == new_k)
113  break;
114  k = new_k;
115  }
116  sin[i + step / 2] = (k * s + 0x7FFF) >> 16;
117  sin[half_pi - i - step / 2] = (k * c + 0x8000) >> 16;
118  }
119  }
120  /* Unshift amplitude */
121  for (i = 0; i <= half_pi; i++)
122  sin[i] = (sin[i] + (1 << (AMPLITUDE_SHIFT - 1))) >> AMPLITUDE_SHIFT;
123  /* Use symmetries to fill the other three quarters */
124  for (i = 0; i < half_pi; i++)
125  sin[half_pi * 2 - i] = sin[i];
126  for (i = 0; i < 2 * half_pi; i++)
127  sin[i + 2 * half_pi] = -sin[i];
128 }
129 
130 static const char *const var_names[] = {
131  "n",
132  "pts",
133  "t",
134  "TB",
135  NULL
136 };
137 
138 enum {
144 };
145 
147 {
148  int ret;
149  SineContext *sine = ctx->priv;
150 
151  if (!(sine->sin = av_malloc(sizeof(*sine->sin) << LOG_PERIOD)))
152  return AVERROR(ENOMEM);
153  sine->dphi = ldexp(sine->frequency, 32) / sine->sample_rate + 0.5;
154  make_sin_table(sine->sin);
155 
156  if (sine->beep_factor) {
157  sine->beep_period = sine->sample_rate;
158  sine->beep_length = sine->beep_period / 25;
159  sine->dphi_beep = ldexp(sine->beep_factor * sine->frequency, 32) /
160  sine->sample_rate + 0.5;
161  }
162 
165  NULL, NULL, NULL, NULL, 0, sine);
166  if (ret < 0)
167  return ret;
168 
169  return 0;
170 }
171 
173 {
174  SineContext *sine = ctx->priv;
175 
178  av_freep(&sine->sin);
179 }
180 
182  AVFilterFormatsConfig **cfg_in,
183  AVFilterFormatsConfig **cfg_out)
184 {
185  const SineContext *sine = ctx->priv;
186  static const AVChannelLayout chlayouts[] = { AV_CHANNEL_LAYOUT_MONO, { 0 } };
187  int sample_rates[] = { sine->sample_rate, -1 };
188  static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16,
190  int ret = ff_set_common_formats_from_list2(ctx, cfg_in, cfg_out, sample_fmts);
191  if (ret < 0)
192  return ret;
193 
194  ret = ff_set_common_channel_layouts_from_list2(ctx, cfg_in, cfg_out, chlayouts);
195  if (ret < 0)
196  return ret;
197 
198  return ff_set_common_samplerates_from_list2(ctx, cfg_in, cfg_out, sample_rates);
199 }
200 
201 static av_cold int config_props(AVFilterLink *outlink)
202 {
203  SineContext *sine = outlink->src->priv;
204  sine->duration = av_rescale(sine->duration, sine->sample_rate, AV_TIME_BASE);
205  return 0;
206 }
207 
209 {
210  AVFilterLink *outlink = ctx->outputs[0];
211  FilterLink *outl = ff_filter_link(outlink);
212  SineContext *sine = ctx->priv;
213  AVFrame *frame;
214  double values[VAR_VARS_NB] = {
215  [VAR_N] = outl->frame_count_in,
216  [VAR_PTS] = sine->pts,
217  [VAR_T] = sine->pts * av_q2d(outlink->time_base),
218  [VAR_TB] = av_q2d(outlink->time_base),
219  };
220  int i, nb_samples = lrint(av_expr_eval(sine->samples_per_frame_expr, values, sine));
221  int16_t *samples;
222 
223  if (!ff_outlink_frame_wanted(outlink))
224  return FFERROR_NOT_READY;
225  if (nb_samples <= 0) {
226  av_log(sine, AV_LOG_WARNING, "nb samples expression evaluated to %d, "
227  "defaulting to 1024\n", nb_samples);
228  nb_samples = 1024;
229  }
230 
231  if (sine->duration) {
232  nb_samples = FFMIN(nb_samples, sine->duration - sine->pts);
233  av_assert1(nb_samples >= 0);
234  if (!nb_samples) {
235  ff_outlink_set_status(outlink, AVERROR_EOF, sine->pts);
236  return 0;
237  }
238  }
239  if (!(frame = ff_get_audio_buffer(outlink, nb_samples)))
240  return AVERROR(ENOMEM);
241  samples = (int16_t *)frame->data[0];
242 
243  for (i = 0; i < nb_samples; i++) {
244  samples[i] = sine->sin[sine->phi >> (32 - LOG_PERIOD)];
245  sine->phi += sine->dphi;
246  if (sine->beep_index < sine->beep_length) {
247  samples[i] += sine->sin[sine->phi_beep >> (32 - LOG_PERIOD)] * 2;
248  sine->phi_beep += sine->dphi_beep;
249  }
250  if (++sine->beep_index == sine->beep_period)
251  sine->beep_index = 0;
252  }
253 
254  frame->pts = sine->pts;
255  sine->pts += nb_samples;
256  return ff_filter_frame(outlink, frame);
257 }
258 
259 static const AVFilterPad sine_outputs[] = {
260  {
261  .name = "default",
262  .type = AVMEDIA_TYPE_AUDIO,
263  .config_props = config_props,
264  },
265 };
266 
268  .name = "sine",
269  .description = NULL_IF_CONFIG_SMALL("Generate sine wave audio signal."),
270  .init = init,
271  .uninit = uninit,
272  .activate = activate,
273  .priv_size = sizeof(SineContext),
274  .inputs = NULL,
277  .priv_class = &sine_class,
278 };
VAR_PTS
@ VAR_PTS
Definition: asrc_sine.c:140
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:98
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:215
SineContext::duration
int64_t duration
Definition: asrc_sine.c:40
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
sine_options
static const AVOption sine_options[]
Definition: asrc_sine.c:71
VAR_N
@ VAR_N
Definition: asrc_sine.c:139
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1062
sample_fmts
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:948
SineContext::frequency
double frequency
Definition: asrc_sine.c:35
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
FFERROR_NOT_READY
return FFERROR_NOT_READY
Definition: filter_design.txt:204
int64_t
long long int64_t
Definition: coverity.c:34
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(sine)
sample_rates
static const int sample_rates[]
Definition: dcaenc.h:34
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:389
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:201
AVOption
AVOption.
Definition: opt.h:429
ff_set_common_channel_layouts_from_list2
int ff_set_common_channel_layouts_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const AVChannelLayout *fmts)
Definition: formats.c:920
float.h
query_formats
static av_cold int query_formats(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out)
Definition: asrc_sine.c:181
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:205
make_sin_table
static void make_sin_table(int16_t *sin)
Definition: asrc_sine.c:90
activate
static int activate(AVFilterContext *ctx)
Definition: asrc_sine.c:208
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:30
formats.h
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:710
uninit
static av_cold void uninit(AVFilterContext *ctx)
Definition: asrc_sine.c:172
AVFilterContext::priv
void * priv
private data for use by the filter
Definition: avfilter.h:472
OPT_DBL
#define OPT_DBL(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:62
av_expr_free
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:358
AVFilterPad
A filter pad used for either input or output.
Definition: filters.h:38
avassert.h
lrint
#define lrint
Definition: tablegen.h:53
av_cold
#define av_cold
Definition: attributes.h:90
duration
int64_t duration
Definition: movenc.c:65
ff_outlink_set_status
static void ff_outlink_set_status(AVFilterLink *link, int status, int64_t pts)
Set the status field of a link from the source filter.
Definition: filters.h:424
s
#define s(width, name)
Definition: cbs_vp9.c:198
AMPLITUDE_SHIFT
#define AMPLITUDE_SHIFT
Definition: asrc_sine.c:88
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
filters.h
ff_set_common_samplerates_from_list2
int ff_set_common_samplerates_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const int *samplerates)
Definition: formats.c:944
ctx
AVFormatContext * ctx
Definition: movenc.c:49
av_expr_eval
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:792
AVExpr
Definition: eval.c:158
var_names
static const char *const var_names[]
Definition: asrc_sine.c:130
FILTER_OUTPUTS
#define FILTER_OUTPUTS(array)
Definition: filters.h:263
OPT_DUR
#define OPT_DUR(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:65
SineContext::beep_index
unsigned beep_index
Definition: asrc_sine.c:46
VAR_T
@ VAR_T
Definition: asrc_sine.c:141
SineContext::samples_per_frame_expr
AVExpr * samples_per_frame_expr
Definition: asrc_sine.c:38
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:75
LOG_PERIOD
#define LOG_PERIOD
Definition: asrc_sine.c:86
NULL
#define NULL
Definition: coverity.c:32
SineContext::sample_rate
int sample_rate
Definition: asrc_sine.c:39
SineContext::pts
int64_t pts
Definition: asrc_sine.c:42
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:49
SineContext
Definition: asrc_sine.c:33
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
AVFilterFormatsConfig
Lists of formats / etc.
Definition: avfilter.h:111
ff_filter_link
static FilterLink * ff_filter_link(AVFilterLink *link)
Definition: filters.h:197
SineContext::beep_factor
double beep_factor
Definition: asrc_sine.c:36
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:94
AVChannelLayout
An AVChannelLayout holds information about the channel layout of audio data.
Definition: channel_layout.h:311
OPT_STR
#define OPT_STR(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:68
for
for(k=2;k<=8;++k)
Definition: h264pred_template.c:425
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:56
sine_outputs
static const AVFilterPad sine_outputs[]
Definition: asrc_sine.c:259
OPT_INT
#define OPT_INT(name, field, def, min, max, descr,...)
Definition: asrc_sine.c:59
SineContext::sin
int16_t * sin
Definition: asrc_sine.c:41
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
SineContext::phi
uint32_t phi
current phase of the sine (2pi = 1<<32)
Definition: asrc_sine.c:43
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:56
AVSampleFormat
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:55
FILTER_QUERY_FUNC2
#define FILTER_QUERY_FUNC2(func)
Definition: filters.h:239
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AV_SAMPLE_FMT_S16
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition: samplefmt.h:58
AVFilterPad::name
const char * name
Pad name.
Definition: filters.h:44
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:146
AVFilter
Filter definition.
Definition: avfilter.h:201
SineContext::beep_length
unsigned beep_length
Definition: asrc_sine.c:47
SineContext::beep_period
unsigned beep_period
Definition: asrc_sine.c:45
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
VAR_VARS_NB
@ VAR_VARS_NB
Definition: asrc_sine.c:143
VAR_TB
@ VAR_TB
Definition: asrc_sine.c:142
ff_set_common_formats_from_list2
int ff_set_common_formats_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const int *fmts)
Definition: formats.c:1016
channel_layout.h
avfilter.h
SineContext::dphi
uint32_t dphi
phase increment between two samples
Definition: asrc_sine.c:44
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:457
ff_asrc_sine
const AVFilter ff_asrc_sine
Definition: asrc_sine.c:267
mem.h
audio.h
AV_CHANNEL_LAYOUT_MONO
#define AV_CHANNEL_LAYOUT_MONO
Definition: channel_layout.h:386
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
ff_outlink_frame_wanted
the definition of that something depends on the semantic of the filter The callback must examine the status of the filter s links and proceed accordingly The status of output links is stored in the status_in and status_out fields and tested by the ff_outlink_frame_wanted() function. If this function returns true
SineContext::phi_beep
uint32_t phi_beep
current phase of the beep
Definition: asrc_sine.c:48
AMPLITUDE
#define AMPLITUDE
Definition: asrc_sine.c:87
SineContext::samples_per_frame
char * samples_per_frame
Definition: asrc_sine.c:37