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