Algorithm Search⌘K

Algorithmcore

Phase vocoder

Also called phase vocoder time stretching.

Time-stretch or pitch-shift audio by changing the hop of the STFT and advancing each bin's phase by its estimated instantaneous frequency.

Time
O(F N log N) worst
Space
O(N) extra
Where
F = the number of analysis frames; N = the frame and FFT length
Properties
deterministicnot exactnot in placeonline
Origin
James L. Flanagan, Roger M. Golden, 1966

The phase vocoder changes the duration of a sound without changing its pitch, or the pitch without changing the duration. It takes the short-time Fourier transform of the input with a hop HaH_a, keeps the magnitude of each bin, gives each bin a new phase that advances by HsH_s times the bin's instantaneous frequency, and puts the frames back with overlap-add at a hop HsH_s. PSOLA does the same jobs in the time domain, one pitch period at a time, and works better on a single voice; the phase vocoder needs no pitch marks and works on any sound.

In plain words

Cut the sound into short, overlapping pieces and find which frequencies are in each piece. To make the sound slower, put the pieces back farther apart than they were cut. If you only move the pieces, the waves in neighboring pieces no longer line up where they overlap, and they cancel or beat. So for each frequency the method measures how far the wave turned between two input pieces, works out the exact frequency from that turn, and turns the wave by the correct, larger amount between two output pieces. The waves then line up again. The result is longer, but every tone keeps its frequency. To raise the pitch, stretch first and then play the result faster.

The problem

Given a signal xx and a ratio α>0\alpha > 0, produce a signal yy of about α\alpha times the duration of xx in which every stationary sinusoid of xx appears with the same frequency and amplitude. A pitch shift by a factor β\beta is a stretch by β\beta followed by sample-rate conversion by β\beta. There is no single correct output for a general sound, so the requirement is exact only for sinusoids.

The algorithm

Let ww be a window of length NN, let ωk=2πk/N\omega_k = 2\pi k / N be the center of bin kk, let Hs=round(αHa)H_s = \text{round}(\alpha H_a), and let princarg\text{princarg} map an angle to [−π,π)[-\pi, \pi) by adding a multiple of 2π2\pi.

  1. PHASE-VOCODER-STRETCH(x, alpha, window w of length N, analysis hop Ha)
  2. 1X_t <- FFT(w * x[t Ha .. t Ha + N - 1]) for t = 0 .. F - 1
  3. 2psi <- arg X_0; the first output frame is IFFT(X_0)
  4. 3for t <- 1 to F - 1 do
  5. 4delta_k <- princarg(arg X_t[k] - arg X_{t-1}[k] - Ha omega_k) for every bin k
  6. 5omega'_k <- omega_k + delta_k / Ha (the instantaneous frequency)
  7. 6psi_k <- psi_k + Hs omega'_k
  8. 7the output frame t is IFFT(|X_t[k]| e^{i psi_k})
  9. 8y <- sum over t of w * frame t at t Hs, divided by the sum of w^2 at t Hs

Lines L4 and L5 are the core. The phase of bin kk moves by HaωH_a \omega between two frames if the bin holds a sinusoid of frequency ω\omega. The measured phase change is only known up to a multiple of 2π2\pi, so the expected part HaωkH_a \omega_k is taken away and the rest is wrapped to [−π,π)[-\pi, \pi). If the true frequency is within π/Ha\pi / H_a of the bin center, the wrapped rest is exactly Ha(ω−ωk)H_a(\omega - \omega_k). Line L8 is the weighted overlap-add, which divides by the sum of the squared windows.

Example

Take fs=8000f_s = 8000 Hz, N=1024N = 1024, Ha=256H_a = 256 with the periodic Hann window, and a sine of 440 Hz with amplitude 0.5. The bins are 7.8125 Hz apart, and the largest one in each frame is k=56k = 56 at 437.5 Hz, with magnitude 119.77.

  • The phases of bin 56 in frames 0 and 1 are −0.56549-0.56549 and −0.06283-0.06283 rad.
  • The expected advance is Haω56=256⋅2π⋅56/1024=28π=87.9646H_a \omega_{56} = 256 \cdot 2\pi \cdot 56 / 1024 = 28\pi = 87.9646 rad.
  • The raw rest −0.06283+0.56549−87.9646=−87.4619-0.06283 + 0.56549 - 87.9646 = -87.4619 wraps to δ=0.502655\delta = 0.502655 rad.
  • So ω′=0.343612+0.502655/256=0.345575\omega' = 0.343612 + 0.502655 / 256 = 0.345575 rad per sample, which is 0.345575⋅8000/2π=440.00000.345575 \cdot 8000 / 2\pi = 440.0000 Hz.

The bins 55, 57 and 58, with magnitudes 35.1, 94.1 and 11.2, also give 440.0000 Hz: all the bins near a sinusoid estimate the same frequency. A stretch by α=1.5\alpha = 1.5 has Hs=384H_s = 384, so each output frame advances the phase of these bins by 384⋅0.345575=132.70384 \cdot 0.345575 = 132.70 rad. The 4096 input samples give 13 frames and 12⋅384+1024=563212 \cdot 384 + 1024 = 5632 output samples. Measured by the zero crossings in the middle of the signals, the input is at 440.17 Hz and the output at 440.09 Hz, with a peak of 0.515. A pitch shift by 1.25 gives 549.97 Hz.

Correctness

These are theorems, proved in proofs/correctness.md:

  • Exact frequency for one exponential. If x[n]=c eiωnx[n] = c\, e^{i\omega n} and ∣ω−ωk∣Ha<π|\omega - \omega_k| H_a < \pi, then line L5 gives ωk′=ω\omega'_k = \omega exactly, for any window.
  • Identity. If Hs=HaH_s = H_a, every output frame equals the analysis frame, and the output equals xx at every sample where the sum of the squared windows is not 0.
  • Exact stretch of one exponential. If x[n]=c eiωnx[n] = c\, e^{i\omega n} and the condition above holds in every bin where X0[k]≠0X_0[k] \ne 0, then output frame tt is w[m] c eiω(tHs+m)w[m]\, c\, e^{i\omega(t H_s + m)}, and the overlap-add gives y[n]=c eiωny[n] = c\, e^{i\omega n}: the same frequency and amplitude, at any length. With the periodic Hann window and ω\omega on a bin center, this holds for every Ha<N/2H_a < N / 2.

A real sinusoid is the sum of two exponentials, and their leakage into each other's bins makes the estimate only close; the 440.0000 Hz above is a measurement. For sounds with several sinusoids in one bin, or with fast changes, the method is a heuristic, and its errors are the artifacts listed under Pitfalls.

Proof: Correctness of the phase vocoderfull

The phase vocoder has no exact specification for a general sound, so we prove what it does exactly: the frequency estimate is exact for a complex exponential, equal hops give back the input, and a complex exponential is stretched with no change of frequency or amplitude.

Setup

The window ww has length NN. Frame tt of the analysis is Xt[k]=∑m=0N−1w[m] x[tHa+m] e−iωkmX_t[k] = \sum_{m=0}^{N-1} w[m]\, x[t H_a + m]\, e^{-i \omega_k m} with ωk=2πk/N\omega_k = 2\pi k / N. The function princarg(a)=a−2π⌊(a+π)/(2π)⌋\text{princarg}(a) = a - 2\pi \lfloor (a + \pi) / (2\pi) \rfloor returns the unique value in [−π,π)[-\pi, \pi) that differs from aa by an integer multiple of 2π2\pi. Write φt[k]=arg⁡Xt[k]\varphi_t[k] = \arg X_t[k]. The algorithm sets ψ0=φ0\psi_0 = \varphi_0 and, for t≥1t \ge 1,

ωt′[k]=ωk+1Haprincarg(φt[k]−φt−1[k]−Haωk),ψt[k]=ψt−1[k]+Hs ωt′[k],\omega'_t[k] = \omega_k + \frac{1}{H_a} \text{princarg}\big(\varphi_t[k] - \varphi_{t-1}[k] - H_a \omega_k\big), \qquad \psi_t[k] = \psi_{t-1}[k] + H_s\, \omega'_t[k],

and output frame tt is ft=IFFT(Yt)f_t = \text{IFFT}(Y_t) with Yt[k]=∣Xt[k]∣ eiψt[k]Y_t[k] = |X_t[k]|\, e^{i \psi_t[k]}. The output is y[n]=∑tw[n−tHs]ft[n−tHs]/S(n)y[n] = \sum_t w[n - t H_s] f_t[n - t H_s] / S(n) with S(n)=∑tw[n−tHs]2S(n) = \sum_t w[n - t H_s]^2, at every nn with S(n)>0S(n) > 0 (terms with the index outside 0..N−10 .. N - 1 are 0).

Lemma 1 (the overlap-add inverts windowed frames)

If ft[m]=w[m] z[tH+m]f_t[m] = w[m]\, z[t H + m] for all tt and mm, for some signal zz, then the weighted overlap-add at hop HH returns z[n]z[n] at every nn with S(n)>0S(n) > 0.

Proof. ∑tw[n−tH]ft[n−tH]=∑tw[n−tH]2z[n]=S(n)z[n]\sum_t w[n - tH] f_t[n - tH] = \sum_t w[n - tH]^2 z[n] = S(n) z[n]. Divide by S(n)S(n). □\square

Theorem 1 (exact frequency for one exponential)

Let x[n]=c eiωnx[n] = c\, e^{i \omega n} with c≠0c \ne 0, and let kk be a bin with X0[k]≠0X_0[k] \ne 0 and ∣ω−ωk∣Ha<π|\omega - \omega_k| H_a < \pi. Then ωt′[k]=ω\omega'_t[k] = \omega for every t≥1t \ge 1.

Proof. Substituting xx,

Xt[k]=c eiωtHa∑mw[m] ei(ω−ωk)m=eiωtHaX0[k].X_t[k] = c\, e^{i \omega t H_a} \sum_m w[m]\, e^{i(\omega - \omega_k) m} = e^{i \omega t H_a} X_0[k].

So Xt[k]≠0X_t[k] \ne 0 and φt[k]−φt−1[k]=ωHa+2πj\varphi_t[k] - \varphi_{t-1}[k] = \omega H_a + 2\pi j for some integer jj. The argument of princarg is (ω−ωk)Ha+2πj(\omega - \omega_k) H_a + 2\pi j. The value (ω−ωk)Ha(\omega - \omega_k) H_a is in (−π,π)(-\pi, \pi) and differs from it by a multiple of 2π2\pi, so princarg returns it. Then ωt′[k]=ωk+(ω−ωk)=ω\omega'_t[k] = \omega_k + (\omega - \omega_k) = \omega. □\square

Theorem 2 (identity for equal hops)

If Hs=HaH_s = H_a, then Yt=XtY_t = X_t for every tt, and y[n]=x[n]y[n] = x[n] at every nn with S(n)>0S(n) > 0.

Proof. We show ψt[k]−φt[k]∈2πZ\psi_t[k] - \varphi_t[k] \in 2\pi\mathbb{Z} by induction on tt. It holds for t=0t = 0. For t≥1t \ge 1, princarg changes its argument by a multiple of 2π2\pi, so

ψt[k]=ψt−1[k]+Haωk+(φt[k]−φt−1[k]−Haωk)+2πj=φt[k]+(ψt−1[k]−φt−1[k])+2πj,\psi_t[k] = \psi_{t-1}[k] + H_a \omega_k + \big(\varphi_t[k] - \varphi_{t-1}[k] - H_a \omega_k\big) + 2\pi j = \varphi_t[k] + (\psi_{t-1}[k] - \varphi_{t-1}[k]) + 2\pi j,

which is φt[k]\varphi_t[k] plus a multiple of 2π2\pi by the hypothesis. Hence Yt[k]=∣Xt[k]∣eiφt[k]=Xt[k]Y_t[k] = |X_t[k]| e^{i \varphi_t[k]} = X_t[k] (for Xt[k]=0X_t[k] = 0 both sides are 0). The IFFT inverts the FFT, so ft[m]=w[m] x[tHa+m]f_t[m] = w[m]\, x[t H_a + m], and Lemma 1 with H=HaH = H_a gives y=xy = x where S>0S > 0. □\square

Theorem 3 (a complex exponential is stretched exactly)

Let x[n]=c eiωnx[n] = c\, e^{i \omega n}, and suppose every bin kk with X0[k]≠0X_0[k] \ne 0 satisfies ∣ω−ωk∣Ha<π|\omega - \omega_k| H_a < \pi. Then for any HsH_s, y[n]=c eiωny[n] = c\, e^{i \omega n} at every nn with S(n)>0S(n) > 0.

Proof. Take a bin with X0[k]≠0X_0[k] \ne 0. By Theorem 1, ψt[k]=φ0[k]+tHsω\psi_t[k] = \varphi_0[k] + t H_s \omega, and ∣Xt[k]∣=∣X0[k]∣|X_t[k]| = |X_0[k]| by the formula in its proof. So Yt[k]=∣X0[k]∣eiφ0[k]eiωtHs=eiωtHsX0[k]Y_t[k] = |X_0[k]| e^{i\varphi_0[k]} e^{i \omega t H_s} = e^{i \omega t H_s} X_0[k]. For a bin with X0[k]=0X_0[k] = 0, also Xt[k]=0X_t[k] = 0 and Yt[k]=0=eiωtHsX0[k]Y_t[k] = 0 = e^{i \omega t H_s} X_0[k]. Hence Yt=eiωtHsX0Y_t = e^{i \omega t H_s} X_0 and

ft[m]=eiωtHsw[m] c eiωm=w[m] c eiω(tHs+m),f_t[m] = e^{i \omega t H_s} w[m]\, c\, e^{i \omega m} = w[m]\, c\, e^{i \omega (t H_s + m)},

which is the windowed frame of the signal z[n]=c eiωnz[n] = c\, e^{i \omega n} at hop HsH_s. Lemma 1 gives y=zy = z where S>0S > 0. □\square

For example, with the periodic Hann window and ω=ωj\omega = \omega_j on a bin center, X0[k]≠0X_0[k] \ne 0 only for k=j−1,j,j+1k = j - 1, j, j + 1, and the condition holds whenever Ha<N/2H_a < N / 2.

Remarks

Real signals. For a real input, Xt[N−k]=Xt[k]‾X_t[N - k] = \overline{X_t[k]}. Since HaωN−k=2πHa−HaωkH_a \omega_{N-k} = 2\pi H_a - H_a \omega_k and princarg(−a)=−princarg(a)\text{princarg}(-a) = -\text{princarg}(a) except when aa is an odd multiple of π\pi, the updates give ψt[N−k]=−ψt[k]\psi_t[N - k] = -\psi_t[k] modulo 2π2\pi outside that case, so YtY_t is conjugate symmetric and ftf_t is real. The code takes the real part, which only removes rounding.

Real sinusoids. A real sinusoid is the sum of two exponentials, at ω\omega and −ω-\omega. Their sum in a bin is not of the form of Theorem 1, so the estimate is only close, with an error that falls as the window rejects the other exponential better. The tests measure 440.0000 Hz for a 440 Hz sine at N=1024N = 1024.

The tests. The tests check Theorem 1 for complex exponentials at several frequencies, Theorem 2 on random noise (error below 10−1010^{-10}) and Lemma 1 directly.

Complexity

With FF analysis frames of NN samples, each frame needs one FFT, NN phase updates and one inverse FFT, so the time is O(FNlog⁡N)O(F N \log N). A streaming version keeps one previous spectrum, the phase array and an output buffer of NN samples, so the extra memory is O(N)O(N). The code on this page keeps all the frames for clarity. For a stretch of LL input samples, F≈L/HaF \approx L / H_a, so the cost per input sample is O((N/Ha)log⁡N)O((N / H_a) \log N), which is O(log⁡N)O(\log N) for the usual overlap of 4.

Properties

  • No pitch marks. Unlike PSOLA, it works on music, chords and noise, and needs no pitch detection.
  • Constant frequency resolution. Every bin is fs/Nf_s / N wide. A long window resolves close partials but smears the onsets in time; a short window does the reverse.
  • Online. Each output frame depends on two input frames, so the method can stream with a delay of one frame.
  • Not exact for real signals. Only single exponentials are kept exactly; everything else is approximate.

Variants and improvements

  • Phase locking. Laroche and Dolson lock the phases of the bins around each spectral peak to the phase of the peak, which keeps the vertical coherence across bins and reduces phasiness.
  • Transient handling. Reset the phases to the analysis phases at detected onsets, so that drum hits stay sharp.
  • Pitch shift. Stretch by β\beta, then resample by β\beta; or move the bins in frequency directly and scale their phase advances.
  • Phase from magnitude. When only magnitudes exist, as in neural speech synthesis, the Griffin-Lim algorithm finds phases that fit them by iteration.

When to use it

Use it to change the speed of music or other polyphonic sound, and for large stretch ratios. For a single voice with small changes of pitch and duration, as in text-to-speech by concatenation, PSOLA is cheaper and sounds more natural.

Pitfalls

  • Phasiness. Each bin gets its own phase, so the bins of one partial drift apart and the sound gets a reverberant, distant quality. This is the main artifact of the basic method.
  • Smeared transients. An attack is spread over a whole window and repeated by the overlap.
  • Hop too large. The estimate is exact only in the bins whose center is within π/Ha\pi / H_a of the frequency, that is within N/(2Ha)N / (2 H_a) bins. The main lobe of the Hann window covers the bins up to 2 bins from the frequency, so all of them are inside only if Ha<N/4H_a < N / 4. The usual choice Ha=N/4H_a = N / 4 is at this limit, and the outer bins of the lobe can then get a wrong frequency.
  • Window sum. Without dividing by the sum of the squared windows, the output gets an amplitude ripple at the hop rate, because for most synthesis hops this sum is not constant over time.
  • Formants in pitch shifting. Resampling moves the spectral envelope with the pitch, so a voice shifted up by more than a few semitones sounds smaller. Keep the envelope apart, as in the source-filter model.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

nlsdsp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small signal processing tools for the natural-language-and-speech pages.

A signal is a list of floats x[0], ..., x[L - 1], usually in [-1, 1]. A frame is
a list of floats. A spectrum is a list of floats or complex numbers.

The defaults of the area are fs = 16000 Hz, frames of 400 samples (25 ms), a hop
of 160 samples (10 ms), the symmetric Hamming window and an FFT length of 512.

The LPC sign convention is A(z) = 1 - sum_{k=1}^{p} a_k z^-k, so the prediction
of x[n] is sum_{k=1}^{p} a_k x[n - k].

This module holds no algorithm of any page of the area: no mel scale, no mel
filter bank, no feature extractor, no pre-emphasis and no zero-crossing rate.
The pages build those on top of it.
"""

import cmath
import math
from typing import List, Sequence, Tuple


def frames(x: Sequence[float], frame_len: int, hop: int) -> List[List[float]]:
    """Cut x into frames of frame_len samples, one every hop samples, with no padding.

    A signal of L >= frame_len samples gives 1 + (L - frame_len) // hop frames.
    A signal shorter than one frame gives no frame. The last samples that do not
    fill a frame are dropped.
    """
    if frame_len <= 0 or hop <= 0:
        raise ValueError("frame_len and hop must be positive")
    n = len(x)
    if n < frame_len:
        return []
    count = 1 + (n - frame_len) // hop
    return [list(x[i * hop : i * hop + frame_len]) for i in range(count)]


def hamming(n: int) -> List[float]:
    """The symmetric Hamming window w[i] = 0.54 - 0.46 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
    if n <= 0:
        raise ValueError("the window length must be positive")
    if n == 1:
        return [1.0]
    return [0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]


def hann(n: int) -> List[float]:
    """The symmetric Hann window w[i] = 0.5 - 0.5 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
    if n <= 0:
        raise ValueError("the window length must be positive")
    if n == 1:
        return [1.0]
    return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]


def fft(x: Sequence[complex]) -> List[complex]:
    """The DFT X[k] = sum_n x[n] exp(-2 pi i k n / N) by the iterative radix 2 FFT.

    The length N must be a power of 2. The cost is O(N log N) operations.
    """
    n = len(x)
    if n == 0 or n & (n - 1):
        raise ValueError("the FFT length must be a power of 2")
    a = [complex(v) for v in x]
    # bit reversal permutation
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        w_step = cmath.exp(-2j * math.pi / size)
        for start in range(0, n, size):
            w = 1.0 + 0.0j
            for k in range(start, start + half):
                u = a[k]
                v = a[k + half] * w
                a[k] = u + v
                a[k + half] = u - v
                w *= w_step
        size *= 2
    return a


def power_spectrum(frame: Sequence[float], nfft: int) -> List[float]:
    """|X[k]|^2 for k = 0 to nfft / 2, where X is the DFT of the frame zero padded to nfft."""
    if len(frame) > nfft:
        raise ValueError("the frame is longer than the FFT length")
    spec = fft(list(frame) + [0.0] * (nfft - len(frame)))
    return [abs(spec[k]) ** 2 for k in range(nfft // 2 + 1)]


def dct2(x: Sequence[float], k: int) -> List[float]:
    """The first k coefficients of the orthonormal DCT-II of x.

    c[j] = s_j sum_{n=0}^{N-1} x[n] cos(pi j (2 n + 1) / (2 N)), with s_0 = sqrt(1 / N)
    and s_j = sqrt(2 / N) for j >= 1. The full transform (k = N) is an orthogonal matrix.
    """
    n = len(x)
    if n == 0:
        raise ValueError("empty input")
    if k < 0 or k > n:
        raise ValueError("k must be between 0 and len(x)")
    out = []
    for j in range(k):
        s = math.sqrt((1.0 if j == 0 else 2.0) / n)
        out.append(s * sum(x[i] * math.cos(math.pi * j * (2 * i + 1) / (2 * n)) for i in range(n)))
    return out


def autocorr(x: Sequence[float], max_lag: int) -> List[float]:
    """r[k] = sum_{n=0}^{L-1-k} x[n] x[n + k] for k = 0 to max_lag (no normalization)."""
    n = len(x)
    return [sum(x[i] * x[i + k] for i in range(n - k)) if k < n else 0.0 for k in range(max_lag + 1)]


def levinson(r: Sequence[float], p: int) -> Tuple[List[float], float]:
    """Solve the normal equations of linear prediction of order p by the Levinson-Durbin recursion.

    Returns (a, e): a = [a_1, ..., a_p] with A(z) = 1 - sum a_k z^-k, and e the
    prediction error of order p. Needs r[0] > 0 and len(r) > p. If the error
    reaches 0 before order p (a perfectly predictable signal), the remaining
    coefficients are 0.
    """
    if len(r) <= p:
        raise ValueError("need r[0] to r[p]")
    if r[0] <= 0:
        raise ValueError("r[0] must be positive")
    a = [0.0] * (p + 1)  # a[0] is unused
    e = float(r[0])
    for i in range(1, p + 1):
        if e <= 0.0:
            break
        acc = r[i] - sum(a[j] * r[i - j] for j in range(1, i))
        k = acc / e
        new = a[:]
        new[i] = k
        for j in range(1, i):
            new[j] = a[j] - k * a[i - j]
        a = new
        e *= 1.0 - k * k
    return a[1:], e


def sine(f: float, fs: float, n: int, amp: float = 1.0, phase: float = 0.0) -> List[float]:
    """x[i] = amp sin(2 pi f i / fs + phase) for i = 0 to n - 1."""
    return [amp * math.sin(2.0 * math.pi * f * i / fs + phase) for i in range(n)]


def pulse_train(f0: float, fs: float, n: int) -> List[float]:
    """Unit pulses at the samples round(j fs / f0), j = 0, 1, 2, ..., and 0 elsewhere, n samples."""
    if f0 <= 0:
        raise ValueError("f0 must be positive")
    x = [0.0] * n
    period = fs / f0
    j = 0
    while True:
        pos = int(math.floor(j * period + 0.5))
        if pos >= n:
            break
        x[pos] = 1.0
        j += 1
    return x


def white_noise(rng, n: int, sigma: float) -> List[float]:
    """n samples of Gaussian noise with mean 0 and standard deviation sigma, from rng (a random.Random)."""
    return [rng.gauss(0.0, sigma) for _ in range(n)]


def all_pole(x: Sequence[float], a: Sequence[float]) -> List[float]:
    """Filter x through 1 / A(z): y[n] = x[n] + sum_{k=1}^{p} a_k y[n - k], with zero initial state."""
    p = len(a)
    y: List[float] = []
    for i, v in enumerate(x):
        acc = float(v)
        for k in range(1, p + 1):
            if i - k < 0:
                break
            acc += a[k - 1] * y[i - k]
        y.append(acc)
    return y
phase_vocoder.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-vocoder/. The authors are listed in prov/M9RGV0.jsonl.

"""The phase vocoder: time stretching by the STFT with phase propagation.

Analysis frames start every Ha samples, synthesis frames every Hs samples, so the
duration changes by the factor Hs / Ha. Each bin keeps its magnitude. Its phase
is advanced by Hs times its instantaneous frequency, estimated from the phase
change between two analysis frames:

    omega_k = 2 pi k / N                                (the bin center)
    delta   = princarg(phi_t[k] - phi_{t-1}[k] - Ha omega_k)
    omega   = omega_k + delta / Ha                      (the instantaneous frequency)
    psi_t[k] = psi_{t-1}[k] + Hs omega                  (the synthesis phase)

where princarg maps an angle to [-pi, pi). The frames are put back by weighted
overlap-add: y = sum_t w(n - t Hs) frame_t(n - t Hs) / sum_t w(n - t Hs)^2.
"""

import cmath
import math
from typing import List, Sequence

from nlsdsp import fft


def princarg(phase: float) -> float:
    """The principal argument: phase + 2 pi m in [-pi, pi) for the integer m that puts it there."""
    return phase - 2.0 * math.pi * math.floor((phase + math.pi) / (2.0 * math.pi))


def periodic_hann(n: int) -> List[float]:
    """w[i] = 0.5 - 0.5 cos(2 pi i / n): the Hann window whose shifts by n / 4 add to a constant."""
    return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / n) for i in range(n)]


def ifft(spec: Sequence[complex]) -> List[complex]:
    """The inverse DFT by the forward FFT of the conjugate."""
    n = len(spec)
    return [v.conjugate() / n for v in fft([s.conjugate() for s in spec])]


def stft(x: Sequence[float], n: int, hop: int, window: Sequence[float]) -> List[List[complex]]:
    """The DFTs of the windowed frames x[t hop .. t hop + n - 1]; the last partial frame is dropped."""
    out = []
    for start in range(0, len(x) - n + 1, hop):
        out.append(fft([x[start + i] * window[i] for i in range(n)]))
    return out


def instantaneous_frequency(prev: complex, cur: complex, k: int, n: int, hop: int) -> float:
    """omega_k + princarg(arg cur - arg prev - hop omega_k) / hop, in radians per sample."""
    omega_k = 2.0 * math.pi * k / n
    delta = princarg(cmath.phase(cur) - cmath.phase(prev) - hop * omega_k)  # @line L4
    return omega_k + delta / hop  # @line L5


def overlap_add(frames: Sequence[Sequence[float]], hop: int, window: Sequence[float]) -> List[float]:
    """Weighted overlap-add: sum of window * frame at t hop, divided by the sum of window^2 where it is not tiny."""
    n = len(window)
    length = (len(frames) - 1) * hop + n if frames else 0
    y = [0.0] * length
    norm = [0.0] * length
    for t, fr in enumerate(frames):
        for i in range(n):
            y[t * hop + i] += window[i] * fr[i]
            norm[t * hop + i] += window[i] ** 2
    return [v / z if z > 1e-8 else 0.0 for v, z in zip(y, norm)]


def time_stretch(x: Sequence[float], ratio: float, n: int = 1024, ha: int = 256) -> List[float]:
    """Stretch the duration of x by about ratio (> 1 is slower) and keep its pitch. n must be a power of 2."""
    hs = round(ha * ratio)
    window = periodic_hann(n)
    spectra = stft(x, n, ha, window)  # @line L1
    if not spectra:
        return []
    psi = [cmath.phase(v) for v in spectra[0]]  # @line L2
    frames = [[v.real for v in ifft(spectra[0])]]
    for t in range(1, len(spectra)):  # @line L3
        prev, cur = spectra[t - 1], spectra[t]
        for k in range(n):
            psi[k] += hs * instantaneous_frequency(prev[k], cur[k], k, n, ha)  # @line L6
        spec = [abs(cur[k]) * cmath.exp(1j * psi[k]) for k in range(n)]  # @line L7
        frames.append([v.real for v in ifft(spec)])
    return overlap_add(frames, hs, window)  # @line L8


def resample_linear(x: Sequence[float], factor: float) -> List[float]:
    """Read x at the positions i * factor by linear interpolation: factor > 1 makes it shorter and higher."""
    out = []
    pos = 0.0
    while pos <= len(x) - 1:
        i = int(pos)
        frac = pos - i
        nxt = x[i + 1] if i + 1 < len(x) else x[i]
        out.append((1 - frac) * x[i] + frac * nxt)
        pos += factor
    return out


def pitch_shift(x: Sequence[float], factor: float, n: int = 1024, ha: int = 256) -> List[float]:
    """Raise the pitch by factor and keep the duration: stretch by factor, then resample by factor."""
    hs = round(ha * factor)
    return resample_linear(time_stretch(x, hs / ha, n, ha), hs / ha)
test_phase_vocoder.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-vocoder/. The authors are listed in prov/M9RGV0.jsonl.

import cmath
import math
import random
import unittest

from nlsdsp import fft, sine
from phase_vocoder import (
    ifft,
    instantaneous_frequency,
    overlap_add,
    periodic_hann,
    pitch_shift,
    princarg,
    resample_linear,
    stft,
    time_stretch,
)

FS = 8000


def zero_crossing_freq(v, lo, hi):
    """The frequency from the rising zero crossings of v in [lo, hi)."""
    c = [i for i in range(max(lo, 1), hi) if v[i - 1] < 0 <= v[i]]
    return (len(c) - 1) / ((c[-1] - c[0]) / FS)


class TestPrincarg(unittest.TestCase):
    def test_range_and_congruence(self):
        rng = random.Random(1)
        for _ in range(500):
            a = rng.uniform(-100.0, 100.0)
            p = princarg(a)
            self.assertGreaterEqual(p, -math.pi)
            self.assertLess(p, math.pi)
            m = (a - p) / (2.0 * math.pi)
            self.assertAlmostEqual(m, round(m), places=9)

    def test_fixed_points(self):
        for a in (0.0, 1.0, -3.0, 3.1):
            self.assertAlmostEqual(princarg(a), a, places=12)
        self.assertAlmostEqual(princarg(math.pi), -math.pi, places=12)


class TestTransforms(unittest.TestCase):
    def test_ifft_inverts_fft(self):
        rng = random.Random(2)
        x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(64)]
        y = ifft(fft(x))
        self.assertLess(max(abs(a - b) for a, b in zip(x, y)), 1e-12)

    def test_hann_overlap_is_constant(self):
        w = periodic_hann(64)
        for i in range(16):
            self.assertAlmostEqual(sum(w[i + 16 * j] for j in range(4)), 2.0, places=12)


class TestInstantaneousFrequency(unittest.TestCase):
    def test_exact_for_complex_exponential(self):
        # A complex exponential of any frequency: the estimate is exact for the bins near it.
        n, hop = 256, 64
        w = periodic_hann(n)
        for f in (0.1, 0.2345, 0.31, 1.0):
            x = [cmath.exp(1j * f * i) for i in range(n + hop)]
            a = fft([x[i] * w[i] for i in range(n)])
            b = fft([x[hop + i] * w[i] for i in range(n)])
            k = round(f * n / (2.0 * math.pi))
            for kk in (k - 1, k, k + 1):
                self.assertAlmostEqual(instantaneous_frequency(a[kk], b[kk], kk, n, hop), f, places=9)

    def test_page_example(self):
        x = sine(440, FS, 4096, 0.5)
        spectra = stft(x, 1024, 256, periodic_hann(1024))
        om = instantaneous_frequency(spectra[0][56], spectra[1][56], 56, 1024, 256)
        self.assertAlmostEqual(om * FS / (2 * math.pi), 440.0, places=4)
        self.assertAlmostEqual(abs(spectra[1][56]), 119.767, places=2)


class TestStretch(unittest.TestCase):
    def test_identity_when_hops_are_equal(self):
        rng = random.Random(3)
        x = [rng.uniform(-1, 1) for _ in range(3000)]
        y = time_stretch(x, 1.0, 256, 64)
        # Where the window sum is not small, the output equals the input.
        self.assertLess(max(abs(a - b) for a, b in zip(x[256:2700], y[256:2700])), 1e-10)

    def test_overlap_add_of_windowed_frames(self):
        w = periodic_hann(16)
        x = [float(i % 7) for i in range(64)]
        fr = [[x[s + i] * w[i] for i in range(16)] for s in range(0, 49, 4)]
        y = overlap_add(fr, 4, w)
        for i in range(12, 52):
            self.assertAlmostEqual(y[i], x[i], places=10)

    def test_length(self):
        x = sine(440, FS, 4096, 0.5)
        for ratio in (0.75, 1.5, 2.0):
            y = time_stretch(x, ratio)
            hs = round(256 * ratio)
            self.assertEqual(len(y), 12 * hs + 1024)

    def test_stretched_sine_keeps_frequency(self):
        x = sine(440, FS, 4096, 0.5)
        y = time_stretch(x, 1.5)
        self.assertEqual(len(y), 5632)
        f = zero_crossing_freq(y, 1100, 4800)
        self.assertLess(abs(f - 440.0) / 440.0, 0.005)
        peak = max(abs(v) for v in y[1100:4800])
        self.assertLess(abs(peak - 0.5), 0.05)

    def test_pitch_shift(self):
        x = sine(440, FS, 4096, 0.5)
        y = pitch_shift(x, 1.25)
        self.assertLess(abs(len(y) - 4096) / 4096, 0.06)
        f = zero_crossing_freq(y, 1100, 3000)
        self.assertLess(abs(f - 550.0) / 550.0, 0.005)

    def test_resample_linear(self):
        x = [float(i) for i in range(10)]
        self.assertEqual(resample_linear(x, 2.0), [0.0, 2.0, 4.0, 6.0, 8.0])
        self.assertEqual(resample_linear(x, 0.5)[:4], [0.0, 0.5, 1.0, 1.5])

    def test_short_input(self):
        self.assertEqual(time_stretch([0.0] * 100, 2.0), [])


if __name__ == "__main__":
    unittest.main()

History

James Flanagan and Roger Golden of Bell Labs published the phase vocoder in 1966 for speech coding: each channel of a filter bank was sent as its magnitude and its phase derivative, the instantaneous frequency, which change slowly and need fewer bits than the wave. Michael Portnoff showed in 1976 how to compute it with the FFT, which made it practical, and it became a standard tool for time stretching and pitch shifting in computer music. Jean Laroche and Mark Dolson analyzed its phasiness in 1999 and proposed phase locking around spectral peaks, which most later implementations use.

References

  1. J. L. Flanagan and R. M. Golden, Phase Vocoder, Bell System Technical Journal 45(9), 1966, 1493 to 1509, the whole paper (the analysis into magnitude and phase derivative per channel, and the synthesis from them)
  2. M. R. Portnoff, Implementation of the digital phase vocoder using the fast Fourier transform, IEEE Transactions on Acoustics, Speech, and Signal Processing 24(3), 1976, 243 to 248, the whole paper (the phase vocoder computed with the FFT)
  3. J. Laroche and M. Dolson, Improved phase vocoder time-scale modification of audio, IEEE Transactions on Speech and Audio Processing 7(3), 1999, 323 to 332, the description of the standard phase vocoder, its phasiness, and the phase locking methods

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example