]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_acrossover.c
avfilter/af_acrossover: simplify coefficients
[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 b0, b1, b2;
43     double a1, a2;
44     double z1, z2;
45 } BiquadContext;
46
47 typedef struct CrossoverChannel {
48     BiquadContext lp[MAX_BANDS][20];
49     BiquadContext hp[MAX_BANDS][20];
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, 9, 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     { "6th",   "6th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "m" },
78     { "8th",   "8th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=3},     0, 0, AF, "m" },
79     { "10th",  "10th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=4},     0, 0, AF, "m" },
80     { "12th",  "12th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=5},     0, 0, AF, "m" },
81     { "14th",  "14th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=6},     0, 0, AF, "m" },
82     { "16th",  "16th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=7},     0, 0, AF, "m" },
83     { "18th",  "18th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=8},     0, 0, AF, "m" },
84     { "20th",  "20th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=9},     0, 0, AF, "m" },
85     { NULL }
86 };
87
88 AVFILTER_DEFINE_CLASS(acrossover);
89
90 static av_cold int init(AVFilterContext *ctx)
91 {
92     AudioCrossoverContext *s = ctx->priv;
93     char *p, *arg, *saveptr = NULL;
94     int i, ret = 0;
95
96     s->splits = av_calloc(MAX_SPLITS, sizeof(*s->splits));
97     if (!s->splits)
98         return AVERROR(ENOMEM);
99
100     p = s->splits_str;
101     for (i = 0; i < MAX_SPLITS; i++) {
102         float freq;
103
104         if (!(arg = av_strtok(p, " |", &saveptr)))
105             break;
106
107         p = NULL;
108
109         if (av_sscanf(arg, "%f", &freq) != 1) {
110             av_log(ctx, AV_LOG_ERROR, "Invalid syntax for frequency[%d].\n", i);
111             return AVERROR(EINVAL);
112         }
113         if (freq <= 0) {
114             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be positive number.\n", freq);
115             return AVERROR(EINVAL);
116         }
117
118         if (i > 0 && freq <= s->splits[i-1]) {
119             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be in increasing order.\n", freq);
120             return AVERROR(EINVAL);
121         }
122
123         s->splits[i] = freq;
124     }
125
126     s->nb_splits = i;
127
128     for (i = 0; i <= s->nb_splits; i++) {
129         AVFilterPad pad  = { 0 };
130         char *name;
131
132         pad.type = AVMEDIA_TYPE_AUDIO;
133         name = av_asprintf("out%d", ctx->nb_outputs);
134         if (!name)
135             return AVERROR(ENOMEM);
136         pad.name = name;
137
138         if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
139             av_freep(&pad.name);
140             return ret;
141         }
142     }
143
144     return ret;
145 }
146
147 static void set_lp(BiquadContext *b, double fc, double q, double sr)
148 {
149     double omega = M_PI * fc / sr;
150     double cosine = cos(omega);
151     double alpha = sin(omega) / (2. * q);
152
153     double b0 = (1. - cosine) / 2.;
154     double b1 = 1. - cosine;
155     double b2 = (1. - cosine) / 2.;
156     double a0 = 1. + alpha;
157     double a1 = -2. * cosine;
158     double a2 = 1. - alpha;
159
160     b->b0 =  b0 / a0;
161     b->b1 =  b1 / a0;
162     b->b2 =  b2 / a0;
163     b->a1 = -a1 / a0;
164     b->a2 = -a2 / a0;
165 }
166
167 static void set_hp(BiquadContext *b, double fc, double q, double sr)
168 {
169     double omega = M_PI * fc / sr;
170     double cosine = cos(omega);
171     double alpha = sin(omega) / (2. * q);
172
173     double b0 = (1. + cosine) / 2.;
174     double b1 = -1. - cosine;
175     double b2 = (1. + cosine) / 2.;
176     double a0 = 1. + alpha;
177     double a1 = -2. * cosine;
178     double a2 = 1. - alpha;
179
180     b->b0 =  b0 / a0;
181     b->b1 =  b1 / a0;
182     b->b2 =  b2 / a0;
183     b->a1 = -a1 / a0;
184     b->a2 = -a2 / a0;
185 }
186
187 static void calc_q_factors(int order, double *q)
188 {
189     double n = order / 2.;
190
191     for (int i = 0; i < n / 2; i++)
192         q[i] = 1. / (-2. * cos(M_PI * (2. * (i + 1) + n - 1.) / (2. * n)));
193 }
194
195 static int config_input(AVFilterLink *inlink)
196 {
197     AVFilterContext *ctx = inlink->dst;
198     AudioCrossoverContext *s = ctx->priv;
199     int sample_rate = inlink->sample_rate;
200     int first_order;
201     double q[16];
202
203     s->xover = av_calloc(inlink->channels, sizeof(*s->xover));
204     if (!s->xover)
205         return AVERROR(ENOMEM);
206
207     s->order = (s->order_opt + 1) * 2;
208     s->filter_count = s->order / 2;
209     first_order = s->filter_count & 1;
210     calc_q_factors(s->order, q);
211
212     for (int ch = 0; ch < inlink->channels; ch++) {
213         for (int band = 0; band <= s->nb_splits; band++) {
214             if (first_order) {
215                 set_lp(&s->xover[ch].lp[band][0], s->splits[band], 0.5, sample_rate);
216                 set_hp(&s->xover[ch].hp[band][0], s->splits[band], 0.5, sample_rate);
217             }
218
219             for (int n = first_order; n < s->filter_count; n++) {
220                 const int idx = s->filter_count / 2 - ((n + first_order) / 2 - first_order) - 1;
221
222                 set_lp(&s->xover[ch].lp[band][n], s->splits[band], q[idx], sample_rate);
223                 set_hp(&s->xover[ch].hp[band][n], s->splits[band], q[idx], sample_rate);
224             }
225         }
226     }
227
228     return 0;
229 }
230
231 static int query_formats(AVFilterContext *ctx)
232 {
233     AVFilterFormats *formats;
234     AVFilterChannelLayouts *layouts;
235     static const enum AVSampleFormat sample_fmts[] = {
236         AV_SAMPLE_FMT_DBLP,
237         AV_SAMPLE_FMT_NONE
238     };
239     int ret;
240
241     layouts = ff_all_channel_counts();
242     if (!layouts)
243         return AVERROR(ENOMEM);
244     ret = ff_set_common_channel_layouts(ctx, layouts);
245     if (ret < 0)
246         return ret;
247
248     formats = ff_make_format_list(sample_fmts);
249     if (!formats)
250         return AVERROR(ENOMEM);
251     ret = ff_set_common_formats(ctx, formats);
252     if (ret < 0)
253         return ret;
254
255     formats = ff_all_samplerates();
256     if (!formats)
257         return AVERROR(ENOMEM);
258     return ff_set_common_samplerates(ctx, formats);
259 }
260
261 static void biquad_process(BiquadContext *b,
262                            double *dst, const double *src,
263                            int nb_samples)
264 {
265     const double b0 = b->b0;
266     const double b1 = b->b1;
267     const double b2 = b->b2;
268     const double a1 = b->a1;
269     const double a2 = b->a2;
270     double z1 = b->z1;
271     double z2 = b->z2;
272
273     for (int n = 0; n < nb_samples; n++) {
274         const double in = src[n];
275         double out;
276
277         out = in * b0 + z1;
278         z1 = b1 * in + z2 + a1 * out;
279         z2 = b2 * in + a2 * out;
280         dst[n] = out;
281     }
282
283     b->z1 = z1;
284     b->z2 = z2;
285 }
286
287 static int filter_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
288 {
289     AudioCrossoverContext *s = ctx->priv;
290     AVFrame *in = s->input_frame;
291     AVFrame **frames = s->frames;
292     const int start = (in->channels * jobnr) / nb_jobs;
293     const int end = (in->channels * (jobnr+1)) / nb_jobs;
294     const int nb_samples = in->nb_samples;
295
296     for (int ch = start; ch < end; ch++) {
297         CrossoverChannel *xover = &s->xover[ch];
298
299         for (int band = 0; band < ctx->nb_outputs; band++) {
300             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
301                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
302                 double *dst = (double *)frames[band + 1]->extended_data[ch];
303                 const double *hsrc = f == 0 ? src : dst;
304                 BiquadContext *hp = &xover->hp[band][f];
305
306                 biquad_process(hp, dst, hsrc, nb_samples);
307             }
308
309             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
310                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
311                 double *dst = (double *)frames[band]->extended_data[ch];
312                 const double *lsrc = f == 0 ? src : dst;
313                 BiquadContext *lp = &xover->lp[band][f];
314
315                 biquad_process(lp, dst, lsrc, nb_samples);
316             }
317         }
318     }
319
320     return 0;
321 }
322
323 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
324 {
325     AVFilterContext *ctx = inlink->dst;
326     AudioCrossoverContext *s = ctx->priv;
327     AVFrame **frames = s->frames;
328     int i, ret = 0;
329
330     for (i = 0; i < ctx->nb_outputs; i++) {
331         frames[i] = ff_get_audio_buffer(ctx->outputs[i], in->nb_samples);
332
333         if (!frames[i]) {
334             ret = AVERROR(ENOMEM);
335             break;
336         }
337
338         frames[i]->pts = in->pts;
339     }
340
341     if (ret < 0)
342         goto fail;
343
344     s->input_frame = in;
345     ctx->internal->execute(ctx, filter_channels, NULL, NULL, FFMIN(inlink->channels,
346                                                                    ff_filter_get_nb_threads(ctx)));
347
348     for (i = 0; i < ctx->nb_outputs; i++) {
349         ret = ff_filter_frame(ctx->outputs[i], frames[i]);
350         frames[i] = NULL;
351         if (ret < 0)
352             break;
353     }
354
355 fail:
356     for (i = 0; i < ctx->nb_outputs; i++)
357         av_frame_free(&frames[i]);
358     av_frame_free(&in);
359     s->input_frame = NULL;
360
361     return ret;
362 }
363
364 static av_cold void uninit(AVFilterContext *ctx)
365 {
366     AudioCrossoverContext *s = ctx->priv;
367     int i;
368
369     av_freep(&s->splits);
370     av_freep(&s->xover);
371
372     for (i = 0; i < ctx->nb_outputs; i++)
373         av_freep(&ctx->output_pads[i].name);
374 }
375
376 static const AVFilterPad inputs[] = {
377     {
378         .name         = "default",
379         .type         = AVMEDIA_TYPE_AUDIO,
380         .filter_frame = filter_frame,
381         .config_props = config_input,
382     },
383     { NULL }
384 };
385
386 AVFilter ff_af_acrossover = {
387     .name           = "acrossover",
388     .description    = NULL_IF_CONFIG_SMALL("Split audio into per-bands streams."),
389     .priv_size      = sizeof(AudioCrossoverContext),
390     .priv_class     = &acrossover_class,
391     .init           = init,
392     .uninit         = uninit,
393     .query_formats  = query_formats,
394     .inputs         = inputs,
395     .outputs        = NULL,
396     .flags          = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
397                       AVFILTER_FLAG_SLICE_THREADS,
398 };