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