]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_sofalizer.c
avfilter/af_sofalizer: speed up fast convolution
[ffmpeg] / libavfilter / af_sofalizer.c
1 /*****************************************************************************
2  * sofalizer.c : SOFAlizer filter for virtual binaural acoustics
3  *****************************************************************************
4  * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda,
5  *                         Acoustics Research Institute (ARI), Vienna, Austria
6  *
7  * Authors: Andreas Fuchs <andi.fuchs.mail@gmail.com>
8  *          Wolfgang Hrauda <wolfgang.hrauda@gmx.at>
9  *
10  * SOFAlizer project coordinator at ARI, main developer of SOFA:
11  *          Piotr Majdak <piotr@majdak.at>
12  *
13  * This program is free software; you can redistribute it and/or modify it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #include <math.h>
29 #include <mysofa.h>
30
31 #include "libavcodec/avfft.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/float_dsp.h"
35 #include "libavutil/intmath.h"
36 #include "libavutil/opt.h"
37 #include "avfilter.h"
38 #include "internal.h"
39 #include "audio.h"
40
41 #define TIME_DOMAIN      0
42 #define FREQUENCY_DOMAIN 1
43
44 typedef struct MySofa {  /* contains data of one SOFA file */
45     struct MYSOFA_HRTF *hrtf;
46     struct MYSOFA_LOOKUP *lookup;
47     struct MYSOFA_NEIGHBORHOOD *neighborhood;
48     int ir_samples;      /* length of one impulse response (IR) */
49     int n_samples;       /* ir_samples to next power of 2 */
50     float *lir, *rir;    /* IRs (time-domain) */
51     float *fir;
52     int max_delay;
53 } MySofa;
54
55 typedef struct VirtualSpeaker {
56     uint8_t set;
57     float azim;
58     float elev;
59 } VirtualSpeaker;
60
61 typedef struct SOFAlizerContext {
62     const AVClass *class;
63
64     char *filename;             /* name of SOFA file */
65     MySofa sofa;                /* contains data of the SOFA file */
66
67     int sample_rate;            /* sample rate from SOFA file */
68     float *speaker_azim;        /* azimuth of the virtual loudspeakers */
69     float *speaker_elev;        /* elevation of the virtual loudspeakers */
70     char *speakers_pos;         /* custom positions of the virtual loudspeakers */
71     float lfe_gain;             /* initial gain for the LFE channel */
72     float gain_lfe;             /* gain applied to LFE channel */
73     int lfe_channel;            /* LFE channel position in channel layout */
74
75     int n_conv;                 /* number of channels to convolute */
76
77                                 /* buffer variables (for convolution) */
78     float *ringbuffer[2];       /* buffers input samples, length of one buffer: */
79                                 /* no. input ch. (incl. LFE) x buffer_length */
80     int write[2];               /* current write position to ringbuffer */
81     int buffer_length;          /* is: longest IR plus max. delay in all SOFA files */
82                                 /* then choose next power of 2 */
83     int n_fft;                  /* number of samples in one FFT block */
84
85                                 /* netCDF variables */
86     int *delay[2];              /* broadband delay for each channel/IR to be convolved */
87
88     float *data_ir[2];          /* IRs for all channels to be convolved */
89                                 /* (this excludes the LFE) */
90     float *temp_src[2];
91     FFTComplex *temp_fft[2];    /* Array to hold FFT values */
92     FFTComplex *temp_afft[2];   /* Array to accumulate FFT values prior to IFFT */
93
94                          /* control variables */
95     float gain;          /* filter gain (in dB) */
96     float rotation;      /* rotation of virtual loudspeakers (in degrees)  */
97     float elevation;     /* elevation of virtual loudspeakers (in deg.) */
98     float radius;        /* distance virtual loudspeakers to listener (in metres) */
99     int type;            /* processing type */
100     int framesize;       /* size of buffer */
101     int normalize;       /* should all IRs be normalized upon import ? */
102     int interpolate;     /* should wanted IRs be interpolated from neighbors ? */
103     int minphase;        /* should all IRs be minphased upon import ? */
104     float anglestep;     /* neighbor search angle step, in agles */
105     float radstep;       /* neighbor search radius step, in meters */
106
107     VirtualSpeaker vspkrpos[64];
108
109     FFTContext *fft[2], *ifft[2];
110     FFTComplex *data_hrtf[2];
111
112     AVFloatDSPContext *fdsp;
113 } SOFAlizerContext;
114
115 static int close_sofa(struct MySofa *sofa)
116 {
117     if (sofa->neighborhood)
118         mysofa_neighborhood_free(sofa->neighborhood);
119     sofa->neighborhood = NULL;
120     if (sofa->lookup)
121         mysofa_lookup_free(sofa->lookup);
122     sofa->lookup = NULL;
123     if (sofa->hrtf)
124         mysofa_free(sofa->hrtf);
125     sofa->hrtf = NULL;
126     av_freep(&sofa->fir);
127
128     return 0;
129 }
130
131 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
132 {
133     struct SOFAlizerContext *s = ctx->priv;
134     struct MYSOFA_HRTF *mysofa;
135     char *license;
136     int ret;
137
138     mysofa = mysofa_load(filename, &ret);
139     s->sofa.hrtf = mysofa;
140     if (ret || !mysofa) {
141         av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
142         return AVERROR(EINVAL);
143     }
144
145     ret = mysofa_check(mysofa);
146     if (ret != MYSOFA_OK) {
147         av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
148         return ret;
149     }
150
151     if (s->normalize)
152         mysofa_loudness(s->sofa.hrtf);
153
154     if (s->minphase)
155         mysofa_minphase(s->sofa.hrtf, 0.01);
156
157     mysofa_tocartesian(s->sofa.hrtf);
158
159     s->sofa.lookup = mysofa_lookup_init(s->sofa.hrtf);
160     if (s->sofa.lookup == NULL)
161         return AVERROR(EINVAL);
162
163     if (s->interpolate)
164         s->sofa.neighborhood = mysofa_neighborhood_init_withstepdefine(s->sofa.hrtf,
165                                                                        s->sofa.lookup,
166                                                                        s->anglestep,
167                                                                        s->radstep);
168
169     s->sofa.fir = av_calloc(s->sofa.hrtf->N * s->sofa.hrtf->R, sizeof(*s->sofa.fir));
170     if (!s->sofa.fir)
171         return AVERROR(ENOMEM);
172
173     if (mysofa->DataSamplingRate.elements != 1)
174         return AVERROR(EINVAL);
175     av_log(ctx, AV_LOG_DEBUG, "Original IR length: %d.\n", mysofa->N);
176     *samplingrate = mysofa->DataSamplingRate.values[0];
177     license = mysofa_getAttribute(mysofa->attributes, (char *)"License");
178     if (license)
179         av_log(ctx, AV_LOG_INFO, "SOFA license: %s\n", license);
180
181     return 0;
182 }
183
184 static int parse_channel_name(char **arg, int *rchannel, char *buf)
185 {
186     int len, i, channel_id = 0;
187     int64_t layout, layout0;
188
189     /* try to parse a channel name, e.g. "FL" */
190     if (av_sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
191         layout0 = layout = av_get_channel_layout(buf);
192         /* channel_id <- first set bit in layout */
193         for (i = 32; i > 0; i >>= 1) {
194             if (layout >= 1LL << i) {
195                 channel_id += i;
196                 layout >>= i;
197             }
198         }
199         /* reject layouts that are not a single channel */
200         if (channel_id >= 64 || layout0 != 1LL << channel_id)
201             return AVERROR(EINVAL);
202         *rchannel = channel_id;
203         *arg += len;
204         return 0;
205     }
206     return AVERROR(EINVAL);
207 }
208
209 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
210 {
211     SOFAlizerContext *s = ctx->priv;
212     char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
213
214     if (!args)
215         return;
216     p = args;
217
218     while ((arg = av_strtok(p, "|", &tokenizer))) {
219         char buf[8];
220         float azim, elev;
221         int out_ch_id;
222
223         p = NULL;
224         if (parse_channel_name(&arg, &out_ch_id, buf)) {
225             av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
226             continue;
227         }
228         if (av_sscanf(arg, "%f %f", &azim, &elev) == 2) {
229             s->vspkrpos[out_ch_id].set = 1;
230             s->vspkrpos[out_ch_id].azim = azim;
231             s->vspkrpos[out_ch_id].elev = elev;
232         } else if (av_sscanf(arg, "%f", &azim) == 1) {
233             s->vspkrpos[out_ch_id].set = 1;
234             s->vspkrpos[out_ch_id].azim = azim;
235             s->vspkrpos[out_ch_id].elev = 0;
236         }
237     }
238
239     av_free(args);
240 }
241
242 static int get_speaker_pos(AVFilterContext *ctx,
243                            float *speaker_azim, float *speaker_elev)
244 {
245     struct SOFAlizerContext *s = ctx->priv;
246     uint64_t channels_layout = ctx->inputs[0]->channel_layout;
247     float azim[16] = { 0 };
248     float elev[16] = { 0 };
249     int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
250
251     if (n_conv > 16)
252         return AVERROR(EINVAL);
253
254     s->lfe_channel = -1;
255
256     if (s->speakers_pos)
257         parse_speaker_pos(ctx, channels_layout);
258
259     /* set speaker positions according to input channel configuration: */
260     for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
261         uint64_t mask = channels_layout & (1ULL << m);
262
263         switch (mask) {
264         case AV_CH_FRONT_LEFT:            azim[ch] =  30;      break;
265         case AV_CH_FRONT_RIGHT:           azim[ch] = 330;      break;
266         case AV_CH_FRONT_CENTER:          azim[ch] =   0;      break;
267         case AV_CH_LOW_FREQUENCY:
268         case AV_CH_LOW_FREQUENCY_2:       s->lfe_channel = ch; break;
269         case AV_CH_BACK_LEFT:             azim[ch] = 150;      break;
270         case AV_CH_BACK_RIGHT:            azim[ch] = 210;      break;
271         case AV_CH_BACK_CENTER:           azim[ch] = 180;      break;
272         case AV_CH_SIDE_LEFT:             azim[ch] =  90;      break;
273         case AV_CH_SIDE_RIGHT:            azim[ch] = 270;      break;
274         case AV_CH_FRONT_LEFT_OF_CENTER:  azim[ch] =  15;      break;
275         case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345;      break;
276         case AV_CH_TOP_CENTER:            azim[ch] =   0;
277                                           elev[ch] =  90;      break;
278         case AV_CH_TOP_FRONT_LEFT:        azim[ch] =  30;
279                                           elev[ch] =  45;      break;
280         case AV_CH_TOP_FRONT_CENTER:      azim[ch] =   0;
281                                           elev[ch] =  45;      break;
282         case AV_CH_TOP_FRONT_RIGHT:       azim[ch] = 330;
283                                           elev[ch] =  45;      break;
284         case AV_CH_TOP_BACK_LEFT:         azim[ch] = 150;
285                                           elev[ch] =  45;      break;
286         case AV_CH_TOP_BACK_RIGHT:        azim[ch] = 210;
287                                           elev[ch] =  45;      break;
288         case AV_CH_TOP_BACK_CENTER:       azim[ch] = 180;
289                                           elev[ch] =  45;      break;
290         case AV_CH_WIDE_LEFT:             azim[ch] =  90;      break;
291         case AV_CH_WIDE_RIGHT:            azim[ch] = 270;      break;
292         case AV_CH_SURROUND_DIRECT_LEFT:  azim[ch] =  90;      break;
293         case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270;      break;
294         case AV_CH_STEREO_LEFT:           azim[ch] =  90;      break;
295         case AV_CH_STEREO_RIGHT:          azim[ch] = 270;      break;
296         case 0:                                                break;
297         default:
298             return AVERROR(EINVAL);
299         }
300
301         if (s->vspkrpos[m].set) {
302             azim[ch] = s->vspkrpos[m].azim;
303             elev[ch] = s->vspkrpos[m].elev;
304         }
305
306         if (mask)
307             ch++;
308     }
309
310     memcpy(speaker_azim, azim, n_conv * sizeof(float));
311     memcpy(speaker_elev, elev, n_conv * sizeof(float));
312
313     return 0;
314
315 }
316
317 typedef struct ThreadData {
318     AVFrame *in, *out;
319     int *write;
320     int **delay;
321     float **ir;
322     int *n_clippings;
323     float **ringbuffer;
324     float **temp_src;
325     FFTComplex **temp_fft;
326     FFTComplex **temp_afft;
327 } ThreadData;
328
329 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
330 {
331     SOFAlizerContext *s = ctx->priv;
332     ThreadData *td = arg;
333     AVFrame *in = td->in, *out = td->out;
334     int offset = jobnr;
335     int *write = &td->write[jobnr];
336     const int *const delay = td->delay[jobnr];
337     const float *const ir = td->ir[jobnr];
338     int *n_clippings = &td->n_clippings[jobnr];
339     float *ringbuffer = td->ringbuffer[jobnr];
340     float *temp_src = td->temp_src[jobnr];
341     const int ir_samples = s->sofa.ir_samples; /* length of one IR */
342     const int n_samples = s->sofa.n_samples;
343     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
344     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
345     const int in_channels = s->n_conv; /* number of input channels */
346     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
347     const int buffer_length = s->buffer_length;
348     /* -1 for AND instead of MODULO (applied to powers of 2): */
349     const uint32_t modulo = (uint32_t)buffer_length - 1;
350     float *buffer[16]; /* holds ringbuffer for each input channel */
351     int wr = *write;
352     int read;
353     int i, l;
354
355     dst += offset;
356     for (l = 0; l < in_channels; l++) {
357         /* get starting address of ringbuffer for each input channel */
358         buffer[l] = ringbuffer + l * buffer_length;
359     }
360
361     for (i = 0; i < in->nb_samples; i++) {
362         const float *temp_ir = ir; /* using same set of IRs for each sample */
363
364         dst[0] = 0;
365         for (l = 0; l < in_channels; l++) {
366             /* write current input sample to ringbuffer (for each channel) */
367             buffer[l][wr] = src[l];
368         }
369
370         /* loop goes through all channels to be convolved */
371         for (l = 0; l < in_channels; l++) {
372             const float *const bptr = buffer[l];
373
374             if (l == s->lfe_channel) {
375                 /* LFE is an input channel but requires no convolution */
376                 /* apply gain to LFE signal and add to output buffer */
377                 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
378                 temp_ir += n_samples;
379                 continue;
380             }
381
382             /* current read position in ringbuffer: input sample write position
383              * - delay for l-th ch. + diff. betw. IR length and buffer length
384              * (mod buffer length) */
385             read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
386
387             if (read + n_samples < buffer_length) {
388                 memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
389             } else {
390                 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
391
392                 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
393                 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
394             }
395
396             /* multiply signal and IR, and add up the results */
397             dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, FFALIGN(ir_samples, 32));
398             temp_ir += n_samples;
399         }
400
401         /* clippings counter */
402         if (fabsf(dst[0]) > 1)
403             n_clippings[0]++;
404
405         /* move output buffer pointer by +2 to get to next sample of processed channel: */
406         dst += 2;
407         src += in_channels;
408         wr   = (wr + 1) & modulo; /* update ringbuffer write position */
409     }
410
411     *write = wr; /* remember write position in ringbuffer for next call */
412
413     return 0;
414 }
415
416 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
417 {
418     SOFAlizerContext *s = ctx->priv;
419     ThreadData *td = arg;
420     AVFrame *in = td->in, *out = td->out;
421     int offset = jobnr;
422     int *write = &td->write[jobnr];
423     FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
424     int *n_clippings = &td->n_clippings[jobnr];
425     float *ringbuffer = td->ringbuffer[jobnr];
426     const int n_samples = s->sofa.n_samples; /* length of one IR */
427     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
428     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
429     const int in_channels = s->n_conv; /* number of input channels */
430     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
431     const int buffer_length = s->buffer_length;
432     /* -1 for AND instead of MODULO (applied to powers of 2): */
433     const uint32_t modulo = (uint32_t)buffer_length - 1;
434     FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
435     FFTComplex *fft_acc = s->temp_afft[jobnr];
436     FFTContext *ifft = s->ifft[jobnr];
437     FFTContext *fft = s->fft[jobnr];
438     const int n_conv = s->n_conv;
439     const int n_fft = s->n_fft;
440     const float fft_scale = 1.0f / s->n_fft;
441     FFTComplex *hrtf_offset;
442     int wr = *write;
443     int n_read;
444     int i, j;
445
446     dst += offset;
447
448     /* find minimum between number of samples and output buffer length:
449      * (important, if one IR is longer than the output buffer) */
450     n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
451     for (j = 0; j < n_read; j++) {
452         /* initialize output buf with saved signal from overflow buf */
453         dst[2 * j]     = ringbuffer[wr];
454         ringbuffer[wr] = 0.0; /* re-set read samples to zero */
455         /* update ringbuffer read/write position */
456         wr  = (wr + 1) & modulo;
457     }
458
459     /* initialize rest of output buffer with 0 */
460     for (j = n_read; j < in->nb_samples; j++) {
461         dst[2 * j] = 0;
462     }
463
464     /* fill FFT accumulation with 0 */
465     memset(fft_acc, 0, sizeof(FFTComplex) * n_fft);
466
467     for (i = 0; i < n_conv; i++) {
468         if (i == s->lfe_channel) { /* LFE */
469             for (j = 0; j < in->nb_samples; j++) {
470                 /* apply gain to LFE signal and add to output buffer */
471                 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
472             }
473             continue;
474         }
475
476         /* outer loop: go through all input channels to be convolved */
477         offset = i * n_fft; /* no. samples already processed */
478         hrtf_offset = hrtf + offset;
479
480         /* fill FFT input with 0 (we want to zero-pad) */
481         memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
482
483         for (j = 0; j < in->nb_samples; j++) {
484             /* prepare input for FFT */
485             /* write all samples of current input channel to FFT input array */
486             fft_in[j].re = src[j * in_channels + i];
487         }
488
489         /* transform input signal of current channel to frequency domain */
490         av_fft_permute(fft, fft_in);
491         av_fft_calc(fft, fft_in);
492         for (j = 0; j < n_fft; j++) {
493             const FFTComplex *hcomplex = hrtf_offset + j;
494             const float re = fft_in[j].re;
495             const float im = fft_in[j].im;
496
497             /* complex multiplication of input signal and HRTFs */
498             /* output channel (real): */
499             fft_acc[j].re += re * hcomplex->re - im * hcomplex->im;
500             /* output channel (imag): */
501             fft_acc[j].im += re * hcomplex->im + im * hcomplex->re;
502         }
503     }
504
505     /* transform output signal of current channel back to time domain */
506     av_fft_permute(ifft, fft_acc);
507     av_fft_calc(ifft, fft_acc);
508
509     for (j = 0; j < in->nb_samples; j++) {
510         /* write output signal of current channel to output buffer */
511         dst[2 * j] += fft_acc[j].re * fft_scale;
512     }
513
514     for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
515         /* write the rest of output signal to overflow buffer */
516         int write_pos = (wr + j) & modulo;
517
518         *(ringbuffer + write_pos) += fft_acc[in->nb_samples + j].re * fft_scale;
519     }
520
521     /* go through all samples of current output buffer: count clippings */
522     for (i = 0; i < out->nb_samples; i++) {
523         /* clippings counter */
524         if (fabsf(dst[0]) > 1) { /* if current output sample > 1 */
525             n_clippings[0]++;
526         }
527
528         /* move output buffer pointer by +2 to get to next sample of processed channel: */
529         dst += 2;
530     }
531
532     /* remember read/write position in ringbuffer for next call */
533     *write = wr;
534
535     return 0;
536 }
537
538 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
539 {
540     AVFilterContext *ctx = inlink->dst;
541     SOFAlizerContext *s = ctx->priv;
542     AVFilterLink *outlink = ctx->outputs[0];
543     int n_clippings[2] = { 0 };
544     ThreadData td;
545     AVFrame *out;
546
547     out = ff_get_audio_buffer(outlink, in->nb_samples);
548     if (!out) {
549         av_frame_free(&in);
550         return AVERROR(ENOMEM);
551     }
552     av_frame_copy_props(out, in);
553
554     td.in = in; td.out = out; td.write = s->write;
555     td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
556     td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
557     td.temp_fft = s->temp_fft;
558     td.temp_afft = s->temp_afft;
559
560     if (s->type == TIME_DOMAIN) {
561         ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
562     } else {
563         ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
564     }
565     emms_c();
566
567     /* display error message if clipping occurred */
568     if (n_clippings[0] + n_clippings[1] > 0) {
569         av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
570                n_clippings[0] + n_clippings[1], out->nb_samples * 2);
571     }
572
573     av_frame_free(&in);
574     return ff_filter_frame(outlink, out);
575 }
576
577 static int query_formats(AVFilterContext *ctx)
578 {
579     struct SOFAlizerContext *s = ctx->priv;
580     AVFilterFormats *formats = NULL;
581     AVFilterChannelLayouts *layouts = NULL;
582     int ret, sample_rates[] = { 48000, -1 };
583
584     ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
585     if (ret)
586         return ret;
587     ret = ff_set_common_formats(ctx, formats);
588     if (ret)
589         return ret;
590
591     layouts = ff_all_channel_layouts();
592     if (!layouts)
593         return AVERROR(ENOMEM);
594
595     ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
596     if (ret)
597         return ret;
598
599     layouts = NULL;
600     ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
601     if (ret)
602         return ret;
603
604     ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
605     if (ret)
606         return ret;
607
608     sample_rates[0] = s->sample_rate;
609     formats = ff_make_format_list(sample_rates);
610     if (!formats)
611         return AVERROR(ENOMEM);
612     return ff_set_common_samplerates(ctx, formats);
613 }
614
615 static int getfilter_float(AVFilterContext *ctx, float x, float y, float z,
616                            float *left, float *right,
617                            float *delay_left, float *delay_right)
618 {
619     struct SOFAlizerContext *s = ctx->priv;
620     float c[3], delays[2];
621     float *fl, *fr;
622     int nearest;
623     int *neighbors;
624     float *res;
625
626     c[0] = x, c[1] = y, c[2] = z;
627     nearest = mysofa_lookup(s->sofa.lookup, c);
628     if (nearest < 0)
629         return AVERROR(EINVAL);
630
631     if (s->interpolate) {
632         neighbors = mysofa_neighborhood(s->sofa.neighborhood, nearest);
633         res = mysofa_interpolate(s->sofa.hrtf, c,
634                                  nearest, neighbors,
635                                  s->sofa.fir, delays);
636     } else {
637         if (s->sofa.hrtf->DataDelay.elements > s->sofa.hrtf->R) {
638             delays[0] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R];
639             delays[1] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R + 1];
640         } else {
641             delays[0] = s->sofa.hrtf->DataDelay.values[0];
642             delays[1] = s->sofa.hrtf->DataDelay.values[1];
643         }
644         res = s->sofa.hrtf->DataIR.values + nearest * s->sofa.hrtf->N * s->sofa.hrtf->R;
645     }
646
647     *delay_left  = delays[0];
648     *delay_right = delays[1];
649
650     fl = res;
651     fr = res + s->sofa.hrtf->N;
652
653     memcpy(left, fl, sizeof(float) * s->sofa.hrtf->N);
654     memcpy(right, fr, sizeof(float) * s->sofa.hrtf->N);
655
656     return 0;
657 }
658
659 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
660 {
661     struct SOFAlizerContext *s = ctx->priv;
662     int n_samples;
663     int ir_samples;
664     int n_conv = s->n_conv; /* no. channels to convolve */
665     int n_fft;
666     float delay_l; /* broadband delay for each IR */
667     float delay_r;
668     int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
669     float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
670     FFTComplex *data_hrtf_l = NULL;
671     FFTComplex *data_hrtf_r = NULL;
672     FFTComplex *fft_in_l = NULL;
673     FFTComplex *fft_in_r = NULL;
674     float *data_ir_l = NULL;
675     float *data_ir_r = NULL;
676     int offset = 0; /* used for faster pointer arithmetics in for-loop */
677     int i, j, azim_orig = azim, elev_orig = elev;
678     int ret = 0;
679     int n_current;
680     int n_max = 0;
681
682     av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.hrtf->N);
683     s->sofa.ir_samples = s->sofa.hrtf->N;
684     s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
685
686     n_samples = s->sofa.n_samples;
687     ir_samples = s->sofa.ir_samples;
688
689     s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
690     s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
691     s->delay[0] = av_calloc(s->n_conv, sizeof(int));
692     s->delay[1] = av_calloc(s->n_conv, sizeof(int));
693
694     if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
695         ret = AVERROR(ENOMEM);
696         goto fail;
697     }
698
699     /* get temporary IR for L and R channel */
700     data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
701     data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
702     if (!data_ir_r || !data_ir_l) {
703         ret = AVERROR(ENOMEM);
704         goto fail;
705     }
706
707     if (s->type == TIME_DOMAIN) {
708         s->temp_src[0] = av_calloc(n_samples, sizeof(float));
709         s->temp_src[1] = av_calloc(n_samples, sizeof(float));
710         if (!s->temp_src[0] || !s->temp_src[1]) {
711             ret = AVERROR(ENOMEM);
712             goto fail;
713         }
714     }
715
716     s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
717     s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
718     if (!s->speaker_azim || !s->speaker_elev) {
719         ret = AVERROR(ENOMEM);
720         goto fail;
721     }
722
723     /* get speaker positions */
724     if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
725         av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
726         goto fail;
727     }
728
729     for (i = 0; i < s->n_conv; i++) {
730         float coordinates[3];
731
732         /* load and store IRs and corresponding delays */
733         azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
734         elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
735
736         coordinates[0] = azim;
737         coordinates[1] = elev;
738         coordinates[2] = radius;
739
740         mysofa_s2c(coordinates);
741
742         /* get id of IR closest to desired position */
743         ret = getfilter_float(ctx, coordinates[0], coordinates[1], coordinates[2],
744                               data_ir_l + n_samples * i,
745                               data_ir_r + n_samples * i,
746                               &delay_l, &delay_r);
747         if (ret < 0)
748             goto fail;
749
750         s->delay[0][i] = delay_l * sample_rate;
751         s->delay[1][i] = delay_r * sample_rate;
752
753         s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
754     }
755
756     /* get size of ringbuffer (longest IR plus max. delay) */
757     /* then choose next power of 2 for performance optimization */
758     n_current = n_samples + s->sofa.max_delay;
759     /* length of longest IR plus max. delay */
760     n_max = FFMAX(n_max, n_current);
761
762     /* buffer length is longest IR plus max. delay -> next power of 2
763        (32 - count leading zeros gives required exponent)  */
764     s->buffer_length = 1 << (32 - ff_clz(n_max));
765     s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
766
767     if (s->type == FREQUENCY_DOMAIN) {
768         av_fft_end(s->fft[0]);
769         av_fft_end(s->fft[1]);
770         s->fft[0] = av_fft_init(log2(s->n_fft), 0);
771         s->fft[1] = av_fft_init(log2(s->n_fft), 0);
772         av_fft_end(s->ifft[0]);
773         av_fft_end(s->ifft[1]);
774         s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
775         s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
776
777         if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
778             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
779             ret = AVERROR(ENOMEM);
780             goto fail;
781         }
782     }
783
784     if (s->type == TIME_DOMAIN) {
785         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
786         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
787     } else {
788         /* get temporary HRTF memory for L and R channel */
789         data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
790         data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
791         if (!data_hrtf_r || !data_hrtf_l) {
792             ret = AVERROR(ENOMEM);
793             goto fail;
794         }
795
796         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
797         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
798         s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
799         s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
800         s->temp_afft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
801         s->temp_afft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
802         if (!s->temp_fft[0] || !s->temp_fft[1] ||
803             !s->temp_afft[0] || !s->temp_afft[1]) {
804             ret = AVERROR(ENOMEM);
805             goto fail;
806         }
807     }
808
809     if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
810         ret = AVERROR(ENOMEM);
811         goto fail;
812     }
813
814     if (s->type == FREQUENCY_DOMAIN) {
815         fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
816         fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
817         if (!fft_in_l || !fft_in_r) {
818             ret = AVERROR(ENOMEM);
819             goto fail;
820         }
821     }
822
823     for (i = 0; i < s->n_conv; i++) {
824         float *lir, *rir;
825
826         offset = i * n_samples; /* no. samples already written */
827
828         lir = data_ir_l + offset;
829         rir = data_ir_r + offset;
830
831         if (s->type == TIME_DOMAIN) {
832             for (j = 0; j < ir_samples; j++) {
833                 /* load reversed IRs of the specified source position
834                  * sample-by-sample for left and right ear; and apply gain */
835                 s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
836                 s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
837             }
838         } else {
839             memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
840             memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
841
842             offset = i * n_fft; /* no. samples already written */
843             for (j = 0; j < ir_samples; j++) {
844                 /* load non-reversed IRs of the specified source position
845                  * sample-by-sample and apply gain,
846                  * L channel is loaded to real part, R channel to imag part,
847                  * IRs ared shifted by L and R delay */
848                 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
849                 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
850             }
851
852             /* actually transform to frequency domain (IRs -> HRTFs) */
853             av_fft_permute(s->fft[0], fft_in_l);
854             av_fft_calc(s->fft[0], fft_in_l);
855             memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
856             av_fft_permute(s->fft[0], fft_in_r);
857             av_fft_calc(s->fft[0], fft_in_r);
858             memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
859         }
860     }
861
862     if (s->type == FREQUENCY_DOMAIN) {
863         s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
864         s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
865         if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
866             ret = AVERROR(ENOMEM);
867             goto fail;
868         }
869
870         memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
871             sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
872         memcpy(s->data_hrtf[1], data_hrtf_r,
873             sizeof(FFTComplex) * n_conv * n_fft);
874     }
875
876 fail:
877     av_freep(&data_hrtf_l); /* free temporary HRTF memory */
878     av_freep(&data_hrtf_r);
879
880     av_freep(&data_ir_l); /* free temprary IR memory */
881     av_freep(&data_ir_r);
882
883     av_freep(&fft_in_l); /* free temporary FFT memory */
884     av_freep(&fft_in_r);
885
886     return ret;
887 }
888
889 static av_cold int init(AVFilterContext *ctx)
890 {
891     SOFAlizerContext *s = ctx->priv;
892     int ret;
893
894     if (!s->filename) {
895         av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
896         return AVERROR(EINVAL);
897     }
898
899     /* preload SOFA file, */
900     ret = preload_sofa(ctx, s->filename, &s->sample_rate);
901     if (ret) {
902         /* file loading error */
903         av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
904     } else { /* no file loading error, resampling not required */
905         av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
906     }
907
908     if (ret) {
909         av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
910         return ret;
911     }
912
913     s->fdsp = avpriv_float_dsp_alloc(0);
914     if (!s->fdsp)
915         return AVERROR(ENOMEM);
916
917     return 0;
918 }
919
920 static int config_input(AVFilterLink *inlink)
921 {
922     AVFilterContext *ctx = inlink->dst;
923     SOFAlizerContext *s = ctx->priv;
924     int ret;
925
926     if (s->type == FREQUENCY_DOMAIN) {
927         inlink->partial_buf_size =
928         inlink->min_samples =
929         inlink->max_samples = s->framesize;
930     }
931
932     /* gain -3 dB per channel */
933     s->gain_lfe = expf((s->gain - 3 * inlink->channels + s->lfe_gain) / 20 * M_LN10);
934
935     s->n_conv = inlink->channels;
936
937     /* load IRs to data_ir[0] and data_ir[1] for required directions */
938     if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
939         return ret;
940
941     av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
942         inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
943
944     return 0;
945 }
946
947 static av_cold void uninit(AVFilterContext *ctx)
948 {
949     SOFAlizerContext *s = ctx->priv;
950
951     close_sofa(&s->sofa);
952     av_fft_end(s->ifft[0]);
953     av_fft_end(s->ifft[1]);
954     av_fft_end(s->fft[0]);
955     av_fft_end(s->fft[1]);
956     s->ifft[0] = NULL;
957     s->ifft[1] = NULL;
958     s->fft[0] = NULL;
959     s->fft[1] = NULL;
960     av_freep(&s->delay[0]);
961     av_freep(&s->delay[1]);
962     av_freep(&s->data_ir[0]);
963     av_freep(&s->data_ir[1]);
964     av_freep(&s->ringbuffer[0]);
965     av_freep(&s->ringbuffer[1]);
966     av_freep(&s->speaker_azim);
967     av_freep(&s->speaker_elev);
968     av_freep(&s->temp_src[0]);
969     av_freep(&s->temp_src[1]);
970     av_freep(&s->temp_afft[0]);
971     av_freep(&s->temp_afft[1]);
972     av_freep(&s->temp_fft[0]);
973     av_freep(&s->temp_fft[1]);
974     av_freep(&s->data_hrtf[0]);
975     av_freep(&s->data_hrtf[1]);
976     av_freep(&s->fdsp);
977 }
978
979 #define OFFSET(x) offsetof(SOFAlizerContext, x)
980 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
981
982 static const AVOption sofalizer_options[] = {
983     { "sofa",      "sofa filename",  OFFSET(filename),  AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
984     { "gain",      "set gain in dB", OFFSET(gain),      AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
985     { "rotation",  "set rotation"  , OFFSET(rotation),  AV_OPT_TYPE_FLOAT,  {.dbl=0},    -360, 360, .flags = FLAGS },
986     { "elevation", "set elevation",  OFFSET(elevation), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -90,  90, .flags = FLAGS },
987     { "radius",    "set radius",     OFFSET(radius),    AV_OPT_TYPE_FLOAT,  {.dbl=1},       0,   5, .flags = FLAGS },
988     { "type",      "set processing", OFFSET(type),      AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
989     { "time",      "time domain",      0,               AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
990     { "freq",      "frequency domain", 0,               AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
991     { "speakers",  "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING,  {.str=0},    0, 0, .flags = FLAGS },
992     { "lfegain",   "set lfe gain",                 OFFSET(lfe_gain),     AV_OPT_TYPE_FLOAT,   {.dbl=0},  -20,40, .flags = FLAGS },
993     { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT,    {.i64=1024},1024,96000, .flags = FLAGS },
994     { "normalize", "normalize IRs",  OFFSET(normalize), AV_OPT_TYPE_BOOL,   {.i64=1},       0,   1, .flags = FLAGS },
995     { "interpolate","interpolate IRs from neighbors",   OFFSET(interpolate),AV_OPT_TYPE_BOOL,    {.i64=0},       0,   1, .flags = FLAGS },
996     { "minphase",  "minphase IRs",   OFFSET(minphase),  AV_OPT_TYPE_BOOL,   {.i64=0},       0,   1, .flags = FLAGS },
997     { "anglestep", "set neighbor search angle step",    OFFSET(anglestep),  AV_OPT_TYPE_FLOAT,   {.dbl=.5},      0.01, 10, .flags = FLAGS },
998     { "radstep",   "set neighbor search radius step",   OFFSET(radstep),    AV_OPT_TYPE_FLOAT,   {.dbl=.01},     0.01,  1, .flags = FLAGS },
999     { NULL }
1000 };
1001
1002 AVFILTER_DEFINE_CLASS(sofalizer);
1003
1004 static const AVFilterPad inputs[] = {
1005     {
1006         .name         = "default",
1007         .type         = AVMEDIA_TYPE_AUDIO,
1008         .config_props = config_input,
1009         .filter_frame = filter_frame,
1010     },
1011     { NULL }
1012 };
1013
1014 static const AVFilterPad outputs[] = {
1015     {
1016         .name = "default",
1017         .type = AVMEDIA_TYPE_AUDIO,
1018     },
1019     { NULL }
1020 };
1021
1022 AVFilter ff_af_sofalizer = {
1023     .name          = "sofalizer",
1024     .description   = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1025     .priv_size     = sizeof(SOFAlizerContext),
1026     .priv_class    = &sofalizer_class,
1027     .init          = init,
1028     .uninit        = uninit,
1029     .query_formats = query_formats,
1030     .inputs        = inputs,
1031     .outputs       = outputs,
1032     .flags         = AVFILTER_FLAG_SLICE_THREADS,
1033 };