Control events are zero-duration log markers about the run rather than
signals on the air. A busy capture carries thousands, and they clutter the
overlay without saying anything about what was transmitted, so the GUI now
starts with that kind hidden; the per-kind checkbox brings it back. The
headless --render path still enables every kind — an export should render
what was asked for, not a GUI preference.
The auto-crop notice was a full modal: it dimmed the window, took focus,
and demanded a click before the user could look at the file they had just
opened. Auto-crop is a helpful default, not a decision worth blocking on.
It is now a bottom-right toast offering Undo / Dismiss, with a progress
strip showing the remaining time so it doesn't just vanish mid-read, and
it is out of UiModalOpen() so it no longer swallows keys or blocks the
spectrogram underneath.
The countdown only advances while the window is focused, so a crop applied
during a background load is still readable when the user returns. The
per-frame step is clamped: auto-crop fires on the frame right after the
blocking STFT compute, and GetFrameTime() there reports the entire
compute, which drained the whole 5 s budget at once and made the toast
flash by in an instant.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
Three things, all surfaced while working a multi-node protocol issue on a
5.7-hour capture.
**Loading was frame-paced, not compute-bound.** The STFT overview advanced
a fixed 200 segments per frame, so the frame limiter — not the FFT — set
the pace: 478k segments at ACTIVE_FPS meant over a minute spent waiting
between frames rather than computing. The tell was absurd: backgrounding
the window, which skips presenting entirely, loaded the same file in
seconds. The progress bar was slower precisely because you were watching
it. The overview is now computed in one blocking call after presenting the
loading panel, so focused load matches the unfocused speed. The panel says
the window will stop responding and drops the percentage, which could not
animate and would have read as a hang. ACTIVE_FPS 30 -> 60 while here;
idle still parks at ~0% CPU through the event-wait path.
Background work also no longer stops when the window loses focus. Pending
work now counts as "active" regardless of focus, so the loop doesn't block
in PollInputEvents waiting for input that isn't coming, and an unfocused
frame with work outstanding skips the draw pass entirely rather than
throttling the high-res fill to the refresh rate.
**Collision detection.** Annotations that overlap in both time and
frequency are flagged, merged into contiguous regions, and drawn as red
bands confined to the band the overlap occupies (padded, so a narrow
overlap stays findable) rather than spanning the full axis and hiding the
signal being pointed at. N / Shift+N and sidebar buttons jump between
regions, centring each without disturbing the current zoom.
Point markers are excluded: control events and assertions have no band and
zero duration, and treating a missing band as "whole spectrum" — which is
how they are *drawn* — made every marker collide with whatever it sat
inside. That was 38% of the reported collisions on a real capture. Only
things that actually occupy the air can interfere. Counts verified against
an independent reference implementation on two captures.
**Scope waveform via min/max summary.** The envelope rescanned every
visible sample every frame — ~245M reads, near 1 GB of memory traffic, on
a multi-hour file, measured at ~60 ms/frame for a few hundred pixel
columns. It now draws from 1024-sample buckets built once at load (60 ms,
1.9 MB), measured at ~0.07 ms/frame. Keeping both extremes per bucket
means single-sample transients still show at full zoom-out, which plain
decimation would drop; verified that no column ever understates a true
peak. Zoomed in past a bucket it falls back to raw samples, which is cheap
there by definition.
Also fixes ComputeCollisions never running for files opened through the
file browser, and moves the collision panel above the annotations dropdown
where it isn't pushed off the bottom of the sidebar.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
Every box drew its label unconditionally, so overlapping transmissions
stacked their text into an unreadable smear — several frame names painted
over each other at the same pixels.
DrawBoxLabel now claims a screen-space rect before drawing and skips the
label if it would intersect one already placed this frame. Draw order
decides the winner, so the topmost box keeps its text and the ones beneath
go quiet instead of smearing. The claim is clipped to the box width, so a
long label reserves only what the scissor actually paints rather than
silencing neighbours over space it never uses. Nothing is lost: hovering
still reports every box under the cursor.
The stacked-hover tooltip now sits above the cursor and centred on it,
flipping below only when there is no room. It previously opened down and
to the right, covering the very boxes being described.
Also removes click-to-pin. It was never asked for, it did not reliably
work, and hover alone answers the question it was meant to serve.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
The source image was sized at one column per STFT segment with no upper
bound. That is fine for short captures but impossible for long ones: a
5.7-hour file at 12 kHz yields ~478k segments, i.e. a 478450x1025 RGBA
image (~2 GB) roughly 29x past the ~16k-per-dimension texture limit every
GL implementation enforces. The upload failed, the texture id stayed 0,
and the draw was skipped — so the spectrogram was simply blank, with no
error anywhere to say why.
Build the image for the segment range actually on screen instead of the
whole file, capped at MAX_SPECTRO_IMAGE_WIDTH. Simply clamping the
full-file width would have fixed the blank render while permanently
discarding the detail zooming is meant to reveal (478k segments into 8k
columns is 59:1, no matter how far in you go). Tying the range to the view
keeps resolution proportional to zoom: 59 segments per column at full
zoom-out, reaching 1:1 by ~1% zoom, with the image never exceeding ~33 MB.
Where several segments do share a column their per-bin MAX is kept rather
than a sum or mean, so a short burst lights its column instead of being
diluted by quiet neighbours — the same reasoning behind a min/max waveform
envelope. Amplitude normalisation is likewise scoped to the visible span,
which keeps rebuild cost independent of total duration and lets the colour
scale follow what is on screen instead of a loud burst hours away.
Rebuilds trigger when the view leaves the cached range, which is padded by
25% so ordinary panning re-renders about once every six frames rather than
every frame. The headless --render path sets no range and so still covers
the whole file, capped; verified end to end on a 5.67-hour capture, which
now renders 8110x1025 with visible structure where it previously produced
nothing at all.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
The hover hit-test collected its result into a single int, and each layer
assigned unconditionally, so the last box drawn won and everything beneath
it was silently dropped. With multiple stations transmitting concurrently
that hid most of what was there: co-located frames in the same band are
indistinguishable on screen, and the tooltip would name exactly one of
them with no indication the others existed.
Collect the hits into a stack during the same draw pass (the collision
math was already there, only the result was being discarded). When more
than one box is under the cursor the tooltip becomes a list — one row per
event, topmost-first, each with its own colour swatch so a row maps back
to a box on screen. Rows lead with node / frame / seq / ch, which is what
actually separates overlapping transmissions. Depth is capped at
MAX_HOVER_STACK with a "+N more" count so a deep pile can't cover the
spectrogram; a single hit still gets the full-detail tooltip as before.
Clicking a stack pins the list so it can be read without holding the
cursor still — otherwise the tooltip vanishes the moment you move toward
it. Click again or Esc to release. A pinned stack is a frozen snapshot,
so live hover does not overwrite it; it is dropped when the annotation
overlay is hidden or a new file is loaded, both of which would leave it
pointing at events that no longer exist.
Clicking stacked annotations pins rather than clearing the selection.
A click on empty space or a lone box clears as before.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
The minimum visible time window was a flat 2% of the file, but view.start
and view.end are normalized to the whole signal — so the achievable time
resolution scaled with file length. A 30-minute recording could never show
less than a 36-second span, while a 30-second one reached 0.6 s. Long
captures were effectively unreadable at the sample level no matter how far
you scrolled.
Derive the floor from the STFT hop instead (MinTimeViewWidth): segments sit
fftSize/HOP_RATIO samples apart, so the real limit is the point where only
a handful of segments span the viewport and further zoom would interpolate
rather than reveal. The floor is now a constant ~43 ms at 48 kHz/1024
regardless of duration — an 844x improvement on a 30-minute file, and it
tightens further with a smaller FFT. Guards cover the unloaded (sampleRate
0) and shorter-than-the-floor cases.
Zooming is also no longer forced to move both axes together. The bare wheel
keeps the existing coupled behaviour; Shift+wheel is time-only and
Ctrl+wheel frequency-only, so a long capture can be stretched along time
without collapsing the frequency range to match.
Time-axis labels now pick their precision from the span between adjacent
ticks (1 to 4 decimals, and m:ss.sss past a minute). At the spans this
change makes reachable the old fixed "%.1fs" printed the same value in
every slot, which read as a frozen axis.
Adds a `wheel X Y N [mod]` action to shot_input.sh for exercising zoom
headlessly, and known_bugs.md for behaviour that is unspecified rather
than broken.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
PlaySelectedRegion copies, bandpasses and normalises the selected span up
front, so the audio in flight is fixed the moment Space is pressed. The
playhead, though, was drawn against the live app.sel and its duration
re-derived from the live selection — so moving or resizing the selection
mid-playback made the marker jump, overrun, or scale against a region
that had nothing to do with what was audible.
Snapshot the played region (playSelStart/playSelEnd) and take the duration
from the buffer's own sample count rather than app.signal.duration, which
is derived pre-mono-downmix and disagrees for stereo files. The playhead
and the scope cursor both read the snapshot; playheadT is clamped at 1.
Also: a sub-threshold click inside an existing selection no longer clears
it. Silently resetting to full range there changes what Space plays, which
is surprising when the click was an aborted drag. A click on empty space
still resets as before.
The *semantics* of editing a selection during playback remain undefined —
whether audio should follow the box, stop, or keep going as it does now.
This commit only makes the marker honest about what is coming out of the
speakers. Recorded in known_bugs.md.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
- Scrollbars: proper track-travel geometry so a min-size thumb stays
inside the track and dragging maps 1:1 to the cursor at any zoom;
clicking the empty track jumps the view to re-center the thumb under
the cursor. Rounded thumbs with hover/active highlight; taller track.
- Spectrum slice (PSD) always spans the full frequency range; ignoring
the selection's freq bounds avoids cropping bins and skewing the
auto-ranged dB axis and peak pick. Selection rect still drawn normally.
- Default annotation overlay opacity 0.06 -> 0.24 (quiet but legible).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The font atlas was rasterized once at a fixed 16px and point-filtered, then
scaled to a logical size at draw time. On HiDPI it got upscaled (acceptable);
on standard-DPI it got downscaled, and point filtering dropped rows/columns of
the anti-aliased glyphs, thinning stems into a faint "hyper-skinny" look.
Bake the atlas at the real physical size text is drawn at
(16 * GetUIScale() * GetWindowScaleDPI().y), quantized to 4px steps, and rebuild
it via EnsureUIFont() once per frame when that density changes (resize, or
moving between monitors of different DPI). Use mipmaps + trilinear filtering so
downsampling stays smooth. Call sites are unchanged: DrawTextEx still scales the
atlas glyph to the same logical size, only the backing resolution differs.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The overview-then-idle high-res fill had two defects that left permanent
black/low-res vertical stripes:
- On any interaction the driver set isBgProcessing=false to pause, but nothing
ever re-armed it, so the background sweep died on the first pan/zoom and the
strided overview was never completed. Now isBgProcessing simply tracks
!bgFinished and the per-frame compute is gated on !IsUserInteracting(), so the
sweep resumes on its own once the user stops interacting.
- The foreground (visible-range) fill overwrote the background sweep cursor
bgHighResSeg with the current view position, so the sweep skipped everything
before the view and stranded it uncomputed. The foreground pass no longer
touches the cursor; the sweep stays monotonic from 0.
Also recolor the displayed image as segments fill in (throttled during the
sweep, forced at completion) instead of only at the very end, so freshly
computed regions actually appear; and short files whose overview is already
full-resolution (skipFactor 1) skip the sweep entirely.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rewrite --render to compute the spectrogram and write a PNG entirely on the
CPU, with no window, no GL context, and no X server. Previously it opened a
hidden GL window and grabbed LoadImageFromScreen(), which still required an X
server (Xvfb); the output was a UI screenshot rather than the spectrogram data.
The new path (RunHeadlessRender) loads the WAV, computes the STFT, colorizes
the bitmap at native STFT resolution, bakes the mLnL annotation overlay onto
it, and exports — all CPU-only. render.c gains a GL-free colorize
(BuildSpectrogramImageCPU), a CPU font loader (LoadFontCPU), and a CPU overlay
drawer (DrawAnnotationsToImage).
Annotations draw outline + label only: mLnL captures contain many overlapping
full-band boxes whose translucent fills alpha-stack to opaque and bury the
signal. The outline marks each region while the spectrogram reads through; a
dark backing strip keeps labels legible. Note: MeasureTextEx/ImageText* bail
when font.texture.id == 0, so the CPU font sets a sentinel non-zero id (the
draw path reads glyph images, never the texture).
Render options: --annotation-opacity (overlay strength), --annotation-kinds
(comma-separated kind filter), --width (resize; default native). Removed the
obsolete --pane/--height window options and the screenshot workaround.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
raylib's frame limiter partial-busy-waits ~5% of every frame interval, so
capping the FPS couldn't get idle CPU below ~5% of a core, and the audio
output device's mixing thread spun continuously even when nothing played.
- Idle render: go fully event-driven when idle. While active (focused +
something animating, or within a 0.5s grace window) run at ACTIVE_FPS;
otherwise EnableEventWaiting() so EndDrawing's PollInputEvents blocks on
glfwWaitEvents until the next input/window event. Unfocused windows skip
drawing entirely and block. Headless render is exempt (its hidden window
gets no events). Replaces the earlier fixed-FPS idle throttle.
- ACTIVE_FPS lowered 60 -> 30: ample for a non-game UI, halves active cost.
- Lazy audio device: open it on demand at first playback (EnsureAudioDevice)
and release it once idle and not playing (ReleaseAudioDevice), reopened on
the next play. Never closes mid-playback (gated on !isPlaying), so audio
always finishes first. Shutdown is guarded with IsAudioDeviceReady().
Idle/backgrounded window now drops to ~0% CPU (no render busy-wait, no audio
thread); snaps back instantly on input.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The main loop redrew the whole scene at 60 fps unconditionally, keeping
the GPU (and, on software GL, the CPU) busy even while idle — enough to
heat the machine. Add two cooling measures (desktop only):
- Idle FPS throttle: drop to 10 fps when nothing needs animating (no
input, mouse movement, playback, loading/background STFT, drag/pan, or
counting-down notice), with a 0.5s grace window; snap back to 60 fps on
activity. Measured ~34% -> ~8% idle CPU on real hardware.
- Focus pause: when the window isn't focused, skip the frame entirely —
pump events via PollInputEvents() + WaitTime() with zero drawing, so
refocus/close still register. Guarded with !headless so the hidden
render window still draws its single capture frame.
Also fix two -Wformat-truncation warnings (surfaced at -O2) in the
tx_frame label path: widen pos[16]->[28] for the worst-case " %d/%d",
and the caller's label buffer lbl[64]->[160] since base can be note[96]
(DrawBoxLabel scissor-clips to the box, so behavior is unchanged).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Commit the accumulated working-tree changes as one snapshot.
- Headless render: `--render OUT.png INPUT.wav` draws the spectrogram
(full window, or `--pane` for the spectrogram pane only) to a PNG
with no visible window. Options: `--annotations`/`--no-annotations`,
`--annotation-opacity`, `--width`/`--height`.
- mLnL annotations: parse the optional `mLnL` RIFF chunk (schema v2)
and render tx_frame/assertion/control overlays, a timeline lane, and
a waveform-scope echo, with hover tooltips on the spectrogram,
timeline, and scope.
- sched_offset_ms: parse the per-frame intent->air latency and surface
it in the hover tooltips (boxes stay air-anchored upstream).
- Supporting: build wiring (rspektrum.make), shared types/headers,
web-build and capture-script tweaks, and removal of the old
synchrosqueezing LaTeX doc.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Make the Emscripten build behave like the desktop app for loading, window
scaling, and exporting. All changes are #ifdef __EMSCRIPTEN__-gated or no-op on
desktop, so native behavior is unchanged.
Scaling:
- Drop FLAG_WINDOW_HIGHDPI on web. The emscripten-GLFW shim forces a fixed
pixel canvas style (!important) when HiDPI-aware, overriding the shell's
100vw/100vh CSS so the canvas can't fill the page; raylib's own resize/window
callbacks also disagree about dividing by devicePixelRatio, desyncing the
framebuffer from the reported screen size.
- Sync raylib's window size to window.innerWidth/innerHeight each frame via
SetWindowSize (guarded against no-op churn). This keeps screen size, GL
viewport, and projection consistent, so the UI fills the viewport and reflows
on resize like the desktop window.
Loading:
- Compute the full-resolution STFT synchronously when a file loads instead of
the desktop overview-then-deferred-high-res path, which relied on many
main-loop iterations yielding to the browser and appeared to stall partway.
- Allow the wasm heap to grow (INITIAL_MEMORY + ALLOW_MEMORY_GROWTH) so longer
recordings fit now that everything is computed up front.
Exports:
- Add Platform_OfferFileToUser(): no-op on desktop (file is already on disk);
on web it reads the just-written file from MEMFS and triggers a browser
download, then unlinks the temp copy. Wired into PNG and WAV export, which
now show just the filename in the status message.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Spectrum slice (S): floating panel plotting the time-averaged power
spectrum of the current selection (or the visible view when there's no
selection). Frequency on X over the region's band, auto-ranged dB on Y,
with a peak marker. Backed by ComputePowerSpectrum() in stft.c (mean
linear power per bin over the time span). The selection stat panel now
biases to the left when this panel is up so the two don't overlap.
Marker/ruler tool (M): press-drag-release drops point A and B; the
overlay shows crosshairs, a connecting line, and a readout of the
ham-useful deltas — Δt, Δf, tone spacing (1/Δt), and drift (Δf/Δt).
Marker mode swaps the LMB-drag gesture from box-select to marker drop
(Alt/middle still pan); RMB/Esc clear the measurement. Markers reset on
new-file load alongside the selection.
Both are gated toggles (off by default), wired into the keymap (so they
self-document in the About dialog) and the sidebar.
Verified headlessly: idle viewport pixel-identical to baseline (AE=0,
deterministic); both panels render correctly with sensible numbers.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
New "Export WAV (W)" button + W key saves the current selection as a mono
WAV — the same band-limited, time-cropped audio you'd hear on playback, so
"what you hear is what you save". Self-documenting filename encodes the
time span and frequency band (rspektrum_sel_<t0>-<t1>s_<f0>-<f1>Hz.wav).
Refactor the shared filtered-region builder out of PlaySelectedRegion
(which also fixes a leak: it never freed regionSamples after
LoadSoundFromWave copies it). Make the export confirmation message persist
~3s instead of flashing for a single frame (affected PNG export too).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Floating tag follows the pointer over the spectrogram showing the time,
frequency, and STFT magnitude (dB) under the cursor — the standard
spectrum-analyzer probe. Suppressed while selecting/panning (which have
their own readout) and when a modal is open.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
ResetForNewSignal only reset the time view + selection, leaving the
previous file's frequency zoom, in-progress drags, and playback running.
Loading a new file now zooms out both axes, cancels any drag/pan/divide,
clears the selection, and stops playback + rewinds the playhead. Display
preferences (colormap, dB scale, FFT size, grid, scope layout) are
preserved by design. All three load paths funnel through this function.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The visible-window + pan-anchor state was 10 flat fields (viewStart, viewEnd,
freqView*, pan*) used densely throughout the zoom/pan/scrollbar code. Group
them into a Viewport sub-struct (app.view.*).
Rename anchored strictly to 'app.' so ScopeView's own view->viewStart/viewEnd
(same field names) are untouched. Settled render verified pixel-identical
(AE=0); End/zoom path verified via injected key input.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The box-selection state was 11 fields spread across three comment blocks
(time sel, freq sel, drag state). Consolidate them into one Selection
sub-struct (app.sel.*) and extract the 4-line 'clear to full range' block —
duplicated in 5 places — into a ClearSelection() helper.
Pure mechanical rename (anchored to app./spa-> so the ScopeView fields of the
same name are untouched) + behavior-identical dedup. Fully-settled render
verified pixel-identical (AE=0).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Replace the global key handling scattered through the main loop with a single
KEYMAP table (key, gate, action, help text) and a DispatchKeymap() pass. The
About/Help overlay now renders its key list straight from the table, so the
on-screen shortcuts can never drift from the actual bindings.
- Order-sensitive keys (Space, Esc) stay inline where their frame ordering
matters; they carry action==NULL and appear in the table for the help list.
- Adds the F11 fullscreen binding the sidebar button already advertised but
that was never actually wired up.
- Fix About title em-dash rendering as '?' (font is ASCII-only); use a hyphen.
Launch render verified pixel-identical (AE=0); keys verified via injected input.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The "Waveform (Time/Amplitude)" label was drawn in the same ~30px band as
the time-axis labels and the horizontal scrollbar, so it overlapped the
"0.0s / 7.7s / ..." ticks. Shorten to "Waveform" and tuck it faded inside
the scope's top-left, clear of that band.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The spectrogram layout metrics (sidebar width, margins, freq-label width,
scrollbar sizes, spectroHeight, viewBounds) were computed with identical
formulas in three places — the input, selection, and render passes — so a
layout tweak meant editing all three in sync (as the scope divider change
just did). Introduce a Layout struct + ComputeLayout(); each site now
unpacks from it into its existing locals, leaving every downstream
coordinate reference untouched. Verified pixel-identical to the previous
build (ImageMagick AE = 0).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Two extensibility easy-wins, both behavior-preserving:
- UiModalOpen() centralizes the "an overlay owns input" check that was
copy-pasted as `!showFileBrowser && !showAbout` across 6 input gates.
New overlays now update one place.
- Colormaps become a COLORMAPS[] table (name + function) indexed by enum.
GetColormapColor and the sidebar both read it, so adding a colormap is
one enum value + one Cmap* fn + one row — and the sidebar name can no
longer drift from the enum (deleted the parallel colormapNames[] array).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Toggling the scope off (P) now drops the divider to the bottom so the
spectrogram fills the whole view, instead of leaving an empty gap. The
divider handle is always drawn and grabbable: drag it up from the bottom
to bring the scope back, or drag it down past ~88% to hide it. Layout uses
an effective-divider helper (1.0 when hidden) so all three layout sites
stay in sync.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
dB floor handling:
- Fix the white-out/inversion when the floor was cranked up: guard the
(ceiling - floor) range in ColorizeSpectrogram so floor >= ceiling
degrades to a hard threshold instead of dividing by ~0 (white) or a
negative (inverted colors).
- Add two amplitude scale modes, toggled in the sidebar:
* Relative: ceiling tracks the signal peak, floor sits N dB below it
(slider = dynamic range, 10..100 dB). Floor can't cross the ceiling.
* Absolute: fixed dBFS scale (0 dBFS = full scale), slider sets an
absolute floor in dBFS. Brightness reflects real level.
Mode + both slider values persist across loads. This replaces the
amplitudeUserSet flag — storing the intent (range / absolute floor)
preserves it across re-scales structurally.
About / Help dialog (no help menu existed):
- F1 or sidebar button; documents the scale modes and the caveats
(dBFS not dBm — a WAV has no power reference; ~6 dB Hann window
offset; pixels are reassigned energy, not raw bins) plus key list.
- Modal: underlying spectrogram input is gated while open; open/close
handled in the main loop so the opening click can't self-close it and
a dismissing click can't fall through into a selection.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Split GenerateSpectrogramTexture into ComputeSpectrogramReassignment
(the expensive synchrosqueezing, cached in app.reassignBuffer) and
ColorizeSpectrogram (cheap). dB-floor and colormap changes now only
re-colorize instead of recomputing the whole reassignment every frame —
the dB slider and colormap switching are smooth on large files.
- AutoScaleAmplitude no longer overwrites a dB floor the user set by hand
(amplitudeUserSet flag, reset per file load).
- Extract ResetForNewSignal() used by all three load paths; removes the
duplicated reset blocks and the double ComputeSTFTInit per load. Drag-drop
now resets the selection like the browser already did.
- Remove the dead lastInteractedFrame field.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
spectrogram.c was ~2950 lines holding everything. Break it into cohesive
translation units; spectrogram.c keeps only globals + the main frame loop.
New modules:
- spectrogram_types.h shared types, constants, extern globals, inline math
- fft.c/.h FFT, bit-reverse, twiddle (standalone, no app deps)
- stft.c/.h STFT compute, adaptive resolution, FFT-size LRU cache
- audio.c/.h WAV/ffmpeg load, FreeSignal, bandpass, playback
- render.c/.h UI scaling, colormaps, texture gen, on-screen drawing
- ui.c/.h file browser, sidebar, sliders, PNG export
Also:
- utils.c now includes utils.h instead of re-typedef'ing AudioSignal/
SignalStats (they had to be hand-synced before).
- Remove dead code: ApplyHannWindow and ComputeSTFTHighResRange were never
called (the live high-res path is ComputeNextHighResChunk).
- Delete the unused raylib-template main.c.
- rspektrum.make: build the new units. premake5.lua: glob src/**.c so a
future regen stays correct.
Pure code movement otherwise; no behavior change. Builds clean (-Wshadow).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Three leaks, all at the relevant choke points:
- ComputeSTFTInit reallocated result->segments without freeing the old
array, and runs twice per load (load site + loadingPhase 0), so every
file load leaked the STFT. Free the previous result at the top.
- LoadWavFile malloc'd signal->samples without freeing the previous
buffer; free it just before the alloc (after all failure returns, so a
failed load never frees the existing signal).
- GenerateSpectrogramTexture overwrote *image with a fresh GenImageColor
without unloading the old one — leaked an image buffer on every reload
and every dB-floor/colormap regen. Unload first (NULL-safe on first use).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Add an LRU cache (4 entries) of fully-computed STFT results keyed by FFT
size, so toggling FFT size restores a cached result instead of recomputing.
Fix the segfault that hit right after the loading screen for files long
enough to use a skipFactor > 1 overview: SaveToCache() deep-copied every
segment using segment[0].numBins and memcpy'd from each segment's spectrum,
but a sparse overview leaves most segments with spectrum == NULL, so it
memcpy'd from NULL.
- Add IsSTFTComplete() / CopySTFT() helpers; CopySTFT copies sparse
segments as NULL instead of dereferencing them.
- Only cache complete (full-resolution) results; never the sparse overview.
- Make a cache hit actually skip recomputation (and stop leaking): restore
the cached result, mark it finished, and rebuild the texture. On a miss,
free the current STFT before recomputing.
- Drop the per-frame re-save that ran every frame while zoomed in.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
After initial overview loads, compute full-res segments in the background
while the user is idle (200 segments/frame, pauses on any interaction).
Foreground high-res computes zoomed-in segments immediately for
responsiveness. Computed segments persist — zooming out never recomputes.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
- Create primitives.h/c for waveform visualization (time/amplitude display)
- Scope view draws signal as per-pixel min/max envelope (Audacity-style)
- Add draggable divider between spectrogram and scope (30%-80% range)
- Fix selection bounds to use correct spectrogram area (not full viewport)
- Scope syncs with spectrogram zoom/pan for aligned time axis
Display Duration, Energy, Peak amplitude, RMS amplitude, and PAPR for
the current time/frequency selection. The stats box:
- Appears next to the selection box (right side, or left if not enough room)
- Centers vertically on the selection box
- Uses a semi-transparent dark background with yellow border
- Updates live while dragging the selection
- Computed in utils.c with ComputeSignalStats()
Add a red vertical line that tracks playback position within the
selected region. The playhead shows the current position in the
spectrogram as audio plays, making it easy to see what part of
the signal is currently being heard.
- playheadT tracks 0-1 normalized position in the selection
- Red line drawn across the spectrogram viewport while playing
- Semi-transparent red highlight behind the line for visibility
- Reset playhead to 0 when playback stops or is stopped
- Frequency tick/label intervals now adapt to zoom level instead of
always showing 0–Nyquist (5Hz → 10kHz depending on zoom)
- Labels use coarser spacing than ticks to avoid clutter
- Fix segfault when zooming out past signal bounds by properly clamping
freqViewStart/freqViewEnd to [0,1] with correct width preservation
in zoom, pan, and scrollbar drag
- Fix firstTick calculation that was off-by-one
Add Export PNG button and keyboard shortcut (E) to export the
spectrogramImage as a PNG file. Supports:
- Cropping to the current time/frequency selection region
- Optional upscaling via the export scale slider (0.0x to 10.0x)
- Exporting the full unscaled image when no selection and scale is 0
Exports to the app's working directory via raylib's ExportImage.
Export status shown as a brief toast notification.
Known issues:
- Frequency scale doesn't adjust properly when zooming (freqView
clamps to [0,1] range but zoom factor isn't frequency-aware)
- Hardcoded export filenames; no filename/path picker yet
For long signals (>60s), initial load computes every Nth segment at
reduced resolution for a fast overview. Full resolution is computed on
demand as the user zooms into specific regions, starting at the current
viewport and computing 50 segments at a time.
Key changes:
- Add skipFactor and highResFinished fields to SpectrogramApp
- ComputeSTFTInit uses calloc to NULL-initialize segments
- ComputeSTFTIncremental skips non-aligned segments (skipFactor stride)
- ComputeSTFTHighResRange computes full-res for a range [start, end)
- GenerateSpectrogramTexture skips NULL segments for normalization
- Zoom trigger computes high-res only for the visible viewport range,
50 segments at a time, staying within viewStart..viewEnd
- No initial high-res block — only fills on-demand as user explores
Move all Unix-specific syscalls (fork, execvp, waitpid, strerror, /tmp)
into a platform layer so the same spectrogram.c can target Windows
(CreateProcess) and WebAssembly (stubs). Key changes:
- src/platform.h: public API with spawn handle, error codes, path helpers
- src/platform_linux.c: fork/execvp implementation, /tmp, strerror
- src/platform_win32.c: CreateProcess implementation, temp dir lookup
- src/platform_web.c: stub implementations (no subprocess support on web)
- src/spectrogram.c: consume only platform.h; replace pid_t/fork/execvp
with Platform_SpawnChild/WaitForChild; use Platform_GetTempDir() for
/tmp path; replace strdup with malloc/memcpy for portability
- Build: add platform_*.c to gmake, Premake, and build_web.sh
Add FLAG_WINDOW_HIGHDPI to enable raylib's automatic framebuffer
scaling on HiDPI displays. Layout coordinates use logical screen size
only, so UI stays proportional to window size while text and graphics
render at full framebuffer resolution for crisp output on any monitor.
Also fix hardcoded pixel offsets in selection bounds rectangle to use
selScale consistently.
- Add incremental STFT processing with loading overlay and progress bar
- Add auto-scaling amplitude (max dB, max-40dB floor) for low-signal files
- Replace fixed bitmap text with TTF font scaled by window size for crisp rendering at any resolution
- Fix command-line file path resolution relative to original working directory
- Scale file browser dialog dimensions by GetUIScale() to prevent text overlap
- Disable ESC key closing the window
- Fix FFT size changes to restart STFT computation