af_sofalizer.c 47.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/*****************************************************************************
 * sofalizer.c : SOFAlizer filter for virtual binaural acoustics
 *****************************************************************************
 * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda,
 *                         Acoustics Research Institute (ARI), Vienna, Austria
 *
 * Authors: Andreas Fuchs <andi.fuchs.mail@gmail.com>
 *          Wolfgang Hrauda <wolfgang.hrauda@gmx.at>
 *
 * SOFAlizer project coordinator at ARI, main developer of SOFA:
 *          Piotr Majdak <piotr@majdak.at>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include <math.h>
#include <netcdf.h>

31
#include "libavcodec/avfft.h"
32 33 34 35 36 37
#include "libavutil/float_dsp.h"
#include "libavutil/opt.h"
#include "avfilter.h"
#include "internal.h"
#include "audio.h"

38 39 40
#define TIME_DOMAIN      0
#define FREQUENCY_DOMAIN 1

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
typedef struct NCSofa {  /* contains data of one SOFA file */
    int ncid;            /* netCDF ID of the opened SOFA file */
    int n_samples;       /* length of one impulse response (IR) */
    int m_dim;           /* number of measurement positions */
    int *data_delay;     /* broadband delay of each IR */
                         /* all measurement positions for each receiver (i.e. ear): */
    float *sp_a;         /* azimuth angles */
    float *sp_e;         /* elevation angles */
    float *sp_r;         /* radii */
                         /* data at each measurement position for each receiver: */
    float *data_ir;      /* IRs (time-domain) */
} NCSofa;

typedef struct SOFAlizerContext {
    const AVClass *class;

    char *filename;             /* name of SOFA file */
    NCSofa sofa;                /* contains data of the SOFA file */

    int sample_rate;            /* sample rate from SOFA file */
61 62
    float *speaker_azim;        /* azimuth of the virtual loudspeakers */
    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 67 68 69 70 71 72 73

    int n_conv;                 /* number of channels to convolute */

                                /* buffer variables (for convolution) */
    float *ringbuffer[2];       /* buffers input samples, length of one buffer: */
                                /* no. input ch. (incl. LFE) x buffer_length */
    int write[2];               /* current write position to ringbuffer */
    int buffer_length;          /* is: longest IR plus max. delay in all SOFA files */
                                /* then choose next power of 2 */
74
    int n_fft;                  /* number of samples in one FFT block */
75 76 77 78 79 80 81

                                /* netCDF variables */
    int *delay[2];              /* broadband delay for each channel/IR to be convolved */

    float *data_ir[2];          /* IRs for all channels to be convolved */
                                /* (this excludes the LFE) */
    float *temp_src[2];
82
    FFTComplex *temp_fft[2];
83 84 85 86 87 88

                         /* control variables */
    float gain;          /* filter gain (in dB) */
    float rotation;      /* rotation of virtual loudspeakers (in degrees)  */
    float elevation;     /* elevation of virtual loudspeakers (in deg.) */
    float radius;        /* distance virtual loudspeakers to listener (in metres) */
89 90 91 92
    int type;            /* processing type */

    FFTContext *fft[2], *ifft[2];
    FFTComplex *data_hrtf[2];
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

    AVFloatDSPContext *fdsp;
} SOFAlizerContext;

static int close_sofa(struct NCSofa *sofa)
{
    av_freep(&sofa->data_delay);
    av_freep(&sofa->sp_a);
    av_freep(&sofa->sp_e);
    av_freep(&sofa->sp_r);
    av_freep(&sofa->data_ir);
    nc_close(sofa->ncid);
    sofa->ncid = 0;

    return 0;
}

static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
{
    struct SOFAlizerContext *s = ctx->priv;
    /* variables associated with content of SOFA file: */
    int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
    char data_delay_dim_name[NC_MAX_NAME];
    float *sp_a, *sp_e, *sp_r, *data_ir;
    char *sofa_conventions;
    char dim_name[NC_MAX_NAME];   /* names of netCDF dimensions */
    size_t *dim_length;           /* lengths of netCDF dimensions */
120
    char *text;
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    unsigned int sample_rate;
    int data_delay_dim_id[2];
    int samplingrate_id;
    int data_delay_id;
    int n_samples;
    int m_dim_id = -1;
    int n_dim_id = -1;
    int data_ir_id;
    size_t att_len;
    int m_dim;
    int *data_delay;
    int sp_id;
    int i, ret;

    s->sofa.ncid = 0;
    status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
        return AVERROR(EINVAL);
    }

    /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
    nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);

    /* -- get number of measurements ("M") and length of one IR ("N") -- */
    dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
    if (!dim_length) {
        nc_close(ncid);
        return AVERROR(ENOMEM);
    }

    for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
        nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
        if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
            m_dim_id = i;
        if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
            n_dim_id = i;
    }

    if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
        av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
        av_freep(&dim_length);
        nc_close(ncid);
        return AVERROR(EINVAL);
    }

167 168
    n_samples = dim_length[n_dim_id]; /* get length of one IR */
    m_dim     = dim_length[m_dim_id]; /* get number of measurements */
169 170 171 172 173 174 175 176 177 178 179 180 181

    av_freep(&dim_length);

    /* -- check file type -- */
    /* get length of attritube "Conventions" */
    status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
        nc_close(ncid);
        return AVERROR_INVALIDDATA;
    }

    /* check whether file is SOFA file */
182 183
    text = av_malloc(att_len + 1);
    if (!text) {
184 185 186 187
        nc_close(ncid);
        return AVERROR(ENOMEM);
    }

188 189 190
    nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
    *(text + att_len) = 0;
    if (strncmp("SOFA", text, 4)) {
191
        av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
192
        av_freep(&text);
193 194 195
        nc_close(ncid);
        return AVERROR(EINVAL);
    }
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    av_freep(&text);

    status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
    if (status == NC_NOERR) {
        text = av_malloc(att_len + 1);
        if (text) {
            nc_get_att_text(ncid, NC_GLOBAL, "License", text);
            *(text + att_len) = 0;
            av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
            av_freep(&text);
        }
    }

    status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
    if (status == NC_NOERR) {
        text = av_malloc(att_len + 1);
        if (text) {
            nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
            *(text + att_len) = 0;
            av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
            av_freep(&text);
        }
    }

    status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
    if (status == NC_NOERR) {
        text = av_malloc(att_len + 1);
        if (text) {
            nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
            *(text + att_len) = 0;
            av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
            av_freep(&text);
        }
    }
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

    status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
        nc_close(ncid);
        return AVERROR_INVALIDDATA;
    }

    sofa_conventions = av_malloc(att_len + 1);
    if (!sofa_conventions) {
        nc_close(ncid);
        return AVERROR(ENOMEM);
    }

    nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
    *(sofa_conventions + att_len) = 0;
    if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
        av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
        av_freep(&sofa_conventions);
        nc_close(ncid);
        return AVERROR(EINVAL);
    }
    av_freep(&sofa_conventions);

    /* -- get sampling rate of HRTFs -- */
    /* read ID, then value */
    status  = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
    status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
        nc_close(ncid);
        return AVERROR(EINVAL);
    }
    *samplingrate = sample_rate; /* remember sampling rate */

    /* -- allocate memory for one value for each measurement position: -- */
    sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
    sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
    sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
    /* delay and IR values required for each ear and measurement position: */
    data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
    data_ir = s->sofa.data_ir = av_malloc_array(m_dim * n_samples, sizeof(float) * 2);

273
    if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        /* if memory could not be allocated */
        close_sofa(&s->sofa);
        return AVERROR(ENOMEM);
    }

    /* get impulse responses (HRTFs): */
    /* get corresponding ID */
    status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
    status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
        ret = AVERROR(EINVAL);
        goto error;
    }

    /* get source positions of the HRTFs in the SOFA file: */
    status  = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
    status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
                (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
    status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
                (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
    status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
                (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
    if (status != NC_NOERR) { /* if any source position variable coudn't be read */
        av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
        ret = AVERROR(EINVAL);
        goto error;
    }

    /* read Data.Delay, check for errors and fit it to data_delay */
    status  = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
    status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
    status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
    if (status != NC_NOERR) {
        av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
        ret = AVERROR(EINVAL);
        goto error;
    }

    /* Data.Delay dimension check */
    /* dimension of Data.Delay is [I R]: */
    if (!strncmp(data_delay_dim_name, "I", 2)) {
        /* check 2 characters to assure string is 0-terminated after "I" */
        int delay[2]; /* delays get from SOFA file: */

        av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
        status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
        if (status != NC_NOERR) {
            av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
            ret = AVERROR(EINVAL);
            goto error;
        }
        int *data_delay_r = data_delay + m_dim;
        for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
            /* assign constant delay value for all measurements to data_delay fields */
            data_delay[i]   = delay[0];
            data_delay_r[i] = delay[1];
        }
        /* dimension of Data.Delay is [M R] */
    } else if (!strncmp(data_delay_dim_name, "M", 2)) {
        av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
        /* get delays from SOFA file: */
        status = nc_get_var_int(ncid, data_delay_id, data_delay);
        if (status != NC_NOERR) {
            av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
            ret = AVERROR(EINVAL);
            goto error;
        }
    } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
        av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
        ret = AVERROR(EINVAL);
        goto error;
    }

    /* save information in SOFA struct: */
    s->sofa.m_dim = m_dim; /* no. measurement positions */
    s->sofa.n_samples = n_samples; /* length on one IR */
    s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
    nc_close(ncid); /* close SOFA file */

    return 0;

error:
    close_sofa(&s->sofa);
    return ret;
}

361 362
static int get_speaker_pos(AVFilterContext *ctx,
                           float *speaker_azim, float *speaker_elev)
363 364 365
{
    struct SOFAlizerContext *s = ctx->priv;
    uint64_t channels_layout = ctx->inputs[0]->channel_layout;
366 367 368
    float azim[10] = { 0 };
    float elev[10] = { 0 };
    int n_conv = ctx->inputs[0]->channels; /* get no. input channels */
369

370
    s->lfe_channel = -1;
371 372 373 374

    /* set speaker positions according to input channel configuration: */
    switch (channels_layout) {
    case AV_CH_LAYOUT_MONO:
375
                            azim[0] = 0;
376 377
                            break;
    case AV_CH_LAYOUT_2POINT1:
378 379
                            s->lfe_channel = 2;
    case AV_CH_LAYOUT_STEREO:
380 381
                            azim[0] = 30;
                            azim[1] = 330;
382 383
                            break;
    case AV_CH_LAYOUT_3POINT1:
384 385
                            s->lfe_channel = 3;
    case AV_CH_LAYOUT_SURROUND:
386 387 388
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
389 390
                            break;
    case AV_CH_LAYOUT_2_1:
391 392 393
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 180;
394 395
                            break;
    case AV_CH_LAYOUT_2_2:
396 397 398 399
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 90;
                            azim[3] = 270;
400 401
                            break;
    case AV_CH_LAYOUT_QUAD:
402 403 404 405
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 120;
                            azim[3] = 240;
406 407
                            break;
    case AV_CH_LAYOUT_4POINT1:
408 409 410 411 412 413 414
                            s->lfe_channel = 3;
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[4] = 180;
                            break;
    case AV_CH_LAYOUT_4POINT0:
415 416 417 418
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 180;
419 420
                            break;
    case AV_CH_LAYOUT_5POINT1:
421
                            s->lfe_channel = 3;
422 423
                            azim[0] = 30;
                            azim[1] = 330;
424 425 426 427 428 429 430 431 432 433
                            azim[2] = 0;
                            azim[4] = 90;
                            azim[5] = 270;
                            break;
    case AV_CH_LAYOUT_5POINT0:
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 90;
                            azim[4] = 270;
434 435
                            break;
    case AV_CH_LAYOUT_5POINT1_BACK:
436
                            s->lfe_channel = 3;
437 438
                            azim[0] = 30;
                            azim[1] = 330;
439 440 441 442 443 444 445 446 447 448
                            azim[2] = 0;
                            azim[4] = 120;
                            azim[5] = 240;
                            break;
    case AV_CH_LAYOUT_5POINT0_BACK:
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 120;
                            azim[4] = 240;
449 450
                            break;
    case AV_CH_LAYOUT_6POINT1:
451
                            s->lfe_channel = 3;
452 453
                            azim[0] = 30;
                            azim[1] = 330;
454 455 456 457 458 459 460 461 462 463 464 465
                            azim[2] = 0;
                            azim[4] = 180;
                            azim[5] = 90;
                            azim[6] = 270;
                            break;
    case AV_CH_LAYOUT_6POINT0:
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 180;
                            azim[4] = 90;
                            azim[5] = 270;
466 467
                            break;
    case AV_CH_LAYOUT_6POINT1_BACK:
468
                            s->lfe_channel = 3;
469 470
                            azim[0] = 30;
                            azim[1] = 330;
471 472 473 474
                            azim[2] = 0;
                            azim[4] = 120;
                            azim[5] = 240;
                            azim[6] = 180;
475 476
                            break;
    case AV_CH_LAYOUT_HEXAGONAL:
477 478
                            azim[0] = 30;
                            azim[1] = 330;
479 480 481
                            azim[2] = 0;
                            azim[3] = 120;
                            azim[4] = 240;
482
                            azim[5] = 180;
483 484
                            break;
    case AV_CH_LAYOUT_7POINT1:
485
                            s->lfe_channel = 3;
486 487
                            azim[0] = 30;
                            azim[1] = 330;
488
                            azim[2] = 0;
489 490
                            azim[4] = 150;
                            azim[5] = 210;
491 492 493 494 495 496 497 498 499 500 501
                            azim[6] = 90;
                            azim[7] = 270;
                            break;
    case AV_CH_LAYOUT_7POINT0:
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 150;
                            azim[4] = 210;
                            azim[5] = 90;
                            azim[6] = 270;
502 503
                            break;
    case AV_CH_LAYOUT_OCTAGONAL:
504 505 506 507 508 509 510 511
                            azim[0] = 30;
                            azim[1] = 330;
                            azim[2] = 0;
                            azim[3] = 150;
                            azim[4] = 210;
                            azim[5] = 180;
                            azim[6] = 90;
                            azim[7] = 270;
512 513 514 515 516
                            break;
    default:
                            return -1;
    }

517 518
    memcpy(speaker_azim, azim, n_conv * sizeof(float));
    memcpy(speaker_elev, elev, n_conv * sizeof(float));
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

    return 0;

}

static int max_delay(struct NCSofa *sofa)
{
    int i, max = 0;

    for (i = 0; i < sofa->m_dim * 2; i++) {
        /* search maximum delay in given SOFA file */
        max = FFMAX(max, sofa->data_delay[i]);
    }

    return max;
}

static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
{
    /* get source positions and M of currently selected SOFA file */
    float *sp_a = s->sofa.sp_a; /* azimuth angle */
    float *sp_e = s->sofa.sp_e; /* elevation angle */
    float *sp_r = s->sofa.sp_r; /* radius */
    int m_dim = s->sofa.m_dim; /* no. measurements */
    int best_id = 0; /* index m currently closest to desired source pos. */
    float delta = 1000; /* offset between desired and currently best pos. */
    float current;
    int i;

    for (i = 0; i < m_dim; i++) {
        /* search through all measurements in currently selected SOFA file */
        /* distance of current to desired source position: */
        current = fabs(sp_a[i] - azim) +
                  fabs(sp_e[i] - elev) +
                  fabs(sp_r[i] - radius);
        if (current <= delta) {
            /* if current distance is smaller than smallest distance so far */
            delta = current;
            best_id = i; /* remember index */
        }
    }

    return best_id;
}

static int compensate_volume(AVFilterContext *ctx)
{
    struct SOFAlizerContext *s = ctx->priv;
    float compensate;
    float energy = 0;
    float *ir;
    int m, j;

    if (s->sofa.ncid) {
        /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
        struct NCSofa *sofa = &s->sofa;
        m = find_m(s, 0, 0, 1);
        /* get energy of that IR and compensate volume */
        ir = sofa->data_ir + 2 * m * sofa->n_samples;
        for (j = 0; j < sofa->n_samples; j++) {
            energy += *(ir + j) * *(ir + j);
        }
        compensate = 256 / (sofa->n_samples * sqrt(energy));
        av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
        ir = sofa->data_ir;
        for (j = 0; j < sofa->n_samples * sofa->m_dim * 2; j++) {
            ir[j] *= compensate; /* apply volume compensation to IRs */
        }
    }

    return 0;
}

typedef struct ThreadData {
    AVFrame *in, *out;
    int *write;
    int **delay;
    float **ir;
    int *n_clippings;
    float **ringbuffer;
    float **temp_src;
600
    FFTComplex **temp_fft;
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
} ThreadData;

static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
{
    SOFAlizerContext *s = ctx->priv;
    ThreadData *td = arg;
    AVFrame *in = td->in, *out = td->out;
    int offset = jobnr;
    int *write = &td->write[jobnr];
    const int *const delay = td->delay[jobnr];
    const float *const ir = td->ir[jobnr];
    int *n_clippings = &td->n_clippings[jobnr];
    float *ringbuffer = td->ringbuffer[jobnr];
    float *temp_src = td->temp_src[jobnr];
    const int n_samples = s->sofa.n_samples; /* length of one IR */
    const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
    float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
618
    const int in_channels = s->n_conv; /* number of input channels */
619
    /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
620
    const int buffer_length = s->buffer_length;
621
    /* -1 for AND instead of MODULO (applied to powers of 2): */
622
    const uint32_t modulo = (uint32_t)buffer_length - 1;
623 624 625
    float *buffer[10]; /* holds ringbuffer for each input channel */
    int wr = *write;
    int read;
626
    int i, l;
627 628 629 630 631 632 633 634 635 636 637 638 639

    dst += offset;
    for (l = 0; l < in_channels; l++) {
        /* get starting address of ringbuffer for each input channel */
        buffer[l] = ringbuffer + l * buffer_length;
    }

    for (i = 0; i < in->nb_samples; i++) {
        const float *temp_ir = ir; /* using same set of IRs for each sample */

        *dst = 0;
        for (l = 0; l < in_channels; l++) {
            /* write current input sample to ringbuffer (for each channel) */
640
            *(buffer[l] + wr) = src[l];
641 642
        }

643 644
        /* loop goes through all channels to be convolved */
        for (l = 0; l < in_channels; l++) {
645 646
            const float *const bptr = buffer[l];

647 648 649 650 651 652 653 654
            if (l == s->lfe_channel) {
                /* LFE is an input channel but requires no convolution */
                /* apply gain to LFE signal and add to output buffer */
                *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
                temp_ir += n_samples;
                continue;
            }

655 656 657 658 659
            /* current read position in ringbuffer: input sample write position
             * - delay for l-th ch. + diff. betw. IR length and buffer length
             * (mod buffer length) */
            read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;

660 661 662
            if (read + n_samples < buffer_length) {
                memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
            } else {
663 664 665 666
                int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);

                memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
                memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
667
            }
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

            /* multiply signal and IR, and add up the results */
            dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
            temp_ir += n_samples;
        }

        /* clippings counter */
        if (fabs(*dst) > 1)
            *n_clippings += 1;

        /* move output buffer pointer by +2 to get to next sample of processed channel: */
        dst += 2;
        src += in_channels;
        wr   = (wr + 1) & modulo; /* update ringbuffer write position */
    }

    *write = wr; /* remember write position in ringbuffer for next call */

    return 0;
}

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
{
    SOFAlizerContext *s = ctx->priv;
    ThreadData *td = arg;
    AVFrame *in = td->in, *out = td->out;
    int offset = jobnr;
    int *write = &td->write[jobnr];
    FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
    int *n_clippings = &td->n_clippings[jobnr];
    float *ringbuffer = td->ringbuffer[jobnr];
    const int n_samples = s->sofa.n_samples; /* length of one IR */
    const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
    float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
    const int in_channels = s->n_conv; /* number of input channels */
    /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
    const int buffer_length = s->buffer_length;
    /* -1 for AND instead of MODULO (applied to powers of 2): */
    const uint32_t modulo = (uint32_t)buffer_length - 1;
    FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
    FFTContext *ifft = s->ifft[jobnr];
    FFTContext *fft = s->fft[jobnr];
    const int n_conv = s->n_conv;
    const int n_fft = s->n_fft;
    int wr = *write;
    int n_read;
    int i, j;

    dst += offset;

    /* find minimum between number of samples and output buffer length:
     * (important, if one IR is longer than the output buffer) */
    n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
    for (j = 0; j < n_read; j++) {
        /* initialize output buf with saved signal from overflow buf */
        dst[2 * j]     = ringbuffer[wr];
        ringbuffer[wr] = 0.0; /* re-set read samples to zero */
        /* update ringbuffer read/write position */
        wr  = (wr + 1) & modulo;
    }

    /* initialize rest of output buffer with 0 */
    for (j = n_read; j < in->nb_samples; j++) {
        dst[2 * j] = 0;
    }

    for (i = 0; i < n_conv; i++) {
        if (i == s->lfe_channel) { /* LFE */
            for (j = 0; j < in->nb_samples; j++) {
                /* apply gain to LFE signal and add to output buffer */
                dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
            }
            continue;
        }

        /* outer loop: go through all input channels to be convolved */
        offset = i * n_fft; /* no. samples already processed */

        /* fill FFT input with 0 (we want to zero-pad) */
        memset(fft_in, 0, sizeof(FFTComplex) * n_fft);

        for (j = 0; j < in->nb_samples; j++) {
            /* prepare input for FFT */
            /* write all samples of current input channel to FFT input array */
            fft_in[j].re = src[j * in_channels + i];
        }

        /* transform input signal of current channel to frequency domain */
        av_fft_permute(fft, fft_in);
        av_fft_calc(fft, fft_in);
        for (j = 0; j < n_fft; j++) {
            const float re = fft_in[j].re;
            const float im = fft_in[j].im;

            /* complex multiplication of input signal and HRTFs */
            /* output channel (real): */
            fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
            /* output channel (imag): */
            fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
        }

        /* transform output signal of current channel back to time domain */
        av_fft_permute(ifft, fft_in);
        av_fft_calc(ifft, fft_in);

        for (j = 0; j < in->nb_samples; j++) {
            /* write output signal of current channel to output buffer */
            dst[2 * j] += fft_in[j].re / (float)n_fft;
        }

        for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
            /* write the rest of output signal to overflow buffer */
            int write_pos = (wr + j) & modulo;

            *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
        }
    }

    /* go through all samples of current output buffer: count clippings */
    for (i = 0; i < out->nb_samples; i++) {
        /* clippings counter */
        if (fabs(*dst) > 1) { /* if current output sample > 1 */
            *n_clippings = *n_clippings + 1;
        }

        /* move output buffer pointer by +2 to get to next sample of processed channel: */
        dst += 2;
    }

    /* remember read/write position in ringbuffer for next call */
    *write = wr;

    return 0;
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
    AVFilterContext *ctx = inlink->dst;
    SOFAlizerContext *s = ctx->priv;
    AVFilterLink *outlink = ctx->outputs[0];
    int n_clippings[2] = { 0 };
    ThreadData td;
    AVFrame *out;

    out = ff_get_audio_buffer(outlink, in->nb_samples);
    if (!out) {
        av_frame_free(&in);
        return AVERROR(ENOMEM);
    }
    av_frame_copy_props(out, in);

    td.in = in; td.out = out; td.write = s->write;
    td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
    td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
822
    td.temp_fft = s->temp_fft;
823

824 825 826 827 828
    if (s->type == TIME_DOMAIN) {
        ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
    } else {
        ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
    }
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    emms_c();

    /* display error message if clipping occured */
    if (n_clippings[0] + n_clippings[1] > 0) {
        av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
               n_clippings[0] + n_clippings[1], out->nb_samples * 2);
    }

    av_frame_free(&in);
    return ff_filter_frame(outlink, out);
}

static int query_formats(AVFilterContext *ctx)
{
    struct SOFAlizerContext *s = ctx->priv;
    AVFilterFormats *formats = NULL;
    AVFilterChannelLayouts *layouts = NULL;
    int ret, sample_rates[] = { 48000, -1 };
    static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
                                                AV_CH_LAYOUT_STEREO,
                                                AV_CH_LAYOUT_2POINT1,
                                                AV_CH_LAYOUT_SURROUND,
                                                AV_CH_LAYOUT_2_1,
                                                AV_CH_LAYOUT_4POINT0,
                                                AV_CH_LAYOUT_QUAD,
                                                AV_CH_LAYOUT_2_2,
                                                AV_CH_LAYOUT_3POINT1,
                                                AV_CH_LAYOUT_5POINT0_BACK,
                                                AV_CH_LAYOUT_5POINT0,
                                                AV_CH_LAYOUT_4POINT1,
                                                AV_CH_LAYOUT_5POINT1_BACK,
                                                AV_CH_LAYOUT_5POINT1,
                                                AV_CH_LAYOUT_6POINT0,
                                                AV_CH_LAYOUT_HEXAGONAL,
                                                AV_CH_LAYOUT_6POINT1,
                                                AV_CH_LAYOUT_6POINT1_BACK,
                                                AV_CH_LAYOUT_7POINT0,
                                                AV_CH_LAYOUT_7POINT1,
                                                AV_CH_LAYOUT_OCTAGONAL,
                                                0, };

    ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
    if (ret)
        return ret;
    ret = ff_set_common_formats(ctx, formats);
    if (ret)
        return ret;

    layouts = ff_make_formatu64_list(channel_layouts);
    if (!layouts)
        return AVERROR(ENOMEM);

    ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
    if (ret)
        return ret;

    layouts = NULL;
    ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
    if (ret)
        return ret;

    ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
    if (ret)
        return ret;

    sample_rates[0] = s->sample_rate;
    formats = ff_make_format_list(sample_rates);
    if (!formats)
        return AVERROR(ENOMEM);
    return ff_set_common_samplerates(ctx, formats);
}

static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
{
    struct SOFAlizerContext *s = ctx->priv;
    const int n_samples = s->sofa.n_samples;
905
    int n_conv = s->n_conv; /* no. channels to convolve */
906
    int n_fft = s->n_fft;
907 908 909 910
    int delay_l[10]; /* broadband delay for each IR */
    int delay_r[10];
    int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
    float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
911 912 913 914
    FFTComplex *data_hrtf_l = NULL;
    FFTComplex *data_hrtf_r = NULL;
    FFTComplex *fft_in_l = NULL;
    FFTComplex *fft_in_r = NULL;
915 916 917
    float *data_ir_l = NULL;
    float *data_ir_r = NULL;
    int offset = 0; /* used for faster pointer arithmetics in for-loop */
918
    int m[10]; /* measurement index m of IR closest to required source positions */
919
    int i, j, azim_orig = azim, elev_orig = elev;
920 921 922 923 924 925

    if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
        av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
        return AVERROR_INVALIDDATA;
    }

926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
    if (s->type == TIME_DOMAIN) {
        s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
        s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));

        /* get temporary IR for L and R channel */
        data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
        data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
        if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
            av_free(data_ir_l);
            av_free(data_ir_r);
            return AVERROR(ENOMEM);
        }
    } else {
        /* get temporary HRTF memory for L and R channel */
        data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
        data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
        if (!data_hrtf_r || !data_hrtf_l) {
            av_free(data_hrtf_l);
            av_free(data_hrtf_r);
            return AVERROR(ENOMEM);
        }
947 948 949 950
    }

    for (i = 0; i < s->n_conv; i++) {
        /* load and store IRs and corresponding delays */
951 952
        azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
        elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
953 954 955 956 957 958 959
        /* get id of IR closest to desired position */
        m[i] = find_m(s, azim, elev, radius);

        /* load the delays associated with the current IRs */
        delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
        delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
        if (s->type == TIME_DOMAIN) {
            offset = i * n_samples; /* no. samples already written */
            for (j = 0; j < n_samples; j++) {
                /* load reversed IRs of the specified source position
                 * sample-by-sample for left and right ear; and apply gain */
                *(data_ir_l + offset + j) = /* left channel */
                *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
                *(data_ir_r + offset + j) = /* right channel */
                *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j  + n_samples) * gain_lin;
            }
        } else {
            fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
            fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
            if (!fft_in_l || !fft_in_r) {
                av_free(data_hrtf_l);
                av_free(data_hrtf_r);
                av_free(fft_in_l);
                av_free(fft_in_r);
                return AVERROR(ENOMEM);
            }

            offset = i * n_fft; /* no. samples already written */
            for (j = 0; j < n_samples; j++) {
                /* load non-reversed IRs of the specified source position
                 * sample-by-sample and apply gain,
                 * L channel is loaded to real part, R channel to imag part,
                 * IRs ared shifted by L and R delay */
                fft_in_l[delay_l[i] + j].re = /* left channel */
                *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
                fft_in_r[delay_r[i] + j].re = /* right channel */
                *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
            }

            /* actually transform to frequency domain (IRs -> HRTFs) */
            av_fft_permute(s->fft[0], fft_in_l);
            av_fft_calc(s->fft[0], fft_in_l);
            memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
            av_fft_permute(s->fft[0], fft_in_r);
            av_fft_calc(s->fft[0], fft_in_r);
            memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
1000 1001 1002 1003 1004 1005
        }

        av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
               m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
    }

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    if (s->type == TIME_DOMAIN) {
        /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
        memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
        memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);

        av_freep(&data_ir_l); /* free temporary IR memory */
        av_freep(&data_ir_r);
    } else {
        s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
        s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
        if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
            av_freep(&data_hrtf_l);
            av_freep(&data_hrtf_r);
            av_freep(&fft_in_l);
            av_freep(&fft_in_r);
            return AVERROR(ENOMEM); /* memory allocation failed */
        }

        memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
            sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
        memcpy(s->data_hrtf[1], data_hrtf_r,
            sizeof(FFTComplex) * n_conv * n_fft);
1028

1029 1030 1031 1032 1033 1034
        av_freep(&data_hrtf_l); /* free temporary HRTF memory */
        av_freep(&data_hrtf_r);

        av_freep(&fft_in_l); /* free temporary FFT memory */
        av_freep(&fft_in_r);
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

    memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
    memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);

    return 0;
}

static av_cold int init(AVFilterContext *ctx)
{
    SOFAlizerContext *s = ctx->priv;
    int ret;

    /* load SOFA file, */
    /* initialize file IDs to 0 before attempting to load SOFA files,
     * this assures that in case of error, only the memory of already
     * loaded files is free'd */
    s->sofa.ncid = 0;
    ret = load_sofa(ctx, s->filename, &s->sample_rate);
    if (ret) {
        /* file loading error */
        av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
    } else { /* no file loading error, resampling not required */
        av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
    }

    if (ret) {
        av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
        return ret;
    }

    s->fdsp = avpriv_float_dsp_alloc(0);
    if (!s->fdsp)
        return AVERROR(ENOMEM);

    return 0;
}

static inline unsigned clz(unsigned x)
{
    unsigned i = sizeof(x) * 8;

    while (x) {
        x >>= 1;
        i--;
    }

    return i;
}

static int config_input(AVFilterLink *inlink)
{
    AVFilterContext *ctx = inlink->dst;
    SOFAlizerContext *s = ctx->priv;
    int nb_input_channels = inlink->channels; /* no. input channels */
    int n_max_ir = 0;
    int n_current;
    int n_max = 0;
    int ret;

1094 1095 1096 1097 1098 1099
    if (s->type == FREQUENCY_DOMAIN) {
        inlink->partial_buf_size =
        inlink->min_samples =
        inlink->max_samples = inlink->sample_rate;
    }

1100 1101 1102
    /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
    s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);

1103
    s->n_conv = nb_input_channels;
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

    /* get size of ringbuffer (longest IR plus max. delay) */
    /* then choose next power of 2 for performance optimization */
    n_current = s->sofa.n_samples + max_delay(&s->sofa);
    if (n_current > n_max) {
        /* length of longest IR plus max. delay (in all SOFA files) */
        n_max = n_current;
        /* length of longest IR (without delay, in all SOFA files) */
        n_max_ir = s->sofa.n_samples;
    }
    /* buffer length is longest IR plus max. delay -> next power of 2
       (32 - count leading zeros gives required exponent)  */
    s->buffer_length = exp2(32 - clz((uint32_t)n_max));
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    s->n_fft         = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));

    if (s->type == FREQUENCY_DOMAIN) {
        av_fft_end(s->fft[0]);
        av_fft_end(s->fft[1]);
        s->fft[0] = av_fft_init(log2(s->n_fft), 0);
        s->fft[1] = av_fft_init(log2(s->n_fft), 0);
        av_fft_end(s->ifft[0]);
        av_fft_end(s->ifft[1]);
        s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
        s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1128 1129 1130 1131 1132

        if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
            av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts.\n");
            return AVERROR(ENOMEM);
        }
1133
    }
1134 1135

    /* Allocate memory for the impulse responses, delays and the ringbuffers */
1136
    /* size: (longest IR) * (number of channels to convolute) */
1137 1138 1139 1140 1141 1142 1143 1144
    s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
    s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
    /* length:  number of channels to convolute */
    s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
    s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
    /* length: (buffer length) * (number of input channels),
     * OR: buffer length (if frequency domain processing)
     * calloc zero-initializes the buffer */
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    if (s->type == TIME_DOMAIN) {
        s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
        s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
    } else {
        s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
        s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
        s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
        s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
        if (!s->temp_fft[0] || !s->temp_fft[1])
            return AVERROR(ENOMEM);
    }

1158
    /* length: number of channels to convolute */
1159 1160
    s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
    s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1161 1162 1163 1164

    /* memory allocation failed: */
    if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
        !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1165
        !s->speaker_azim || !s->speaker_elev)
1166 1167 1168 1169 1170
        return AVERROR(ENOMEM);

    compensate_volume(ctx);

    /* get speaker positions */
1171
    if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1172 1173 1174
        av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
        return ret;
    }
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    /* load IRs to data_ir[0] and data_ir[1] for required directions */
    if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
        return ret;

    av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
        inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);

    return 0;
}

static av_cold void uninit(AVFilterContext *ctx)
{
    SOFAlizerContext *s = ctx->priv;

    if (s->sofa.ncid) {
        av_freep(&s->sofa.sp_a);
        av_freep(&s->sofa.sp_e);
        av_freep(&s->sofa.sp_r);
        av_freep(&s->sofa.data_delay);
        av_freep(&s->sofa.data_ir);
    }
1197 1198 1199 1200
    av_fft_end(s->ifft[0]);
    av_fft_end(s->ifft[1]);
    av_fft_end(s->fft[0]);
    av_fft_end(s->fft[1]);
1201 1202 1203 1204 1205 1206
    av_freep(&s->delay[0]);
    av_freep(&s->delay[1]);
    av_freep(&s->data_ir[0]);
    av_freep(&s->data_ir[1]);
    av_freep(&s->ringbuffer[0]);
    av_freep(&s->ringbuffer[1]);
1207 1208
    av_freep(&s->speaker_azim);
    av_freep(&s->speaker_elev);
1209 1210
    av_freep(&s->temp_src[0]);
    av_freep(&s->temp_src[1]);
1211 1212 1213 1214
    av_freep(&s->temp_fft[0]);
    av_freep(&s->temp_fft[1]);
    av_freep(&s->data_hrtf[0]);
    av_freep(&s->data_hrtf[1]);
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    av_freep(&s->fdsp);
}

#define OFFSET(x) offsetof(SOFAlizerContext, x)
#define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM

static const AVOption sofalizer_options[] = {
    { "sofa",      "sofa filename",  OFFSET(filename),  AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
    { "gain",      "set gain in dB", OFFSET(gain),      AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
    { "rotation",  "set rotation"  , OFFSET(rotation),  AV_OPT_TYPE_FLOAT,  {.dbl=0},    -360, 360, .flags = FLAGS },
    { "elevation", "set elevation",  OFFSET(elevation), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -90,  90, .flags = FLAGS },
    { "radius",    "set radius",     OFFSET(radius),    AV_OPT_TYPE_FLOAT,  {.dbl=1},       0,   3, .flags = FLAGS },
1227 1228 1229
    { "type",      "set processing", OFFSET(type),      AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
    { "time",      "time domain",      0,               AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
    { "freq",      "frequency domain", 0,               AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    { NULL }
};

AVFILTER_DEFINE_CLASS(sofalizer);

static const AVFilterPad inputs[] = {
    {
        .name         = "default",
        .type         = AVMEDIA_TYPE_AUDIO,
        .config_props = config_input,
        .filter_frame = filter_frame,
    },
    { NULL }
};

static const AVFilterPad outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_AUDIO,
    },
    { NULL }
};

AVFilter ff_af_sofalizer = {
    .name          = "sofalizer",
    .description   = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
    .priv_size     = sizeof(SOFAlizerContext),
    .priv_class    = &sofalizer_class,
    .init          = init,
    .uninit        = uninit,
    .query_formats = query_formats,
    .inputs        = inputs,
    .outputs       = outputs,
    .flags         = AVFILTER_FLAG_SLICE_THREADS,
};