Real-time audio spectrum visualizer using FFT
https://mooncakes.io/docs/IvanAXu/moonFFTmusic@0.1.4

| # | Feature | Description |
|---|---|---|
| 1 | Attack/release envelope | Fast rise (0.7), slow fall (0.15) — natural amplitude decay |
| 2 | Spatial smoothing | In-place 3-tap blur [0.2, 0.6, 0.2] with rolling buffer (no temp array) |
| 3 | Row-level brightness gradient | 3D glow effect — top of bars brighter, bottom dimmer |
| 4 | Left-side dB scale | Professional meter labels: 0dB, -12, -24, -36, -48 |
| 5 | Segmented RMS meter | Green (<60%) → yellow (<85%) → red zones with dB readout |
| 6 | Peak hold markers | Bold ━ with exponential decay (×0.88 per frame) |
| 7 | Separator line | ── between header and spectrum area |
| 8 | Musical note detection | Shows note name + octave + cents (e.g., A#4+, A3-) |
| 9 | Bar grouping | Subtle gap every 3 bars for cleaner visual separation |
| 10 | Bottom glow reflection | 3-row dim mirror of spectrum with fading intensity |
| 11 | Dashed reference line | ┄ pattern at -12dB, · at gap positions |
| 12 | Bar tops | Top cell is a fractional block flush on the body (no half-cell gap) |
| 13 | Peak frequency marker | Dominant bar's contour glyph glows yellow on the envelope row |
| 14 | Vertical frequency grid | Faint ╎ at label positions (50Hz – 10kHz) |
| 15 | Magnitude-based color | Brightness = 50% row position + 50% magnitude ratio |
| 16 | True-color 24-bit RGB gradient | Smooth HSL-based rainbow (blue→cyan→green→yellow→red) with a white-glow core, using \u001b[38;2;R;G;Bm, precomputed per-bar |
| 17 | Beat detection with pulse glow | RMS energy history tracking; border flashes warm orange on detected beats, ♫ indicator in header |
| 18 | Waveform strip | Time-domain signal display at bottom showing the actual audio waveform shape |
| Optimization | Before | After | Impact |
|---|---|---|---|
| FFT data layout | Array[Complex] (3 allocs/butterfly) | Array[Double] re/im (0 allocs) | ~15,000 fewer allocs/frame |
| Twiddle factors | Recomputed per stage (log₂N times) | Single table, strided lookup | Eliminates N/2 cos/sin calls/frame |
| Hann window | Recomputed per frame | Precomputed once at startup | Eliminates N cos calls/frame |
| Bin mapping | log_freq_bin() per bar per frame | Precomputed bin_map[] array | Eliminates 60 pow/log2 calls/frame |
| Grid detection | Linear search per bar per row | Precomputed is_grid[] boolean array | O(1) lookup vs O(k) search |
| Frequency labels | O(n²) string concatenation | StringBuilder | Linear-time label rendering |
| Spatial smoothing | Temp array allocation per frame | In-place rolling buffer | Zero per-frame array allocs |
| FFT buffers | Allocated per frame | Pre-allocated, reused | Zero per-frame array allocs |
| Color table | Array[Array[String]] (2D, double indirection) | Flat Array[String] with bar*nbl+level index | One array access vs two per bar per row |
| Height processing | 4 separate loops over num_bars | 2 fused loops (height+envelope, smoothing+peak) | Halves loop overhead |
| Row invariants | row_contrib[row] + beat_boost recomputed per bar | Hoisted as row_base per row | Eliminates 1560 redundant additions/frame |
| Bar offset | bar * num_brightness_levels per bar per row | Precomputed bar_offsets[] array | Eliminates 1560 multiplications/frame |
| Color table access | Safe ctx.color_table[bar][level] | color_tbl.unsafe_get(bar_off + level) | Bypasses bounds check in hot path |
| Bin aggregation | Safe ctx.bin_starts[bar] access | unsafe_get + local reference | Bypasses bounds check |
| Waveform fill | Safe array access | unsafe_set/unsafe_get | Bypasses bounds check |
| Total time string | format_time(total, rate) per frame | Precomputed once at startup | Eliminates string formatting per frame |
| Frequency label text | O(60×8) nested loop + format_freq per frame | Precomputed label_strings[] array | Eliminates 480 iterations + string formatting/frame |
| dB scale labels | hsl_to_rgb per row per frame | Precomputed db_scale_labels[] array | Eliminates 20 hsl_to_rgb calls/frame |
| Waveform colors | String interpolation per bar per frame | Precomputed 9×256=2304 color table | Eliminates 60 string interpolations/frame |
| Sparkline colors | String interpolation per bar per frame | Precomputed 4×8=32 color table | Eliminates 60 string interpolations/frame |
| bar_offsets array | Array::makei per frame | Precomputed in DisplayContext | Eliminates 1 array allocation/frame |
| bar_fade array | Array::make per frame | Reusable field in PeakTrail | Eliminates 1 array allocation/frame |
| Height double conversion | to_double() × height_factor per bar per row | Precomputed heights_d[] before row loop | Eliminates 2400 to_double+multiply/frame |
| IIR anti-flicker state | Array[Int32] (integer IIR can't eliminate ±1 oscillation) | Array[Double] (float IIR before quantization) | Eliminates residual ±1 flicker |
| Dominant bar marker | Raw dominant_bar recomputed per frame | Sticky dom_bar passed from main.mbt | Eliminates dominant-marker jumping |
| Rainbow hue rotation | rotate_hue() 1920 string allocs/frame | Precomputed 40 color tables, swap index | Zero per-frame string allocs |
| heights_d/peak_heights_d | Array::make per frame | Pre-allocated in DisplayContext | Eliminates 120 Double allocs/frame |
| Terminal height | Fixed max_height=26 (45 lines/frame) | Auto-detect LINES env var | Eliminates scroll flicker on small terminals |
| Layout compaction | 45 lines/frame (header+sep+26 bars+5 glow+...) | 30 lines/frame (removed sep, glow 5→3) | Fits 30-line terminals |
# Unix (Linux / macOS)
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
# Verify installation
moon versioncd moonFFTmusic
# Generate a 440Hz test tone and visualize it
./run.sh
# Specify a WAV file and FFT size
./run.sh assets/chord.wav 1024cd moonFFTmusic
# Step 1: Generate a test WAV file
python3 scripts/gen_wav.py assets/test.wav music # 120BPM loop: kick+bass+chords+hats
python3 scripts/gen_wav.py assets/chord.wav chord # Chord: 220+440+880+2000Hz
# Step 2: Build the project
moon build --target native
# Step 3: Run the visualizer
moon run src/main assets/test.wav 1024cd moonFFTmusic
moon build --target native
# Binary location after build
./_build/native/debug/build/src/main/main.exe assets/test.wav 1024moon run src/main /path/to/your/song.wav 2048| Argument | Required | Default | Description |
|---|---|---|---|
| wav_file | Yes | — | Path to a 16-bit PCM WAV file |
| fft_size | No | 1024 | FFT window size, must be power of 2 |
| Detection | Node probed |
|---|---|
| NVIDIA | /dev/nvidia0 … /dev/nvidia15 |
| AMD / Intel (DRM) | /dev/dri/card0 … card7, /dev/dri/renderD128 … renderD135 |
| CPU fallback | no GPU node found |
| Scheme | Description |
|---|---|
| rainbow (default) | Hue anchored to frequency (indigo bass → red treble) with an aurora hue rotation |
| fire | Red base → yellow crest, painted by loudness — every column shares one flame ramp |
| ice | Violet base → cyan crest, painted by loudness — a cold crystalline look |
╔━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╗
║ 🎵 MoonFFTmusic — Real-time Spectrum Analyzer ║
║ 44100Hz | FFT 1024 | Peak 43Hz (F1-) ♫ | 120 BPM | 0:1.0 ║
╚━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╝
│ ╱────╱╱──────────────╲╲∨╱╱──╲╲╲╲──────────────╱╱──∨──╲╲─────
│ 🎹 ▮▏│▏││▏│▏│▏││▏│▏││▏│▏│▏│ C3-C5 ♥ ○○●○
│0dB ╎ ████████████▆▃ ╎ ╎ ╎ ╎ ╎
│ ╎ ██████████████ ╎ ╎ ╎ ╎ ╎
│ ━━━━━━██████████████ ╎ ╎ ╎ ╎ ╎
│ ━━━━━▇██████████████ ╎ ╎ ╎ ╎ ╎
│ ━━━━━███████████████━━╎ ▁ ╎ ╎ ╎ ╎
│ ━━━━━███████████████━━╎ █━ ╎ ╎ ╎ ╎
│ ━━━━━███████████████━━╎ ██━ ╎ ╎ ╎ ╎
│-6dB ━━━━▇███████████████▄━╎ ██━ ╎ ╎ ╎ ╎
│ ┄━━━━█████████████████━╎┄┄██━┄╎┄┄┄┄┄╎┄┄┄┄┄┄┄┄╎┄┄┄┄┄┄╎┄┄┄┄┄┄┄
│ ━━━━█████████████████━╎ ██━ ╎ ╎ ╎ ╎
│ ▆▆▆▆█████████████████━╎ ██━ ╎ ╎ ╎ ╎
│ █████████████████████━╎ ██━ ╎ ╎ ╎ ╎
│ ━█████████████████████━━ ━██▆ ╎ ╎ ╎ ╎
│ ━█████████████████████━━━━███━╎ ╎ ╎ ╎
│-12dB━█████████████████████━━━▅███━╎ ╎ ╎ ╎
│ ━█████████████████████━━━████━╎ ╎ ╎ ╎
│ ━██████████████████████━━████━╎ ╎ ╎ ━━ ╎
│ ▇██████████████████████━━████━╎ ╎ ╎ ━━ ━━
│ ███████████████████████━━████━╎ ╎ ╎ ━━ ━━
│ ███████████████████████━━████▇╎ ╎ ╎ ▃▃━━━
│-18dB███████████████████████━▃█████━ ╎ ╎ ██━▄▄
│ ███████████████████████▃██████━ ╎ ╎ ██▁██
│ ██████████████████████████████━ ╎ ╎ ━█████━
│ ██████████████████████████████▂ ╎ ╎ ━█████━
│ ███████████████████████████████ ╎ ╎ ▇█████▃
│ ███████████████████████████████━ ╎ ╎ ███████
│ ███████████████████████████████▁ ╎ ╎━███████━
│-24dB████████████████████████████████ ╎ ╎████████▄
│ ████████████████████████████████▁ ╎ ━█████████━
│ █████████████████████████████████ ╎ ██████████▆
│ █████████████████████████████████▆ ╎ ▅███████████▄
│ ██████████████████████████████████▇▂╎ ▁▆█████████████▅▁
│ ████████████████████████████████████▆▄▃▃▄▆█████████████████▆
└─────────────────────────────────────────────────────────────────
50Hz 100Hz 200Hz 500Hz 1kHz 2kHz 5kHz 10kHz
WV ⠴⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠲⠖⠒⠒⠒⠒⠒⠒⠒⠦⠤⠤⠤⢤⣀⡤⣄⣀⣀⣀⣀⣀⣀⣠⠤⠖⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠶⠒⠒⠒
BASS ██████████░░░░ MID ████████░░░░░░ TREB ███░░░░░░░░░░░
RMS: [████████████████████████████████░░░░░░░░░░░░] -16.9 dB
║║║║║║║║║║║║║║║║║║║║║▓░░░░░░░░░░░░░░░░░░░░ 50% 0:1.0 / 0:2.0| Effect | Description |
|---|---|
| 🌈 Rainbow hue rotation | Color spectrum flows and shifts 3°/frame like aurora (rainbow scheme) |
| 🏔️ Monstercat smoothing | Neighbor fill from cava: tall bars prop up valleys (h[j] ← h[i]/1.5^|i-j|), reading as continuous ridges instead of sawtooth |
| 📌 Peak caps | cava-style: bright-white ━ cap holds above each bar, then falls with accelerating gravity |
| ⚡ Beat flash border | Accents flash white-hot, soft beats warm; ═→━ on strong hits |
| 💥 Beat bloom | Fast beat pulse + sustained intensity brighten all bars |
| 👑 Bar top crown | Topmost fractional cell gets +8 brightness — glowing crest |
| 📡 Scanline | A +2 brightness row sweeps up/down across spectrum |
| 🔦 Dominant spotlight | Main frequency bar + neighbors brighten on beat pulses |
| 📊 Progress pulse | Cyan→violet progress bar (distinct from spectrum) pulses on beats |
| 🎚️ RMS beat glow | RMS label turns yellow on strong beats |
| 🌊 Spectrogram waterfall | 3-row scrolling history; per-frequency hue (matches bars) with intensity brightness |
| 🎹 Piano keyboard | 2-octave mini keyboard with detected note highlighted ▮ |
| 🎵 BPM estimation | Beat timing analysis with ♥/♡ indicator and BPM display in header |
| 🥁 Rhythm indicator | 4-step beat marker advancing with each detected beat |
| 🔊 Frequency band meters | BASS/MID/TREBLE 10-cell horizontal energy meters |
| 🎛️ Auto-gain control | Dynamic sensitivity adjustment for quiet/loud sections |
| 🎶 Note detection | Real-time MIDI note name (e.g. G4+) with cents deviation |
| Feature | Usage |
|---|---|
| #derive(Debug) | Auto-generated debug output for Complex, WavData, GpuInfo, ComputeDevice |
| Array::unsafe_get/unsafe_set | Bypass bounds check in FFT butterfly hot loop (SoA) |
| Array::mapi_in_place | In-place Hann window application (Complex path) |
| Array::makei | Functional array construction for precomputed tables |
| StringBuilder | Efficient string building for all terminal output |
| Double::clamp / Int32::clamp | Safe value clamping with labeled arguments |
| match patterns | Chunk type dispatch, arg parsing, bar render states, HSL→RGB |
| guard patterns | Early return on file not found / parse failure |
| test blocks | 32 inline tests for FFT correctness, SoA FFT, WAV parsing, args |
| enum + match | ChunkType/BarState enums for dispatch |
| mut struct fields | Mutable BeatDetector state (history_idx, beat_intensity) |
| Bit tricks | n & (n-1) for power-of-2 check, bit-reversal permutation |
| SoA pattern | Separate Array[Double] re/im for zero-alloc FFT |
| Precomputed tables | Twiddle factors, Hann window, bin mapping, bar colors — all computed once at startup |
# Run all 32 inline tests
moon test --target native
# Type check with no warnings
moon check --target native --deny-warn
# Format check
moon fmt --checkmoonFFTmusic/
├── .github/workflows/ci.yml # GitHub Actions CI
├── src/main/
│ ├── moon.pkg # Package imports
│ ├── fft.mbt # FFT engine (Complex + SoA) + tests
│ ├── wav.mbt # WAV parser + tests
│ ├── device.mbt # GPU/CPU device detection + selection
│ ├── display.mbt # ANSI renderer (18 effects, true-color, beat detection)
│ └── main.mbt # Entry point + SoA FFT loop + arg parsing + tests
├── scripts/
│ └── gen_wav.py # WAV file generator (sine/chord/music modes)
├── assets/
│ ├── chord.wav # Demo chord WAV (220+440+880+2000Hz)
│ └── test.wav # Demo music loop (120BPM, dynamic)
├── run.sh # Build & run script
├── moon.mod # Module definition
└── README.md