]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_headphone.c
avfilter/af_headphone: Avoid indirection for function pointer
[ffmpeg] / libavfilter / af_headphone.c
1 /*
2  * Copyright (C) 2017 Paul B Mahol
3  * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <math.h>
22
23 #include "libavutil/avstring.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/float_dsp.h"
26 #include "libavutil/intmath.h"
27 #include "libavutil/opt.h"
28 #include "libavcodec/avfft.h"
29
30 #include "avfilter.h"
31 #include "filters.h"
32 #include "internal.h"
33 #include "audio.h"
34
35 #define TIME_DOMAIN      0
36 #define FREQUENCY_DOMAIN 1
37
38 #define HRIR_STEREO 0
39 #define HRIR_MULTI  1
40
41 typedef struct HeadphoneContext {
42     const AVClass *class;
43
44     char *map;
45     int type;
46
47     int lfe_channel;
48
49     int have_hrirs;
50     int eof_hrirs;
51
52     int ir_len;
53     int air_len;
54
55     int nb_hrir_inputs;
56
57     int nb_irs;
58
59     float gain;
60     float lfe_gain, gain_lfe;
61
62     float *ringbuffer[2];
63     int write[2];
64
65     int buffer_length;
66     int n_fft;
67     int size;
68     int hrir_fmt;
69
70     float *data_ir[2];
71     float *temp_src[2];
72     FFTComplex *temp_fft[2];
73     FFTComplex *temp_afft[2];
74
75     FFTContext *fft[2], *ifft[2];
76     FFTComplex *data_hrtf[2];
77
78     float (*scalarproduct_float)(const float *v1, const float *v2, int len);
79     struct hrir_inputs {
80         int          ir_len;
81         int          eof;
82     } hrir_in[64];
83     uint64_t mapping[64];
84 } HeadphoneContext;
85
86 static int parse_channel_name(const char *arg, uint64_t *rchannel)
87 {
88     uint64_t layout = av_get_channel_layout(arg);
89
90     if (av_get_channel_layout_nb_channels(layout) != 1)
91         return AVERROR(EINVAL);
92     *rchannel = layout;
93     return 0;
94 }
95
96 static void parse_map(AVFilterContext *ctx)
97 {
98     HeadphoneContext *s = ctx->priv;
99     char *arg, *tokenizer, *p;
100     uint64_t used_channels = 0;
101
102     p = s->map;
103     while ((arg = av_strtok(p, "|", &tokenizer))) {
104         uint64_t out_channel;
105
106         p = NULL;
107         if (parse_channel_name(arg, &out_channel)) {
108             av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", arg);
109             continue;
110         }
111         if (used_channels & out_channel) {
112             av_log(ctx, AV_LOG_WARNING, "Ignoring duplicate channel '%s'.\n", arg);
113             continue;
114         }
115         used_channels        |= out_channel;
116         s->mapping[s->nb_irs] = out_channel;
117         s->nb_irs++;
118     }
119
120     if (s->hrir_fmt == HRIR_MULTI)
121         s->nb_hrir_inputs = 1;
122     else
123         s->nb_hrir_inputs = s->nb_irs;
124 }
125
126 typedef struct ThreadData {
127     AVFrame *in, *out;
128     int *write;
129     float **ir;
130     int *n_clippings;
131     float **ringbuffer;
132     float **temp_src;
133     FFTComplex **temp_fft;
134     FFTComplex **temp_afft;
135 } ThreadData;
136
137 static int headphone_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
138 {
139     HeadphoneContext *s = ctx->priv;
140     ThreadData *td = arg;
141     AVFrame *in = td->in, *out = td->out;
142     int offset = jobnr;
143     int *write = &td->write[jobnr];
144     const float *const ir = td->ir[jobnr];
145     int *n_clippings = &td->n_clippings[jobnr];
146     float *ringbuffer = td->ringbuffer[jobnr];
147     float *temp_src = td->temp_src[jobnr];
148     const int ir_len = s->ir_len;
149     const int air_len = s->air_len;
150     const float *src = (const float *)in->data[0];
151     float *dst = (float *)out->data[0];
152     const int in_channels = in->channels;
153     const int buffer_length = s->buffer_length;
154     const uint32_t modulo = (uint32_t)buffer_length - 1;
155     float *buffer[64];
156     int wr = *write;
157     int read;
158     int i, l;
159
160     dst += offset;
161     for (l = 0; l < in_channels; l++) {
162         buffer[l] = ringbuffer + l * buffer_length;
163     }
164
165     for (i = 0; i < in->nb_samples; i++) {
166         const float *temp_ir = ir;
167
168         *dst = 0;
169         for (l = 0; l < in_channels; l++) {
170             *(buffer[l] + wr) = src[l];
171         }
172
173         for (l = 0; l < in_channels; l++) {
174             const float *const bptr = buffer[l];
175
176             if (l == s->lfe_channel) {
177                 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
178                 temp_ir += air_len;
179                 continue;
180             }
181
182             read = (wr - (ir_len - 1) + buffer_length) & modulo;
183
184             if (read + ir_len < buffer_length) {
185                 memcpy(temp_src, bptr + read, ir_len * sizeof(*temp_src));
186             } else {
187                 int len = FFMIN(air_len - (read % ir_len), buffer_length - read);
188
189                 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
190                 memcpy(temp_src + len, bptr, (air_len - len) * sizeof(*temp_src));
191             }
192
193             dst[0] += s->scalarproduct_float(temp_ir, temp_src, FFALIGN(ir_len, 32));
194             temp_ir += air_len;
195         }
196
197         if (fabsf(dst[0]) > 1)
198             n_clippings[0]++;
199
200         dst += 2;
201         src += in_channels;
202         wr   = (wr + 1) & modulo;
203     }
204
205     *write = wr;
206
207     return 0;
208 }
209
210 static int headphone_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
211 {
212     HeadphoneContext *s = ctx->priv;
213     ThreadData *td = arg;
214     AVFrame *in = td->in, *out = td->out;
215     int offset = jobnr;
216     int *write = &td->write[jobnr];
217     FFTComplex *hrtf = s->data_hrtf[jobnr];
218     int *n_clippings = &td->n_clippings[jobnr];
219     float *ringbuffer = td->ringbuffer[jobnr];
220     const int ir_len = s->ir_len;
221     const float *src = (const float *)in->data[0];
222     float *dst = (float *)out->data[0];
223     const int in_channels = in->channels;
224     const int buffer_length = s->buffer_length;
225     const uint32_t modulo = (uint32_t)buffer_length - 1;
226     FFTComplex *fft_in = s->temp_fft[jobnr];
227     FFTComplex *fft_acc = s->temp_afft[jobnr];
228     FFTContext *ifft = s->ifft[jobnr];
229     FFTContext *fft = s->fft[jobnr];
230     const int n_fft = s->n_fft;
231     const float fft_scale = 1.0f / s->n_fft;
232     FFTComplex *hrtf_offset;
233     int wr = *write;
234     int n_read;
235     int i, j;
236
237     dst += offset;
238
239     n_read = FFMIN(ir_len, in->nb_samples);
240     for (j = 0; j < n_read; j++) {
241         dst[2 * j]     = ringbuffer[wr];
242         ringbuffer[wr] = 0.0;
243         wr  = (wr + 1) & modulo;
244     }
245
246     for (j = n_read; j < in->nb_samples; j++) {
247         dst[2 * j] = 0;
248     }
249
250     memset(fft_acc, 0, sizeof(FFTComplex) * n_fft);
251
252     for (i = 0; i < in_channels; i++) {
253         if (i == s->lfe_channel) {
254             for (j = 0; j < in->nb_samples; j++) {
255                 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
256             }
257             continue;
258         }
259
260         offset = i * n_fft;
261         hrtf_offset = hrtf + offset;
262
263         memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
264
265         for (j = 0; j < in->nb_samples; j++) {
266             fft_in[j].re = src[j * in_channels + i];
267         }
268
269         av_fft_permute(fft, fft_in);
270         av_fft_calc(fft, fft_in);
271         for (j = 0; j < n_fft; j++) {
272             const FFTComplex *hcomplex = hrtf_offset + j;
273             const float re = fft_in[j].re;
274             const float im = fft_in[j].im;
275
276             fft_acc[j].re += re * hcomplex->re - im * hcomplex->im;
277             fft_acc[j].im += re * hcomplex->im + im * hcomplex->re;
278         }
279     }
280
281     av_fft_permute(ifft, fft_acc);
282     av_fft_calc(ifft, fft_acc);
283
284     for (j = 0; j < in->nb_samples; j++) {
285         dst[2 * j] += fft_acc[j].re * fft_scale;
286     }
287
288     for (j = 0; j < ir_len - 1; j++) {
289         int write_pos = (wr + j) & modulo;
290
291         *(ringbuffer + write_pos) += fft_acc[in->nb_samples + j].re * fft_scale;
292     }
293
294     for (i = 0; i < out->nb_samples; i++) {
295         if (fabsf(dst[0]) > 1) {
296             n_clippings[0]++;
297         }
298
299         dst += 2;
300     }
301
302     *write = wr;
303
304     return 0;
305 }
306
307 static int check_ir(AVFilterLink *inlink, int input_number)
308 {
309     AVFilterContext *ctx = inlink->dst;
310     HeadphoneContext *s = ctx->priv;
311     int ir_len, max_ir_len;
312
313     ir_len = ff_inlink_queued_samples(inlink);
314     max_ir_len = 65536;
315     if (ir_len > max_ir_len) {
316         av_log(ctx, AV_LOG_ERROR, "Too big length of IRs: %d > %d.\n", ir_len, max_ir_len);
317         return AVERROR(EINVAL);
318     }
319     s->hrir_in[input_number].ir_len = ir_len;
320     s->ir_len = FFMAX(ir_len, s->ir_len);
321
322     return 0;
323 }
324
325 static int headphone_frame(HeadphoneContext *s, AVFrame *in, AVFilterLink *outlink)
326 {
327     AVFilterContext *ctx = outlink->src;
328     int n_clippings[2] = { 0 };
329     ThreadData td;
330     AVFrame *out;
331
332     out = ff_get_audio_buffer(outlink, in->nb_samples);
333     if (!out) {
334         av_frame_free(&in);
335         return AVERROR(ENOMEM);
336     }
337     out->pts = in->pts;
338
339     td.in = in; td.out = out; td.write = s->write;
340     td.ir = s->data_ir; td.n_clippings = n_clippings;
341     td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
342     td.temp_fft = s->temp_fft;
343     td.temp_afft = s->temp_afft;
344
345     if (s->type == TIME_DOMAIN) {
346         ctx->internal->execute(ctx, headphone_convolute, &td, NULL, 2);
347     } else {
348         ctx->internal->execute(ctx, headphone_fast_convolute, &td, NULL, 2);
349     }
350     emms_c();
351
352     if (n_clippings[0] + n_clippings[1] > 0) {
353         av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
354                n_clippings[0] + n_clippings[1], out->nb_samples * 2);
355     }
356
357     av_frame_free(&in);
358     return ff_filter_frame(outlink, out);
359 }
360
361 static int convert_coeffs(AVFilterContext *ctx, AVFilterLink *inlink)
362 {
363     struct HeadphoneContext *s = ctx->priv;
364     const int ir_len = s->ir_len;
365     int nb_input_channels = ctx->inputs[0]->channels;
366     float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10);
367     AVFrame *frame;
368     int ret = 0;
369     int n_fft;
370     int i, j, k;
371
372     s->air_len = 1 << (32 - ff_clz(ir_len));
373     if (s->type == TIME_DOMAIN) {
374         s->air_len = FFALIGN(s->air_len, 32);
375     }
376     s->buffer_length = 1 << (32 - ff_clz(s->air_len));
377     s->n_fft = n_fft = 1 << (32 - ff_clz(ir_len + s->size));
378
379     if (s->type == FREQUENCY_DOMAIN) {
380         s->fft[0] = av_fft_init(av_log2(s->n_fft), 0);
381         s->fft[1] = av_fft_init(av_log2(s->n_fft), 0);
382         s->ifft[0] = av_fft_init(av_log2(s->n_fft), 1);
383         s->ifft[1] = av_fft_init(av_log2(s->n_fft), 1);
384
385         if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
386             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
387             ret = AVERROR(ENOMEM);
388             goto fail;
389         }
390     }
391
392     if (s->type == TIME_DOMAIN) {
393         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
394         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
395     } else {
396         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
397         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
398         s->temp_fft[0] = av_calloc(s->n_fft, sizeof(FFTComplex));
399         s->temp_fft[1] = av_calloc(s->n_fft, sizeof(FFTComplex));
400         s->temp_afft[0] = av_calloc(s->n_fft, sizeof(FFTComplex));
401         s->temp_afft[1] = av_calloc(s->n_fft, sizeof(FFTComplex));
402         if (!s->temp_fft[0] || !s->temp_fft[1] ||
403             !s->temp_afft[0] || !s->temp_afft[1]) {
404             ret = AVERROR(ENOMEM);
405             goto fail;
406         }
407     }
408
409     if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
410         ret = AVERROR(ENOMEM);
411         goto fail;
412     }
413
414     if (s->type == TIME_DOMAIN) {
415         s->temp_src[0] = av_calloc(s->air_len, sizeof(float));
416         s->temp_src[1] = av_calloc(s->air_len, sizeof(float));
417
418         s->data_ir[0] = av_calloc(nb_input_channels * s->air_len, sizeof(*s->data_ir[0]));
419         s->data_ir[1] = av_calloc(nb_input_channels * s->air_len, sizeof(*s->data_ir[1]));
420         if (!s->data_ir[0] || !s->data_ir[1] || !s->temp_src[0] || !s->temp_src[1]) {
421             ret = AVERROR(ENOMEM);
422             goto fail;
423         }
424     } else {
425         s->data_hrtf[0] = av_calloc(n_fft, sizeof(*s->data_hrtf[0]) * nb_input_channels);
426         s->data_hrtf[1] = av_calloc(n_fft, sizeof(*s->data_hrtf[1]) * nb_input_channels);
427         if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
428             ret = AVERROR(ENOMEM);
429             goto fail;
430         }
431     }
432
433     for (i = 0; i < s->nb_hrir_inputs; av_frame_free(&frame), i++) {
434         int len = s->hrir_in[i].ir_len;
435         float *ptr;
436
437         ret = ff_inlink_consume_samples(ctx->inputs[i + 1], len, len, &frame);
438         if (ret < 0)
439             goto fail;
440         ptr = (float *)frame->extended_data[0];
441
442         if (s->hrir_fmt == HRIR_STEREO) {
443             int idx = av_get_channel_layout_channel_index(inlink->channel_layout,
444                                                           s->mapping[i]);
445             if (idx < 0)
446                 continue;
447             if (s->type == TIME_DOMAIN) {
448                 float *data_ir_l = s->data_ir[0] + idx * s->air_len;
449                 float *data_ir_r = s->data_ir[1] + idx * s->air_len;
450
451                 for (j = 0; j < len; j++) {
452                     data_ir_l[j] = ptr[len * 2 - j * 2 - 2] * gain_lin;
453                     data_ir_r[j] = ptr[len * 2 - j * 2 - 1] * gain_lin;
454                 }
455             } else {
456                 FFTComplex *fft_in_l = s->data_hrtf[0] + idx * n_fft;
457                 FFTComplex *fft_in_r = s->data_hrtf[1] + idx * n_fft;
458
459                 for (j = 0; j < len; j++) {
460                     fft_in_l[j].re = ptr[j * 2    ] * gain_lin;
461                     fft_in_r[j].re = ptr[j * 2 + 1] * gain_lin;
462                 }
463
464                 av_fft_permute(s->fft[0], fft_in_l);
465                 av_fft_calc(s->fft[0], fft_in_l);
466                 av_fft_permute(s->fft[0], fft_in_r);
467                 av_fft_calc(s->fft[0], fft_in_r);
468             }
469         } else {
470             int I, N = ctx->inputs[1]->channels;
471
472             for (k = 0; k < N / 2; k++) {
473                 int idx = av_get_channel_layout_channel_index(inlink->channel_layout,
474                                                               s->mapping[k]);
475                 if (idx < 0)
476                     continue;
477
478                 I = k * 2;
479                 if (s->type == TIME_DOMAIN) {
480                     float *data_ir_l = s->data_ir[0] + idx * s->air_len;
481                     float *data_ir_r = s->data_ir[1] + idx * s->air_len;
482
483                     for (j = 0; j < len; j++) {
484                         data_ir_l[j] = ptr[len * N - j * N - N + I    ] * gain_lin;
485                         data_ir_r[j] = ptr[len * N - j * N - N + I + 1] * gain_lin;
486                     }
487                 } else {
488                     FFTComplex *fft_in_l = s->data_hrtf[0] + idx * n_fft;
489                     FFTComplex *fft_in_r = s->data_hrtf[1] + idx * n_fft;
490
491                     for (j = 0; j < len; j++) {
492                         fft_in_l[j].re = ptr[j * N + I    ] * gain_lin;
493                         fft_in_r[j].re = ptr[j * N + I + 1] * gain_lin;
494                     }
495
496                     av_fft_permute(s->fft[0], fft_in_l);
497                     av_fft_calc(s->fft[0], fft_in_l);
498                     av_fft_permute(s->fft[0], fft_in_r);
499                     av_fft_calc(s->fft[0], fft_in_r);
500                 }
501             }
502         }
503     }
504
505     s->have_hrirs = 1;
506
507 fail:
508     return ret;
509 }
510
511 static int activate(AVFilterContext *ctx)
512 {
513     HeadphoneContext *s = ctx->priv;
514     AVFilterLink *inlink = ctx->inputs[0];
515     AVFilterLink *outlink = ctx->outputs[0];
516     AVFrame *in = NULL;
517     int i, ret;
518
519     FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[0], ctx);
520     if (!s->eof_hrirs) {
521         int eof = 1;
522         for (i = 0; i < s->nb_hrir_inputs; i++) {
523             AVFilterLink *input = ctx->inputs[i + 1];
524
525             if (s->hrir_in[i].eof)
526                 continue;
527
528             if ((ret = check_ir(input, i)) < 0)
529                 return ret;
530
531             if (ff_outlink_get_status(input) == AVERROR_EOF) {
532                 if (!ff_inlink_queued_samples(input)) {
533                     av_log(ctx, AV_LOG_ERROR, "No samples provided for "
534                            "HRIR stream %d.\n", i);
535                     return AVERROR_INVALIDDATA;
536                 }
537                 s->hrir_in[i].eof = 1;
538             } else {
539                 if (ff_outlink_frame_wanted(ctx->outputs[0]))
540                     ff_inlink_request_frame(input);
541                 eof = 0;
542             }
543         }
544         if (!eof)
545             return 0;
546         s->eof_hrirs = 1;
547
548         ret = convert_coeffs(ctx, inlink);
549         if (ret < 0)
550             return ret;
551     } else if (!s->have_hrirs)
552         return AVERROR_EOF;
553
554     if ((ret = ff_inlink_consume_samples(ctx->inputs[0], s->size, s->size, &in)) > 0) {
555         ret = headphone_frame(s, in, outlink);
556         if (ret < 0)
557             return ret;
558     }
559
560     if (ret < 0)
561         return ret;
562
563     FF_FILTER_FORWARD_STATUS(ctx->inputs[0], ctx->outputs[0]);
564     if (ff_outlink_frame_wanted(ctx->outputs[0]))
565         ff_inlink_request_frame(ctx->inputs[0]);
566
567     return 0;
568 }
569
570 static int query_formats(AVFilterContext *ctx)
571 {
572     struct HeadphoneContext *s = ctx->priv;
573     AVFilterFormats *formats = NULL;
574     AVFilterChannelLayouts *layouts = NULL;
575     AVFilterChannelLayouts *stereo_layout = NULL;
576     AVFilterChannelLayouts *hrir_layouts = NULL;
577     int ret, i;
578
579     ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
580     if (ret)
581         return ret;
582     ret = ff_set_common_formats(ctx, formats);
583     if (ret)
584         return ret;
585
586     layouts = ff_all_channel_layouts();
587     if (!layouts)
588         return AVERROR(ENOMEM);
589
590     ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->outcfg.channel_layouts);
591     if (ret)
592         return ret;
593
594     ret = ff_add_channel_layout(&stereo_layout, AV_CH_LAYOUT_STEREO);
595     if (ret)
596         return ret;
597     ret = ff_channel_layouts_ref(stereo_layout, &ctx->outputs[0]->incfg.channel_layouts);
598     if (ret)
599         return ret;
600
601     if (s->hrir_fmt == HRIR_MULTI) {
602         hrir_layouts = ff_all_channel_counts();
603         if (!hrir_layouts)
604             return AVERROR(ENOMEM);
605         ret = ff_channel_layouts_ref(hrir_layouts, &ctx->inputs[1]->outcfg.channel_layouts);
606         if (ret)
607             return ret;
608     } else {
609         for (i = 1; i <= s->nb_hrir_inputs; i++) {
610             ret = ff_channel_layouts_ref(stereo_layout, &ctx->inputs[i]->outcfg.channel_layouts);
611             if (ret)
612                 return ret;
613         }
614     }
615
616     formats = ff_all_samplerates();
617     if (!formats)
618         return AVERROR(ENOMEM);
619     return ff_set_common_samplerates(ctx, formats);
620 }
621
622 static int config_input(AVFilterLink *inlink)
623 {
624     AVFilterContext *ctx = inlink->dst;
625     HeadphoneContext *s = ctx->priv;
626
627     if (s->nb_irs < inlink->channels) {
628         av_log(ctx, AV_LOG_ERROR, "Number of HRIRs must be >= %d.\n", inlink->channels);
629         return AVERROR(EINVAL);
630     }
631
632     s->lfe_channel = av_get_channel_layout_channel_index(inlink->channel_layout,
633                                                          AV_CH_LOW_FREQUENCY);
634     return 0;
635 }
636
637 static av_cold int init(AVFilterContext *ctx)
638 {
639     HeadphoneContext *s = ctx->priv;
640     int i, ret;
641
642     AVFilterPad pad = {
643         .name         = "in0",
644         .type         = AVMEDIA_TYPE_AUDIO,
645         .config_props = config_input,
646     };
647     if ((ret = ff_insert_inpad(ctx, 0, &pad)) < 0)
648         return ret;
649
650     if (!s->map) {
651         av_log(ctx, AV_LOG_ERROR, "Valid mapping must be set.\n");
652         return AVERROR(EINVAL);
653     }
654
655     parse_map(ctx);
656
657     for (i = 0; i < s->nb_hrir_inputs; i++) {
658         char *name = av_asprintf("hrir%d", i);
659         AVFilterPad pad = {
660             .name         = name,
661             .type         = AVMEDIA_TYPE_AUDIO,
662         };
663         if (!name)
664             return AVERROR(ENOMEM);
665         if ((ret = ff_insert_inpad(ctx, i + 1, &pad)) < 0) {
666             av_freep(&pad.name);
667             return ret;
668         }
669     }
670
671     if (s->type == TIME_DOMAIN) {
672         AVFloatDSPContext *fdsp = avpriv_float_dsp_alloc(0);
673         if (!fdsp)
674             return AVERROR(ENOMEM);
675         s->scalarproduct_float = fdsp->scalarproduct_float;
676         av_free(fdsp);
677     }
678
679     return 0;
680 }
681
682 static int config_output(AVFilterLink *outlink)
683 {
684     AVFilterContext *ctx = outlink->src;
685     HeadphoneContext *s = ctx->priv;
686     AVFilterLink *inlink = ctx->inputs[0];
687
688     if (s->hrir_fmt == HRIR_MULTI) {
689         AVFilterLink *hrir_link = ctx->inputs[1];
690
691         if (hrir_link->channels < inlink->channels * 2) {
692             av_log(ctx, AV_LOG_ERROR, "Number of channels in HRIR stream must be >= %d.\n", inlink->channels * 2);
693             return AVERROR(EINVAL);
694         }
695     }
696
697     s->gain_lfe = expf((s->gain - 3 * inlink->channels + s->lfe_gain) / 20 * M_LN10);
698
699     return 0;
700 }
701
702 static av_cold void uninit(AVFilterContext *ctx)
703 {
704     HeadphoneContext *s = ctx->priv;
705
706     av_fft_end(s->ifft[0]);
707     av_fft_end(s->ifft[1]);
708     av_fft_end(s->fft[0]);
709     av_fft_end(s->fft[1]);
710     av_freep(&s->data_ir[0]);
711     av_freep(&s->data_ir[1]);
712     av_freep(&s->ringbuffer[0]);
713     av_freep(&s->ringbuffer[1]);
714     av_freep(&s->temp_src[0]);
715     av_freep(&s->temp_src[1]);
716     av_freep(&s->temp_fft[0]);
717     av_freep(&s->temp_fft[1]);
718     av_freep(&s->temp_afft[0]);
719     av_freep(&s->temp_afft[1]);
720     av_freep(&s->data_hrtf[0]);
721     av_freep(&s->data_hrtf[1]);
722
723     for (unsigned i = 1; i < ctx->nb_inputs; i++)
724         av_freep(&ctx->input_pads[i].name);
725 }
726
727 #define OFFSET(x) offsetof(HeadphoneContext, x)
728 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
729
730 static const AVOption headphone_options[] = {
731     { "map",       "set channels convolution mappings",  OFFSET(map),      AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
732     { "gain",      "set gain in dB",                     OFFSET(gain),     AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
733     { "lfe",       "set lfe gain in dB",                 OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
734     { "type",      "set processing",                     OFFSET(type),     AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
735     { "time",      "time domain",                        0,                AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
736     { "freq",      "frequency domain",                   0,                AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
737     { "size",      "set frame size",                     OFFSET(size),     AV_OPT_TYPE_INT,    {.i64=1024},1024,96000, .flags = FLAGS },
738     { "hrir",      "set hrir format",                    OFFSET(hrir_fmt), AV_OPT_TYPE_INT,    {.i64=HRIR_STEREO}, 0, 1, .flags = FLAGS, "hrir" },
739     { "stereo",    "hrir files have exactly 2 channels", 0,                AV_OPT_TYPE_CONST,  {.i64=HRIR_STEREO}, 0, 0, .flags = FLAGS, "hrir" },
740     { "multich",   "single multichannel hrir file",      0,                AV_OPT_TYPE_CONST,  {.i64=HRIR_MULTI},  0, 0, .flags = FLAGS, "hrir" },
741     { NULL }
742 };
743
744 AVFILTER_DEFINE_CLASS(headphone);
745
746 static const AVFilterPad outputs[] = {
747     {
748         .name          = "default",
749         .type          = AVMEDIA_TYPE_AUDIO,
750         .config_props  = config_output,
751     },
752     { NULL }
753 };
754
755 AVFilter ff_af_headphone = {
756     .name          = "headphone",
757     .description   = NULL_IF_CONFIG_SMALL("Apply headphone binaural spatialization with HRTFs in additional streams."),
758     .priv_size     = sizeof(HeadphoneContext),
759     .priv_class    = &headphone_class,
760     .init          = init,
761     .uninit        = uninit,
762     .query_formats = query_formats,
763     .activate      = activate,
764     .inputs        = NULL,
765     .outputs       = outputs,
766     .flags         = AVFILTER_FLAG_SLICE_THREADS | AVFILTER_FLAG_DYNAMIC_INPUTS,
767 };