]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_acrossover.c
avfilter/af_acrossover: improve quality for odd order butterworth
[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     BiquadContext ap[MAX_BANDS][MAX_BANDS][20];
51 } CrossoverChannel;
52
53 typedef struct AudioCrossoverContext {
54     const AVClass *class;
55
56     char *splits_str;
57     int order_opt;
58
59     int order;
60     int filter_count;
61     int first_order;
62     int ap_filter_count;
63     int nb_splits;
64     float *splits;
65
66     CrossoverChannel *xover;
67
68     AVFrame *input_frame;
69     AVFrame *frames[MAX_BANDS];
70 } AudioCrossoverContext;
71
72 #define OFFSET(x) offsetof(AudioCrossoverContext, x)
73 #define AF AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
74
75 static const AVOption acrossover_options[] = {
76     { "split", "set split frequencies", OFFSET(splits_str), AV_OPT_TYPE_STRING, {.str="500"}, 0, 0, AF },
77     { "order", "set order",             OFFSET(order_opt),  AV_OPT_TYPE_INT,    {.i64=1},     0, 9, AF, "m" },
78     { "2nd",   "2nd order",             0,                  AV_OPT_TYPE_CONST,  {.i64=0},     0, 0, AF, "m" },
79     { "4th",   "4th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=1},     0, 0, AF, "m" },
80     { "6th",   "6th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "m" },
81     { "8th",   "8th order",             0,                  AV_OPT_TYPE_CONST,  {.i64=3},     0, 0, AF, "m" },
82     { "10th",  "10th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=4},     0, 0, AF, "m" },
83     { "12th",  "12th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=5},     0, 0, AF, "m" },
84     { "14th",  "14th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=6},     0, 0, AF, "m" },
85     { "16th",  "16th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=7},     0, 0, AF, "m" },
86     { "18th",  "18th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=8},     0, 0, AF, "m" },
87     { "20th",  "20th order",            0,                  AV_OPT_TYPE_CONST,  {.i64=9},     0, 0, AF, "m" },
88     { NULL }
89 };
90
91 AVFILTER_DEFINE_CLASS(acrossover);
92
93 static av_cold int init(AVFilterContext *ctx)
94 {
95     AudioCrossoverContext *s = ctx->priv;
96     char *p, *arg, *saveptr = NULL;
97     int i, ret = 0;
98
99     s->splits = av_calloc(MAX_SPLITS, sizeof(*s->splits));
100     if (!s->splits)
101         return AVERROR(ENOMEM);
102
103     p = s->splits_str;
104     for (i = 0; i < MAX_SPLITS; i++) {
105         float freq;
106
107         if (!(arg = av_strtok(p, " |", &saveptr)))
108             break;
109
110         p = NULL;
111
112         if (av_sscanf(arg, "%f", &freq) != 1) {
113             av_log(ctx, AV_LOG_ERROR, "Invalid syntax for frequency[%d].\n", i);
114             return AVERROR(EINVAL);
115         }
116         if (freq <= 0) {
117             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be positive number.\n", freq);
118             return AVERROR(EINVAL);
119         }
120
121         if (i > 0 && freq <= s->splits[i-1]) {
122             av_log(ctx, AV_LOG_ERROR, "Frequency %f must be in increasing order.\n", freq);
123             return AVERROR(EINVAL);
124         }
125
126         s->splits[i] = freq;
127     }
128
129     s->nb_splits = i;
130
131     for (i = 0; i <= s->nb_splits; i++) {
132         AVFilterPad pad  = { 0 };
133         char *name;
134
135         pad.type = AVMEDIA_TYPE_AUDIO;
136         name = av_asprintf("out%d", ctx->nb_outputs);
137         if (!name)
138             return AVERROR(ENOMEM);
139         pad.name = name;
140
141         if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
142             av_freep(&pad.name);
143             return ret;
144         }
145     }
146
147     return ret;
148 }
149
150 static void set_lp(BiquadContext *b, double fc, double q, double sr)
151 {
152     double omega = M_PI * fc / sr;
153     double cosine = cos(omega);
154     double alpha = sin(omega) / (2. * q);
155
156     double b0 = (1. - cosine) / 2.;
157     double b1 = 1. - cosine;
158     double b2 = (1. - cosine) / 2.;
159     double a0 = 1. + alpha;
160     double a1 = -2. * cosine;
161     double a2 = 1. - alpha;
162
163     b->b0 =  b0 / a0;
164     b->b1 =  b1 / a0;
165     b->b2 =  b2 / a0;
166     b->a1 = -a1 / a0;
167     b->a2 = -a2 / a0;
168 }
169
170 static void set_hp(BiquadContext *b, double fc, double q, double sr)
171 {
172     double omega = M_PI * fc / sr;
173     double cosine = cos(omega);
174     double alpha = sin(omega) / (2. * q);
175
176     double b0 = (1. + cosine) / 2.;
177     double b1 = -1. - cosine;
178     double b2 = (1. + cosine) / 2.;
179     double a0 = 1. + alpha;
180     double a1 = -2. * cosine;
181     double a2 = 1. - alpha;
182
183     b->b0 =  b0 / a0;
184     b->b1 =  b1 / a0;
185     b->b2 =  b2 / a0;
186     b->a1 = -a1 / a0;
187     b->a2 = -a2 / a0;
188 }
189
190 static void set_ap(BiquadContext *b, double fc, double q, double sr)
191 {
192     double omega = M_PI * fc / sr;
193     double cosine = cos(omega);
194     double alpha = sin(omega) / (2. * q);
195
196     double a0 = 1. + alpha;
197     double a1 = -2. * cosine;
198     double a2 = 1. - alpha;
199     double b0 = a2;
200     double b1 = a1;
201     double b2 = a0;
202
203     b->b0 =  b0 / a0;
204     b->b1 =  b1 / a0;
205     b->b2 =  b2 / a0;
206     b->a1 = -a1 / a0;
207     b->a2 = -a2 / a0;
208 }
209
210 static void set_ap1(BiquadContext *b, double fc, double sr)
211 {
212     double omega = M_PI * fc / sr;
213     double K = tan(omega);
214
215     b->a1 = -(1. - K) / (1. + K);
216     b->a2 = 0.;
217     b->b0 = -b->a1;
218     b->b1 = 1.;
219     b->b2 = 0.;
220 }
221
222 static void calc_q_factors(int order, double *q)
223 {
224     double n = order / 2.;
225
226     for (int i = 0; i < n / 2; i++)
227         q[i] = 1. / (-2. * cos(M_PI * (2. * (i + 1) + n - 1.) / (2. * n)));
228 }
229
230 static int config_input(AVFilterLink *inlink)
231 {
232     AVFilterContext *ctx = inlink->dst;
233     AudioCrossoverContext *s = ctx->priv;
234     int sample_rate = inlink->sample_rate;
235     double q[16];
236
237     s->xover = av_calloc(inlink->channels, sizeof(*s->xover));
238     if (!s->xover)
239         return AVERROR(ENOMEM);
240
241     s->order = (s->order_opt + 1) * 2;
242     s->filter_count = s->order / 2;
243     s->first_order = s->filter_count & 1;
244     s->ap_filter_count = s->filter_count / 2 + s->first_order;
245     calc_q_factors(s->order, q);
246
247     for (int ch = 0; ch < inlink->channels; ch++) {
248         for (int band = 0; band <= s->nb_splits; band++) {
249             if (s->first_order) {
250                 set_lp(&s->xover[ch].lp[band][0], s->splits[band], 0.5, sample_rate);
251                 set_hp(&s->xover[ch].hp[band][0], s->splits[band], 0.5, sample_rate);
252             }
253
254             for (int n = s->first_order; n < s->filter_count; n++) {
255                 const int idx = s->filter_count / 2 - ((n + s->first_order) / 2 - s->first_order) - 1;
256
257                 set_lp(&s->xover[ch].lp[band][n], s->splits[band], q[idx], sample_rate);
258                 set_hp(&s->xover[ch].hp[band][n], s->splits[band], q[idx], sample_rate);
259             }
260
261             for (int x = 0; x <= s->nb_splits && s->first_order; x++)
262                 set_ap1(&s->xover[ch].ap[x][band][0], s->splits[band], sample_rate);
263
264             for (int n = s->first_order; n < s->ap_filter_count; n++) {
265                 const int idx = (s->filter_count / 2 - ((n * 2 + s->first_order) / 2 - s->first_order) - 1);
266
267                 for (int x = 0; x <= s->nb_splits; x++)
268                     set_ap(&s->xover[ch].ap[x][band][n], s->splits[band], q[idx], sample_rate);
269             }
270         }
271     }
272
273     return 0;
274 }
275
276 static int query_formats(AVFilterContext *ctx)
277 {
278     AVFilterFormats *formats;
279     AVFilterChannelLayouts *layouts;
280     static const enum AVSampleFormat sample_fmts[] = {
281         AV_SAMPLE_FMT_DBLP,
282         AV_SAMPLE_FMT_NONE
283     };
284     int ret;
285
286     layouts = ff_all_channel_counts();
287     if (!layouts)
288         return AVERROR(ENOMEM);
289     ret = ff_set_common_channel_layouts(ctx, layouts);
290     if (ret < 0)
291         return ret;
292
293     formats = ff_make_format_list(sample_fmts);
294     if (!formats)
295         return AVERROR(ENOMEM);
296     ret = ff_set_common_formats(ctx, formats);
297     if (ret < 0)
298         return ret;
299
300     formats = ff_all_samplerates();
301     if (!formats)
302         return AVERROR(ENOMEM);
303     return ff_set_common_samplerates(ctx, formats);
304 }
305
306 static void biquad_process(BiquadContext *b,
307                            double *dst, const double *src,
308                            int nb_samples)
309 {
310     const double b0 = b->b0;
311     const double b1 = b->b1;
312     const double b2 = b->b2;
313     const double a1 = b->a1;
314     const double a2 = b->a2;
315     double z1 = b->z1;
316     double z2 = b->z2;
317
318     for (int n = 0; n < nb_samples; n++) {
319         const double in = src[n];
320         double out;
321
322         out = in * b0 + z1;
323         z1 = b1 * in + z2 + a1 * out;
324         z2 = b2 * in + a2 * out;
325         dst[n] = out;
326     }
327
328     b->z1 = z1;
329     b->z2 = z2;
330 }
331
332 static int filter_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
333 {
334     AudioCrossoverContext *s = ctx->priv;
335     AVFrame *in = s->input_frame;
336     AVFrame **frames = s->frames;
337     const int start = (in->channels * jobnr) / nb_jobs;
338     const int end = (in->channels * (jobnr+1)) / nb_jobs;
339     const int nb_samples = in->nb_samples;
340
341     for (int ch = start; ch < end; ch++) {
342         CrossoverChannel *xover = &s->xover[ch];
343
344         for (int band = 0; band < ctx->nb_outputs; band++) {
345             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
346                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
347                 double *dst = (double *)frames[band + 1]->extended_data[ch];
348                 const double *hsrc = f == 0 ? src : dst;
349                 BiquadContext *hp = &xover->hp[band][f];
350
351                 biquad_process(hp, dst, hsrc, nb_samples);
352             }
353
354             for (int f = 0; band + 1 < ctx->nb_outputs && f < s->filter_count; f++) {
355                 const double *src = band == 0 ? (const double *)in->extended_data[ch] : (const double *)frames[band]->extended_data[ch];
356                 double *dst = (double *)frames[band]->extended_data[ch];
357                 const double *lsrc = f == 0 ? src : dst;
358                 BiquadContext *lp = &xover->lp[band][f];
359
360                 biquad_process(lp, dst, lsrc, nb_samples);
361             }
362
363             for (int aband = band + 1; aband < ctx->nb_outputs; aband++) {
364                 if (s->first_order) {
365                     const double *src = (const double *)frames[band]->extended_data[ch];
366                     double *dst = (double *)frames[band]->extended_data[ch];
367                     BiquadContext *ap = &xover->ap[band][aband][0];
368
369                     biquad_process(ap, dst, src, nb_samples);
370                 }
371
372                 for (int f = s->first_order; f < s->ap_filter_count; f++) {
373                     const double *src = (const double *)frames[band]->extended_data[ch];
374                     double *dst = (double *)frames[band]->extended_data[ch];
375                     BiquadContext *ap = &xover->ap[band][aband][f];
376
377                     biquad_process(ap, dst, src, nb_samples);
378                 }
379             }
380         }
381
382         for (int band = 0; band < ctx->nb_outputs && s->first_order; band++) {
383             if (band & 1) {
384                 double *dst = (double *)frames[band]->extended_data[ch];
385
386                 for (int n = 0; n < nb_samples; n++)
387                     dst[n] *= -1.;
388             }
389         }
390     }
391
392     return 0;
393 }
394
395 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
396 {
397     AVFilterContext *ctx = inlink->dst;
398     AudioCrossoverContext *s = ctx->priv;
399     AVFrame **frames = s->frames;
400     int i, ret = 0;
401
402     for (i = 0; i < ctx->nb_outputs; i++) {
403         frames[i] = ff_get_audio_buffer(ctx->outputs[i], in->nb_samples);
404
405         if (!frames[i]) {
406             ret = AVERROR(ENOMEM);
407             break;
408         }
409
410         frames[i]->pts = in->pts;
411     }
412
413     if (ret < 0)
414         goto fail;
415
416     s->input_frame = in;
417     ctx->internal->execute(ctx, filter_channels, NULL, NULL, FFMIN(inlink->channels,
418                                                                    ff_filter_get_nb_threads(ctx)));
419
420     for (i = 0; i < ctx->nb_outputs; i++) {
421         ret = ff_filter_frame(ctx->outputs[i], frames[i]);
422         frames[i] = NULL;
423         if (ret < 0)
424             break;
425     }
426
427 fail:
428     for (i = 0; i < ctx->nb_outputs; i++)
429         av_frame_free(&frames[i]);
430     av_frame_free(&in);
431     s->input_frame = NULL;
432
433     return ret;
434 }
435
436 static av_cold void uninit(AVFilterContext *ctx)
437 {
438     AudioCrossoverContext *s = ctx->priv;
439     int i;
440
441     av_freep(&s->splits);
442     av_freep(&s->xover);
443
444     for (i = 0; i < ctx->nb_outputs; i++)
445         av_freep(&ctx->output_pads[i].name);
446 }
447
448 static const AVFilterPad inputs[] = {
449     {
450         .name         = "default",
451         .type         = AVMEDIA_TYPE_AUDIO,
452         .filter_frame = filter_frame,
453         .config_props = config_input,
454     },
455     { NULL }
456 };
457
458 AVFilter ff_af_acrossover = {
459     .name           = "acrossover",
460     .description    = NULL_IF_CONFIG_SMALL("Split audio into per-bands streams."),
461     .priv_size      = sizeof(AudioCrossoverContext),
462     .priv_class     = &acrossover_class,
463     .init           = init,
464     .uninit         = uninit,
465     .query_formats  = query_formats,
466     .inputs         = inputs,
467     .outputs        = NULL,
468     .flags          = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
469                       AVFILTER_FLAG_SLICE_THREADS,
470 };