]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_sofalizer.c
Merge commit 'f1ccd076801444ab7f524cb13e0886faaf10fd50'
[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 <netcdf.h>
30
31 #include "libavcodec/avfft.h"
32 #include "libavutil/float_dsp.h"
33 #include "libavutil/opt.h"
34 #include "avfilter.h"
35 #include "internal.h"
36 #include "audio.h"
37
38 #define TIME_DOMAIN      0
39 #define FREQUENCY_DOMAIN 1
40
41 typedef struct NCSofa {  /* contains data of one SOFA file */
42     int ncid;            /* netCDF ID of the opened SOFA file */
43     int n_samples;       /* length of one impulse response (IR) */
44     int m_dim;           /* number of measurement positions */
45     int *data_delay;     /* broadband delay of each IR */
46                          /* all measurement positions for each receiver (i.e. ear): */
47     float *sp_a;         /* azimuth angles */
48     float *sp_e;         /* elevation angles */
49     float *sp_r;         /* radii */
50                          /* data at each measurement position for each receiver: */
51     float *data_ir;      /* IRs (time-domain) */
52 } NCSofa;
53
54 typedef struct SOFAlizerContext {
55     const AVClass *class;
56
57     char *filename;             /* name of SOFA file */
58     NCSofa sofa;                /* contains data of the SOFA file */
59
60     int sample_rate;            /* sample rate from SOFA file */
61     float *speaker_azim;        /* azimuth of the virtual loudspeakers */
62     float *speaker_elev;        /* elevation of the virtual loudspeakers */
63     float gain_lfe;             /* gain applied to LFE channel */
64     int lfe_channel;            /* LFE channel position in channel layout */
65
66     int n_conv;                 /* number of channels to convolute */
67
68                                 /* buffer variables (for convolution) */
69     float *ringbuffer[2];       /* buffers input samples, length of one buffer: */
70                                 /* no. input ch. (incl. LFE) x buffer_length */
71     int write[2];               /* current write position to ringbuffer */
72     int buffer_length;          /* is: longest IR plus max. delay in all SOFA files */
73                                 /* then choose next power of 2 */
74     int n_fft;                  /* number of samples in one FFT block */
75
76                                 /* netCDF variables */
77     int *delay[2];              /* broadband delay for each channel/IR to be convolved */
78
79     float *data_ir[2];          /* IRs for all channels to be convolved */
80                                 /* (this excludes the LFE) */
81     float *temp_src[2];
82     FFTComplex *temp_fft[2];
83
84                          /* control variables */
85     float gain;          /* filter gain (in dB) */
86     float rotation;      /* rotation of virtual loudspeakers (in degrees)  */
87     float elevation;     /* elevation of virtual loudspeakers (in deg.) */
88     float radius;        /* distance virtual loudspeakers to listener (in metres) */
89     int type;            /* processing type */
90
91     FFTContext *fft[2], *ifft[2];
92     FFTComplex *data_hrtf[2];
93
94     AVFloatDSPContext *fdsp;
95 } SOFAlizerContext;
96
97 static int close_sofa(struct NCSofa *sofa)
98 {
99     av_freep(&sofa->data_delay);
100     av_freep(&sofa->sp_a);
101     av_freep(&sofa->sp_e);
102     av_freep(&sofa->sp_r);
103     av_freep(&sofa->data_ir);
104     nc_close(sofa->ncid);
105     sofa->ncid = 0;
106
107     return 0;
108 }
109
110 static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
111 {
112     struct SOFAlizerContext *s = ctx->priv;
113     /* variables associated with content of SOFA file: */
114     int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
115     char data_delay_dim_name[NC_MAX_NAME];
116     float *sp_a, *sp_e, *sp_r, *data_ir;
117     char *sofa_conventions;
118     char dim_name[NC_MAX_NAME];   /* names of netCDF dimensions */
119     size_t *dim_length;           /* lengths of netCDF dimensions */
120     char *text;
121     unsigned int sample_rate;
122     int data_delay_dim_id[2];
123     int samplingrate_id;
124     int data_delay_id;
125     int n_samples;
126     int m_dim_id = -1;
127     int n_dim_id = -1;
128     int data_ir_id;
129     size_t att_len;
130     int m_dim;
131     int *data_delay;
132     int sp_id;
133     int i, ret;
134
135     s->sofa.ncid = 0;
136     status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
137     if (status != NC_NOERR) {
138         av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
139         return AVERROR(EINVAL);
140     }
141
142     /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
143     nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);
144
145     /* -- get number of measurements ("M") and length of one IR ("N") -- */
146     dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
147     if (!dim_length) {
148         nc_close(ncid);
149         return AVERROR(ENOMEM);
150     }
151
152     for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
153         nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
154         if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
155             m_dim_id = i;
156         if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
157             n_dim_id = i;
158     }
159
160     if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
161         av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
162         av_freep(&dim_length);
163         nc_close(ncid);
164         return AVERROR(EINVAL);
165     }
166
167     n_samples = dim_length[n_dim_id]; /* get length of one IR */
168     m_dim     = dim_length[m_dim_id]; /* get number of measurements */
169
170     av_freep(&dim_length);
171
172     /* -- check file type -- */
173     /* get length of attritube "Conventions" */
174     status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
175     if (status != NC_NOERR) {
176         av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
177         nc_close(ncid);
178         return AVERROR_INVALIDDATA;
179     }
180
181     /* check whether file is SOFA file */
182     text = av_malloc(att_len + 1);
183     if (!text) {
184         nc_close(ncid);
185         return AVERROR(ENOMEM);
186     }
187
188     nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
189     *(text + att_len) = 0;
190     if (strncmp("SOFA", text, 4)) {
191         av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
192         av_freep(&text);
193         nc_close(ncid);
194         return AVERROR(EINVAL);
195     }
196     av_freep(&text);
197
198     status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
199     if (status == NC_NOERR) {
200         text = av_malloc(att_len + 1);
201         if (text) {
202             nc_get_att_text(ncid, NC_GLOBAL, "License", text);
203             *(text + att_len) = 0;
204             av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
205             av_freep(&text);
206         }
207     }
208
209     status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
210     if (status == NC_NOERR) {
211         text = av_malloc(att_len + 1);
212         if (text) {
213             nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
214             *(text + att_len) = 0;
215             av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
216             av_freep(&text);
217         }
218     }
219
220     status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
221     if (status == NC_NOERR) {
222         text = av_malloc(att_len + 1);
223         if (text) {
224             nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
225             *(text + att_len) = 0;
226             av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
227             av_freep(&text);
228         }
229     }
230
231     status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
232     if (status != NC_NOERR) {
233         av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
234         nc_close(ncid);
235         return AVERROR_INVALIDDATA;
236     }
237
238     sofa_conventions = av_malloc(att_len + 1);
239     if (!sofa_conventions) {
240         nc_close(ncid);
241         return AVERROR(ENOMEM);
242     }
243
244     nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
245     *(sofa_conventions + att_len) = 0;
246     if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
247         av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
248         av_freep(&sofa_conventions);
249         nc_close(ncid);
250         return AVERROR(EINVAL);
251     }
252     av_freep(&sofa_conventions);
253
254     /* -- get sampling rate of HRTFs -- */
255     /* read ID, then value */
256     status  = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
257     status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
258     if (status != NC_NOERR) {
259         av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
260         nc_close(ncid);
261         return AVERROR(EINVAL);
262     }
263     *samplingrate = sample_rate; /* remember sampling rate */
264
265     /* -- allocate memory for one value for each measurement position: -- */
266     sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
267     sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
268     sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
269     /* delay and IR values required for each ear and measurement position: */
270     data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
271     data_ir = s->sofa.data_ir = av_malloc_array(m_dim * n_samples, sizeof(float) * 2);
272
273     if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
274         /* if memory could not be allocated */
275         close_sofa(&s->sofa);
276         return AVERROR(ENOMEM);
277     }
278
279     /* get impulse responses (HRTFs): */
280     /* get corresponding ID */
281     status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
282     status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
283     if (status != NC_NOERR) {
284         av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
285         ret = AVERROR(EINVAL);
286         goto error;
287     }
288
289     /* get source positions of the HRTFs in the SOFA file: */
290     status  = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
291     status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
292                 (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
293     status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
294                 (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
295     status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
296                 (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
297     if (status != NC_NOERR) { /* if any source position variable coudn't be read */
298         av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
299         ret = AVERROR(EINVAL);
300         goto error;
301     }
302
303     /* read Data.Delay, check for errors and fit it to data_delay */
304     status  = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
305     status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
306     status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
307     if (status != NC_NOERR) {
308         av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
309         ret = AVERROR(EINVAL);
310         goto error;
311     }
312
313     /* Data.Delay dimension check */
314     /* dimension of Data.Delay is [I R]: */
315     if (!strncmp(data_delay_dim_name, "I", 2)) {
316         /* check 2 characters to assure string is 0-terminated after "I" */
317         int delay[2]; /* delays get from SOFA file: */
318
319         av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
320         status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
321         if (status != NC_NOERR) {
322             av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
323             ret = AVERROR(EINVAL);
324             goto error;
325         }
326         int *data_delay_r = data_delay + m_dim;
327         for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
328             /* assign constant delay value for all measurements to data_delay fields */
329             data_delay[i]   = delay[0];
330             data_delay_r[i] = delay[1];
331         }
332         /* dimension of Data.Delay is [M R] */
333     } else if (!strncmp(data_delay_dim_name, "M", 2)) {
334         av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
335         /* get delays from SOFA file: */
336         status = nc_get_var_int(ncid, data_delay_id, data_delay);
337         if (status != NC_NOERR) {
338             av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
339             ret = AVERROR(EINVAL);
340             goto error;
341         }
342     } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
343         av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
344         ret = AVERROR(EINVAL);
345         goto error;
346     }
347
348     /* save information in SOFA struct: */
349     s->sofa.m_dim = m_dim; /* no. measurement positions */
350     s->sofa.n_samples = n_samples; /* length on one IR */
351     s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
352     nc_close(ncid); /* close SOFA file */
353
354     return 0;
355
356 error:
357     close_sofa(&s->sofa);
358     return ret;
359 }
360
361 static int get_speaker_pos(AVFilterContext *ctx,
362                            float *speaker_azim, float *speaker_elev)
363 {
364     struct SOFAlizerContext *s = ctx->priv;
365     uint64_t channels_layout = ctx->inputs[0]->channel_layout;
366     float azim[10] = { 0 };
367     float elev[10] = { 0 };
368     int n_conv = ctx->inputs[0]->channels; /* get no. input channels */
369
370     s->lfe_channel = -1;
371
372     /* set speaker positions according to input channel configuration: */
373     switch (channels_layout) {
374     case AV_CH_LAYOUT_MONO:
375                             azim[0] = 0;
376                             break;
377     case AV_CH_LAYOUT_2POINT1:
378                             s->lfe_channel = 2;
379     case AV_CH_LAYOUT_STEREO:
380                             azim[0] = 30;
381                             azim[1] = 330;
382                             break;
383     case AV_CH_LAYOUT_3POINT1:
384                             s->lfe_channel = 3;
385     case AV_CH_LAYOUT_SURROUND:
386                             azim[0] = 30;
387                             azim[1] = 330;
388                             azim[2] = 0;
389                             break;
390     case AV_CH_LAYOUT_2_1:
391                             azim[0] = 30;
392                             azim[1] = 330;
393                             azim[2] = 180;
394                             break;
395     case AV_CH_LAYOUT_2_2:
396                             azim[0] = 30;
397                             azim[1] = 330;
398                             azim[2] = 90;
399                             azim[3] = 270;
400                             break;
401     case AV_CH_LAYOUT_QUAD:
402                             azim[0] = 30;
403                             azim[1] = 330;
404                             azim[2] = 120;
405                             azim[3] = 240;
406                             break;
407     case AV_CH_LAYOUT_4POINT1:
408                             s->lfe_channel = 3;
409                             azim[0] = 30;
410                             azim[1] = 330;
411                             azim[2] = 0;
412                             azim[4] = 180;
413                             break;
414     case AV_CH_LAYOUT_4POINT0:
415                             azim[0] = 30;
416                             azim[1] = 330;
417                             azim[2] = 0;
418                             azim[3] = 180;
419                             break;
420     case AV_CH_LAYOUT_5POINT1:
421                             s->lfe_channel = 3;
422                             azim[0] = 30;
423                             azim[1] = 330;
424                             azim[2] = 0;
425                             azim[4] = 90;
426                             azim[5] = 270;
427                             break;
428     case AV_CH_LAYOUT_5POINT0:
429                             azim[0] = 30;
430                             azim[1] = 330;
431                             azim[2] = 0;
432                             azim[3] = 90;
433                             azim[4] = 270;
434                             break;
435     case AV_CH_LAYOUT_5POINT1_BACK:
436                             s->lfe_channel = 3;
437                             azim[0] = 30;
438                             azim[1] = 330;
439                             azim[2] = 0;
440                             azim[4] = 120;
441                             azim[5] = 240;
442                             break;
443     case AV_CH_LAYOUT_5POINT0_BACK:
444                             azim[0] = 30;
445                             azim[1] = 330;
446                             azim[2] = 0;
447                             azim[3] = 120;
448                             azim[4] = 240;
449                             break;
450     case AV_CH_LAYOUT_6POINT1:
451                             s->lfe_channel = 3;
452                             azim[0] = 30;
453                             azim[1] = 330;
454                             azim[2] = 0;
455                             azim[4] = 180;
456                             azim[5] = 90;
457                             azim[6] = 270;
458                             break;
459     case AV_CH_LAYOUT_6POINT0:
460                             azim[0] = 30;
461                             azim[1] = 330;
462                             azim[2] = 0;
463                             azim[3] = 180;
464                             azim[4] = 90;
465                             azim[5] = 270;
466                             break;
467     case AV_CH_LAYOUT_6POINT1_BACK:
468                             s->lfe_channel = 3;
469                             azim[0] = 30;
470                             azim[1] = 330;
471                             azim[2] = 0;
472                             azim[4] = 120;
473                             azim[5] = 240;
474                             azim[6] = 180;
475                             break;
476     case AV_CH_LAYOUT_HEXAGONAL:
477                             azim[0] = 30;
478                             azim[1] = 330;
479                             azim[2] = 0;
480                             azim[3] = 120;
481                             azim[4] = 240;
482                             azim[5] = 180;
483                             break;
484     case AV_CH_LAYOUT_7POINT1:
485                             s->lfe_channel = 3;
486                             azim[0] = 30;
487                             azim[1] = 330;
488                             azim[2] = 0;
489                             azim[4] = 150;
490                             azim[5] = 210;
491                             azim[6] = 90;
492                             azim[7] = 270;
493                             break;
494     case AV_CH_LAYOUT_7POINT0:
495                             azim[0] = 30;
496                             azim[1] = 330;
497                             azim[2] = 0;
498                             azim[3] = 150;
499                             azim[4] = 210;
500                             azim[5] = 90;
501                             azim[6] = 270;
502                             break;
503     case AV_CH_LAYOUT_OCTAGONAL:
504                             azim[0] = 30;
505                             azim[1] = 330;
506                             azim[2] = 0;
507                             azim[3] = 150;
508                             azim[4] = 210;
509                             azim[5] = 180;
510                             azim[6] = 90;
511                             azim[7] = 270;
512                             break;
513     default:
514                             return -1;
515     }
516
517     memcpy(speaker_azim, azim, n_conv * sizeof(float));
518     memcpy(speaker_elev, elev, n_conv * sizeof(float));
519
520     return 0;
521
522 }
523
524 static int max_delay(struct NCSofa *sofa)
525 {
526     int i, max = 0;
527
528     for (i = 0; i < sofa->m_dim * 2; i++) {
529         /* search maximum delay in given SOFA file */
530         max = FFMAX(max, sofa->data_delay[i]);
531     }
532
533     return max;
534 }
535
536 static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
537 {
538     /* get source positions and M of currently selected SOFA file */
539     float *sp_a = s->sofa.sp_a; /* azimuth angle */
540     float *sp_e = s->sofa.sp_e; /* elevation angle */
541     float *sp_r = s->sofa.sp_r; /* radius */
542     int m_dim = s->sofa.m_dim; /* no. measurements */
543     int best_id = 0; /* index m currently closest to desired source pos. */
544     float delta = 1000; /* offset between desired and currently best pos. */
545     float current;
546     int i;
547
548     for (i = 0; i < m_dim; i++) {
549         /* search through all measurements in currently selected SOFA file */
550         /* distance of current to desired source position: */
551         current = fabs(sp_a[i] - azim) +
552                   fabs(sp_e[i] - elev) +
553                   fabs(sp_r[i] - radius);
554         if (current <= delta) {
555             /* if current distance is smaller than smallest distance so far */
556             delta = current;
557             best_id = i; /* remember index */
558         }
559     }
560
561     return best_id;
562 }
563
564 static int compensate_volume(AVFilterContext *ctx)
565 {
566     struct SOFAlizerContext *s = ctx->priv;
567     float compensate;
568     float energy = 0;
569     float *ir;
570     int m;
571
572     if (s->sofa.ncid) {
573         /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
574         struct NCSofa *sofa = &s->sofa;
575         m = find_m(s, 0, 0, 1);
576         /* get energy of that IR and compensate volume */
577         ir = sofa->data_ir + 2 * m * sofa->n_samples;
578         if (sofa->n_samples & 31) {
579             energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
580         } else {
581             energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
582         }
583         compensate = 256 / (sofa->n_samples * sqrt(energy));
584         av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
585         ir = sofa->data_ir;
586         /* apply volume compensation to IRs */
587         s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
588         emms_c();
589     }
590
591     return 0;
592 }
593
594 typedef struct ThreadData {
595     AVFrame *in, *out;
596     int *write;
597     int **delay;
598     float **ir;
599     int *n_clippings;
600     float **ringbuffer;
601     float **temp_src;
602     FFTComplex **temp_fft;
603 } ThreadData;
604
605 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
606 {
607     SOFAlizerContext *s = ctx->priv;
608     ThreadData *td = arg;
609     AVFrame *in = td->in, *out = td->out;
610     int offset = jobnr;
611     int *write = &td->write[jobnr];
612     const int *const delay = td->delay[jobnr];
613     const float *const ir = td->ir[jobnr];
614     int *n_clippings = &td->n_clippings[jobnr];
615     float *ringbuffer = td->ringbuffer[jobnr];
616     float *temp_src = td->temp_src[jobnr];
617     const int n_samples = s->sofa.n_samples; /* length of one IR */
618     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
619     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
620     const int in_channels = s->n_conv; /* number of input channels */
621     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
622     const int buffer_length = s->buffer_length;
623     /* -1 for AND instead of MODULO (applied to powers of 2): */
624     const uint32_t modulo = (uint32_t)buffer_length - 1;
625     float *buffer[10]; /* holds ringbuffer for each input channel */
626     int wr = *write;
627     int read;
628     int i, l;
629
630     dst += offset;
631     for (l = 0; l < in_channels; l++) {
632         /* get starting address of ringbuffer for each input channel */
633         buffer[l] = ringbuffer + l * buffer_length;
634     }
635
636     for (i = 0; i < in->nb_samples; i++) {
637         const float *temp_ir = ir; /* using same set of IRs for each sample */
638
639         *dst = 0;
640         for (l = 0; l < in_channels; l++) {
641             /* write current input sample to ringbuffer (for each channel) */
642             *(buffer[l] + wr) = src[l];
643         }
644
645         /* loop goes through all channels to be convolved */
646         for (l = 0; l < in_channels; l++) {
647             const float *const bptr = buffer[l];
648
649             if (l == s->lfe_channel) {
650                 /* LFE is an input channel but requires no convolution */
651                 /* apply gain to LFE signal and add to output buffer */
652                 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
653                 temp_ir += n_samples;
654                 continue;
655             }
656
657             /* current read position in ringbuffer: input sample write position
658              * - delay for l-th ch. + diff. betw. IR length and buffer length
659              * (mod buffer length) */
660             read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
661
662             if (read + n_samples < buffer_length) {
663                 memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
664             } else {
665                 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
666
667                 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
668                 memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
669             }
670
671             /* multiply signal and IR, and add up the results */
672             dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
673             temp_ir += n_samples;
674         }
675
676         /* clippings counter */
677         if (fabs(*dst) > 1)
678             *n_clippings += 1;
679
680         /* move output buffer pointer by +2 to get to next sample of processed channel: */
681         dst += 2;
682         src += in_channels;
683         wr   = (wr + 1) & modulo; /* update ringbuffer write position */
684     }
685
686     *write = wr; /* remember write position in ringbuffer for next call */
687
688     return 0;
689 }
690
691 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
692 {
693     SOFAlizerContext *s = ctx->priv;
694     ThreadData *td = arg;
695     AVFrame *in = td->in, *out = td->out;
696     int offset = jobnr;
697     int *write = &td->write[jobnr];
698     FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
699     int *n_clippings = &td->n_clippings[jobnr];
700     float *ringbuffer = td->ringbuffer[jobnr];
701     const int n_samples = s->sofa.n_samples; /* length of one IR */
702     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
703     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
704     const int in_channels = s->n_conv; /* number of input channels */
705     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
706     const int buffer_length = s->buffer_length;
707     /* -1 for AND instead of MODULO (applied to powers of 2): */
708     const uint32_t modulo = (uint32_t)buffer_length - 1;
709     FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
710     FFTContext *ifft = s->ifft[jobnr];
711     FFTContext *fft = s->fft[jobnr];
712     const int n_conv = s->n_conv;
713     const int n_fft = s->n_fft;
714     int wr = *write;
715     int n_read;
716     int i, j;
717
718     dst += offset;
719
720     /* find minimum between number of samples and output buffer length:
721      * (important, if one IR is longer than the output buffer) */
722     n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
723     for (j = 0; j < n_read; j++) {
724         /* initialize output buf with saved signal from overflow buf */
725         dst[2 * j]     = ringbuffer[wr];
726         ringbuffer[wr] = 0.0; /* re-set read samples to zero */
727         /* update ringbuffer read/write position */
728         wr  = (wr + 1) & modulo;
729     }
730
731     /* initialize rest of output buffer with 0 */
732     for (j = n_read; j < in->nb_samples; j++) {
733         dst[2 * j] = 0;
734     }
735
736     for (i = 0; i < n_conv; i++) {
737         if (i == s->lfe_channel) { /* LFE */
738             for (j = 0; j < in->nb_samples; j++) {
739                 /* apply gain to LFE signal and add to output buffer */
740                 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
741             }
742             continue;
743         }
744
745         /* outer loop: go through all input channels to be convolved */
746         offset = i * n_fft; /* no. samples already processed */
747
748         /* fill FFT input with 0 (we want to zero-pad) */
749         memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
750
751         for (j = 0; j < in->nb_samples; j++) {
752             /* prepare input for FFT */
753             /* write all samples of current input channel to FFT input array */
754             fft_in[j].re = src[j * in_channels + i];
755         }
756
757         /* transform input signal of current channel to frequency domain */
758         av_fft_permute(fft, fft_in);
759         av_fft_calc(fft, fft_in);
760         for (j = 0; j < n_fft; j++) {
761             const float re = fft_in[j].re;
762             const float im = fft_in[j].im;
763
764             /* complex multiplication of input signal and HRTFs */
765             /* output channel (real): */
766             fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
767             /* output channel (imag): */
768             fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
769         }
770
771         /* transform output signal of current channel back to time domain */
772         av_fft_permute(ifft, fft_in);
773         av_fft_calc(ifft, fft_in);
774
775         for (j = 0; j < in->nb_samples; j++) {
776             /* write output signal of current channel to output buffer */
777             dst[2 * j] += fft_in[j].re / (float)n_fft;
778         }
779
780         for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
781             /* write the rest of output signal to overflow buffer */
782             int write_pos = (wr + j) & modulo;
783
784             *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
785         }
786     }
787
788     /* go through all samples of current output buffer: count clippings */
789     for (i = 0; i < out->nb_samples; i++) {
790         /* clippings counter */
791         if (fabs(*dst) > 1) { /* if current output sample > 1 */
792             *n_clippings = *n_clippings + 1;
793         }
794
795         /* move output buffer pointer by +2 to get to next sample of processed channel: */
796         dst += 2;
797     }
798
799     /* remember read/write position in ringbuffer for next call */
800     *write = wr;
801
802     return 0;
803 }
804
805 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
806 {
807     AVFilterContext *ctx = inlink->dst;
808     SOFAlizerContext *s = ctx->priv;
809     AVFilterLink *outlink = ctx->outputs[0];
810     int n_clippings[2] = { 0 };
811     ThreadData td;
812     AVFrame *out;
813
814     out = ff_get_audio_buffer(outlink, in->nb_samples);
815     if (!out) {
816         av_frame_free(&in);
817         return AVERROR(ENOMEM);
818     }
819     av_frame_copy_props(out, in);
820
821     td.in = in; td.out = out; td.write = s->write;
822     td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
823     td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
824     td.temp_fft = s->temp_fft;
825
826     if (s->type == TIME_DOMAIN) {
827         ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
828     } else {
829         ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
830     }
831     emms_c();
832
833     /* display error message if clipping occured */
834     if (n_clippings[0] + n_clippings[1] > 0) {
835         av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
836                n_clippings[0] + n_clippings[1], out->nb_samples * 2);
837     }
838
839     av_frame_free(&in);
840     return ff_filter_frame(outlink, out);
841 }
842
843 static int query_formats(AVFilterContext *ctx)
844 {
845     struct SOFAlizerContext *s = ctx->priv;
846     AVFilterFormats *formats = NULL;
847     AVFilterChannelLayouts *layouts = NULL;
848     int ret, sample_rates[] = { 48000, -1 };
849     static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
850                                                 AV_CH_LAYOUT_STEREO,
851                                                 AV_CH_LAYOUT_2POINT1,
852                                                 AV_CH_LAYOUT_SURROUND,
853                                                 AV_CH_LAYOUT_2_1,
854                                                 AV_CH_LAYOUT_4POINT0,
855                                                 AV_CH_LAYOUT_QUAD,
856                                                 AV_CH_LAYOUT_2_2,
857                                                 AV_CH_LAYOUT_3POINT1,
858                                                 AV_CH_LAYOUT_5POINT0_BACK,
859                                                 AV_CH_LAYOUT_5POINT0,
860                                                 AV_CH_LAYOUT_4POINT1,
861                                                 AV_CH_LAYOUT_5POINT1_BACK,
862                                                 AV_CH_LAYOUT_5POINT1,
863                                                 AV_CH_LAYOUT_6POINT0,
864                                                 AV_CH_LAYOUT_HEXAGONAL,
865                                                 AV_CH_LAYOUT_6POINT1,
866                                                 AV_CH_LAYOUT_6POINT1_BACK,
867                                                 AV_CH_LAYOUT_7POINT0,
868                                                 AV_CH_LAYOUT_7POINT1,
869                                                 AV_CH_LAYOUT_OCTAGONAL,
870                                                 0, };
871
872     ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
873     if (ret)
874         return ret;
875     ret = ff_set_common_formats(ctx, formats);
876     if (ret)
877         return ret;
878
879     layouts = ff_make_formatu64_list(channel_layouts);
880     if (!layouts)
881         return AVERROR(ENOMEM);
882
883     ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
884     if (ret)
885         return ret;
886
887     layouts = NULL;
888     ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
889     if (ret)
890         return ret;
891
892     ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
893     if (ret)
894         return ret;
895
896     sample_rates[0] = s->sample_rate;
897     formats = ff_make_format_list(sample_rates);
898     if (!formats)
899         return AVERROR(ENOMEM);
900     return ff_set_common_samplerates(ctx, formats);
901 }
902
903 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
904 {
905     struct SOFAlizerContext *s = ctx->priv;
906     const int n_samples = s->sofa.n_samples;
907     int n_conv = s->n_conv; /* no. channels to convolve */
908     int n_fft = s->n_fft;
909     int delay_l[10]; /* broadband delay for each IR */
910     int delay_r[10];
911     int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
912     float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
913     FFTComplex *data_hrtf_l = NULL;
914     FFTComplex *data_hrtf_r = NULL;
915     FFTComplex *fft_in_l = NULL;
916     FFTComplex *fft_in_r = NULL;
917     float *data_ir_l = NULL;
918     float *data_ir_r = NULL;
919     int offset = 0; /* used for faster pointer arithmetics in for-loop */
920     int m[10]; /* measurement index m of IR closest to required source positions */
921     int i, j, azim_orig = azim, elev_orig = elev;
922
923     if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
924         av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
925         return AVERROR_INVALIDDATA;
926     }
927
928     if (s->type == TIME_DOMAIN) {
929         s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
930         s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
931
932         /* get temporary IR for L and R channel */
933         data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
934         data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
935         if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
936             av_free(data_ir_l);
937             av_free(data_ir_r);
938             return AVERROR(ENOMEM);
939         }
940     } else {
941         /* get temporary HRTF memory for L and R channel */
942         data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
943         data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
944         if (!data_hrtf_r || !data_hrtf_l) {
945             av_free(data_hrtf_l);
946             av_free(data_hrtf_r);
947             return AVERROR(ENOMEM);
948         }
949     }
950
951     for (i = 0; i < s->n_conv; i++) {
952         /* load and store IRs and corresponding delays */
953         azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
954         elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
955         /* get id of IR closest to desired position */
956         m[i] = find_m(s, azim, elev, radius);
957
958         /* load the delays associated with the current IRs */
959         delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
960         delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
961
962         if (s->type == TIME_DOMAIN) {
963             offset = i * n_samples; /* no. samples already written */
964             for (j = 0; j < n_samples; j++) {
965                 /* load reversed IRs of the specified source position
966                  * sample-by-sample for left and right ear; and apply gain */
967                 *(data_ir_l + offset + j) = /* left channel */
968                 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
969                 *(data_ir_r + offset + j) = /* right channel */
970                 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j  + n_samples) * gain_lin;
971             }
972         } else {
973             fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
974             fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
975             if (!fft_in_l || !fft_in_r) {
976                 av_free(data_hrtf_l);
977                 av_free(data_hrtf_r);
978                 av_free(fft_in_l);
979                 av_free(fft_in_r);
980                 return AVERROR(ENOMEM);
981             }
982
983             offset = i * n_fft; /* no. samples already written */
984             for (j = 0; j < n_samples; j++) {
985                 /* load non-reversed IRs of the specified source position
986                  * sample-by-sample and apply gain,
987                  * L channel is loaded to real part, R channel to imag part,
988                  * IRs ared shifted by L and R delay */
989                 fft_in_l[delay_l[i] + j].re = /* left channel */
990                 *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
991                 fft_in_r[delay_r[i] + j].re = /* right channel */
992                 *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
993             }
994
995             /* actually transform to frequency domain (IRs -> HRTFs) */
996             av_fft_permute(s->fft[0], fft_in_l);
997             av_fft_calc(s->fft[0], fft_in_l);
998             memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
999             av_fft_permute(s->fft[0], fft_in_r);
1000             av_fft_calc(s->fft[0], fft_in_r);
1001             memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
1002         }
1003
1004         av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
1005                m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
1006     }
1007
1008     if (s->type == TIME_DOMAIN) {
1009         /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
1010         memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
1011         memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
1012
1013         av_freep(&data_ir_l); /* free temporary IR memory */
1014         av_freep(&data_ir_r);
1015     } else {
1016         s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
1017         s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
1018         if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
1019             av_freep(&data_hrtf_l);
1020             av_freep(&data_hrtf_r);
1021             av_freep(&fft_in_l);
1022             av_freep(&fft_in_r);
1023             return AVERROR(ENOMEM); /* memory allocation failed */
1024         }
1025
1026         memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
1027             sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
1028         memcpy(s->data_hrtf[1], data_hrtf_r,
1029             sizeof(FFTComplex) * n_conv * n_fft);
1030
1031         av_freep(&data_hrtf_l); /* free temporary HRTF memory */
1032         av_freep(&data_hrtf_r);
1033
1034         av_freep(&fft_in_l); /* free temporary FFT memory */
1035         av_freep(&fft_in_r);
1036     }
1037
1038     memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
1039     memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
1040
1041     return 0;
1042 }
1043
1044 static av_cold int init(AVFilterContext *ctx)
1045 {
1046     SOFAlizerContext *s = ctx->priv;
1047     int ret;
1048
1049     /* load SOFA file, */
1050     /* initialize file IDs to 0 before attempting to load SOFA files,
1051      * this assures that in case of error, only the memory of already
1052      * loaded files is free'd */
1053     s->sofa.ncid = 0;
1054     ret = load_sofa(ctx, s->filename, &s->sample_rate);
1055     if (ret) {
1056         /* file loading error */
1057         av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
1058     } else { /* no file loading error, resampling not required */
1059         av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
1060     }
1061
1062     if (ret) {
1063         av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
1064         return ret;
1065     }
1066
1067     s->fdsp = avpriv_float_dsp_alloc(0);
1068     if (!s->fdsp)
1069         return AVERROR(ENOMEM);
1070
1071     return 0;
1072 }
1073
1074 static inline unsigned clz(unsigned x)
1075 {
1076     unsigned i = sizeof(x) * 8;
1077
1078     while (x) {
1079         x >>= 1;
1080         i--;
1081     }
1082
1083     return i;
1084 }
1085
1086 static int config_input(AVFilterLink *inlink)
1087 {
1088     AVFilterContext *ctx = inlink->dst;
1089     SOFAlizerContext *s = ctx->priv;
1090     int nb_input_channels = inlink->channels; /* no. input channels */
1091     int n_max_ir = 0;
1092     int n_current;
1093     int n_max = 0;
1094     int ret;
1095
1096     if (s->type == FREQUENCY_DOMAIN) {
1097         inlink->partial_buf_size =
1098         inlink->min_samples =
1099         inlink->max_samples = inlink->sample_rate;
1100     }
1101
1102     /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
1103     s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
1104
1105     s->n_conv = nb_input_channels;
1106
1107     /* get size of ringbuffer (longest IR plus max. delay) */
1108     /* then choose next power of 2 for performance optimization */
1109     n_current = s->sofa.n_samples + max_delay(&s->sofa);
1110     if (n_current > n_max) {
1111         /* length of longest IR plus max. delay (in all SOFA files) */
1112         n_max = n_current;
1113         /* length of longest IR (without delay, in all SOFA files) */
1114         n_max_ir = s->sofa.n_samples;
1115     }
1116     /* buffer length is longest IR plus max. delay -> next power of 2
1117        (32 - count leading zeros gives required exponent)  */
1118     s->buffer_length = exp2(32 - clz((uint32_t)n_max));
1119     s->n_fft         = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));
1120
1121     if (s->type == FREQUENCY_DOMAIN) {
1122         av_fft_end(s->fft[0]);
1123         av_fft_end(s->fft[1]);
1124         s->fft[0] = av_fft_init(log2(s->n_fft), 0);
1125         s->fft[1] = av_fft_init(log2(s->n_fft), 0);
1126         av_fft_end(s->ifft[0]);
1127         av_fft_end(s->ifft[1]);
1128         s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
1129         s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1130
1131         if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
1132             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts.\n");
1133             return AVERROR(ENOMEM);
1134         }
1135     }
1136
1137     /* Allocate memory for the impulse responses, delays and the ringbuffers */
1138     /* size: (longest IR) * (number of channels to convolute) */
1139     s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1140     s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1141     /* length:  number of channels to convolute */
1142     s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
1143     s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
1144     /* length: (buffer length) * (number of input channels),
1145      * OR: buffer length (if frequency domain processing)
1146      * calloc zero-initializes the buffer */
1147
1148     if (s->type == TIME_DOMAIN) {
1149         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1150         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1151     } else {
1152         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
1153         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
1154         s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1155         s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1156         if (!s->temp_fft[0] || !s->temp_fft[1])
1157             return AVERROR(ENOMEM);
1158     }
1159
1160     /* length: number of channels to convolute */
1161     s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
1162     s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1163
1164     /* memory allocation failed: */
1165     if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
1166         !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1167         !s->speaker_azim || !s->speaker_elev)
1168         return AVERROR(ENOMEM);
1169
1170     compensate_volume(ctx);
1171
1172     /* get speaker positions */
1173     if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1174         av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
1175         return ret;
1176     }
1177
1178     /* load IRs to data_ir[0] and data_ir[1] for required directions */
1179     if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
1180         return ret;
1181
1182     av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
1183         inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
1184
1185     return 0;
1186 }
1187
1188 static av_cold void uninit(AVFilterContext *ctx)
1189 {
1190     SOFAlizerContext *s = ctx->priv;
1191
1192     if (s->sofa.ncid) {
1193         av_freep(&s->sofa.sp_a);
1194         av_freep(&s->sofa.sp_e);
1195         av_freep(&s->sofa.sp_r);
1196         av_freep(&s->sofa.data_delay);
1197         av_freep(&s->sofa.data_ir);
1198     }
1199     av_fft_end(s->ifft[0]);
1200     av_fft_end(s->ifft[1]);
1201     av_fft_end(s->fft[0]);
1202     av_fft_end(s->fft[1]);
1203     av_freep(&s->delay[0]);
1204     av_freep(&s->delay[1]);
1205     av_freep(&s->data_ir[0]);
1206     av_freep(&s->data_ir[1]);
1207     av_freep(&s->ringbuffer[0]);
1208     av_freep(&s->ringbuffer[1]);
1209     av_freep(&s->speaker_azim);
1210     av_freep(&s->speaker_elev);
1211     av_freep(&s->temp_src[0]);
1212     av_freep(&s->temp_src[1]);
1213     av_freep(&s->temp_fft[0]);
1214     av_freep(&s->temp_fft[1]);
1215     av_freep(&s->data_hrtf[0]);
1216     av_freep(&s->data_hrtf[1]);
1217     av_freep(&s->fdsp);
1218 }
1219
1220 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1221 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1222
1223 static const AVOption sofalizer_options[] = {
1224     { "sofa",      "sofa filename",  OFFSET(filename),  AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
1225     { "gain",      "set gain in dB", OFFSET(gain),      AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
1226     { "rotation",  "set rotation"  , OFFSET(rotation),  AV_OPT_TYPE_FLOAT,  {.dbl=0},    -360, 360, .flags = FLAGS },
1227     { "elevation", "set elevation",  OFFSET(elevation), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -90,  90, .flags = FLAGS },
1228     { "radius",    "set radius",     OFFSET(radius),    AV_OPT_TYPE_FLOAT,  {.dbl=1},       0,   3, .flags = FLAGS },
1229     { "type",      "set processing", OFFSET(type),      AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
1230     { "time",      "time domain",      0,               AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
1231     { "freq",      "frequency domain", 0,               AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
1232     { NULL }
1233 };
1234
1235 AVFILTER_DEFINE_CLASS(sofalizer);
1236
1237 static const AVFilterPad inputs[] = {
1238     {
1239         .name         = "default",
1240         .type         = AVMEDIA_TYPE_AUDIO,
1241         .config_props = config_input,
1242         .filter_frame = filter_frame,
1243     },
1244     { NULL }
1245 };
1246
1247 static const AVFilterPad outputs[] = {
1248     {
1249         .name = "default",
1250         .type = AVMEDIA_TYPE_AUDIO,
1251     },
1252     { NULL }
1253 };
1254
1255 AVFilter ff_af_sofalizer = {
1256     .name          = "sofalizer",
1257     .description   = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1258     .priv_size     = sizeof(SOFAlizerContext),
1259     .priv_class    = &sofalizer_class,
1260     .init          = init,
1261     .uninit        = uninit,
1262     .query_formats = query_formats,
1263     .inputs        = inputs,
1264     .outputs       = outputs,
1265     .flags         = AVFILTER_FLAG_SLICE_THREADS,
1266 };