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