Browse code

avfilter: add native headphone spatialization filter

Signed-off-by: Paul B Mahol <onemda@gmail.com>

Paul B Mahol authored on 2017/06/08 04:23:14
Showing 6 changed files
... ...
@@ -19,6 +19,7 @@ version <next>:
19 19
 - surround audio filter
20 20
 - sofalizer filter switched to libmysofa
21 21
 - Gremlin Digital Video demuxer and decoder
22
+- headphone audio filter
22 23
 
23 24
 version 3.3:
24 25
 - CrystalHD decoder moved to new decode API
... ...
@@ -2789,6 +2789,49 @@ Samples where the target gain does not match between channels
2789 2789
 @end table
2790 2790
 @end table
2791 2791
 
2792
+@section headphone
2793
+
2794
+Apply head-related transfer functions (HRTFs) to create virtual
2795
+loudspeakers around the user for binaural listening via headphones.
2796
+The HRIRs are provided via additional streams, for each channel
2797
+one stereo input stream is needed.
2798
+
2799
+The filter accepts the following options:
2800
+
2801
+@table @option
2802
+@item map
2803
+Set mapping of input streams for convolution.
2804
+The argument is a '|'-separated list of channel names in order as they
2805
+are given as additional stream inputs for filter.
2806
+This also specify number of input streams. Number of input streams
2807
+must be not less than number of channels in first stream plus one.
2808
+
2809
+@item gain
2810
+Set gain applied to audio. Value is in dB. Default is 0.
2811
+
2812
+@item type
2813
+Set processing type. Can be @var{time} or @var{freq}. @var{time} is
2814
+processing audio in time domain which is slow.
2815
+@var{freq} is processing audio in frequency domain which is fast.
2816
+Default is @var{freq}.
2817
+
2818
+@item lfe
2819
+Set custom gain for LFE channels. Value is in dB. Default is 0.
2820
+@end table
2821
+
2822
+@subsection Examples
2823
+
2824
+@itemize
2825
+@item
2826
+Full example using wav files as coefficients with amovie filters for 7.1 downmix,
2827
+each amovie filter use stereo file with IR coefficients as input.
2828
+The files give coefficients for each position of virtual loudspeaker:
2829
+@example
2830
+ffmpeg -i input.wav -lavfi-complex "amovie=azi_270_ele_0_DFC.wav[sr],amovie=azi_90_ele_0_DFC.wav[sl],amovie=azi_225_ele_0_DFC.wav[br],amovie=azi_135_ele_0_DFC.wav[bl],amovie=azi_0_ele_0_DFC.wav,asplit[fc][lfe],amovie=azi_35_ele_0_DFC.wav[fl],amovie=azi_325_ele_0_DFC.wav[fr],[a:0][fl][fr][fc][lfe][bl][br][sl][sr]headphone=FL|FR|FC|LFE|BL|BR|SL|SR"
2831
+output.wav
2832
+@end example
2833
+@end itemize
2834
+
2792 2835
 @section highpass
2793 2836
 
2794 2837
 Apply a high-pass filter with 3dB point frequency.
... ...
@@ -92,6 +92,7 @@ OBJS-$(CONFIG_EXTRASTEREO_FILTER)            += af_extrastereo.o
92 92
 OBJS-$(CONFIG_FIREQUALIZER_FILTER)           += af_firequalizer.o
93 93
 OBJS-$(CONFIG_FLANGER_FILTER)                += af_flanger.o generate_wave_table.o
94 94
 OBJS-$(CONFIG_HDCD_FILTER)                   += af_hdcd.o
95
+OBJS-$(CONFIG_HEADPHONE_FILTER)              += af_headphone.o
95 96
 OBJS-$(CONFIG_HIGHPASS_FILTER)               += af_biquads.o
96 97
 OBJS-$(CONFIG_JOIN_FILTER)                   += af_join.o
97 98
 OBJS-$(CONFIG_LADSPA_FILTER)                 += af_ladspa.o
98 99
new file mode 100644
... ...
@@ -0,0 +1,811 @@
0
+/*
1
+ * Copyright (C) 2017 Paul B Mahol
2
+ * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include <math.h>
21
+
22
+#include "libavutil/audio_fifo.h"
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 "internal.h"
32
+#include "audio.h"
33
+
34
+#define TIME_DOMAIN      0
35
+#define FREQUENCY_DOMAIN 1
36
+
37
+typedef struct HeadphoneContext {
38
+    const AVClass *class;
39
+
40
+    char *map;
41
+    int type;
42
+
43
+    int lfe_channel;
44
+
45
+    int have_hrirs;
46
+    int eof_hrirs;
47
+    int64_t pts;
48
+
49
+    int ir_len;
50
+
51
+    int mapping[64];
52
+
53
+    int nb_inputs;
54
+
55
+    int nb_irs;
56
+
57
+    float gain;
58
+    float lfe_gain, gain_lfe;
59
+
60
+    float *ringbuffer[2];
61
+    int write[2];
62
+
63
+    int buffer_length;
64
+    int n_fft;
65
+    int size;
66
+
67
+    int *delay[2];
68
+    float *data_ir[2];
69
+    float *temp_src[2];
70
+    FFTComplex *temp_fft[2];
71
+
72
+    FFTContext *fft[2], *ifft[2];
73
+    FFTComplex *data_hrtf[2];
74
+
75
+    AVFloatDSPContext *fdsp;
76
+    struct headphone_inputs {
77
+        AVAudioFifo *fifo;
78
+        AVFrame     *frame;
79
+        int          ir_len;
80
+        int          delay_l;
81
+        int          delay_r;
82
+        int          eof;
83
+    } *in;
84
+} HeadphoneContext;
85
+
86
+static int parse_channel_name(HeadphoneContext *s, int x, char **arg, int *rchannel, char *buf)
87
+{
88
+    int len, i, channel_id = 0;
89
+    int64_t layout, layout0;
90
+
91
+    if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
92
+        layout0 = layout = av_get_channel_layout(buf);
93
+        if (layout == AV_CH_LOW_FREQUENCY)
94
+            s->lfe_channel = x;
95
+        for (i = 32; i > 0; i >>= 1) {
96
+            if (layout >= 1LL << i) {
97
+                channel_id += i;
98
+                layout >>= i;
99
+            }
100
+        }
101
+        if (channel_id >= 64 || layout0 != 1LL << channel_id)
102
+            return AVERROR(EINVAL);
103
+        *rchannel = channel_id;
104
+        *arg += len;
105
+        return 0;
106
+    }
107
+    return AVERROR(EINVAL);
108
+}
109
+
110
+static void parse_map(AVFilterContext *ctx)
111
+{
112
+    HeadphoneContext *s = ctx->priv;
113
+    char *arg, *tokenizer, *p, *args = av_strdup(s->map);
114
+    int i;
115
+
116
+    if (!args)
117
+        return;
118
+    p = args;
119
+
120
+    s->lfe_channel = -1;
121
+    s->nb_inputs = 1;
122
+
123
+    for (i = 0; i < 64; i++) {
124
+        s->mapping[i] = -1;
125
+    }
126
+
127
+    while ((arg = av_strtok(p, "|", &tokenizer))) {
128
+        int out_ch_id;
129
+        char buf[8];
130
+
131
+        p = NULL;
132
+        if (parse_channel_name(s, s->nb_inputs - 1, &arg, &out_ch_id, buf)) {
133
+            av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
134
+            continue;
135
+        }
136
+        s->mapping[s->nb_inputs - 1] = out_ch_id;
137
+        s->nb_inputs++;
138
+    }
139
+    s->nb_irs = s->nb_inputs - 1;
140
+
141
+    av_free(args);
142
+}
143
+
144
+typedef struct ThreadData {
145
+    AVFrame *in, *out;
146
+    int *write;
147
+    int **delay;
148
+    float **ir;
149
+    int *n_clippings;
150
+    float **ringbuffer;
151
+    float **temp_src;
152
+    FFTComplex **temp_fft;
153
+} ThreadData;
154
+
155
+static int headphone_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
156
+{
157
+    HeadphoneContext *s = ctx->priv;
158
+    ThreadData *td = arg;
159
+    AVFrame *in = td->in, *out = td->out;
160
+    int offset = jobnr;
161
+    int *write = &td->write[jobnr];
162
+    const int *const delay = td->delay[jobnr];
163
+    const float *const ir = td->ir[jobnr];
164
+    int *n_clippings = &td->n_clippings[jobnr];
165
+    float *ringbuffer = td->ringbuffer[jobnr];
166
+    float *temp_src = td->temp_src[jobnr];
167
+    const int ir_len = s->ir_len;
168
+    const float *src = (const float *)in->data[0];
169
+    float *dst = (float *)out->data[0];
170
+    const int in_channels = in->channels;
171
+    const int buffer_length = s->buffer_length;
172
+    const uint32_t modulo = (uint32_t)buffer_length - 1;
173
+    float *buffer[16];
174
+    int wr = *write;
175
+    int read;
176
+    int i, l;
177
+
178
+    dst += offset;
179
+    for (l = 0; l < in_channels; l++) {
180
+        buffer[l] = ringbuffer + l * buffer_length;
181
+    }
182
+
183
+    for (i = 0; i < in->nb_samples; i++) {
184
+        const float *temp_ir = ir;
185
+
186
+        *dst = 0;
187
+        for (l = 0; l < in_channels; l++) {
188
+            *(buffer[l] + wr) = src[l];
189
+        }
190
+
191
+        for (l = 0; l < in_channels; l++) {
192
+            const float *const bptr = buffer[l];
193
+
194
+            if (l == s->lfe_channel) {
195
+                *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
196
+                temp_ir += FFALIGN(ir_len, 16);
197
+                continue;
198
+            }
199
+
200
+            read = (wr - *(delay + l) - (ir_len - 1) + buffer_length) & modulo;
201
+
202
+            if (read + ir_len < buffer_length) {
203
+                memcpy(temp_src, bptr + read, ir_len * sizeof(*temp_src));
204
+            } else {
205
+                int len = FFMIN(ir_len - (read % ir_len), buffer_length - read);
206
+
207
+                memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
208
+                memcpy(temp_src + len, bptr, (ir_len - len) * sizeof(*temp_src));
209
+            }
210
+
211
+            dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, ir_len);
212
+            temp_ir += FFALIGN(ir_len, 16);
213
+        }
214
+
215
+        if (fabs(*dst) > 1)
216
+            *n_clippings += 1;
217
+
218
+        dst += 2;
219
+        src += in_channels;
220
+        wr   = (wr + 1) & modulo;
221
+    }
222
+
223
+    *write = wr;
224
+
225
+    return 0;
226
+}
227
+
228
+static int headphone_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
229
+{
230
+    HeadphoneContext *s = ctx->priv;
231
+    ThreadData *td = arg;
232
+    AVFrame *in = td->in, *out = td->out;
233
+    int offset = jobnr;
234
+    int *write = &td->write[jobnr];
235
+    FFTComplex *hrtf = s->data_hrtf[jobnr];
236
+    int *n_clippings = &td->n_clippings[jobnr];
237
+    float *ringbuffer = td->ringbuffer[jobnr];
238
+    const int ir_len = s->ir_len;
239
+    const float *src = (const float *)in->data[0];
240
+    float *dst = (float *)out->data[0];
241
+    const int in_channels = in->channels;
242
+    const int buffer_length = s->buffer_length;
243
+    const uint32_t modulo = (uint32_t)buffer_length - 1;
244
+    FFTComplex *fft_in = s->temp_fft[jobnr];
245
+    FFTContext *ifft = s->ifft[jobnr];
246
+    FFTContext *fft = s->fft[jobnr];
247
+    const int n_fft = s->n_fft;
248
+    const float fft_scale = 1.0f / s->n_fft;
249
+    FFTComplex *hrtf_offset;
250
+    int wr = *write;
251
+    int n_read;
252
+    int i, j;
253
+
254
+    dst += offset;
255
+
256
+    n_read = FFMIN(s->ir_len, in->nb_samples);
257
+    for (j = 0; j < n_read; j++) {
258
+        dst[2 * j]     = ringbuffer[wr];
259
+        ringbuffer[wr] = 0.0;
260
+        wr  = (wr + 1) & modulo;
261
+    }
262
+
263
+    for (j = n_read; j < in->nb_samples; j++) {
264
+        dst[2 * j] = 0;
265
+    }
266
+
267
+    for (i = 0; i < in_channels; i++) {
268
+        if (i == s->lfe_channel) {
269
+            for (j = 0; j < in->nb_samples; j++) {
270
+                dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
271
+            }
272
+            continue;
273
+        }
274
+
275
+        offset = i * n_fft;
276
+        hrtf_offset = hrtf + offset;
277
+
278
+        memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
279
+
280
+        for (j = 0; j < in->nb_samples; j++) {
281
+            fft_in[j].re = src[j * in_channels + i];
282
+        }
283
+
284
+        av_fft_permute(fft, fft_in);
285
+        av_fft_calc(fft, fft_in);
286
+        for (j = 0; j < n_fft; j++) {
287
+            const FFTComplex *hcomplex = hrtf_offset + j;
288
+            const float re = fft_in[j].re;
289
+            const float im = fft_in[j].im;
290
+
291
+            fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
292
+            fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
293
+        }
294
+
295
+        av_fft_permute(ifft, fft_in);
296
+        av_fft_calc(ifft, fft_in);
297
+
298
+        for (j = 0; j < in->nb_samples; j++) {
299
+            dst[2 * j] += fft_in[j].re * fft_scale;
300
+        }
301
+
302
+        for (j = 0; j < ir_len - 1; j++) {
303
+            int write_pos = (wr + j) & modulo;
304
+
305
+            *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
306
+        }
307
+    }
308
+
309
+    for (i = 0; i < out->nb_samples; i++) {
310
+        if (fabs(*dst) > 1) {
311
+            n_clippings[0]++;
312
+        }
313
+
314
+        dst += 2;
315
+    }
316
+
317
+    *write = wr;
318
+
319
+    return 0;
320
+}
321
+
322
+static int read_ir(AVFilterLink *inlink, AVFrame *frame)
323
+{
324
+    AVFilterContext *ctx = inlink->dst;
325
+    HeadphoneContext *s = ctx->priv;
326
+    int ir_len, max_ir_len, input_number;
327
+
328
+    for (input_number = 0; input_number < s->nb_inputs; input_number++)
329
+        if (inlink == ctx->inputs[input_number])
330
+            break;
331
+
332
+    av_audio_fifo_write(s->in[input_number].fifo, (void **)frame->extended_data,
333
+                        frame->nb_samples);
334
+    av_frame_free(&frame);
335
+
336
+    ir_len = av_audio_fifo_size(s->in[input_number].fifo);
337
+    max_ir_len = 4096;
338
+    if (ir_len > max_ir_len) {
339
+        av_log(ctx, AV_LOG_ERROR, "Too big length of IRs: %d > %d.\n", ir_len, max_ir_len);
340
+        return AVERROR(EINVAL);
341
+    }
342
+    s->in[input_number].ir_len = ir_len;
343
+    s->ir_len = FFMAX(ir_len, s->ir_len);
344
+
345
+    return 0;
346
+}
347
+
348
+static int headphone_frame(HeadphoneContext *s, AVFilterLink *outlink)
349
+{
350
+    AVFilterContext *ctx = outlink->src;
351
+    AVFrame *in = s->in[0].frame;
352
+    int n_clippings[2] = { 0 };
353
+    ThreadData td;
354
+    AVFrame *out;
355
+
356
+    av_audio_fifo_read(s->in[0].fifo, (void **)in->extended_data, s->size);
357
+
358
+    out = ff_get_audio_buffer(outlink, in->nb_samples);
359
+    if (!out) {
360
+        av_frame_free(&in);
361
+        return AVERROR(ENOMEM);
362
+    }
363
+    out->pts = s->pts;
364
+    if (s->pts != AV_NOPTS_VALUE)
365
+        s->pts += av_rescale_q(out->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
366
+
367
+    td.in = in; td.out = out; td.write = s->write;
368
+    td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
369
+    td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
370
+    td.temp_fft = s->temp_fft;
371
+
372
+    if (s->type == TIME_DOMAIN) {
373
+        ctx->internal->execute(ctx, headphone_convolute, &td, NULL, 2);
374
+    } else {
375
+        ctx->internal->execute(ctx, headphone_fast_convolute, &td, NULL, 2);
376
+    }
377
+    emms_c();
378
+
379
+    if (n_clippings[0] + n_clippings[1] > 0) {
380
+        av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
381
+               n_clippings[0] + n_clippings[1], out->nb_samples * 2);
382
+    }
383
+
384
+    return ff_filter_frame(outlink, out);
385
+}
386
+
387
+static int convert_coeffs(AVFilterContext *ctx, AVFilterLink *inlink)
388
+{
389
+    struct HeadphoneContext *s = ctx->priv;
390
+    const int ir_len = s->ir_len;
391
+    int nb_irs = s->nb_irs;
392
+    int nb_input_channels = ctx->inputs[0]->channels;
393
+    float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10);
394
+    FFTComplex *data_hrtf_l = NULL;
395
+    FFTComplex *data_hrtf_r = NULL;
396
+    FFTComplex *fft_in_l = NULL;
397
+    FFTComplex *fft_in_r = NULL;
398
+    float *data_ir_l = NULL;
399
+    float *data_ir_r = NULL;
400
+    int offset = 0;
401
+    int n_fft;
402
+    int i, j;
403
+
404
+    s->buffer_length = 1 << (32 - ff_clz(s->ir_len));
405
+    s->n_fft = n_fft = 1 << (32 - ff_clz(s->ir_len + inlink->sample_rate));
406
+
407
+    if (s->type == FREQUENCY_DOMAIN) {
408
+        fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
409
+        fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
410
+        if (!fft_in_l || !fft_in_r) {
411
+            return AVERROR(ENOMEM);
412
+        }
413
+
414
+        av_fft_end(s->fft[0]);
415
+        av_fft_end(s->fft[1]);
416
+        s->fft[0] = av_fft_init(log2(s->n_fft), 0);
417
+        s->fft[1] = av_fft_init(log2(s->n_fft), 0);
418
+        av_fft_end(s->ifft[0]);
419
+        av_fft_end(s->ifft[1]);
420
+        s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
421
+        s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
422
+
423
+        if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
424
+            av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
425
+            return AVERROR(ENOMEM);
426
+        }
427
+    }
428
+
429
+    s->data_ir[0] = av_calloc(FFALIGN(s->ir_len, 16), sizeof(float) * s->nb_irs);
430
+    s->data_ir[1] = av_calloc(FFALIGN(s->ir_len, 16), sizeof(float) * s->nb_irs);
431
+    s->delay[0] = av_malloc_array(s->nb_irs, sizeof(float));
432
+    s->delay[1] = av_malloc_array(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_malloc_array(s->n_fft, sizeof(FFTComplex));
441
+        s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
442
+        if (!s->temp_fft[0] || !s->temp_fft[1])
443
+            return AVERROR(ENOMEM);
444
+    }
445
+
446
+    if (!s->data_ir[0] || !s->data_ir[1] ||
447
+        !s->ringbuffer[0] || !s->ringbuffer[1])
448
+        return AVERROR(ENOMEM);
449
+
450
+    s->in[0].frame = ff_get_audio_buffer(ctx->inputs[0], s->size);
451
+    if (!s->in[0].frame)
452
+        return AVERROR(ENOMEM);
453
+    for (i = 0; i < s->nb_irs; i++) {
454
+        s->in[i + 1].frame = ff_get_audio_buffer(ctx->inputs[i + 1], s->ir_len);
455
+        if (!s->in[i + 1].frame)
456
+            return AVERROR(ENOMEM);
457
+    }
458
+
459
+    if (s->type == TIME_DOMAIN) {
460
+        s->temp_src[0] = av_calloc(FFALIGN(ir_len, 16), sizeof(float));
461
+        s->temp_src[1] = av_calloc(FFALIGN(ir_len, 16), sizeof(float));
462
+
463
+        data_ir_l = av_calloc(nb_irs * FFALIGN(ir_len, 16), sizeof(*data_ir_l));
464
+        data_ir_r = av_calloc(nb_irs * FFALIGN(ir_len, 16), sizeof(*data_ir_r));
465
+        if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
466
+            av_free(data_ir_l);
467
+            av_free(data_ir_r);
468
+            return AVERROR(ENOMEM);
469
+        }
470
+    } else {
471
+        data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * nb_irs);
472
+        data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * nb_irs);
473
+        if (!data_hrtf_r || !data_hrtf_l) {
474
+            av_free(data_hrtf_l);
475
+            av_free(data_hrtf_r);
476
+            return AVERROR(ENOMEM);
477
+        }
478
+    }
479
+
480
+    for (i = 0; i < s->nb_irs; i++) {
481
+        int len = s->in[i + 1].ir_len;
482
+        int delay_l = s->in[i + 1].delay_l;
483
+        int delay_r = s->in[i + 1].delay_r;
484
+        int idx = -1;
485
+        float *ptr;
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 = j;
494
+                break;
495
+            }
496
+        }
497
+        if (idx == -1)
498
+            continue;
499
+
500
+        av_audio_fifo_read(s->in[i + 1].fifo, (void **)s->in[i + 1].frame->extended_data, len);
501
+        ptr = (float *)s->in[i + 1].frame->extended_data[0];
502
+
503
+        if (s->type == TIME_DOMAIN) {
504
+            offset = idx * FFALIGN(len, 16);
505
+            for (j = 0; j < len; j++) {
506
+                data_ir_l[offset + j] = ptr[len * 2 - j * 2 - 2] * gain_lin;
507
+                data_ir_r[offset + j] = ptr[len * 2 - j * 2 - 1] * gain_lin;
508
+            }
509
+        } else {
510
+            memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
511
+            memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
512
+
513
+            offset = idx * n_fft;
514
+            for (j = 0; j < len; j++) {
515
+                fft_in_l[delay_l + j].re = ptr[j * 2    ] * gain_lin;
516
+                fft_in_r[delay_r + j].re = ptr[j * 2 + 1] * gain_lin;
517
+            }
518
+
519
+            av_fft_permute(s->fft[0], fft_in_l);
520
+            av_fft_calc(s->fft[0], fft_in_l);
521
+            memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
522
+            av_fft_permute(s->fft[0], fft_in_r);
523
+            av_fft_calc(s->fft[0], fft_in_r);
524
+            memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
525
+        }
526
+    }
527
+
528
+    if (s->type == TIME_DOMAIN) {
529
+        memcpy(s->data_ir[0], data_ir_l, sizeof(float) * nb_irs * FFALIGN(ir_len, 16));
530
+        memcpy(s->data_ir[1], data_ir_r, sizeof(float) * nb_irs * FFALIGN(ir_len, 16));
531
+
532
+        av_freep(&data_ir_l);
533
+        av_freep(&data_ir_r);
534
+    } else {
535
+        s->data_hrtf[0] = av_malloc_array(n_fft * s->nb_irs, sizeof(FFTComplex));
536
+        s->data_hrtf[1] = av_malloc_array(n_fft * s->nb_irs, sizeof(FFTComplex));
537
+        if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
538
+            av_freep(&data_hrtf_l);
539
+            av_freep(&data_hrtf_r);
540
+            av_freep(&fft_in_l);
541
+            av_freep(&fft_in_r);
542
+            return AVERROR(ENOMEM);
543
+        }
544
+
545
+        memcpy(s->data_hrtf[0], data_hrtf_l,
546
+            sizeof(FFTComplex) * nb_irs * n_fft);
547
+        memcpy(s->data_hrtf[1], data_hrtf_r,
548
+            sizeof(FFTComplex) * nb_irs * n_fft);
549
+
550
+        av_freep(&data_hrtf_l);
551
+        av_freep(&data_hrtf_r);
552
+
553
+        av_freep(&fft_in_l);
554
+        av_freep(&fft_in_r);
555
+    }
556
+
557
+    s->have_hrirs = 1;
558
+
559
+    return 0;
560
+}
561
+
562
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
563
+{
564
+    AVFilterContext *ctx = inlink->dst;
565
+    HeadphoneContext *s = ctx->priv;
566
+    AVFilterLink *outlink = ctx->outputs[0];
567
+    int ret = 0;
568
+
569
+    av_audio_fifo_write(s->in[0].fifo, (void **)in->extended_data,
570
+                        in->nb_samples);
571
+    if (s->pts == AV_NOPTS_VALUE)
572
+        s->pts = in->pts;
573
+
574
+    av_frame_free(&in);
575
+
576
+    if (!s->have_hrirs && s->eof_hrirs) {
577
+        ret = convert_coeffs(ctx, inlink);
578
+        if (ret < 0)
579
+            return ret;
580
+    }
581
+
582
+    if (s->have_hrirs) {
583
+        while (av_audio_fifo_size(s->in[0].fifo) >= s->size) {
584
+            ret = headphone_frame(s, outlink);
585
+            if (ret < 0)
586
+                break;
587
+        }
588
+    }
589
+    return ret;
590
+}
591
+
592
+static int query_formats(AVFilterContext *ctx)
593
+{
594
+    struct HeadphoneContext *s = ctx->priv;
595
+    AVFilterFormats *formats = NULL;
596
+    AVFilterChannelLayouts *layouts = NULL;
597
+    int ret, i;
598
+
599
+    ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
600
+    if (ret)
601
+        return ret;
602
+    ret = ff_set_common_formats(ctx, formats);
603
+    if (ret)
604
+        return ret;
605
+
606
+    layouts = ff_all_channel_layouts();
607
+    if (!layouts)
608
+        return AVERROR(ENOMEM);
609
+
610
+    ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
611
+    if (ret)
612
+        return ret;
613
+
614
+    layouts = NULL;
615
+    ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
616
+    if (ret)
617
+        return ret;
618
+
619
+    for (i = 1; i < s->nb_inputs; i++) {
620
+        ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts);
621
+        if (ret)
622
+            return ret;
623
+    }
624
+
625
+    ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
626
+    if (ret)
627
+        return ret;
628
+
629
+    formats = ff_all_samplerates();
630
+    if (!formats)
631
+        return AVERROR(ENOMEM);
632
+    return ff_set_common_samplerates(ctx, formats);
633
+}
634
+
635
+static int config_input(AVFilterLink *inlink)
636
+{
637
+    AVFilterContext *ctx = inlink->dst;
638
+    HeadphoneContext *s = ctx->priv;
639
+
640
+    if (s->type == FREQUENCY_DOMAIN) {
641
+        inlink->partial_buf_size =
642
+        inlink->min_samples =
643
+        inlink->max_samples = inlink->sample_rate;
644
+    }
645
+
646
+    if (s->nb_irs < inlink->channels) {
647
+        av_log(ctx, AV_LOG_ERROR, "Number of inputs must be >= %d.\n", inlink->channels + 1);
648
+        return AVERROR(EINVAL);
649
+    }
650
+
651
+    return 0;
652
+}
653
+
654
+static av_cold int init(AVFilterContext *ctx)
655
+{
656
+    HeadphoneContext *s = ctx->priv;
657
+    int i;
658
+
659
+    AVFilterPad pad = {
660
+        .name         = "in0",
661
+        .type         = AVMEDIA_TYPE_AUDIO,
662
+        .config_props = config_input,
663
+        .filter_frame = filter_frame,
664
+    };
665
+    ff_insert_inpad(ctx, 0, &pad);
666
+
667
+    if (!s->map) {
668
+        av_log(ctx, AV_LOG_ERROR, "Valid mapping must be set.\n");
669
+        return AVERROR(EINVAL);
670
+    }
671
+
672
+    parse_map(ctx);
673
+
674
+    s->in = av_calloc(s->nb_inputs, sizeof(*s->in));
675
+    if (!s->in)
676
+        return AVERROR(ENOMEM);
677
+
678
+    for (i = 1; i < s->nb_inputs; i++) {
679
+        char *name = av_asprintf("hrir%d", i - 1);
680
+        AVFilterPad pad = {
681
+            .name         = name,
682
+            .type         = AVMEDIA_TYPE_AUDIO,
683
+            .filter_frame = read_ir,
684
+        };
685
+        if (!name)
686
+            return AVERROR(ENOMEM);
687
+        ff_insert_inpad(ctx, i, &pad);
688
+    }
689
+
690
+    s->fdsp = avpriv_float_dsp_alloc(0);
691
+    if (!s->fdsp)
692
+        return AVERROR(ENOMEM);
693
+    s->pts = AV_NOPTS_VALUE;
694
+
695
+    return 0;
696
+}
697
+
698
+static int config_output(AVFilterLink *outlink)
699
+{
700
+    AVFilterContext *ctx = outlink->src;
701
+    HeadphoneContext *s = ctx->priv;
702
+    AVFilterLink *inlink = ctx->inputs[0];
703
+    int i;
704
+
705
+    if (s->type == TIME_DOMAIN)
706
+        s->size = 1024;
707
+    else
708
+        s->size = inlink->sample_rate;
709
+
710
+    for (i = 0; i < s->nb_inputs; i++) {
711
+        s->in[i].fifo = av_audio_fifo_alloc(ctx->inputs[i]->format, ctx->inputs[i]->channels, 1024);
712
+        if (!s->in[i].fifo)
713
+            return AVERROR(ENOMEM);
714
+    }
715
+    s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
716
+
717
+    return 0;
718
+}
719
+
720
+static int request_frame(AVFilterLink *outlink)
721
+{
722
+    AVFilterContext *ctx = outlink->src;
723
+    HeadphoneContext *s = ctx->priv;
724
+    int i, ret;
725
+
726
+    for (i = 1; !s->eof_hrirs && i < s->nb_inputs; i++) {
727
+        if (!s->in[i].eof) {
728
+            ret = ff_request_frame(ctx->inputs[i]);
729
+            if (ret == AVERROR_EOF) {
730
+                s->in[i].eof = 1;
731
+                ret = 0;
732
+            }
733
+            return ret;
734
+        } else {
735
+            if (i == s->nb_inputs - 1)
736
+                s->eof_hrirs = 1;
737
+        }
738
+    }
739
+    return ff_request_frame(ctx->inputs[0]);
740
+}
741
+
742
+static av_cold void uninit(AVFilterContext *ctx)
743
+{
744
+    HeadphoneContext *s = ctx->priv;
745
+    int i;
746
+
747
+    av_fft_end(s->ifft[0]);
748
+    av_fft_end(s->ifft[1]);
749
+    av_fft_end(s->fft[0]);
750
+    av_fft_end(s->fft[1]);
751
+    av_freep(&s->delay[0]);
752
+    av_freep(&s->delay[1]);
753
+    av_freep(&s->data_ir[0]);
754
+    av_freep(&s->data_ir[1]);
755
+    av_freep(&s->ringbuffer[0]);
756
+    av_freep(&s->ringbuffer[1]);
757
+    av_freep(&s->temp_src[0]);
758
+    av_freep(&s->temp_src[1]);
759
+    av_freep(&s->temp_fft[0]);
760
+    av_freep(&s->temp_fft[1]);
761
+    av_freep(&s->data_hrtf[0]);
762
+    av_freep(&s->data_hrtf[1]);
763
+    av_freep(&s->fdsp);
764
+
765
+    for (i = 0; i < s->nb_inputs; i++) {
766
+        av_frame_free(&s->in[i].frame);
767
+        av_audio_fifo_free(s->in[i].fifo);
768
+        if (ctx->input_pads && i)
769
+            av_freep(&ctx->input_pads[i].name);
770
+    }
771
+    av_freep(&s->in);
772
+}
773
+
774
+#define OFFSET(x) offsetof(HeadphoneContext, x)
775
+#define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
776
+
777
+static const AVOption headphone_options[] = {
778
+    { "map",       "set channels convolution mappings",  OFFSET(map),      AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
779
+    { "gain",      "set gain in dB",                     OFFSET(gain),     AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
780
+    { "lfe",       "set lfe gain in dB",                 OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
781
+    { "type",      "set processing",                     OFFSET(type),     AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
782
+    { "time",      "time domain",                        0,                AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
783
+    { "freq",      "frequency domain",                   0,                AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
784
+    { NULL }
785
+};
786
+
787
+AVFILTER_DEFINE_CLASS(headphone);
788
+
789
+static const AVFilterPad outputs[] = {
790
+    {
791
+        .name          = "default",
792
+        .type          = AVMEDIA_TYPE_AUDIO,
793
+        .config_props  = config_output,
794
+        .request_frame = request_frame,
795
+    },
796
+    { NULL }
797
+};
798
+
799
+AVFilter ff_af_headphone = {
800
+    .name          = "headphone",
801
+    .description   = NULL_IF_CONFIG_SMALL("Apply headphone binaural spatialization with HRTFs in additional streams."),
802
+    .priv_size     = sizeof(HeadphoneContext),
803
+    .priv_class    = &headphone_class,
804
+    .init          = init,
805
+    .uninit        = uninit,
806
+    .query_formats = query_formats,
807
+    .inputs        = NULL,
808
+    .outputs       = outputs,
809
+    .flags         = AVFILTER_FLAG_SLICE_THREADS | AVFILTER_FLAG_DYNAMIC_INPUTS,
810
+};
... ...
@@ -105,6 +105,7 @@ static void register_all(void)
105 105
     REGISTER_FILTER(FIREQUALIZER,   firequalizer,   af);
106 106
     REGISTER_FILTER(FLANGER,        flanger,        af);
107 107
     REGISTER_FILTER(HDCD,           hdcd,           af);
108
+    REGISTER_FILTER(HEADPHONE,      headphone,      af);
108 109
     REGISTER_FILTER(HIGHPASS,       highpass,       af);
109 110
     REGISTER_FILTER(JOIN,           join,           af);
110 111
     REGISTER_FILTER(LADSPA,         ladspa,         af);
... ...
@@ -30,7 +30,7 @@
30 30
 #include "libavutil/version.h"
31 31
 
32 32
 #define LIBAVFILTER_VERSION_MAJOR   6
33
-#define LIBAVFILTER_VERSION_MINOR  91
33
+#define LIBAVFILTER_VERSION_MINOR  92
34 34
 #define LIBAVFILTER_VERSION_MICRO 100
35 35
 
36 36
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \