]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_acrossover.c
avfilter/af_acrossover: use transposed direct II form
[ffmpeg] / libavfilter / af_acrossover.c
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 /**
20  * @file
21  * Crossover filter
22  *
23  * Split an audio stream into several bands.
24  */
25
26 #include "libavutil/attributes.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/eval.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/opt.h"
32
33 #include "audio.h"
34 #include "avfilter.h"
35 #include "formats.h"
36 #include "internal.h"
37
38 #define MAX_SPLITS 16
39 #define MAX_BANDS MAX_SPLITS + 1
40
41 typedef struct BiquadContext {
42     double a0, a1, a2;
43     double b1, b2;
44     double z1, z2;
45 } BiquadContext;
46
47 typedef struct CrossoverChannel {
48     BiquadContext lp[MAX_BANDS][16];
49     BiquadContext hp[MAX_BANDS][16];
50 } CrossoverChannel;
51
52 typedef struct AudioCrossoverContext {
53     const AVClass *class;
54
55     char *splits_str;
56     int order_opt;
57
58     int order;
59     int filter_count;
60     int nb_splits;
61     float *splits;
62
63     CrossoverChannel *xover;
64
65     AVFrame *input_frame;
66     AVFrame *frames[MAX_BANDS];
67 } AudioCrossoverContext;
68
69 #define OFFSET(x) offsetof(AudioCrossoverContext, x)
70 #define AF AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
71
72 static const AVOption acrossover_options[] = {
73     { "split", "set split frequencies", OFFSET(splits_str), AV_OPT_TYPE_STRING, {.str="500"}, 0, 0, AF },
74     { "order", "set order",             OFFSET(order_opt),  AV_OPT_TYPE_INT,    {.i64=1},     0, 4, AF, "m" },
75     { "2nd",   "2nd order",             0,                  AV_OPT_TYPE_CONST,  {.i64=0},     0, 0, AF, "m" },
76     { "4th",   "4th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=1},     0, 0, AF, "m" },
77     { "8th",   "8th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "m" },
78     { "12th",  "12th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=3},     0, 0, AF, "m" },
79     { "16th",  "16th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=4},     0, 0, AF, "m" },
80     { NULL }
81 };
82
83 AVFILTER_DEFINE_CLASS(acrossover);
84
85 static av_cold int init(AVFilterContext *ctx)
86 {
87     AudioCrossoverContext *s = ctx->priv;
88     char *p, *arg, *saveptr = NULL;
89     int i, ret = 0;
90
91     s->splits = av_calloc(MAX_SPLITS, sizeof(*s->splits));
92     if (!s->splits)
93         return AVERROR(ENOMEM);
94
95     p = s->splits_str;
96     for (i = 0; i < MAX_SPLITS; i++) {
97         float freq;
98
99         if (!(arg = av_strtok(p, " |", &saveptr)))
100             break;
101
102         p = NULL;
103
104         if (av_sscanf(arg, "%f", &freq) != 1) {
105             av_log(ctx, AV_LOG_ERROR, "Invalid syntax for frequency[%d].\n", i);
106             return AVERROR(EINVAL);
107         }
108         if (freq <= 0) {
109             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be positive number.\n", freq);
110             return AVERROR(EINVAL);
111         }
112
113         if (i > 0 && freq <= s->splits[i-1]) {
114             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be in increasing order.\n", freq);
115             return AVERROR(EINVAL);
116         }
117
118         s->splits[i] = freq;
119     }
120
121     s->nb_splits = i;
122
123     for (i = 0; i <= s->nb_splits; i++) {
124         AVFilterPad pad  = { 0 };
125         char *name;
126
127         pad.type = AVMEDIA_TYPE_AUDIO;
128         name = av_asprintf("out%d", ctx->nb_outputs);
129         if (!name)
130             return AVERROR(ENOMEM);
131         pad.name = name;
132
133         if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
134             av_freep(&pad.name);
135             return ret;
136         }
137     }
138
139     return ret;
140 }
141
142 static void set_lp(BiquadContext *b, double fc, double q, double sr)
143 {
144     double thetac = 2.0 * M_PI * fc / sr;
145     double d = 1.0 / q;
146     double beta = 0.5 * (1.0 - (d / 2.0) * sin(thetac)) / (1.0 + (d / 2.0) * sin(thetac));
147     double gamma = (0.5 + beta) * cos(thetac);
148
149     b->a0 = (0.5 + beta - gamma) / 2.0;
150     b->a1 = 0.5 + beta - gamma;
151     b->a2 = b->a1 / 2.0;
152     b->b1 = 2.0 * gamma;
153     b->b2 = -2.0 * beta;
154 }
155
156 static void set_hp(BiquadContext *b, double fc, double q, double sr)
157 {
158     double thetac = 2.0 * M_PI * fc / sr;
159     double d = 1.0 / q;
160     double beta = 0.5 * (1.0 - (d / 2.0) * sin(thetac)) / (1.0 + (d / 2.0) * sin(thetac));
161     double gamma = (0.5 + beta) * cos(thetac);
162
163     b->a0 = (0.5 + beta + gamma) / 2.0;
164     b->a1 = -(0.5 + beta + gamma);
165     b->a2 = b->a0;
166     b->b1 = 2.0 * gamma;
167     b->b2 = -2.0 * beta;
168 }
169
170 static void calc_q_factors(int order, double *q)
171 {
172     int num = 1, den = 4 * order;
173
174     for (int i = 0; i < order; i++) {
175         q[i] = fabs(1. / (2. * cos(num * M_PI / den)));
176         num += 2;
177     }
178 }
179
180 static int config_input(AVFilterLink *inlink)
181 {
182     AVFilterContext *ctx = inlink->dst;
183     AudioCrossoverContext *s = ctx->priv;
184     int sample_rate = inlink->sample_rate;
185     double q[16] = { 0.5 };
186
187     s->xover = av_calloc(inlink->channels, sizeof(*s->xover));
188     if (!s->xover)
189         return AVERROR(ENOMEM);
190
191     s->order = FFMAX(2, s->order_opt * 4);
192     s->filter_count = s->order / 2;
193     calc_q_factors(s->filter_count / 2, q + (s->order == 2));
194
195     for (int ch = 0; ch < inlink->channels; ch++) {
196         for (int band = 0; band <= s->nb_splits; band++) {
197             for (int n = 0; n < s->filter_count; n++) {
198                 const int idx = (n + (s->order == 2)) / 2;
199
200                 set_lp(&s->xover[ch].lp[band][n], s->splits[band], q[idx], sample_rate);
201                 set_hp(&s->xover[ch].hp[band][n], s->splits[band], q[idx], sample_rate);
202             }
203         }
204     }
205
206     return 0;
207 }
208
209 static int query_formats(AVFilterContext *ctx)
210 {
211     AVFilterFormats *formats;
212     AVFilterChannelLayouts *layouts;
213     static const enum AVSampleFormat sample_fmts[] = {
214         AV_SAMPLE_FMT_DBLP,
215         AV_SAMPLE_FMT_NONE
216     };
217     int ret;
218
219     layouts = ff_all_channel_counts();
220     if (!layouts)
221         return AVERROR(ENOMEM);
222     ret = ff_set_common_channel_layouts(ctx, layouts);
223     if (ret < 0)
224         return ret;
225
226     formats = ff_make_format_list(sample_fmts);
227     if (!formats)
228         return AVERROR(ENOMEM);
229     ret = ff_set_common_formats(ctx, formats);
230     if (ret < 0)
231         return ret;
232
233     formats = ff_all_samplerates();
234     if (!formats)
235         return AVERROR(ENOMEM);
236     return ff_set_common_samplerates(ctx, formats);
237 }
238
239 static void biquad_process(BiquadContext *b,
240                            double *dst, const double *src,
241                            int nb_samples)
242 {
243     const double a0 = b->a0;
244     const double a1 = b->a1;
245     const double a2 = b->a2;
246     const double b1 = b->b1;
247     const double b2 = b->b2;
248     double z1 = b->z1;
249     double z2 = b->z2;
250
251     for (int n = 0; n < nb_samples; n++) {
252         const double in = src[n];
253         double out;
254
255         out = in * a0 + z1;
256         z1 = a1 * in + z2 + b1 * out;
257         z2 = a2 * in + b2 * out;
258         dst[n] = out;
259     }
260
261     b->z1 = z1;
262     b->z2 = z2;
263 }
264
265 static int filter_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
266 {
267     AudioCrossoverContext *s = ctx->priv;
268     AVFrame *in = s->input_frame;
269     AVFrame **frames = s->frames;
270     const int start = (in->channels * jobnr) / nb_jobs;
271     const int end = (in->channels * (jobnr+1)) / nb_jobs;
272     const int nb_samples = in->nb_samples;
273
274     for (int ch = start; ch < end; ch++) {
275         CrossoverChannel *xover = &s->xover[ch];
276
277         for (int band = 0; band < ctx->nb_outputs; band++) {
278             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
279                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
280                 double *dst = (double *)frames[band + 1]->extended_data[ch];
281                 const double *hsrc = f == 0 ? src : dst;
282                 BiquadContext *hp = &xover->hp[band][f];
283
284                 biquad_process(hp, dst, hsrc, nb_samples);
285             }
286
287             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
288                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
289                 double *dst = (double *)frames[band]->extended_data[ch];
290                 const double *lsrc = f == 0 ? src : dst;
291                 BiquadContext *lp = &xover->lp[band][f];
292
293                 biquad_process(lp, dst, lsrc, nb_samples);
294             }
295         }
296     }
297
298     return 0;
299 }
300
301 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
302 {
303     AVFilterContext *ctx = inlink->dst;
304     AudioCrossoverContext *s = ctx->priv;
305     AVFrame **frames = s->frames;
306     int i, ret = 0;
307
308     for (i = 0; i < ctx->nb_outputs; i++) {
309         frames[i] = ff_get_audio_buffer(ctx->outputs[i], in->nb_samples);
310
311         if (!frames[i]) {
312             ret = AVERROR(ENOMEM);
313             break;
314         }
315
316         frames[i]->pts = in->pts;
317     }
318
319     if (ret < 0)
320         goto fail;
321
322     s->input_frame = in;
323     ctx->internal->execute(ctx, filter_channels, NULL, NULL, FFMIN(inlink->channels,
324                                                                    ff_filter_get_nb_threads(ctx)));
325
326     for (i = 0; i < ctx->nb_outputs; i++) {
327         ret = ff_filter_frame(ctx->outputs[i], frames[i]);
328         frames[i] = NULL;
329         if (ret < 0)
330             break;
331     }
332
333 fail:
334     for (i = 0; i < ctx->nb_outputs; i++)
335         av_frame_free(&frames[i]);
336     av_frame_free(&in);
337     s->input_frame = NULL;
338
339     return ret;
340 }
341
342 static av_cold void uninit(AVFilterContext *ctx)
343 {
344     AudioCrossoverContext *s = ctx->priv;
345     int i;
346
347     av_freep(&s->splits);
348     av_freep(&s->xover);
349
350     for (i = 0; i < ctx->nb_outputs; i++)
351         av_freep(&ctx->output_pads[i].name);
352 }
353
354 static const AVFilterPad inputs[] = {
355     {
356         .name         = "default",
357         .type         = AVMEDIA_TYPE_AUDIO,
358         .filter_frame = filter_frame,
359         .config_props = config_input,
360     },
361     { NULL }
362 };
363
364 AVFilter ff_af_acrossover = {
365     .name           = "acrossover",
366     .description    = NULL_IF_CONFIG_SMALL("Split audio into per-bands streams."),
367     .priv_size      = sizeof(AudioCrossoverContext),
368     .priv_class     = &acrossover_class,
369     .init           = init,
370     .uninit         = uninit,
371     .query_formats  = query_formats,
372     .inputs         = inputs,
373     .outputs        = NULL,
374     .flags          = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
375                       AVFILTER_FLAG_SLICE_THREADS,
376 };