FFmpeg
Loading...
Searching...
No Matches
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
33typedef struct SamplingContext {
34 uint32_t phi; ///< current phase of the sine (2pi = 1<<32)
35 uint32_t dphi; ///< phase increment between two samples
36 int phi_rem; ///< current fractional phase in 1/dphi_den subfractions
40
57
58#define CONTEXT SineContext
59#define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
60
61#define OPT_GENERIC(name, field, def, min, max, descr, type, deffield, ...) \
62 { name, descr, offsetof(CONTEXT, field), AV_OPT_TYPE_ ## type, \
63 { .deffield = def }, min, max, FLAGS, __VA_ARGS__ }
64
65#define OPT_INT(name, field, def, min, max, descr, ...) \
66 OPT_GENERIC(name, field, def, min, max, descr, INT, i64, __VA_ARGS__)
67
68#define OPT_DBL(name, field, def, min, max, descr, ...) \
69 OPT_GENERIC(name, field, def, min, max, descr, DOUBLE, dbl, __VA_ARGS__)
70
71#define OPT_DUR(name, field, def, min, max, descr, ...) \
72 OPT_GENERIC(name, field, def, min, max, descr, DURATION, str, __VA_ARGS__)
73
74#define OPT_STR(name, field, def, min, max, descr, ...) \
75 OPT_GENERIC(name, field, def, min, max, descr, STRING, str, __VA_ARGS__)
76
77static const AVOption sine_options[] = {
78 OPT_DBL("frequency", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
79 OPT_DBL("f", frequency, 440, 0, DBL_MAX, "set the sine frequency",),
80 OPT_DBL("beep_factor", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
81 OPT_DBL("b", beep_factor, 0, 0, DBL_MAX, "set the beep frequency factor",),
82 OPT_INT("sample_rate", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
83 OPT_INT("r", sample_rate, 44100, 1, INT_MAX, "set the sample rate",),
84 OPT_DUR("duration", duration, 0, 0, INT64_MAX, "set the audio duration",),
85 OPT_DUR("d", duration, 0, 0, INT64_MAX, "set the audio duration",),
86 OPT_STR("samples_per_frame", samples_per_frame, "1024", 0, 0, "set the number of samples per frame",),
87 {NULL}
88};
89
91
92#define LOG_PERIOD 15
93#define AMPLITUDE 4095
94#define AMPLITUDE_SHIFT 3
95
96static void make_sin_table(int16_t *sin)
97{
98 unsigned half_pi = 1 << (LOG_PERIOD - 2);
99 unsigned ampls = AMPLITUDE << AMPLITUDE_SHIFT;
100 uint64_t unit2 = (uint64_t)(ampls * ampls) << 32;
101 unsigned step, i, c, s, k, new_k, n2;
102
103 /* Principle: if u = exp(i*a1) and v = exp(i*a2), then
104 exp(i*(a1+a2)/2) = (u+v) / length(u+v) */
105 sin[0] = 0;
106 sin[half_pi] = ampls;
107 for (step = half_pi; step > 1; step /= 2) {
108 /* k = (1 << 16) * amplitude / length(u+v)
109 In exact values, k is constant at a given step */
110 k = 0x10000;
111 for (i = 0; i < half_pi / 2; i += step) {
112 s = sin[i] + sin[i + step];
113 c = sin[half_pi - i] + sin[half_pi - i - step];
114 n2 = s * s + c * c;
115 /* Newton's method to solve n² * k² = unit² */
116 while (1) {
117 new_k = (k + unit2 / ((uint64_t)k * n2) + 1) >> 1;
118 if (k == new_k)
119 break;
120 k = new_k;
121 }
122 sin[i + step / 2] = (k * s + 0x7FFF) >> 16;
123 sin[half_pi - i - step / 2] = (k * c + 0x8000) >> 16;
124 }
125 }
126 /* Unshift amplitude */
127 for (i = 0; i <= half_pi; i++)
128 sin[i] = (sin[i] + (1 << (AMPLITUDE_SHIFT - 1))) >> AMPLITUDE_SHIFT;
129 /* Use symmetries to fill the other three quarters */
130 for (i = 0; i < half_pi; i++)
131 sin[half_pi * 2 - i] = sin[i];
132 for (i = 0; i < 2 * half_pi; i++)
133 sin[i + 2 * half_pi] = -sin[i];
134}
135
136static const char *const var_names[] = {
137 "n",
138 "pts",
139 "t",
140 "TB",
141 NULL
142};
143
144enum {
150};
151
152static void sampling_init(SamplingContext *c, double frequency, int sample_rate)
153{
155 int r_den, max_r_den;
156
157 max_r_den = INT_MAX / sample_rate;
158 frequency = fmod(frequency, sample_rate);
159 r = av_d2q(fmod(frequency, 1.0), max_r_den);
160 r_den = FFMIN(r.den, max_r_den);
161 c->dphi = ldexp(frequency, 32) / sample_rate;
162 c->dphi_den = r_den * sample_rate;
163 c->dphi_rem = round((ldexp(frequency, 32) / sample_rate - c->dphi) * c->dphi_den);
164 if (c->dphi_rem >= c->dphi_den) {
165 c->dphi++;
166 c->dphi_rem = 0;
167 }
168 c->phi_rem = (-c->dphi_den - 1) / 2;
169}
170
172{
173 c->phi += c->dphi;
174 c->phi_rem += c->dphi_rem;
175 if (c->phi_rem >= 0) {
176 c->phi_rem -= c->dphi_den;
177 c->phi++;
178 }
179}
180
182{
183 int ret;
184 SineContext *sine = ctx->priv;
185
186 if (!(sine->sin = av_malloc(sizeof(*sine->sin) << LOG_PERIOD)))
187 return AVERROR(ENOMEM);
188 sampling_init(&sine->signal, sine->frequency, sine->sample_rate);
189 make_sin_table(sine->sin);
190
191 if (sine->beep_factor) {
192 sine->beep_period = sine->sample_rate;
193 sine->beep_length = sine->beep_period / 25;
194 sampling_init(&sine->beep, sine->beep_factor * sine->frequency, sine->sample_rate);
195 }
196
199 NULL, NULL, NULL, NULL, 0, sine);
200 if (ret < 0)
201 return ret;
202
203 return 0;
204}
205
207{
208 SineContext *sine = ctx->priv;
209
212 av_freep(&sine->sin);
213}
214
216 AVFilterFormatsConfig **cfg_in,
217 AVFilterFormatsConfig **cfg_out)
218{
219 const SineContext *sine = ctx->priv;
220 static const AVChannelLayout chlayouts[] = { AV_CHANNEL_LAYOUT_MONO, { 0 } };
221 int sample_rates[] = { sine->sample_rate, -1 };
222 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16,
224 int ret = ff_set_sample_formats_from_list2(ctx, cfg_in, cfg_out, sample_fmts);
225 if (ret < 0)
226 return ret;
227
228 ret = ff_set_common_channel_layouts_from_list2(ctx, cfg_in, cfg_out, chlayouts);
229 if (ret < 0)
230 return ret;
231
232 return ff_set_common_samplerates_from_list2(ctx, cfg_in, cfg_out, sample_rates);
233}
234
236{
237 SineContext *sine = outlink->src->priv;
238 sine->duration = av_rescale(sine->duration, sine->sample_rate, AV_TIME_BASE);
239 return 0;
240}
241
243{
244 AVFilterLink *outlink = ctx->outputs[0];
245 FilterLink *outl = ff_filter_link(outlink);
246 SineContext *sine = ctx->priv;
247 AVFrame *frame;
248 double values[VAR_VARS_NB] = {
249 [VAR_N] = outl->frame_count_in,
250 [VAR_PTS] = sine->pts,
251 [VAR_T] = sine->pts * av_q2d(outlink->time_base),
252 [VAR_TB] = av_q2d(outlink->time_base),
253 };
254 int i, nb_samples = lrint(av_expr_eval(sine->samples_per_frame_expr, values, sine));
255 int16_t *samples;
256
257 if (!ff_outlink_frame_wanted(outlink))
258 return FFERROR_NOT_READY;
259 if (nb_samples <= 0) {
260 av_log(ctx, AV_LOG_WARNING, "nb samples expression evaluated to %d, "
261 "defaulting to 1024\n", nb_samples);
262 nb_samples = 1024;
263 }
264
265 if (sine->duration) {
266 nb_samples = FFMIN(nb_samples, sine->duration - sine->pts);
267 av_assert1(nb_samples >= 0);
268 if (!nb_samples) {
269 ff_outlink_set_status(outlink, AVERROR_EOF, sine->pts);
270 return 0;
271 }
272 }
273 if (!(frame = ff_get_audio_buffer(outlink, nb_samples)))
274 return AVERROR(ENOMEM);
275 samples = (int16_t *)frame->data[0];
276
277 for (i = 0; i < nb_samples; i++) {
278 samples[i] = sine->sin[sine->signal.phi >> (32 - LOG_PERIOD)];
279 sampling_advance(&sine->signal);
280 if (sine->beep_index < sine->beep_length) {
281 samples[i] += sine->sin[sine->beep.phi >> (32 - LOG_PERIOD)] * 2;
282 sampling_advance(&sine->beep);
283 }
284 if (++sine->beep_index == sine->beep_period)
285 sine->beep_index = 0;
286 }
287
288 frame->pts = sine->pts;
289 sine->pts += nb_samples;
290 return ff_filter_frame(outlink, frame);
291}
292
293static const AVFilterPad sine_outputs[] = {
294 {
295 .name = "default",
296 .type = AVMEDIA_TYPE_AUDIO,
297 .config_props = config_props,
298 },
299};
300
302 .p.name = "sine",
303 .p.description = NULL_IF_CONFIG_SMALL("Generate sine wave audio signal."),
304 .p.priv_class = &sine_class,
305 .init = init,
306 .uninit = uninit,
307 .activate = activate,
308 .priv_size = sizeof(SineContext),
311};
static enum AVSampleFormat sample_fmts[]
Definition adpcmenc.c:933
@ VAR_T
Definition aeval.c:53
static int query_formats(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out)
Definition aeval.c:246
const FFFilter ff_asrc_sine
Definition asrc_sine.c:301
#define OPT_STR(name, field, def, min, max, descr,...)
Definition asrc_sine.c:74
#define OPT_DBL(name, field, def, min, max, descr,...)
Definition asrc_sine.c:68
static void make_sin_table(int16_t *sin)
Definition asrc_sine.c:96
static const AVFilterPad sine_outputs[]
Definition asrc_sine.c:293
static av_always_inline void sampling_advance(SamplingContext *c)
Definition asrc_sine.c:171
#define AMPLITUDE_SHIFT
Definition asrc_sine.c:94
#define LOG_PERIOD
Definition asrc_sine.c:92
#define OPT_DUR(name, field, def, min, max, descr,...)
Definition asrc_sine.c:71
static const AVOption sine_options[]
Definition asrc_sine.c:77
static av_cold int query_formats(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out)
Definition asrc_sine.c:215
static int activate(AVFilterContext *ctx)
Definition asrc_sine.c:242
#define OPT_INT(name, field, def, min, max, descr,...)
Definition asrc_sine.c:65
static av_cold void uninit(AVFilterContext *ctx)
Definition asrc_sine.c:206
#define AMPLITUDE
Definition asrc_sine.c:93
static av_cold int config_props(AVFilterLink *outlink)
Definition asrc_sine.c:235
static void sampling_init(SamplingContext *c, double frequency, int sample_rate)
Definition asrc_sine.c:152
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
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition avfilter.c:1068
int ff_outlink_frame_wanted(AVFilterLink *link)
Test if a frame is wanted on an output link.
Definition avfilter.c:1690
Main libavfilter public API header.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
Public libavutil channel layout APIs header.
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static const int sample_rates[]
Definition dcaenc.h:34
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:608
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition eval.c:368
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition eval.c:824
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:735
simple arithmetic expression evaluator
static int64_t duration
Definition ffplay.c:330
int ff_set_common_samplerates_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const int *samplerates)
Definition formats.c:1050
int ff_set_common_channel_layouts_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const AVChannelLayout *fmts)
Definition formats.c:1026
int ff_set_sample_formats_from_list2(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out, const enum AVSampleFormat *fmts)
Definition formats.c:1154
#define AV_CHANNEL_LAYOUT_MONO
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition rational.c:110
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition rational.h:104
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
AVSampleFormat
Audio sample formats.
Definition samplefmt.h:55
@ AV_SAMPLE_FMT_NONE
Definition samplefmt.h:56
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition samplefmt.h:58
#define AV_TIME_BASE
Internal time base represented as integer.
Definition avutil.h:253
#define r
Definition input.c:42
static av_cold void uninit(AVBitStreamFilterContext *ctx)
static int activate(AVBitStreamFilterContext *ctx)
#define FILTER_OUTPUTS(array)
Definition filters.h:265
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:629
#define FFERROR_NOT_READY
Filters implementation helper functions and internal structures.
Definition filters.h:34
static FilterLink * ff_filter_link(AVFilterLink *link)
Definition filters.h:199
#define AVFILTER_DEFINE_CLASS(fname)
Definition filters.h:478
#define FILTER_QUERY_FUNC2(func)
Definition filters.h:241
#define av_always_inline
Definition attributes.h:72
#define av_cold
Definition attributes.h:117
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
static av_always_inline av_const double round(double x)
Definition libm.h:446
#define FFMIN(a, b)
Definition macros.h:49
Memory handling functions.
@ VAR_PTS
Definition noise.c:49
@ VAR_TB
Definition noise.c:48
@ VAR_N
Definition noise.c:47
@ VAR_VARS_NB
Definition noise.c:59
static const char *const var_names[]
Definition noise.c:30
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
static int config_props(AVBitStreamFilterLink *link)
Definition source.c:181
An AVChannelLayout holds information about the channel layout of audio data.
Describe the class of an AVClass context structure.
Definition log.h:76
Definition eval.c:171
An instance of a filter.
Definition avfilter.h:273
void * priv
private data for use by the filter
Definition avfilter.h:288
Lists of formats / etc.
Definition avfilter.h:120
A filter pad used for either input or output.
Definition filters.h:40
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
AVOption.
Definition opt.h:428
Rational number (pair of numerator and denominator).
Definition rational.h:58
uint32_t phi
current phase of the sine (2pi = 1<<32)
Definition asrc_sine.c:34
uint32_t dphi
phase increment between two samples
Definition asrc_sine.c:35
int phi_rem
current fractional phase in 1/dphi_den subfractions
Definition asrc_sine.c:36
double beep_factor
Definition asrc_sine.c:44
char * samples_per_frame
Definition asrc_sine.c:45
int16_t * sin
Definition asrc_sine.c:49
AVExpr * samples_per_frame_expr
Definition asrc_sine.c:46
unsigned beep_length
Definition asrc_sine.c:55
unsigned beep_period
Definition asrc_sine.c:53
int64_t pts
Definition asrc_sine.c:50
int64_t duration
Definition asrc_sine.c:48
SamplingContext beep
Definition asrc_sine.c:52
double frequency
Definition asrc_sine.c:43
unsigned beep_index
Definition asrc_sine.c:54
int sample_rate
Definition asrc_sine.c:47
SamplingContext signal
Definition asrc_sine.c:51
#define lrint
Definition tablegen.h:53
#define av_freep(p)
#define av_log(a,...)
static AVFormatContext * ctx
Definition movenc.c:49
static double c[64]