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