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