]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_acrossover.c
avfilter/af_acrossover: add even more orders
[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][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 thetac = 2.0 * M_PI * fc / sr;
150     double d = 1.0 / q;
151     double beta = 0.5 * (1.0 - (d / 2.0) * sin(thetac)) / (1.0 + (d / 2.0) * sin(thetac));
152     double gamma = (0.5 + beta) * cos(thetac);
153
154     b->a0 = (0.5 + beta - gamma) / 2.0;
155     b->a1 = 0.5 + beta - gamma;
156     b->a2 = b->a1 / 2.0;
157     b->b1 = 2.0 * gamma;
158     b->b2 = -2.0 * beta;
159 }
160
161 static void set_hp(BiquadContext *b, double fc, double q, double sr)
162 {
163     double thetac = 2.0 * M_PI * fc / sr;
164     double d = 1.0 / q;
165     double beta = 0.5 * (1.0 - (d / 2.0) * sin(thetac)) / (1.0 + (d / 2.0) * sin(thetac));
166     double gamma = (0.5 + beta) * cos(thetac);
167
168     b->a0 = (0.5 + beta + gamma) / 2.0;
169     b->a1 = -(0.5 + beta + gamma);
170     b->a2 = b->a0;
171     b->b1 = 2.0 * gamma;
172     b->b2 = -2.0 * beta;
173 }
174
175 static void calc_q_factors(int order, double *q)
176 {
177     double n = order / 2.;
178
179     for (int i = 0; i < n / 2; i++)
180         q[i] = 1. / (-2. * cos(M_PI * (2. * (i + 1) + n - 1.) / (2. * n)));
181 }
182
183 static int config_input(AVFilterLink *inlink)
184 {
185     AVFilterContext *ctx = inlink->dst;
186     AudioCrossoverContext *s = ctx->priv;
187     int sample_rate = inlink->sample_rate;
188     int first_order;
189     double q[16];
190
191     s->xover = av_calloc(inlink->channels, sizeof(*s->xover));
192     if (!s->xover)
193         return AVERROR(ENOMEM);
194
195     s->order = (s->order_opt + 1) * 2;
196     s->filter_count = s->order / 2;
197     first_order = s->filter_count & 1;
198     calc_q_factors(s->order, q);
199
200     for (int ch = 0; ch < inlink->channels; ch++) {
201         for (int band = 0; band <= s->nb_splits; band++) {
202             if (first_order) {
203                 set_lp(&s->xover[ch].lp[band][0], s->splits[band], 0.5, sample_rate);
204                 set_hp(&s->xover[ch].hp[band][0], s->splits[band], 0.5, sample_rate);
205             }
206
207             for (int n = first_order; n < s->filter_count; n++) {
208                 const int idx = s->filter_count / 2 - ((n + first_order) / 2 - first_order) - 1;
209
210                 set_lp(&s->xover[ch].lp[band][n], s->splits[band], q[idx], sample_rate);
211                 set_hp(&s->xover[ch].hp[band][n], s->splits[band], q[idx], sample_rate);
212             }
213         }
214     }
215
216     return 0;
217 }
218
219 static int query_formats(AVFilterContext *ctx)
220 {
221     AVFilterFormats *formats;
222     AVFilterChannelLayouts *layouts;
223     static const enum AVSampleFormat sample_fmts[] = {
224         AV_SAMPLE_FMT_DBLP,
225         AV_SAMPLE_FMT_NONE
226     };
227     int ret;
228
229     layouts = ff_all_channel_counts();
230     if (!layouts)
231         return AVERROR(ENOMEM);
232     ret = ff_set_common_channel_layouts(ctx, layouts);
233     if (ret < 0)
234         return ret;
235
236     formats = ff_make_format_list(sample_fmts);
237     if (!formats)
238         return AVERROR(ENOMEM);
239     ret = ff_set_common_formats(ctx, formats);
240     if (ret < 0)
241         return ret;
242
243     formats = ff_all_samplerates();
244     if (!formats)
245         return AVERROR(ENOMEM);
246     return ff_set_common_samplerates(ctx, formats);
247 }
248
249 static void biquad_process(BiquadContext *b,
250                            double *dst, const double *src,
251                            int nb_samples)
252 {
253     const double a0 = b->a0;
254     const double a1 = b->a1;
255     const double a2 = b->a2;
256     const double b1 = b->b1;
257     const double b2 = b->b2;
258     double z1 = b->z1;
259     double z2 = b->z2;
260
261     for (int n = 0; n < nb_samples; n++) {
262         const double in = src[n];
263         double out;
264
265         out = in * a0 + z1;
266         z1 = a1 * in + z2 + b1 * out;
267         z2 = a2 * in + b2 * out;
268         dst[n] = out;
269     }
270
271     b->z1 = z1;
272     b->z2 = z2;
273 }
274
275 static int filter_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
276 {
277     AudioCrossoverContext *s = ctx->priv;
278     AVFrame *in = s->input_frame;
279     AVFrame **frames = s->frames;
280     const int start = (in->channels * jobnr) / nb_jobs;
281     const int end = (in->channels * (jobnr+1)) / nb_jobs;
282     const int nb_samples = in->nb_samples;
283
284     for (int ch = start; ch < end; ch++) {
285         CrossoverChannel *xover = &s->xover[ch];
286
287         for (int band = 0; band < ctx->nb_outputs; band++) {
288             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
289                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
290                 double *dst = (double *)frames[band + 1]->extended_data[ch];
291                 const double *hsrc = f == 0 ? src : dst;
292                 BiquadContext *hp = &xover->hp[band][f];
293
294                 biquad_process(hp, dst, hsrc, nb_samples);
295             }
296
297             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
298                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
299                 double *dst = (double *)frames[band]->extended_data[ch];
300                 const double *lsrc = f == 0 ? src : dst;
301                 BiquadContext *lp = &xover->lp[band][f];
302
303                 biquad_process(lp, dst, lsrc, nb_samples);
304             }
305         }
306     }
307
308     return 0;
309 }
310
311 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
312 {
313     AVFilterContext *ctx = inlink->dst;
314     AudioCrossoverContext *s = ctx->priv;
315     AVFrame **frames = s->frames;
316     int i, ret = 0;
317
318     for (i = 0; i < ctx->nb_outputs; i++) {
319         frames[i] = ff_get_audio_buffer(ctx->outputs[i], in->nb_samples);
320
321         if (!frames[i]) {
322             ret = AVERROR(ENOMEM);
323             break;
324         }
325
326         frames[i]->pts = in->pts;
327     }
328
329     if (ret < 0)
330         goto fail;
331
332     s->input_frame = in;
333     ctx->internal->execute(ctx, filter_channels, NULL, NULL, FFMIN(inlink->channels,
334                                                                    ff_filter_get_nb_threads(ctx)));
335
336     for (i = 0; i < ctx->nb_outputs; i++) {
337         ret = ff_filter_frame(ctx->outputs[i], frames[i]);
338         frames[i] = NULL;
339         if (ret < 0)
340             break;
341     }
342
343 fail:
344     for (i = 0; i < ctx->nb_outputs; i++)
345         av_frame_free(&frames[i]);
346     av_frame_free(&in);
347     s->input_frame = NULL;
348
349     return ret;
350 }
351
352 static av_cold void uninit(AVFilterContext *ctx)
353 {
354     AudioCrossoverContext *s = ctx->priv;
355     int i;
356
357     av_freep(&s->splits);
358     av_freep(&s->xover);
359
360     for (i = 0; i < ctx->nb_outputs; i++)
361         av_freep(&ctx->output_pads[i].name);
362 }
363
364 static const AVFilterPad inputs[] = {
365     {
366         .name         = "default",
367         .type         = AVMEDIA_TYPE_AUDIO,
368         .filter_frame = filter_frame,
369         .config_props = config_input,
370     },
371     { NULL }
372 };
373
374 AVFilter ff_af_acrossover = {
375     .name           = "acrossover",
376     .description    = NULL_IF_CONFIG_SMALL("Split audio into per-bands streams."),
377     .priv_size      = sizeof(AudioCrossoverContext),
378     .priv_class     = &acrossover_class,
379     .init           = init,
380     .uninit         = uninit,
381     .query_formats  = query_formats,
382     .inputs         = inputs,
383     .outputs        = NULL,
384     .flags          = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
385                       AVFILTER_FLAG_SLICE_THREADS,
386 };