Rotate sound between time and spectral domain and apply transformations.
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-10-13 21:42:25 +02:00
bin Initial commit 2026-10-13 21:42:25 +02:00
src Initial commit 2026-10-13 21:42:25 +02:00
tests Initial commit 2026-10-13 21:42:25 +02:00
.gitignore Initial commit 2026-10-13 21:42:25 +02:00
BUILD_INFO.txt Initial commit 2026-10-13 21:42:25 +02:00
Cargo.lock Initial commit 2026-10-13 21:42:25 +02:00
Cargo.toml Initial commit 2026-10-13 21:42:25 +02:00
README.md Initial commit 2026-10-13 21:42:25 +02:00

spectral-rotate

A Linux Rust CLI for converting a complete WAV recording into two WAVs containing its Fourier magnitudes and phases, and converting those files back into time-domain audio.

Build and install

The download also includes bin/spectral-rotate-linux-x86_64, a prebuilt Linux x86-64 executable linked against glibc. Run it directly (use chmod +x if your archive extractor drops executable permissions). On other architectures or incompatible libc versions, build from source using the commands below.

Install a current stable Rust toolchain and a C linker (on Debian/Ubuntu, build-essential supplies the linker), then run:

cargo build --release --locked
cargo test --locked
# Optional: install the command into ~/.cargo/bin
cargo install --path . --locked

The executable is target/release/spectral-rotate. It has no external audio or FFT library dependency. --help and each subcommand's --help describe the CLI.

Usage

# Time -> frequency
spectral-rotate to-frequency input.wav --amplitudes amplitudes.wav --phases phases.wav

# Frequency -> time, preserving the original phases
spectral-rotate to-time amplitudes.wav --phases phases.wav --output restored.wav

# Frequency -> time with zero phases (default)
spectral-rotate to-time amplitudes.wav --output zero-phase.wav

# Frequency -> time with random phases
spectral-rotate to-time amplitudes.wav --random-phases --output randomized.wav

# Repeatable random phases
spectral-rotate to-time amplitudes.wav --random-phases --seed 42 --output seeded.wav

forward and inverse are aliases for to-frequency and to-time. -a, -p, and -o abbreviate --amplitudes, --phases, and --output. The phase file and --random-phases are mutually exclusive. A seed requires --random-phases. Output paths must not already exist; input files cannot be overwritten. Parent directories must exist.

Spectrum editing (version 0.2.0)

# Move bins up 100 positions; discard overflow, zero-fill the bottom
spectral-rotate to-time amplitudes.wav -p phases.wav --shift 100 -o shifted.wav

# Circular shift backward by one quarter of the entire bin sequence
spectral-rotate to-time amplitudes.wav --shift-rel -0.25 --wrap -o rotated.wav

# Reverse the full spectrum, then shift down 12 bins with clipping
spectral-rotate to-time amplitudes.wav -p phases.wav --flip --shift -12 --wrap=false -o flipped.wav
Argument Meaning
--shift INTEGER Move bins by a signed number of positions; positive increases indices.
--shift-rel NUMBER Fraction of full length N, in [-1, 1]; converted to round(NUMBER * N) bins, with half values rounded away from zero.
--wrap / --wrap=true Wrap shifted bins circularly at either edge.
--wrap=false (default) Discard bins shifted outside the array and fill vacated positions with zero magnitude.
--flip Reverse all N positions: source bin k moves to N-1-k.

--shift and --shift-rel are mutually exclusive. With wrapping, a relative shift of +1 or -1 is a full revolution and leaves positions unchanged. With clipping, either value removes every bin. Larger integer shifts work too: wrapping reduces modulo N; clipping shifts of at least N in either direction produce silence. Frame count, sample rate, and channel count remain unchanged.

Processing order is clamp negative magnitudes to zero → assign supplied, zero, or random phases → flip → shift → inverse FFT → retain real component. Magnitude and phase travel together as one complex coefficient. For random phases, assignment happens before any positional edits.

These operations use the existing full, two-sided FFT array in natural order, not a sorted nonnegative-frequency axis. A reversal is not the same operation as swapping positive and negative frequency signs (k -> -k mod N). In particular, a full reversal moves DC to index N-1.

Signed integer WAV files are decoded normally. Negative amplitude values are clamped to zero (max(value, 0)), not made positive with an absolute value, not rebased by adding a DC offset, and not reinterpreted as unsigned bit patterns. Nonnegative samples in a signed file are unchanged. This also applies to negative float samples. Phase samples retain their signs.

Exact file convention

For an input with N frames, C channels, and sample rate Fs, each output has exactly N frames, C channels, and sample rate Fs. Every channel is transformed independently. In a multichannel WAV, samples are interleaved in the normal WAV order: frame k contains bin k for each channel.

The transform covers the entire recording. There is no window, STFT, overlap, resampling, FFT-size rounding, or zero padding. N need not be a power of two.

X[k] = sum over n=0..N-1 of x[n] * exp(-i * 2*pi*k*n/N)
amplitudes[k] = abs(X[k]) / N
phases[k] = atan2(imag(X[k]), real(X[k]))    (radians)

x[n] = sum over k=0..N-1 of
       amplitudes[k] * exp(i * phases[k]) * exp(i * 2*pi*k*n/N)

The inverse FFT is unnormalized because the forward magnitudes already include 1/N. This is a two-sided normalized magnitude spectrum, not a one-sided peak-amplitude or power spectrum. A bin-centered cosine of amplitude A has magnitude A/2 at each of its positive and negative frequency bins.

Bin index Meaning
0 DC, 0 Hz
1 through floor((N-1)/2) Positive frequencies, k * Fs / N Hz
N/2, only when N is even Nyquist, Fs/2 Hz
floor(N/2)+1 through N-1 Negative frequencies, (k-N) * Fs / N Hz

The bins are in natural FFT order, without fftshift. Frequency resolution is Fs/N Hz. Keeping Fs in the WAV header gives the spectrum files the same playback duration as the input; it does not make their sample positions time coordinates.

Magnitudes are nonnegative. Phases are in [-pi, pi] on export; import accepts finite radians. Zero-magnitude bins have no meaningful phase. No extra metadata or sidecar is needed, but these conventions must be retained when editing files.

Real audio and phase handling

An unmodified real signal has conjugate symmetry: X[N-k] = conjugate(X[k]). DC and even-length Nyquist coefficients are real. Editor changes, clamping, shifting, and flipping may break this symmetry.

Version 0.2.0 accepts asymmetric spectra. It computes the complete complex inverse FFT and writes its real component as the audio WAV. A warning is printed for each channel with asymmetry above a float32 rounding tolerance (2e-6 * maximum_channel_magnitude + 1e-12). The imaginary component cannot be represented in the real audio output and is discarded. This is mathematically equivalent to projecting the spectrum to Y[k] = (X[k] + conjugate(X[(N-k) mod N])) / 2 before inversion. Both halves of the input contribute; the program does not replace one half with a mirror of the other. As a consequence, asymmetric edited magnitudes are not necessarily preserved in a subsequent forward transform, and cancellation is possible.

  • With a phase WAV, both supplied halves are used. Mismatched sample rate, channel count, or frame count is still an error.
  • Without a phase WAV, all phases are zero. This cannot recover the original timing or waveform, but preserves magnitudes when they are symmetric and positional edits do not break that symmetry.
  • With --random-phases, positive-frequency bins receive uniformly random phases in [-pi, pi), and their partners receive the opposite phases. Each bin keeps its own clamped magnitude. DC and Nyquist receive random signs (phases 0 or pi). Channels are randomized independently. Symmetric inputs remain real before positional edits. A seed repeats results for this locked dependency set, not necessarily across future software versions.

Sample formats and precision

  • Reads uncompressed integer PCM WAV: 8, 16, packed 24, and 32 bits.
  • Reads IEEE float32 WAV. Compressed WAV and float64 WAV are not supported.
  • PCM is converted to float64 by dividing by 2^(bits-1), mapping its minimum to -1 and its maximum to just below +1. Float input is taken literally.
  • FFT, polar conversion, and inverse FFT use float64.
  • All outputs, including reconstructed audio, are IEEE float32 WAV.
  • No clipping, peak normalization, dB conversion, or dithering is applied. Float samples outside [-1, 1] remain intact. NaN, infinity, and values that cannot be represented as finite float32 output are errors.

The magnitude/phase float32 serialization introduces small round-trip error; this is not bit-exact archival storage for integer32 input. Zero/random phases can substantially increase waveform peaks even while preserving energy. Spectrum files are data containers; audio editors that normalize, clip, resample, or convert them to integer PCM can destroy the stored information.

Length, memory, and file limits

Any positive frame count supported by available memory can be transformed, including odd and prime lengths. Empty files are rejected. This is an in-memory whole-file FFT, so it cannot handle an unlimited-duration stream. Awkward or prime lengths can take more time and scratch memory than smoothly factored lengths.

Forward processing holds about 24NC bytes of float64 input/output arrays plus 16*N bytes for the channel's complex buffer, FFT scratch, and plan memory. Inverse memory depends on whether a phase file is loaded. Large jobs can exceed system memory; allocation failures inside FFT/dependency code can abort the process.

The WAV backend uses standard RIFF, with a roughly 4 GiB per-file limit. RF64 and Wave64 are not supported. An output size check rejects files beyond that limit. Float32 output can exceed the limit even if a smaller integer input fits it. At 48 kHz stereo, 4 GiB of float32 samples represents about 3.1 hours, but RAM may become the limiting factor much earlier.

Outputs are encoded into temporary files beside their destinations, flushed, and published without overwriting existing files. On an ordinary publish error, already published files from the batch are removed on a best-effort basis. Publishing a pair is not a filesystem transaction: a crash between publishing the two files can leave only one. File metadata beyond sample rate and channel count (e.g. tags, cue points, speaker/channel masks) is not preserved.

Verification

cargo test --locked covers float32 file round trips at single-sample, even, odd, prime and composite lengths; stereo channel isolation; known DFT bin values; PCM 8/16/24/32 decoding; float samples outside [-1, 1]; zero/random magnitude preservation; seeded reproducibility; nonfinite samples and invalid metadata; overwrite protection; failed-output cleanup; and actual CLI execution and option conflicts. Additional edit tests cover exact wrapped/clipped mappings, i64 shift extremes, relative shift bounds and rounding, single-bin spectra, negative-value clamping, and an independent direct inverse-DFT oracle across multiple lengths, channels, phases, flips, and shifts.

Implementation references: RustFFT and Hound.