[FFmpeg-devel] [RFC][WIP][PATCH] avfilter: add SOFAlizer audio filter
Paul B Mahol
onemda at gmail.com
Thu Dec 10 00:43:58 CET 2015
Signed-off-by: Paul B Mahol <onemda at gmail.com>
---
libavfilter/Makefile | 1 +
libavfilter/af_sofalizer.c | 816 +++++++++++++++++++++++++++++++++++++++++++++
libavfilter/allfilters.c | 1 +
3 files changed, 818 insertions(+)
create mode 100644 libavfilter/af_sofalizer.c
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 8884d1d..d7a3f61 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -87,6 +87,7 @@ OBJS-$(CONFIG_SIDECHAINCOMPRESS_FILTER) += af_sidechaincompress.o
OBJS-$(CONFIG_SIDECHAINGATE_FILTER) += af_agate.o
OBJS-$(CONFIG_SILENCEDETECT_FILTER) += af_silencedetect.o
OBJS-$(CONFIG_SILENCEREMOVE_FILTER) += af_silenceremove.o
+OBJS-$(CONFIG_SOFALIZER_FILTER) += af_sofalizer.o
OBJS-$(CONFIG_STEREOTOOLS_FILTER) += af_stereotools.o
OBJS-$(CONFIG_STEREOWIDEN_FILTER) += af_stereowiden.o
OBJS-$(CONFIG_TREBLE_FILTER) += af_biquads.o
diff --git a/libavfilter/af_sofalizer.c b/libavfilter/af_sofalizer.c
new file mode 100644
index 0000000..8e4da74
--- /dev/null
+++ b/libavfilter/af_sofalizer.c
@@ -0,0 +1,816 @@
+/*****************************************************************************
+ * 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 at gmail.com>
+ * Wolfgang Hrauda <wolfgang.hrauda at gmx.at>
+ *
+ * SOFAlizer project coordinator at ARI, main developer of SOFA:
+ * Piotr Majdak <piotr at 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 <netcdf.h>
+
+#include "libavutil/opt.h"
+#include "avfilter.h"
+#include "internal.h"
+#include "audio.h"
+
+#define N_SOFA 3 /* no. SOFA files loaded (for instant comparison) */
+#define N_POSITIONS 4 /* no. virtual source positions (advanced settings) */
+
+typedef struct NCSofa { /* contains data of one SOFA file */
+ int i_ncid; /* netCDF ID of the opened SOFA file */
+ int i_n_samples; /* length of one impulse response (IR) */
+ int i_m_dim; /* number of measurement positions */
+ int *pi_data_delay; /* broadband delay of each IR */
+ /* all measurement positions for each receiver (i.e. ear): */
+ float *pf_sp_a; /* azimuth angles */
+ float *pf_sp_e; /* elevation angles */
+ float *pf_sp_r; /* radii */
+ /* dataat at each measurement position for each receiver: */
+ float *pf_data_ir; /* IRs (time-domain) */
+} NCSofa;
+
+typedef struct SOFAlizerContext {
+ const AVClass *class;
+
+ char *filename[N_SOFA];
+ struct NCSofa sofa[N_SOFA]; /* contains data of the SOFA files */
+
+ float *pf_speaker_pos; /* positions of the virtual loudspekaers */
+ float f_gain_lfe;
+
+ int i_n_conv; /* number of channels to convolute */
+ int i_n_clippings_l;
+ int i_n_clippings_r;
+
+ /* buffer variables (for convolution) */
+ float *pf_ringbuffer_l; /* buffers input samples, length of one buffer: */
+ float *pf_ringbuffer_r; /* no. input ch. (incl. LFE) x i_buffer_length */
+ int i_write_l; /* current write position to ringbuffer */
+ int i_write_r; /* current write position to ringbuffer */
+ int i_buffer_length; /* is: longest IR plus max. delay in all SOFA files */
+ /* then choose next power of 2 */
+ int i_n_longest_filter; /* longest IR + max. delay in all SOFA files */
+ int i_output_buffer_length; /* remember no. samples in output buffer */
+
+ /* netCDF variables */
+ int i_sofa_id; /* selected SOFA file */
+ int *pi_delay_l; /* broadband delay for each channel/IR to be convolved */
+ int *pi_delay_r;
+ float *pf_data_ir_l; /* IRs for all channels to be convolved */
+ float *pf_data_ir_r; /* (this excludes the LFE) */
+
+ /* control variables */
+ float f_gain; /* filter gain (in dB) */
+ float f_rotation; /* rotation of virtual loudspeakers (in degrees) */
+ float f_elevation; /* elevation of virtual loudspeakers (in deg.) */
+ float f_radius; /* distance virtual loudspeakers to listener (in metres) */
+ int i_switch; /* 0: source positions according to input format plus */
+ /* user's rotation and elevation settings, */
+ /* 1-4: virtual source pos. defined in advanced settings */
+ /* - from advanced settings: virtual source positions: */
+ int pi_azimuth_array[N_POSITIONS]; /* azimuth angles (in deg.) */
+ int pi_elevation_array[N_POSITIONS]; /* elevation angles (in deg.) */
+
+ int lfe; /* whether or not the LFE channel is used */
+} SOFAlizerContext;
+
+static int close_sofa(struct NCSofa *sofa)
+{
+ av_freep(&sofa->pi_data_delay);
+ av_freep(&sofa->pf_sp_a);
+ av_freep(&sofa->pf_sp_e);
+ av_freep(&sofa->pf_sp_r);
+ av_freep(&sofa->pf_data_ir);
+ nc_close(sofa->i_ncid);
+ sofa->i_ncid = 0;
+ return 0;
+}
+
+static int load_sofa(AVFilterContext *ctx, char *filename,
+ int i_sofa_id , int *samplingrate)
+{
+ struct SOFAlizerContext *s = ctx->priv;
+ /* variables associated with content of SOFA file: */
+ int i_ncid, i_n_dims, i_n_vars, i_n_gatts, i_n_unlim_dim_id, i_status;
+ unsigned int i_samplingrate;
+ int i_n_samples = 0;
+ int i_m_dim = 0;
+ s->sofa[i_sofa_id].i_ncid = 0;
+ i_status = nc_open( filename , NC_NOWRITE, &i_ncid); /* open SOFA file read-only */
+ if (i_status != NC_NOERR)
+ {
+ av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
+ return -1;
+ }
+ /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
+ nc_inq(i_ncid, &i_n_dims, &i_n_vars, &i_n_gatts, &i_n_unlim_dim_id);
+
+ /* -- get number of measurements ("M") and length of one IR ("N") -- */
+ char psz_dim_names[i_n_dims][NC_MAX_NAME]; /* names of netCDF dimensions */
+ size_t pi_dim_length[i_n_dims]; /* lengths of netCDF dimensions */
+ int i_m_dim_id = -1;
+ int i_n_dim_id = -1;
+ for( int i = 0; i < i_n_dims; i++ ) /* go through all dimensions of file */
+ {
+ nc_inq_dim( i_ncid, i, psz_dim_names[i], &pi_dim_length[i] ); /* get dimensions */
+ if ( !strncmp("M", psz_dim_names[i], 1 ) ) /* get ID of dimension "M" */
+ i_m_dim_id = i;
+ if ( !strncmp("N", psz_dim_names[i], 1 ) ) /* get ID of dimension "N" */
+ i_n_dim_id = i;
+ }
+ if( ( i_m_dim_id == -1 ) || ( i_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");
+ nc_close(i_ncid);
+ return -1;
+ }
+ i_n_samples = pi_dim_length[i_n_dim_id]; /* get number of measurements */
+ i_m_dim = pi_dim_length[i_m_dim_id]; /* get length of one IR */
+
+ /* -- check file type -- */
+ size_t i_att_len; /* get length of attritube "Conventions" */
+ i_status = nc_inq_attlen(i_ncid, NC_GLOBAL, "Conventions", &i_att_len);
+ if (i_status != NC_NOERR)
+ {
+ av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
+ nc_close(i_ncid);
+ return -1;
+ }
+ char psz_conventions[i_att_len + 1]; /* check whether file is SOFA file */
+ nc_get_att_text(i_ncid , NC_GLOBAL, "Conventions", psz_conventions);
+ *( psz_conventions + i_att_len ) = 0;
+ if ( strncmp( "SOFA" , psz_conventions, 4 ) )
+ {
+ av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
+ nc_close(i_ncid);
+ return -1;
+ }
+
+ /* -- check if attribute "SOFAConventions" is "SimpleFreeFieldHRIR": -- */
+ nc_inq_attlen (i_ncid, NC_GLOBAL, "SOFAConventions", &i_att_len );
+ char psz_sofa_conventions[i_att_len + 1];
+ nc_get_att_text(i_ncid, NC_GLOBAL, "SOFAConventions", psz_sofa_conventions);
+ *( psz_sofa_conventions + i_att_len ) = 0;
+ if ( strncmp( "SimpleFreeFieldHRIR" , psz_sofa_conventions, i_att_len ) )
+ {
+ av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
+ nc_close(i_ncid);
+ return -1;
+ }
+
+ /* -- get sampling rate of HRTFs -- */
+ int i_samplingrate_id; /* read ID, then value */
+ i_status = nc_inq_varid( i_ncid, "Data.SamplingRate", &i_samplingrate_id);
+ i_status += nc_get_var_uint( i_ncid, i_samplingrate_id, &i_samplingrate );
+ if (i_status != NC_NOERR)
+ {
+ av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
+ nc_close(i_ncid);
+ return -1;
+ }
+ *samplingrate = i_samplingrate; /* remember sampling rate */
+
+ /* -- allocate memory for one value for each measurement position: -- */
+ float *pf_sp_a = s->sofa[i_sofa_id].pf_sp_a = av_malloc(sizeof(float) * i_m_dim);
+ float *pf_sp_e = s->sofa[i_sofa_id].pf_sp_e = av_malloc(sizeof(float) * i_m_dim);
+ float *pf_sp_r = s->sofa[i_sofa_id].pf_sp_r = av_malloc(sizeof(float) * i_m_dim);
+ /* delay and IR values required for each ear and measurement position: */
+ int *pi_data_delay = s->sofa[i_sofa_id].pi_data_delay =
+ av_calloc (i_m_dim * 2, sizeof(int));
+ float *pf_data_ir = s->sofa[i_sofa_id].pf_data_ir =
+ av_malloc(sizeof(float) * 2 * i_m_dim * i_n_samples);
+
+ if (!pi_data_delay || !pf_sp_a || !pf_sp_e || !pf_sp_r || !pf_data_ir) {
+ /* if memory could not be allocated */
+ close_sofa( &s->sofa[i_sofa_id] );
+ return AVERROR(ENOMEM);
+ }
+
+ /* get impulse responses (HRTFs): */
+ int i_data_ir_id; /* get corresponding ID */
+ i_status = nc_inq_varid( i_ncid, "Data.IR", &i_data_ir_id);
+ i_status += nc_get_var_float( i_ncid, i_data_ir_id, pf_data_ir); /* read and store IRs */
+ if (i_status != NC_NOERR) {
+ av_log( ctx, AV_LOG_ERROR, "Couldn't read Data.IR!" );
+ goto error;
+ }
+
+ /* get source positions of the HRTFs in the SOFA file: */
+ int i_sp_id;
+ i_status = nc_inq_varid(i_ncid, "SourcePosition", &i_sp_id); /* get corresponding ID */
+ i_status += nc_get_vara_float (i_ncid, i_sp_id, (size_t[2]){ 0 , 0 } ,
+ (size_t[2]){ i_m_dim , 1 } , pf_sp_a ); /* read & store azimuth angles */
+ i_status += nc_get_vara_float (i_ncid, i_sp_id, (size_t[2]){ 0 , 1 } ,
+ (size_t[2]){ i_m_dim , 1 } , pf_sp_e ); /* read & store elevation angles */
+ i_status += nc_get_vara_float (i_ncid, i_sp_id, (size_t[2]){ 0 , 2 } ,
+ (size_t[2]){ i_m_dim , 1 } , pf_sp_r ); /* read & store radii */
+ if (i_status != NC_NOERR) { /* if any source position variable coudn't be read */
+ av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
+ goto error;
+ }
+
+ /* read Data.Delay, check for errors and fit it to pi_data_delay */
+ int i_data_delay_id;
+ int pi_data_delay_dim_id[2];
+ char psz_data_delay_dim_name[NC_MAX_NAME];
+
+ i_status = nc_inq_varid(i_ncid, "Data.Delay", &i_data_delay_id);
+ i_status += nc_inq_vardimid ( i_ncid, i_data_delay_id, &pi_data_delay_dim_id[0]);
+ i_status += nc_inq_dimname ( i_ncid, pi_data_delay_dim_id[0], psz_data_delay_dim_name );
+ if (i_status != NC_NOERR) {
+ av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
+ goto error;
+ }
+
+ /* Data.Delay dimension check */
+ /* dimension of Data.Delay is [I R]: */
+ if (!strncmp(psz_data_delay_dim_name, "I", 2)) {
+ /* check 2 characters to assure string is 0-terminated after "I" */
+ int pi_Delay[2]; /* delays get from SOFA file: */
+ av_log ( ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n" );
+ i_status = nc_get_var_int( i_ncid, i_data_delay_id, &pi_Delay[0] );
+ if ( i_status != NC_NOERR )
+ {
+ av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
+ goto error;
+ }
+ int *pi_data_delay_r = pi_data_delay + i_m_dim;
+ for ( int i = 0 ; i < i_m_dim ; i++ ) /* extend given dimension [I R] to [M R] */
+ { /* assign constant delay value for all measurements to data_delay fields */
+ *( pi_data_delay + i ) = pi_Delay[0];
+ *( pi_data_delay_r + i ) = pi_Delay[1];
+ }
+ /* dimension of Data.Delay is [M R] */
+ } else if (!strncmp(psz_data_delay_dim_name, "M", 2)) {
+ av_log( ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
+ /* get delays from SOFA file: */
+ i_status = nc_get_var_int( i_ncid, i_data_delay_id, pi_data_delay );
+ if (i_status != NC_NOERR)
+ {
+ av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
+ 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");
+ goto error;
+ }
+
+ /* save information in SOFA struct: */
+ s->sofa[i_sofa_id].i_m_dim = i_m_dim; /* no. measurement positions */
+ s->sofa[i_sofa_id].i_n_samples = i_n_samples; /* length on one IR */
+ s->sofa[i_sofa_id].i_ncid = i_ncid; /* netCDF ID of SOFA file */
+ nc_close(i_ncid); /* close SOFA file */
+
+ return 0;
+
+error:
+ close_sofa( &s->sofa[i_sofa_id] );
+ return -1;
+}
+
+static int get_speaker_pos(AVFilterContext *ctx, float *pf_speaker_pos )
+{
+ /* get input channel configuration: */
+ uint64_t i_physical_channels = ctx->inputs[0]->channel_layout;
+ float *pf_pos_temp;
+ int i_input_nb = ctx->inputs[0]->channels; /* get no. input channels */
+ int i_n_conv = i_input_nb;
+ if (i_physical_channels & AV_CH_LOW_FREQUENCY) { /* if LFE is used */
+ /* decrease number of channels to be convolved: */
+ i_n_conv = i_input_nb - 1;
+ }
+
+ /* set speaker positions according to input channel configuration: */
+ switch (i_physical_channels) {
+ case AV_CH_LAYOUT_MONO:
+ pf_pos_temp = (float[1]){ 0 };
+ break;
+ case AV_CH_LAYOUT_STEREO:
+ case AV_CH_LAYOUT_2_1:
+ pf_pos_temp = (float[2]){ 30 , 330 };
+ break;
+ case AV_CH_LAYOUT_SURROUND:
+ case AV_CH_LAYOUT_3POINT1:
+ pf_pos_temp = (float[3]){ 30 , 330 , 0 };
+ break;
+ case AV_CH_LAYOUT_4POINT0:
+ case AV_CH_LAYOUT_4POINT1: pf_pos_temp = (float[4]){ 30 , 330 , 120 , 240 };
+ break;
+ case AV_CH_LAYOUT_5POINT0:
+ case AV_CH_LAYOUT_5POINT1:
+ pf_pos_temp = (float[5]){ 30 , 330 , 120 , 240 , 0 };
+ break;
+ case AV_CH_LAYOUT_6POINT0:
+ pf_pos_temp = (float[6]){ 30 , 330 , 90 , 270 , 150 , 210 };
+ break;
+ case AV_CH_LAYOUT_7POINT0:
+ case AV_CH_LAYOUT_7POINT1:
+ pf_pos_temp = (float[7]){ 30 , 330 , 90 , 270 , 150 , 210 , 0 };
+ break;
+ //case AV_CH_LAYOUT_8POINT1:
+ // pf_pos_temp = (float[8]){ 30 , 330 , 90 , 270 , 150 , 210 , 180 , 0 };
+ // break;
+ default:
+ return -1;
+ }
+
+ memcpy(pf_speaker_pos, pf_pos_temp, i_n_conv * sizeof(float));
+
+ return 0;
+
+}
+
+static int MaxDelay ( struct NCSofa *sofa )
+{
+ int i_max = 0;
+ for ( int i = 0; i < ( sofa->i_m_dim * 2 ) ; i++ )
+ { /* search maximum delay in given SOFA file */
+ if ( *( sofa->pi_data_delay + i ) > i_max )
+ i_max = *( sofa->pi_data_delay + i) ;
+ }
+ return i_max;
+}
+
+static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
+{
+ /* get source positions and M of currently selected SOFA file */
+ float *pf_sp_a = s->sofa[s->i_sofa_id].pf_sp_a; /* azimuth angle */
+ float *pf_sp_e = s->sofa[s->i_sofa_id].pf_sp_e; /* elevation angle */
+ float *pf_sp_r = s->sofa[s->i_sofa_id].pf_sp_r; /* radius */
+ int i_m_dim = s->sofa[s->i_sofa_id].i_m_dim; /* no. measurements */
+
+ int i_best_id = 0; /* index m currently closest to desired source pos. */
+ float delta = 1000; /* offset between desired and currently best pos. */
+ float f_current;
+ for ( int i = 0; i < i_m_dim ; i++ )
+ { /* search through all measurements in currently selected SOFA file */
+ /* distance of current to desired source position: */
+ f_current = fabs ( *(pf_sp_a++) - azim )
+ + fabs( *(pf_sp_e++) - elev )
+ + fabs( *(pf_sp_r++) - radius );
+ if ( f_current <= delta )
+ { /* if current distance is smaller than smallest distance so far */
+ delta = f_current;
+ i_best_id = i; /* remember index */
+ }
+ }
+ return i_best_id;
+}
+
+static int compensate_volume(AVFilterContext *ctx)
+{
+ struct SOFAlizerContext *s = ctx->priv;
+ float f_energy = 0;
+ int i_m;
+ int i_sofa_id_backup = s->i_sofa_id;
+ float *pf_ir;
+ float f_compensate;
+ /* compensate volume for each SOFA file */
+ for ( int i = 0 ; i < N_SOFA ; i++ ) { /* go through all SOFA files */
+ if( s->sofa[i].i_ncid ) {
+ /* find IR at front center position in i-th SOFA file (IR closest to 0°,0°,1m) */
+ struct NCSofa *p_sofa = &s->sofa[i];
+ s->i_sofa_id = i;
+ i_m = find_m( s, 0, 0, 1 );
+ /* get energy of that IR and compensate volume */
+ pf_ir = p_sofa->pf_data_ir + 2 * i_m * p_sofa->i_n_samples;
+ for (int j = 0 ; j < p_sofa->i_n_samples ; j++) {
+ f_energy += *(pf_ir + j ) * *(pf_ir + j);
+ }
+ f_compensate = 256 / (p_sofa->i_n_samples * sqrt(f_energy));
+ av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", f_compensate);
+ pf_ir = p_sofa->pf_data_ir;
+ for (int j = 0; j < ( p_sofa->i_n_samples * p_sofa->i_m_dim * 2 ) ; j++) {
+ *( pf_ir + j ) *= f_compensate; /* apply volume compensation to IRs */
+ }
+ }
+ }
+
+ s->i_sofa_id = i_sofa_id_backup;
+
+ return 0;
+}
+
+static void sofalizer_convolute(SOFAlizerContext *s, AVFrame *in, AVFrame *out, int offset,
+ int *write, int *delay, float *pf_ir, int *i_n_clippings,
+ float *ringbuffer)
+{
+ int i_n_samples = s->sofa[s->i_sofa_id].i_n_samples; /* length of one IR */
+ const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
+ float *pf_temp_ir;
+ float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
+ int i_read;
+ int i_input_nb = in->channels; /* number of input channels */
+ /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
+ int i_buffer_length = s->i_buffer_length;
+ /* -1 for AND instead of MODULO (applied to powers of 2): */
+ uint32_t i_modulo = (uint32_t) i_buffer_length - 1;
+ float *pf_ringbuffer[i_input_nb]; /* holds ringbuffer for each input channel */
+
+ dst += offset;
+ for (int l = 0 ; l < i_input_nb ; l++ ) {
+ /* get starting address of ringbuffer for each input channel */
+ pf_ringbuffer[l] = ringbuffer + l * i_buffer_length ;
+ }
+ int i_write = *write;
+
+ for (int i = 0; i < in->nb_samples; i++)
+ { /* i is not used as an index in the loop! */
+ *(dst) = 0;
+ for ( int l = 0 ; l < i_input_nb ; l++ )
+ { /* write current input sample to ringbuffer (for each channel) */
+ *( pf_ringbuffer[l] + i_write ) = *src++;
+ }
+ pf_temp_ir = pf_ir; /* using same set of IRs for each sample */
+ /* loop goes through all channels to be convolved (excl. LFE): */
+ for ( int l = 0 ; l < s->i_n_conv ; l++ )
+ {
+ /* current read position in ringbuffer: input sample write position
+ * - delay for l-th ch. + diff. betw. IR length and buffer length
+ * (mod buffer length) */
+ i_read = (i_write - *(delay + l) -
+ (i_n_samples - 1 ) + i_buffer_length ) & i_modulo;
+
+ for (int j = 0; j < i_n_samples; j++) { /* go through samples of IR */
+ /* multiply signal and IR, and add up the results */
+ *dst += *(pf_ringbuffer[l] + ((i_read++) & i_modulo)) * *(pf_temp_ir++);
+ }
+ }
+ if (s->lfe) { /* LFE */
+ /* apply gain to LFE signal and add to output buffer */
+ *dst += *( pf_ringbuffer[s->i_n_conv] + i_write ) * s->f_gain_lfe;
+ }
+ /* clippings counter */
+ if (fabs(*dst) >= 1)
+ *i_n_clippings += 1;
+
+ /* move output buffer pointer by +2 to get to next sample of processed channel: */
+ dst += 2;
+ i_write = ( i_write + 1 ) & i_modulo; /* update ringbuffer write position */
+ }
+
+ *write = i_write; /* remember write position in ringbuffer for next call */
+
+ return;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+ AVFilterContext *ctx = inlink->dst;
+ SOFAlizerContext *s = ctx->priv;
+ AVFilterLink *outlink = ctx->outputs[0];
+ 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);
+
+ /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
+ s->f_gain_lfe = expf((s->f_gain - 3 * inlink->channels - 6) / 20 * logf(10));
+
+ sofalizer_convolute(s, in, out, 0, &s->i_write_l,
+ s->pi_delay_l, s->pf_data_ir_l,
+ &s->i_n_clippings_l,
+ s->pf_ringbuffer_l);
+ sofalizer_convolute(s, in, out, 1, &s->i_write_r,
+ s->pi_delay_r, s->pf_data_ir_r,
+ &s->i_n_clippings_r,
+ s->pf_ringbuffer_r);
+
+ /* display error message if clipping occured */
+ if (s->i_n_clippings_l + s->i_n_clippings_r > 0 ) {
+ av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.",
+ s->i_n_clippings_l + s->i_n_clippings_r, out->nb_samples * 2);
+ }
+
+ av_frame_free(&in);
+ return ff_filter_frame(outlink, out);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+ AVFilterFormats *formats = NULL;
+ AVFilterChannelLayouts *layouts = NULL;
+ static int sample_rates[] = { 48000, -1 };
+ int ret;
+
+ ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
+ if (ret)
+ return ret;
+ ret = ff_set_common_formats(ctx, formats);
+ if (ret)
+ return ret;
+
+ ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_5POINT0);
+ if (ret)
+ return ret;
+ ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_5POINT1);
+ if (ret)
+ return ret;
+
+ 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;
+
+ 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 i_azim, int i_elev, float f_radius)
+{
+ struct SOFAlizerContext *s = ctx->priv;
+ if (!s->sofa[s->i_sofa_id].i_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." );
+ return -1;
+ }
+ const int i_n_samples = s->sofa[s->i_sofa_id].i_n_samples;
+ int i_n_conv = s->i_n_conv; /* no. channels to convolve (excl. LFE) */
+ int pi_delay_l[i_n_conv]; /* broadband delay for each IR */
+ int pi_delay_r[i_n_conv];
+ int i_input_nb = ctx->inputs[0]->channels; /* no. input channels */
+ float f_gain_lin = expf( (s->f_gain - 3 * i_input_nb) / 20 * logf(10) ); /* gain - 3dB/channel */
+
+ float *pf_data_ir_l = NULL;
+ float *pf_data_ir_r = NULL;
+
+ /* get temporary IR for L and R channel */
+ pf_data_ir_l = av_malloc(sizeof(float) * i_n_conv * i_n_samples);
+ pf_data_ir_r = av_malloc(sizeof(float) * i_n_conv * i_n_samples);
+ if (!pf_data_ir_r || !pf_data_ir_l)
+ return AVERROR(ENOMEM);
+
+ int i_offset = 0; /* used for faster pointer arithmetics in for-loop */
+
+ int i_m[s->i_n_conv]; /* measurement index m of IR closest to required source positions */
+ if (s->i_switch) { /* if switch not 0, use pre-defined virtual source positions */
+ i_azim = s->pi_azimuth_array[s->i_switch - 1];
+ i_elev = s->pi_elevation_array[s->i_switch -1];
+ }
+ int i_azim_orig = i_azim;
+
+ for ( int i = 0; i < s->i_n_conv; i++ ) {
+ /* load and store IRs and corresponding delays */
+ i_azim = (int)( s->pf_speaker_pos[i] + i_azim_orig ) % 360;
+ /* get id of IR closest to desired position */
+ i_m[i] = find_m( s, i_azim, i_elev, f_radius );
+
+ /* load the delays associated with the current IRs */
+ pi_delay_l[i] = *( s->sofa[s->i_sofa_id].pi_data_delay + 2 * i_m[i] );
+ pi_delay_r[i] = *( s->sofa[s->i_sofa_id].pi_data_delay + 2 * i_m[i] + 1);
+
+ i_offset = i * i_n_samples; /* no. samples already written */
+ for (int j = 0; j < i_n_samples; j++) {
+ /* load reversed IRs of the specified source position
+ * sample-by-sample for left and right ear; and apply gain */
+ *( pf_data_ir_l + i_offset + j ) = /* left channel */
+ *( s->sofa[s->i_sofa_id].pf_data_ir +
+ 2 * i_m[i] * i_n_samples + i_n_samples - 1 - j ) * f_gain_lin;
+ *( pf_data_ir_r + i_offset + j ) = /* right channel */
+ *( s->sofa[s->i_sofa_id].pf_data_ir +
+ 2 * i_m[i] * i_n_samples + i_n_samples - 1 - j + i_n_samples ) * f_gain_lin;
+ }
+
+ av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
+ i_m[i], *(s->sofa[s->i_sofa_id].pf_sp_a + i_m[i]),
+ *(s->sofa[s->i_sofa_id].pf_sp_e + i_m[i]),
+ *(s->sofa[s->i_sofa_id].pf_sp_r + i_m[i]) );
+ }
+
+ /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
+ memcpy(s->pf_data_ir_l, pf_data_ir_l,
+ sizeof(float) * i_n_conv * i_n_samples);
+ memcpy(s->pf_data_ir_r, pf_data_ir_r,
+ sizeof(float) * i_n_conv * i_n_samples);
+
+ av_free(pf_data_ir_l); /* free temporary IR memory */
+ av_free(pf_data_ir_r);
+
+ memcpy(s->pi_delay_l, &pi_delay_l[0], sizeof(int) * s->i_n_conv);
+ memcpy(s->pi_delay_r, &pi_delay_r[0], sizeof(int) * s->i_n_conv);
+
+ 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 i_samplingrate = 0; /* get sampling rate of audio file/stream: */
+ int i_status = 0; /* zero, if no file could be loaded */
+
+ /* load SOFA files, resample if sampling rate different from audio file */
+ for (int i = 0; i < N_SOFA; i++) {
+ /* 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 ( e.g. in FreeAllSofa() ) */
+ s->sofa[i].i_ncid = 0;
+ }
+ for (int i = 0; i < N_SOFA; i++ ) {
+ if ( load_sofa( ctx, s->filename[i], i , &i_samplingrate) != 0 )
+ { /* file loading error */
+ av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file %d: '%s'\n", i + 1, s->filename[i] );
+ } else { /* no file loading error, resampling not required */
+ av_log(ctx, AV_LOG_DEBUG, "File %d: '%s' loaded.\n", i + 1 , s->filename[i] );
+ i_status++; /* increase status after successful file loading */
+ }
+ }
+ if (!i_status) {
+ av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify at least one valid SOFA file.\n" );
+ return -1;
+ }
+
+ int i_input_nb = inlink->channels; /* no. input channels */
+ if (inlink->channel_layout & AV_CH_LOW_FREQUENCY) { /* if LFE is used */
+ s->lfe = 1;
+ s->i_n_conv = i_input_nb - 1 ; /* LFE is an input channel but requires no convolution */
+ } else /* if LFE is not used */ {
+ s->lfe = 0;
+ s->i_n_conv = i_input_nb ;
+ }
+
+ /* get size of ringbuffer (longest IR plus max. delay) */
+ /* then choose next power of 2 for performance optimization */
+ int i_n_max = 0;
+ int i_n_current;
+ int i_n_max_ir = 0;
+ for ( int i = 0 ; i < N_SOFA ; i++ )
+ { /* go through all SOFA files and determine the longest IR */
+ if ( s->sofa[i].i_ncid != 0 )
+ {
+ i_n_current = s->sofa[i].i_n_samples + MaxDelay ( &s->sofa[i] );
+ if ( i_n_current > i_n_max )
+ {
+ /* length of longest IR plus max. delay (in all SOFA files) */
+ i_n_max = i_n_current;
+ /* length of longest IR (without delay, in all SOFA files) */
+ i_n_max_ir = s->sofa[i].i_n_samples;
+ }
+ }
+ }
+ s->i_n_longest_filter = i_n_max; /* longest IR plus max. delay */
+ /* buffer length is longest IR plus max. delay -> next power of 2
+ (32 - count leading zeros gives required exponent) */
+ s->i_buffer_length = exp2(32 - clz((uint32_t)i_n_max));
+
+ s->i_output_buffer_length = 0; /* initialization */
+
+ /* Allocate memory for the impulse responses, delays and the ringbuffers */
+ /* size: (longest IR) * (number of channels to convolute), without LFE */
+ s->pf_data_ir_l = malloc( sizeof(float) * i_n_max_ir * s->i_n_conv );
+ s->pf_data_ir_r = malloc( sizeof(float) * i_n_max_ir * s->i_n_conv );
+ /* length: number of channels to convolute */
+ s->pi_delay_l = malloc ( sizeof( int ) * s->i_n_conv );
+ s->pi_delay_r = malloc ( sizeof( int ) * s->i_n_conv );
+ /* length: (buffer length) * (number of input channels),
+ * OR: buffer length (if frequency domain processing)
+ * calloc zero-initializes the buffer */
+ s->pf_ringbuffer_l = av_calloc(s->i_buffer_length * i_input_nb, sizeof(float));
+ s->pf_ringbuffer_r = av_calloc(s->i_buffer_length * i_input_nb, sizeof(float));
+ /* length: number of channels to convolute */
+ s->pf_speaker_pos = malloc( sizeof( float) * s->i_n_conv );
+
+ /* memory allocation failed: */
+ if ( !s->pf_data_ir_l || !s->pf_data_ir_r || !s->pi_delay_l ||
+ !s->pi_delay_r || !s->pf_ringbuffer_l || !s->pf_ringbuffer_r ||
+ !s->pf_speaker_pos )
+ return AVERROR(ENOMEM);
+
+ compensate_volume(ctx);
+
+ /* get speaker positions */
+ if (get_speaker_pos(ctx, s->pf_speaker_pos)) {
+ av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
+ return -1;
+ }
+ /* load IRs to pf_data_ir_l and pf_data_ir_r for required directions */
+ /* only load IRs if time-domain convolution is used,
+ * otherwise, data is loaded on FFT size change */
+ if (load_data(ctx, s->f_rotation, s->f_elevation, s->f_radius)) {
+ return AVERROR(ENOMEM);
+ }
+
+ av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
+ inlink->sample_rate, s->i_n_conv, i_input_nb, (int)s->i_buffer_length );
+
+ return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+ SOFAlizerContext *s = ctx->priv;
+
+ /* go through all SOFA files and free associated memory: */
+ for ( int i = 0 ; i < N_SOFA ; i++) {
+ if (s->sofa[i].i_ncid) {
+ av_freep(&s->sofa[i].pf_sp_a );
+ av_freep(&s->sofa[i].pf_sp_e );
+ av_freep(&s->sofa[i].pf_sp_r );
+ av_freep(&s->sofa[i].pi_data_delay );
+ av_freep(&s->sofa[i].pf_data_ir );
+ }
+ }
+ av_freep(&s->pi_delay_l );
+ av_freep(&s->pi_delay_r );
+ av_freep(&s->pf_data_ir_l );
+ av_freep(&s->pf_data_ir_r );
+ av_freep(&s->pf_ringbuffer_l );
+ av_freep(&s->pf_ringbuffer_r );
+ av_freep(&s->pf_speaker_pos );
+}
+
+#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[0]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
+ { "gain", "set gain in dB", OFFSET(f_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
+ { "rotation", "set rotation" , OFFSET(f_rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
+ { "elevation", "set elevation", OFFSET(f_elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
+ { "radius", "set radius", OFFSET(f_radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 2.1, .flags = FLAGS },
+ { "azi1", "set pos 1. azimuth", OFFSET(pi_azimuth_array[0]), AV_OPT_TYPE_INT, {.i64=90}, -180, 180, .flags = FLAGS },
+ { "ele1", "set pos 1. elevation", OFFSET(pi_elevation_array[0]), AV_OPT_TYPE_INT, {.i64=0}, -90, 90, .flags = FLAGS },
+ { "azi2", "set pos 2. azimuth", OFFSET(pi_azimuth_array[1]), AV_OPT_TYPE_INT, {.i64=180}, -180, 180, .flags = FLAGS },
+ { "ele2", "set pos 2. elevation", OFFSET(pi_elevation_array[1]), AV_OPT_TYPE_INT, {.i64=0}, -90, 90, .flags = FLAGS },
+ { "azi3", "set pos 3. azimuth", OFFSET(pi_azimuth_array[2]), AV_OPT_TYPE_INT, {.i64=-90}, -180, 180, .flags = FLAGS },
+ { "ele3", "set pos 3. elevation", OFFSET(pi_elevation_array[2]), AV_OPT_TYPE_INT, {.i64=0}, -90, 90, .flags = FLAGS },
+ { "azi4", "set pos 4. azimuth", OFFSET(pi_azimuth_array[3]), AV_OPT_TYPE_INT, {.i64=0}, -180, 180, .flags = FLAGS },
+ { "ele4", "set pos 4. elevation", OFFSET(pi_elevation_array[3]), AV_OPT_TYPE_INT, {.i64=90}, -90, 90, .flags = FLAGS },
+ { 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,
+ .uninit = uninit,
+ .query_formats = query_formats,
+ .inputs = inputs,
+ .outputs = outputs,
+};
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 0eeef53..131e067 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -109,6 +109,7 @@ void avfilter_register_all(void)
REGISTER_FILTER(SIDECHAINGATE, sidechaingate, af);
REGISTER_FILTER(SILENCEDETECT, silencedetect, af);
REGISTER_FILTER(SILENCEREMOVE, silenceremove, af);
+ REGISTER_FILTER(SOFALIZER, sofalizer, af);
REGISTER_FILTER(STEREOTOOLS, stereotools, af);
REGISTER_FILTER(STEREOWIDEN, stereowiden, af);
REGISTER_FILTER(TREBLE, treble, af);
--
1.9.1
More information about the ffmpeg-devel
mailing list