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