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