Sunday, February 4, 2024

The Math of The ITD Filter and Thoughts on Asymmetry

In a recent post titled "(Almost) Linear Phase Crossfeed" I only explained my intents for creating these filters and the effect I achieved with them. In this post I'll explain the underlying math and go through the MATLAB implementation.

I called this post "The Math of The ITD Filter" for the reason I think this naming is more correct. This is because the purpose of this all-pass filter is just to create an interaural time delay (ITD). Thus, it's not a complete cross-feed or HRTF filter but rather a part of it. As mentioned in the paper "Modeling the direction-continuous time-of-arrival in head-related transfer functions" by H. Ziegelwanger and P. Majdak, an HRTF can be decomposed into three components: minimum phase, frequency-dependent TOA (time-of-arrival), and excess phase. As authors explain, the "TOA component" is just another name for the ITD psychoacoustic cue, and that is what our filters emulate.

Time-Domain vs. Frequency-Domain Filter Construction

Since there is a duality between time and frequency domains, any filter or a signal can be constructed in one of them and transformed into another domain as needed. The choice of the domain is a matter of convenience and of the application area. If you are looking for concrete examples, there is an interesting discussion in the paper "Transfer-Function Measurement with Sweeps" by S. Müller and P. Massarani about time-domain and frequency-domain approaches for generation of log sweeps used in measurements.

Constructing in the time domain looks more intuitive at the first glance. After all, we are creating a frequency dependent time delay. So, in my initial attempts I experimented with splitting the frequency spectrum into bands using linear phase crossover filters, then delaying these bands, and combining them back. This is an easy and intuitive way for creating frequency-dependent delays, however stitching these differently delayed bands back does not happen seamlessly. Because of abrupt changes of the phase at connection points, the group delay behaves quite erratically. I realized that I need to learn how to create smooth transitions.

So my next idea was to create the filter by emulating its effect on a measurement sweep, and then deriving the filter from this sweep. This is easy to model because we just need to delay parts of the sweep that correspond to affected frequencies. Since in a measurement sweep each frequency has its own time position, we know which parts we need to delay. "To delay" in this context actually means "alter the phase." For example, if the 1000 Hz band has to be delayed by 100 μs, we need to delay the phase of that part of the sweep by 0.1 * 2π radians. That's because a full cycle of 1 kHz is 1 ms = 1000 μs, so we need to hold it back by 1/10 of the cycle.

This phase delay can be created easily while we are generating a measurement sweep in the time domain. Since we "drive" this generation, we can control the delay and make it changing smoothly along the transition frequency bands. I experimented with this approach, and realized that manipulation of the phase has its own constraints—I have explained these in my previous post about this filter. That is, for any filter used for real-valued signals, we have to make to phase to start from 0 at 0 Hz (DC), and end with zero phase at the end of our frequency interval (half of the sampling rate). The only other possibility is to start with π radians and end with π—this creates a phase-inverting filter.

This is how this requirement affects our filter. Since we want to achieve a group delay which is a constant over some frequency range, it implies that the phase shift must change with the constant rate on that range (this is by the definition of the group delay). That means, the phase must be constantly decreasing or increasing, depending on the sign of the group delay. But this descent (or ascent) must start somewhere! Due to the restriction I stated in the previous paragraph, we can't have a non-zero phase at 0 Hz. So, I came to an understanding that I need to build a phase shift in the ultrasound region, and then drive the phase back to 0 across the frequency region where I need to create the desired group delay. Phase must change smoothly, as otherwise its derivative, the group delay, will jump up and down.

This realization finally helped me to create the filter with the required group delay behavior. However, constructing the filter via the time domain creates artifacts at the ends of the frequency spectrum (this is explained in the paper on measurements sweeps). Because of that, modern measurement software usually uses sweeps generated in the frequency domain. These sweeps are also more natural for performing manipulations in the frequency domain, which can be done fast by means of direct or inverse FFTs. So, after discussing this topic on the Acourate forum, I've got advice from its author Dr. Brüggemann to construct my filters in the frequency domain.

Implementation Details

Creating a filter in the frequency domain essentially means generating a sequence of complex numbers corresponding to each frequency bin. Since we generate an all-pass filter, the magnitude component is always a unity (zero amplification), and we only need to generate values to create phase shifts. However, the parameters of the filter we are creating are not phase shifts themselves but rather their derivatives, that is, group delays.

This is not a big problem, though, because mostly our group delay is a constant, thus it's a derivative of a linear function. The difficult part is to create a smooth transition of the phase between regions. As I have understood from my time-domain generation attempts, a good function for creating smooth transitions is the sine (or cosine), because its derivative is the cosine (or sine) which is essentially the same function, but phase-shifted. Thus, the transitions of both the phase and the group delay will behave similarly.

So, I ended up with two functions. The first function is:

φ_main(x) = -gd * x

And its negated derivative is our group delay:

gd = -φ_main'(x)

The "main" function is used for the "main" interval where the group delay is the specified constant. And another function is:

φ_knee(x) = -gd * sin(x)

Where gd is the desired group delay in microseconds. By choosing the input range we can get an ascending slope which transitions into a linear region, or a descending slope.

Besides the group delay, another input parameter is the stop frequency for the time shift. There are also a couple of "implicit" parameters of the filter:

  • the band for building the initial phase shift in the ultrasound region;
  • the width of the transition band from the time shift to zero phase at the stop frequency.

Graphically, we can represent the phase function and the resulting group delay as follows (the phase is in blue and the group delay is in red):

Unfortunately, the scale of the group delay values is quite large. Here is a zoom in on the region of our primary interest:

For the initial ramp up region, I have found that a function sin(x) + x gives a smoother "top" compared to a sine used alone. So there is the third function:

φ_ramp(x) = (sin(x) +x) / π

Note that this function does not depend on the group delay. What we need from it is to create the initial ramp up of the phase from 0 to the point where it starts descending.

Getting from the phase function to the filter is rather easy. The complex number in this case is . The angle φ is in radians, thus the values produced by our φ_main and φ_knee, must be multiplied by .

Since we work with discrete signals, we need to choose how many bins of the FFT to use. I use 65536 bins for the initial generation, this has enough resolution in the low frequency region. And the final filters can be made shorter by applying a window (more details are in the MATLAB section below).

Verification in Audio Analyzers

Checking the resulting group delay of the filter is possible in the MATLAB itself, as I have shown in the graphs above. However, to double-check, we want to make an independent verification using some audio analyzing software like Acourate or REW. For that, we need to apply inverse FFT to the FFT we have created, and save the resulting impulse response as a WAV file. Below is a screenshot from FuzzMeasure (I used it because it can put these neat labels on the graph):

I loaded two impulses, both ending at 2150 Hz: one has a -50 μs group delay (red graph), another 85 μs (blue graph). The absolute values of the group delay displayed on the graph (170+ ms) are not important because they are counted from the beginning of the time domain representation, thus they depend on the position of the IR peak. What we are interested in are the differences. We can see that at the flat region past 2 kHz the value is 170.667 ms for both graphs. Whereas, for the blue graph the value at ~200 Hz is 170.752 ms. The difference between these values is 85 μs. For the red graph, the difference is 617-667 = -50 μs. As we can see, this agrees with the filter specification.

In REW, the group delay is relative to the IR peak. However, it has a different issue. Being a room acoustics software, REW by default applies an asymmetric window which significantly truncates the left part of the impulse. This works great for minimum-phase IRs, however since the IR of our filter is symmetric, this default weighting creates as significant ripple at low frequencies:

In order to display our filter correctly, we need to choose the Rectangular window in the "IR windows" dialog, and expand it to maximum both on the left and the right side:

After adjusting windowing this way, the group delay is displayed correctly:

We can see that the group delays are the same as before: -50 μs and 85 μs. Thus, verification confirms that the filters do what is intended, but we need to understand how to use audio analyzing software correctly.

MATLAB Implementation Explained

Now, knowing that our filter works, let's understand how it is made. The full code of the MATLAB script is here, along with a couple of example generated filters.

The main part is the function called create_itd_filter. This is its signature:

function lp_pulse_td = create_itd_filter(...
    in_N, in_Fs, in_stopband, in_kneeband, in_gd, in_wN)

The input parameters are:

  • in_N: the number of FFT bins used for filter creation;
  • in_FS: the sampling rate;
  • in_stopband: the frequency at which the group delay must return to 0;
  • in_kneeband: the frequency at which the group delay starts its return to 0;
  • in_gd: the group delay for the "head shadowing" region;
  • in_wN: the number of samples in the generated IR after windowing.

From these parameters, the script derives some more values:

    bin_w = in_Fs / in_N;
    bin_i = round([1 18 25 in_kneeband in_stopband] ./ bin_w);
    bin_i(1) = 1;
    f_hz = bin_i .* bin_w;

bin_w is the FFT bin width, in Hz. Using it, we calculate the indexes of FFT bins for the frequencies we are interested in. Let's recall the shape of our group delay curve:

Note that 1 Hz value is only nominal. In fact, we are interested the first bin for our first point, so we set its index explicitly, in order to avoid rounding errors. And then we translate bin indexes back to frequencies (f_hz) by multiplying them by the bin width. Use of frequencies that represent the centers of bins is the usual practice for avoiding energy spillage between bins.

Next, we define the functions for the phase, either directly, or as integrals of the group delay function:

    gd_w = @(x) -in_gd * x; % f_hz(3)..f_hz(4)
    syms x;
    gd_knee_f = -in_gd * (cos(pi*((x - f_hz(4))/(f_hz(5)-f_hz(4)))) + 1)/2;
    gd_knee_w = int(gd_knee_f);
    gd_rev_knee_f = -in_gd * cos(pi/2*((x - f_hz(3))/(f_hz(3)-f_hz(2))));
    gd_rev_knee_w = int(gd_rev_knee_f);

gd_w is the φ_main function from the previous section. It is used between the frequency points 3 and 4. gd_knee_f is the knee for the group delay, its integral is the φ_knee function for the phase shift. As a reminder, this knee function is used as a transition between the constant group delay (point 4) and zero delay (point 5). We run the cosine on the interval [0, π], and transform it, so that it yields values in the range from 1 to 0, allowing us to descent from in_gd to 0.

But we also need to have a knee before our constant group delay (from the point 2 to the point 3), to ramp it up from 0. Ramping up can be done faster, so we run the cosine function on the interval [-π/2, 0]. The resulting range goes naturally from 0 to 1, no need to transform it.

Now we use these functions to go backwards from the point 5 to the point 2:

    w = zeros(1, in_N);
    w(bin_i(4):bin_i(5)) = subs(gd_knee_w, x, ...
        linspace(f_hz(4), f_hz(5), bin_i(5)-bin_i(4)+1)) - ...
        subs(gd_knee_w, x, f_hz(5));
    offset_4 = w(bin_i(4));
    w(bin_i(3):bin_i(4)) = gd_w(...
        linspace(f_hz(3), f_hz(4), bin_i(4)-bin_i(3)+1)) - ...
        gd_w(f_hz(4)) + offset_4;
    offset_3 = w(bin_i(3));
    w(bin_i(2):bin_i(3)) = subs(gd_rev_knee_w, x, ...
        linspace(f_hz(2), f_hz(3), bin_i(3)-bin_i(2)+1)) - ...
        subs(gd_rev_knee_w, x, f_hz(3)) + offset_3;
    offset_2 = w(bin_i(2));

Since gd_knee_w and gd_rev_knee_w are symbolic functions, we apply them via the MATLAB function subs. When going from point to point, we need to move each segment of the resulting phase vertically to align the connection points.

Now, the interesting part. We are at the point 2, and our group delay is 0. However, the phase shift is not 0, you can check the value of offset_2 in the debugger if you wish. Since the interval from the point 1 to the point 2 lies in the ultrasonic region, the group delay there is irrelevant. What is important is to drive the phase shift so that it is equal to 0 in the point 1. This is where the φ_ramp function comes handy. It has a smooth top which connects nicely to the top of the knee, and it yields 0 at the input value 0.

    ramp_w = @(x) (x + sin(x)) / pi;
    w(bin_i(1):bin_i(2)) = offset_2 * ramp_w(linspace(0, pi, bin_i(2)-bin_i(1)+1));

Then we fill our the values of FFT bins by providing our calculated phase to the complex exponential:

    pulse_fd = exp(1i * 2*pi * w);

Then, in order to produce a real-valued filter, the FFT must be symmetric relative to the center frequency (see this summary by J. O. Smith, for example). So, for example, the FFT (Bode plot) of the filter may look like this:

Below is the code that performs necessary mirroring:

    pulse_fd(in_N/2+2:in_N) = conj(flip(pulse_fd(2:in_N/2)));
    pulse_fd(1) = 1;
    pulse_fd(in_N/2+1) = 1;

Now we switch to the time domain using inverse FFT:

    pulse_td = ifft(pulse_fd);

This impulse has its peak in the beginning. In order to produce a linear phase filter, the impulse must be shifted to the center of the filter:

    lp_pulse_td = circshift(pulse_td, in_N/2-pidx+1);

And finally, we apply the window. I used REW to check which one works best, and I found that the classic von Hann window does the job. Here we cut and window:

    cut_i = (in_N - in_wN) / 2;
    lp_pulse_td = lp_pulse_td(cut_i:cut_i+in_wN-1);
    lp_pulse_td = hann(in_wN)' .* lp_pulse_td;

That's it. Now we can save the produced IR into a stereo WAV file. I use a two channel file because I have found that having a bit of asymmetry works better for externalization:

lp_pulse_td1 = create_itd_filter(N, Fs, stopband, kneeband, gd1, wN);
lp_pulse_td2 = create_itd_filter(N, Fs, stopband, kneeband, gd2, wN);
filename = sprintf('itd_%dusL_%dusR_%dHz_%dk_%d.wav', ...
    fix(gd1 * 1e6), fix(gd2 * 1e6), stopband, wN / 1024, Fs / 1000);
audiowrite(filename, [lp_pulse_td1(:), lp_pulse_td2(:)], Fs, 'BitsPerSample', 64);

These IR files can be used in any convolution engine. They are also can be loaded into audio analyzer software.

Application and Thoughts on Asymmetry

For a practical use, we need to create 4 filters: a pair for ipsi- and contra-lateral source, and these are different for the left and right ear. Why the asymmetry? The paper I referenced in the introduction of this post, and other papers suggest that ITD of real humans are not symmetrical. My own experiments with using different delay values also confirm that asymmetric delays feel more natural. It's interesting that even the delay of arrival between ipsi- and contra-lateral ears can be made slightly different for the left and right direction. Maybe this originates from the fact that we never hold our head ideally straight. The difference is quite small anyway. Below are the delays that I ended up using for myself:

  • ipsilateral left: -50 μs, right: -60 μs;
  • contralateral left: 85 μs, right: 65 μs.

As we can see, difference between the left hand source path and the right hand source path is 10 μs (135 μs vs. 125 μs). This corresponds approximately to a 3.4 mm sound path, which seems to be reasonable.

Note that if we take the "standard" inter-ear distance of 17.5 cm, that gives us roughly a 510 μs TOA delay. However, this corresponds to a source which is 90° from the center. While, for stereo records we should use just about one third of this value. Also, your actual inter-ear distance can be smaller. In any case, since this is just a rough model, it makes sense to experiment and try using different values.

Regarding the choice of the frequencies for the knee- and stop-bands. With the increase of the frequency the information from the phase difference becomes more and more ambiguous. Various sources suggest that the ambiguity in the time information starts at about 1400 Hz. My own brief experiments suggest that if we keep the ITD along the whole audio spectrum, it makes determination of source position more difficult for narrowband sources starting from 2150 Hz. Thus, I decided to set the transition band between those two values.

Wednesday, December 20, 2023

Headphone Stereo Improved, Part III

Providing another update on my ongoing project of the DIY stereo spatializer for headphones. A couple of months ago my plan was to write a post with a guide for setting up parameters of the blocks of the chain. However, as usual, some experiments and theoretical considerations introduced significant changes to the original plan.

Spatial Signal Analysis

Since the times when I started experimenting with mid-side processing, I realized that measurements that employ sending the test signal to one channel only must be accompanied by measurements that send it to both channels at the same time. Also, the processed output inevitably appears on both channels of binaural playback chain, and thus they both must be captured.

Because of this, whenever I measure a binaural chain, I use the following combinations of inputs and outputs:

  • Input into left channel, output from the left channel, and output from the right channel: L→L and L→R. And if the system is not perfectly symmetric, then we also need to consider R→R and R→L.
  • Correlated input into both channels (exactly the same signal), output from the left and the right channel: L+R→L, L+R→R.
  • Anti-correlated input into both channels (one of the channels reversed, I usually reverse the right channel): L-R→L, L-R→R. I must note that for completeness, I should also measure R-L→L and R-L→R, but I usually skip these in order to save time. Also note that in an ideal situation (identical L and R signals, ideal summing), the difference would be zero. However, as we will see, in a real acoustical environment it is very far from that.

So, that's 8 measurements (if we skip R-L→L and R-L→R). In addition to these, it is also helpful to look at the behavior of reverberation. I measure it for L→L and R→R real or simulated acoustic paths.

Now, in order to perform the analysis, I create the following derivatives using "Trace Arithmetic" in REW:

  • If reverb (real or simulated) is present, I apply FDW window of 15 cycles to all measurements.
  • Apply magnitudes spectral division (REW operation "|A| / |B|") for L→R over L→L, and R→L over R→R. Then average (REW operation "(A + B) / 2") the results and apply psychoacoustic smoothing. This is the approximate magnitude of the crossfeed filter for the contra-lateral channel.
  • Apply magnitudes spectral division for L+R→L over L→L, and L+R→R over R→R. Then also average and smooth. This is the relative magnitude of the "phantom center" compared to purely unilateral speaker sources.
  • Finally, apply magnitudes spectral division for L-R→L over L+R→L, L-R→R over L+R→R, average and smoothen the result. This shows the relative magnitude of the "ambient component" compared to the phantom center.

The fact that we divide magnitudes helps to remove the uncertainties of the measurement equipment and allows comparing measurements taken under different conditions. This set of measurements can be called "spatial signal analysis" for the reason that it actually helps to understand how the resulting 3D audio field will be perceived by a human listener.

I have performed this kind of analysis both for my DIY spatializer chain, and also for my desktop speaker setup (using binaural microphones), and for comparison purposes, with Apple's spatializer over AirPods Pro (2nd gen), in "Fixed" mode, personalized for me using their wizard. From my experience, the analysis seems to be quite useful in understanding the reasons why I hear the test tracks (see the Part II of the series) this or that way on a certain real or simulated audio setup. It also helps in revealing flaws and limitations of the setups. Recalling the saying by Floyd Toole that a measurement microphone and a spectrum analyzer is not a good substitute for human ears and the brain, I would like to believe that binaural measurement like this one, although still imperfect, does in fact model the human perception much closer.

Updated Processing Chain

Unsurprisingly, after measuring different systems and comparing the results, I had to correct the topology of the processing chain (the initial version was introduced in the Part I). The updated diagram is presented below, and the explanations follow it:

Compared to the original version, there are now 4 parallel input "lanes" (on the diagram, I have grouped them in 2x2 formation), and their function and the set of plugins comprising them is also different. Obviously, the most important component—the direct sound is still there, and similarly to the original version of the chain, the direct sound remains practically unaltered, except for adjusting the level of the phantom "center" compared to pure left and right and ambient components. By the way, instead of Mid/Side plugin I switched to "Phantom Center" plugin by Bertom Audio. The second lane is intended to control the level and the spectral shape of the ambient component.

Let me explain this frontend part before we proceed to the rest of the chain. After making the "spatial analysis" measurements, I realized that in a real speaker setup, the ambient component of the recording is greatly amplified by the room, and depending on the properties of the walls, it can even exceed in level "direct" signal sources. On measurements, this can be seen by comparing the magnitudes of uncorrelated (L→L, R→R), correlated (L+R→L, L+R→R), and anti-correlated (L-R→L, L-R→R) sets. The human body also plays an important role as an acoustical element here, and the results of measurements done using binaural microphones differ drastically from "traditional" measurements using a measurement microphone on a stand.

As a result, the ambient component has received a dedicated processing lane, so that its level and the spectral shape can be adjusted individually. By the way, in the old version of the chain, I used the Mid/Side representation of the stereo signal in order to tune the ambient sound component independently of the direct component. In the updated version, I switched to a plugin which extracts the phantom center based on the inter-channel correlation. As a result, pure unilateral signals are separated from the phantom center (recall from my post on Mid/Side Equalization that the "Mid" component still contains left and right, albeit in a reduced level compared to the phantom center).

Continuing on the chain topology, the output from the input lanes is mixed and is fed to the block which applies Mid/Side Equalization. This block replaces the FF/DF block I was using previously. To recap, the old FF/DF block was tuned after the paper by D. Hammershøi and H. Møller, which provides statistically averaged free-field and diffuse-field curves from binaural measurements of noise loudness on human subjects, compared to traditional noise measurements with a standalone microphone. The new version of the equalization block in my chain is derived from actual acoustic measurement in my room, on my body. Thus, I believe, it represents my personal characteristics more faithfully.

Following the Direct/Ambient EQ block, there are two parallel lanes for simulating binaural leakage and reproducing the effect of the torso reflection. This is part of the crossfeed unit, yet it's a bit more advanced than a simple crossfeed. In order to be truer to human anatomy, I added a delayed signal which mimics the effect of the torso reflection. Inevitably, this creates a comb filter, however this simulated reflection provides a significant effect of externalization, and also makes the timbre of the reproduced signal more natural. With careful tuning, the psychoacoustic perception of the comb filter can be minimized.

I must say, previously I misunderstood the secondary peak in the ETC which I observed when applying the crossfeed with the RedLine Monitor while having the "distance" parameter set to a non-zero value. Now I see that it is there to simulate the torso reflection. However, the weak point of such a generalized simulation is that the comb filter created with this reflection can be easily heard. In order to hide it, we need to adjust the parameters of the reflected impulse: the delay, the level, and the frequency response to match more naturally the properties of our body. After this adjustment, the hearing system starts naturally "ignoring" it, effectively transforming it into a perception of "externalization," same as it happens with the reflection from our physical torso. Part of adjustment that makes this simulated reflection more natural is making it asymmetric. Obviously, our physical torso and the resulting reflection is asymmetric as well.

Note that the delayed paths are intentionally band-limited to simulate partial absorption of higher frequencies of the audible range by parts of our bodies. This also inhibits the effects of comb filtering on the higher frequencies.

The output from the "ipsi-" and "contralateral" blocks of the chain gets shaped by crossfeed filters. If you recall, previously I came up with a crossfeed implementation which uses close to linear phase filters. I still use the all-pass component in the new chain, for creating the group delay, however, the shape of the magnitude response of the filter for the opposite (contralateral) ear is now more complex, and reflects the effect of the head diffraction.

And finally, we get to the block which adjusts the output to particular headphones being used. For my experiments and for recreational listening I ended up using Zero:Red IEMs by Truthear due to their low distortion (see the measurements by Amir from ASR) and "natural" frequency response. Yet, it is not "natural" enough for binaural playback, and still need to be adjusted.

Tuning the Processing Chain

Naturally, there are lots of parameters in this chain, and tuning it can be a time-consuming, yet captivating process. The initial part of tuning can be done objectively, by performing the "spatial signal analysis" mentioned before and comparing the results between different setups. It's unlikely that any of the setups is "ideal," and thus the results need to be considered with caution and shouldn't be just copied blindly.

Another reason why blind copying is not advised is due to uncertainties of the measurement process. From the high level point of view, a measurement of the room sound via binaural microphones blocking the ear canal should be equivalent to the sound that arrives to ear-blocking IEMs by wires. Conceptually, IEMs will just propagate the sound further, to the ear drum. The problem is that a combination of arbitrary mics and arbitrary IEMs create a non-flat "insertion gain." I could easily check that by making a binaural recording and then listening to it via IEMs—it's "close," but still not fully realistic. Ideally, a headset with mics should be used which was tuned by the manufacturer to achieve a flat insertion gain. However, in practice it's very hard to find a good one.

Direct and Ambient Sound Field Ratios

Initially, I've spent some time trying to bring the ratios between correlated and uncorrelated components, and the major features of their magnitude response differences to be similar to my room setup. However, I was aware that the room has too many reflections, and too much uncorrelated sound resulting from it. This is why the reproduction of "off-stage" positions from the test track described in the part II of the blog post series has some technical flaws. Nevertheless, let's take a look at these ratios. The graph below shows how the magnitude response of fully correlated (L+R) components differ from uncorrelated direct paths (L→L, R→R), averaged, and smoothed psychoacoustically (as a reminder, this is a binaural measurement using microphones that block the ear canal):

We can see that the bass sums up and becomes louder than individual left and right channels by 6 dB—that's totally unsurprising because I have a mono subwoofer, and the radiation pattern of LXmini speakers which I used for this measurement is omnidirectional at low frequencies. As the direction pattern becomes more dipole-like, the sound level of the sum becomes closer to the sound level of an individual speaker. Around 2 kHz the sum even becomes quieter than a single channel—I guess this is due to acoustical effects of the head and torso. However, the general trend is what one would expect—two speakers play louder than one.

Now let's take a look at the magnitude ratio between the anti-correlated, "ambient" component, and fully correlated sound. Basically, the graph below shows the magnitude response of the filter that would turn the direct sound component into the ambient component:

It's interesting that in theory, anti-correlated signals should totally cancel each other. However, that only happens under ideal conditions, like digital or electrical summing—and that's exactly what we see below 120 Hz due to the digital summing of the signals sent to the subwoofer. But then, as the signal switches to stereo speakers, there is far less correlation, and cancellation does not occur. In fact, due to reflections and head refraction, these initially anti-correlated (at the electrical level) signals become more correlated, and can even end up having higher energy than correlated signal, when summed. Again, we see that around the 2 kHz region, and then, around 6.5 kHz, and 11 kHz.

The domination of the ambient component can actually be verified by listening. To confirm it, I used my narrow-banded mono signals, and created an "anti-correlated" set by inverting the right channel. Then I started playing through speakers pairs of correlated and anti-correlated test signals for the same frequency band—and indeed—sometimes the anti-correlated pair sounded louder! However, the question is—should I actually replicate this behavior in the headphone setup, or not?

The dominance of the ambient (diffuse) component over direct (free-field) component around 6.5 kHz and 11 kHz agrees with the diffuse-field and free-field compensation curves from the Hammershøi and Møller paper I mentioned above. However, in the 2 kHz region it's the free field component that should dominate.

I tried to verify whether fixing the dominance of the ambient component in the 1200—3000 Hz band actually helps to fix the issue with "off-stage" positions, but I couldn't! Trying to correct this band both with Mid/Side equalization, and with the "phantom center" plugin couldn't affect the balance of fields, neither objectively (I re-measured with the same binaural approach), nor subjectively. I have concluded that either there must be some "destructive interference" happening to correlated signals, similar to room modes, or it's a natural consequence of head and torso reflections.

This is why subjective evaluations are needed. For comparison, this is how the balances between correlated and unilateral, and anti-correlated vs. correlated end up looking like in my headphone spatializer, overlaid with the previous graphs measured binaurally in the room, this is the direct component over unilateral signals:

This is the ambient component over direct:

Obviously, they do not look the same as their room-measured peers. The only similar feature is the peak in the diffuse component around 11 kHz (and I had to exaggerate it to achieve the desired effect).

You might have noticed two interesting differences: first, the level of the fully correlated sound for the spatializer is not much higher than levels of individual left and right channels. Otherwise, the center sounds too loud and close. Perhaps, this has something to do with a difference how binaural summing works in the case of dichotic (headphone) playback versus real speakers.

The second difference is in the level of bass for the ambient component. As I've found, enhancing the level of bass somehow makes the sound more "enveloping." This might be similar to the difference between using a mono subwoofer vs. stereo subwoofers in a room setup, as documented by Dr. Griesinger in his AES paper "Reproducing Low Frequency Spaciousness and Envelopment in Listening Rooms".

The other two "large-scale" parameters resulting from the spatial signal analysis that I needed to tune were the magnitude profile for the contra-lateral ear (the crossfeed filter), and the level of reverb. Let's start with the crossfeed filter which is linked to shoulder reflection simulation.

Shoulder Reflection Tuning And Crossfeed

The shoulder reflection I mentioned previously quite seriously affects the magnitude profile for all signals. Thus, if we intend to model the major peaks of valleys of the magnitude profile for the crossfeed filter, we need to take care of tuning the model of the shoulder reflection first. I start it objectively, by looking at the peaks in the ETC of the binaural recording. We are interested in the peaks that are located at approximately 500–700 microsecond delay—this is the approximate distance from the shoulder to the ear. Why not to use the exact distance measured on your body? Since we are not modeling this reflection faithfully, it will not sound natural anyway. So we can start from any close enough value and then adjust by ear.

There are other reflections, too: the closest to the main pulse are reflections from the ear pinna, and further down in time are wall reflections—we don't model these. The reason is that wall reflections are confusing, and in the room setup we usually try to get rid of them. And pinna reflections are so close to the main impulse, so they mostly affect the magnitude profile, which we adjust anyway.

So, above is the ETC graph of direct (ipsilateral) paths for the left ear. Contralateral paths are important, too (also for the left ear):

Torso reflections have rather complex pattern which heavily depends on the relative position of the source to the body (see the paper "Some Effects of the Torso on Head-Related Transfer Functions" by O. Kirkeby et al as an example). Since we don't know the actual positions of virtual sources in stereo encoding, we can only provide some ballpark estimation.

So, I started with an estimation from these ETC graphs. However, in order to achieve more naturally sounding setup, I've turned to listening. A reflection like this usually produces a combing effect. We hear this combing all the time, however we don't notice it because the hearing system tunes it out. Try listening to a loud noise, like a jet engine sound, or sea waves—they sound "normal." However, if you change your normal torso reflection by holding a palm of a hand near your shoulder, you will start hearing the combing effect. Similarly, when the model of the torso reflection is not natural, combing effect can be heard when listening to correlated or anti-correlated pink noise. The task it to tweak the timing and relative level of the reflection to make it as unnoticeable as possible (without reducing the reflection level too much, of course). This is what I ended up with, overlaid with the previous graphs:

Again, we can see that they end up being different from the measured results. One interesting point is that they have to be asymmetrical for left and the right ear, as this leads to more naturally sounding result.

Reverberation Level

Tuning the reverberation has ended up being an interesting process. If you recall previous posts, I use actual reverberation of my room, which sounds surprisingly good in the spatializer. However, in order to stay within the reverb profile recommended for music studios, I reduce its level to make it decay faster than in real room. Adding too much reverb can be deceiving because it makes the sound "bigger" and might improve externalization, however it also makes virtual sources too wide and diffuse. This of course depends on the kind of music you are listening to, and personal taste.

There are two tricks I've learning while experimenting. The first one I actually borrowed from Apple's spatializer. While analyzing their sound, I've found that they do not apply reverb below 120 Hz, like, at all. Perhaps, this is done to avoid effects of room modes. I tried that, and it somewhat cleared up the image. However, having no bass reverb makes the sound in headphones more "flat." I decided to add the bass back, but with a sufficient delay, in order to minimize its effect. I also limited it application to "ambient" components only. As a result, the simulated sound field has become wider and more natural. Below are reverb levels for my room, my processing chain, and for comparison purpose, captured from Apple's stereo spatializer, playing through AirPods Pro.

The tolerance corridor is calculated for the size of the room that I have.

We can see that for my spatializer, the reverb level is within the studio standard. And below is the Apple's reverb:

A great advantage of having your own processing chain is that you can experiment a lot, something that is not really possible in a physical room and with off-the-shelf implementations.

Tuning the Headphones

As I've mentioned, I found Zero:Red by Truthear to be surprisingly good for listening to the spatializer. I'm not sure whether this is due to their low distortion, or due to their factory tuning. Nevertheless, the tuning has still to be corrected.

Actually, before doing any tuning, I had to work on the comfort. These Zero:Reds have quite a thick nozzle—larger than 6 mm in diameter, and with any stock ear tips they were hurting my ear canals. I found tips with thinner ends—SpinFit CP155. With them, I almost forget that I have anything insert into my ears.

Then, the first thing to tune was to reduce the bass. Ideally, the sensory system should not be able to detect that the sound is originating from the source close to your head. For that, there must be no vibration perceived. For these Zero:Reds I had to reduce overall bass region by 15 dB down, plus address individual resonances. A good way to detect them is to run a really long logarithmic sweep through the bass region. You would think that reducing the bass that much makes the sound too "lightweight," however, the bass from reverb and late reverb does the trick. In fact, one interesting feeling that I get is the sense of floor "rumbling" through my feet! Seriously, first couple of times I was checking if I accidentally left the subwoofer on, or is it vibration from the washing machine—but in fact this just is a sensory illusion. My hypothesis is that there are perception paths that help to hear the bass by feeling it with body, and these paths are at least partially bidirectional, so hearing the bass in headphones "the right way" somehow can invoke a physical feeling of it.

All subsequent tuning was more subtle and subjective, based on listening to many tracks and correcting what wasn't sounding "right." That's of course not the best way to do tuning, but it worked for me on these particular IEMs. After doing the tweaking, I have compared the magnitude response of my spatializer over Zero:Reds with Apple's spatializer over AirPods. In order to be able to compare "apples to apples," I have measured both headphones using the QuantAsylum QA490 rig. Below is how the setup looked like (note that on the photo, I have ER4SRs inserted into QA490, not Zero:Reds):

And here are the measurements. Note that since QA490 is not an IEC-compliant ear simulator, measured responses can only be compared to each other. The upper two graphs are for the left earphone, the lower two are for the right headphone, offset by -15 dB. Measurements actually look rather similar. AirPods can be distinguished by having more bass, and I think that's one of the reasons why to my ears they sound less "immersive" to me:

Another likely reason is that I tend to use linear phase equalizers, at the cost of latency, while Apple spatializer likely uses minimum phase filters which modify timing relationships severely.

Conclusion

Creating a compelling, and especially "believable" stereo spatialization is anything but easy. Thankfully, these days even at home it is possible to make measurements that may serve as a starting point for further adjustment of the processing chain. A challenging part is finding headphones that would allow disappearing in one's ears, or on one's head, as concealing them from the hearing system is one of the prerequesites for tricking the brain that the sound is coming from around you.

Friday, September 22, 2023

(Almost) Linear Phase Crossfeed

After checking how Mid/Side EQ affects unilateral signals (see the post), I realized that a regular minimum phase implementation of crossfeed affects signals processed with Mid/Side EQ in a way which degrades their time accuracy. I decided to fix that.

As a demonstration, let's take a look at what happens when we take a signal which exists in the left channel only and first process it with crossfeed, and then with a Mid/Side EQ filter. Our source signal is a simple Dirac pulse, attenuated by -6 dB. Since we apply digital filters only, we don't have to use more complicated measurement techniques that involve sweeps or noise. The crossfeed implementation is my usual Redline Monitor plugin by 112 dB, with the "classical" setting of 60 degrees virtual speaker angle, zero distance and no center attenuation. Then, a Mid/Side linear phase (phase-preserving) EQ applies a dip of -3 dB at 4.5 kHz with Q factor 4 to the "Mid" component only. Below I show in succession how the frequency and phase response, as well as the group delay of the signal changes for the left and the right channel.

This is the source signal:

This is what happens after we apply crossfeed. We can see that both amplitude and phase got modified, and the filter intentionally creates a group delay in order to imitate the effect of a sound wave first hitting the closer ear (this is what I call the "direct" path), and then propagating to more distant one, on the opposite side of the head (see my old post about the Redline Monitor plugin), I call this the "opposite" path:

And now, we apply Mid/Side EQ on top of it (recall that it's a dip of -3 dB at 4.5 kHz with Q factor 4 to the "Mid" component only):

Take a closer look at the right channel, especially at the group delay graph (bottom right). You can see a wiggle there which is on the order of the group delay that was applied by the crossfeed filter. Although the amplitude is down by about -22 dB at that point, this is still something we can hear, and this affects our perception of the source position, making it "fuzzier."

As I explained previously in the post on Mid/Side Equalization, changing the "Mid" and the "Side" components independently makes some artifacts being produced when we combine the M/S components in order to convert them back into L/R stereo representation. Application of the crossfeed prior to the Mid/Side equalization adds a huge impact both to the phase and to the group delay. This is because a minimum phase implementation of the crossfeed effect creates different phase shifts for the signals on the "direct" and on the "opposite" paths. To demonstrate that it's indeed due to the phase shifts from the crossfeed, let's see what happens when we instead use linear phase filters in the crossfeed section (the shape of the magnitude response is intentionally not the same as of the Redline):

This looks much better and clean. And as you can see, the filter still modifies the group delay and phase, but not across the whole spectrum. That's why I call this implementation "Almost Linear Phase." What we do here is we still apply a frequency-dependent delay to the signal, however we do it more surgically, only in the region where we do not expect any modifications done by the Mid-Side EQ part. That means, both the linear phase crossfeed and the M/S EQ filters must be developed and used together. That's exactly what I do in my evolving spatializer implementation (see Part I and Part II). As I know that in my chain the M/S equalization is only applied starting from 500 Hz (to remind you, it is used to apply diffuse-to-free field (and vice versa) compensation separately to correlated and negatively correlated parts of the signal), I developed a crossfeed filter which only applies the group delay up to that frequency point, and keeping the phase shift at 0 afterwards.

Note that 500 Hz does not actually correspond to physical properties of sound waves related to the human head size. In typical crossfeed implementations, the delay for imitating sound wave propagation is applied up to 700–1100 Hz (see publications by S. Linkwitz and J. Conover). Thus, limiting the application to lower frequencies is sort of a trade-off. However, if you recall the "philosophy" behind my approach—that we don't actually try to emulate speakers and the room, but rather try to extract the information about the recorded venue, with minimal modifications to the source signal, this trade-off makes sense.

Crossfeed Filter Modeling

One possible approach I could use to shape my crossfeed filters is to copy them from an existing implementation. However, since with linear phase filters I can control the amplitude and the phase components independently, I decided to read a bit more recent publications about head transfer function modeling. I found two excellent publications by E. Benjamin and P. Brown from Dolby Laboratories: An Experimental Verification of Localization in Two-Channel Stereo and The effect of head diffraction on stereo localization in the mid-frequency range. They explore the effect of the frequency-dependent changes of the acoustic signal as it reaches our ears, which happens due to diffraction of the sound by the head. I took these results into consideration when shaping the filter response for the opposite ear path, and also when choosing the values for the group delay.

Besides the virtual speakers angle, Redline Monitor also has the parameter called "center attenuation." This is essentially the attenuation of the Mid component in the Mid/Side representation. Thus, the same effect can be achieved by putting the MSED plugin (I covered it in the post about Mid/Side Equalization) in front of the crossfeed, and tuning the "Mid Mute" knob to the desired value (it is convenient that MSED actually uses decibels for "Mid Mute" and "Side Mute" knobs).

As for the "distance" parameter of Redline Monitor, I don't intent to use it at all. In my chain, I simulate the effect of distance with reverb. In Redline Monitor, when one sets the "distance" to anything other than 0 m, the plugin adds a combing filter. Another effect that the "distance" parameter affects is the relative level between the "direct" and the "opposite" processing paths. This makes sense, as the source which is closer to the head will be more affected by the head shadowing effect than the source far away. In fact, the aforementioned AES papers suggest that by setting ILD to high values, for example 30 dB, it is possible to create an effect of a talker being close to one of your ears (do you recall Dolby Atmos demos now?). However, since I actually want headphone sound to be perceived further from the head, I want to keep the inter-channel separation as low as possible, unless it degrades lateral positioning.

Filter Construction

I must note that constructing an all-phase filter with a precisely specified group delay is not a trivial task. I have tried many approaches doing this "by hand" in Acourate, and ended up with using Matlab. Since it's a somewhat math-intensive topic, I will explain it in more details in a separate post. For now, let's look again at the shapes for the group delay of such a filter, for the "direct" path and the "opposite" path:

This is the filter which delays the frequencies up to 500 Hz by 160 μs (microseconds). After the constant group delay part, it quickly goes down to exactly zero, also bringing back the phase shift to 0 degrees. That's how we enable the rest of the filter to be phase preserving. Those who a bit familiar with signal processing could ask—since a constant positive group delay means that the phase shift is linearly going down, where did it start from a non-zero value in the first place? The natural restriction on any filter is that at 0 Hz frequency (sometimes this is called the "DC component") it must have either 0 or 180 degrees phase shift. What we do in order to fulfill this requirement, is we use the region from 0 to 20 Hz to build up the phase shift rapidly, and then we bring it down along the region from 20 Hz to 500 Hz (note that the frequency axis start from 2 Hz on the graphs below):

Yes, the group delay in the "ultrasound" region is a couple of milliseconds, which is an order of magnitude greater than the group delay used for crossfeed. But, since we don't hear that, it's OK.

A delaying all-pass filter is used for the "opposite" path of the crossfeed filter. For the "direct" path, we need to create an inverse filter in terms of the time delay, that means, a filter which "hastens" the group delay. This is to ensure that a mono signal (equal in the left and right channels) does not get altered significantly by our processing. Such a signal is processed by both the "direct" and the "opposite" filters, and the results are summed. If the delays in these filters are inverse of each other, the sum will have a zero group delay, otherwise it won't.

The similar constraint is applied to the frequency response. That means, if we sum the filters for the "direct" and the "opposite" channels, the resulting frequency response must be flat. This is also true for the original minimum-phase Redline filters.

So, I used the following steps in order to produce my linear phase versions of crossfeed filters using Acourate:

  1. With help of Matlab, I have created an all-pass filter which applies a 160 µs delay between 20 and 500 Hz, and a filter which speeds up the same region by 128 µs (the reason for inexact symmetry is that the channel on the "opposite" path is attenuating). The important constraint is that the resulting group delay between paths must be between about 250–300 µs.

  2. I created a simple sloped down amplitude response: starting from -3.3 dB at 20 Hz and ending with -9 dB at 25600 Hz, and with help from Acourate convolved it with the delaying all-pass filter—this has become the starting point for the "opposite" path filter. For the direct path, I simply took the "direct" path filter which has the needed "anti-delay" (hastening), and a flat magnitude response.

Then I applied the following steps multiple times:

  1. Sum filters for the "direct" and the "opposite" paths. The resulting amplitude will not be flat, and now our goal is to fix that.

  2. Create an inverse frequency response filter for the sum (Acourate creates it with a linear phase).

  3. Convolve this inverse filter with either the filter for the "direct" or for the "opposite" path. This is a bit of an art—choosing the section of the filter to correct, and which path to apply it to. The aim is to retain a simple shape for both paths of the filter.

Below are the shapes I ended up with:

The filters that we have created can be cut to 16384 taps for the 96 kHz sampling rate. We need to keep relatively large number of taps in order to have enough resolution at low frequencies where we perform our phase manipulations.

Is There Any Difference?

After going through all these laborious steps, what improvements did we achieve over the original minimum phase filters of the Redline Monitor? First, as I've mentioned in the beginning, the main goal for me was to eliminate any phase difference between left and right channels after crossfeed processing in order to minimize artifacts from Mid/Side EQing. As we have seen in the first section of the post, this goal was achieved.

Sonically, a lot of difference can be heard even when listening to pink noise. Below is a recording where I switch between unprocessed pink noise combined from a correlated layer and an anti-correlated layer, then processed using RedLine Monitor at 60 degrees, 0 m distance, 0 dB center, and then processed with my almost linear-phase crossfeed (the track is for headphone listening, obviousl):

To me, my processing sounds more like how I hear the unprocessed version on speakers (the actual effect heavily depends on the headphones used). The noise processed by Redline has fuzzier phantom center, and there is much less enveloping on the sides. So I think, the (almost) linear phase implementation of crossfeed is sonically more accurate.