Commit Graph

182 Commits

Author SHA1 Message Date
tyler bc8bcf78b7 fix: web text corruption, blocking-load notice, no-cache dev server
**Most UI text drew with raylib's built-in font, not the loaded one.**
Thirteen call sites used DrawText/MeasureText directly instead of the
project's DrawTextScaled/MeasureTextScaled wrappers, so the cursor and
marker readouts, spectrum panel labels and export toast rendered from
raylib's default bitmap atlas. On desktop that merely looked slightly off;
on web it renders as garbage. The only raw calls left are the two
fallbacks inside the wrappers themselves.

**The rail tooltip held a dangling pointer.** RailButton stored a
TextFormat() result for the deferred draw pass, and raylib documents that
string as expiring once TextFormat has been called a few more times — which
it has by then. It copies into owned storage now.

**Loading a large file in the browser looked like a crash.** The web build
computes its whole STFT in one synchronous pass, with no frame presented in
between, so nothing drawn on the canvas during that window ever reaches the
screen. A notice now goes into the host DOM instead, which the browser
paints independently, and yields once so that paint actually happens before
the work starts. Because that yield unwinds the stack under ASYNCIFY, the
load block is guarded by stftBusy — without it the re-entered main loop
calls ComputeSTFTInit again and frees the STFT the suspended call is still
building.

**Removed EXPORTED_FUNCTIONS from the web link flags.** It replaces
emscripten's default export list rather than extending it, so everything
unnamed is dead-code-eliminated. The upload callback stays reachable via
the EMSCRIPTEN_KEEPALIVE already on its definition.

**Adds serve_web.py**, a dev server that sends no-store. Browsers cache
.wasm hard enough that a plain reload runs a stale module while the page
looks freshly loaded — which makes a rebuild appear to change nothing.
That cost most of a debugging session today: three separate fixes were
tested against a binary that never changed, each returning an identical
fault at an identical address. README now points at it and says why.

Documents the remaining web issue in known_bugs.md: large captures still
corrupt text after loading. Leading theory is ALLOW_MEMORY_GROWTH
reallocating the heap mid-load and invalidating pointers cached across
that moment, which fits the symptom being text specifically.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 18:38:59 -07:00
tyler 40623feadc feat: web file upload, axis-locked grid, averaged cursor readout
**File loading on the web.** The browser build's filesystem is an in-memory
sandbox, so the file browser could only ever list what the page itself had
written — useless for opening a capture off the user's disk. Adds
Platform_NeedsFileUpload / RequestFileUpload / TakeUploadedFile: no-ops on
desktop, and on web they drive a real <input type="file">, copy the chosen
bytes into MEMFS, and hand the path back through a callback the main loop
polls. The ordinary load path takes it from there, so mLnL parsing and
collision detection work identically.

All three entry points (the O key, File -> Open, and the empty-state
button) route through the same place, so they can't disagree about what
"open" means. ccall/cwrap/FS and the callback symbol needed explicit
export — recent emscripten omits them by default and the failure is
silent until someone clicks the button.

The empty-state banner was centred with the old 320px sidebar's width
hardcoded and never measured its text, so it sat well off-centre once the
rail shrank to 46px. It now measures and centres against the area right of
the rail, and says something useful on web.

**Grid was not locked to the axes.** It drew a fixed 10x8 even divisions of
the viewport rectangle, with no idea what time or frequency those lines
fell on — so they marked arbitrary values and slid continuously while
panning, never coinciding with the labels. Both axes now draw at real
values from a 1-2-5 ladder, and the time labels moved onto that same
ladder (they were at 11 fixed fractions of the view, printing values like
"3.47s" that matched no gridline). Grid and labels share one set of
spacing helpers so they cannot drift apart again.

**Cursor dB readout was a single bin.** On an OFDM burst that swings ~30 dB
between adjacent subcarriers and symbols, so the number reported where the
cursor landed rather than the level of the signal under it. Now averaged
over +/-3 segments x +/-6 bins (~76 Hz x 300 ms at 12 kHz / 2048, under a
third of the narrowest mLink channel, so it stays inside one signal).
Simulated against Rayleigh-distributed subcarriers this cuts the standard
deviation from 5.6 dB to 0.44 dB.

The mean is taken over power and converted afterwards: averaging dB values
is a geometric mean of power and read ~2 dB low. The window is sized in
STFT cells rather than screen pixels, which would otherwise mean something
different at every zoom — one pixel spans hundreds of segments zoomed out
and a fraction of a bin zoomed in.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 16:23:26 -07:00
tyler 56b1666850 fix: playhead drift, replay, and cursor flicker; add selection transport
**Playhead ran ahead of the audio.** It was dead-reckoned by summing
GetFrameTime() every frame, so every frame's *render* work counted as
playback time and the error compounded — by seconds over a long region,
and worst when zoomed out where each frame does the most work. That is why
it tracked fine zoomed in. It is now derived from a wall-clock instant
captured when the buffer is handed to the device, so it cannot drift from
the audio regardless of frame timing.

**Replay after a natural finish left the marker stuck at the end.** The
rail's play button never cleared playbackFinished, so the stale
playheadT > 1.0 persisted and DrawPlayhead early-returned while the audio
played from the top. The Space path already handled this; the button did
not.

**No way to replay a subrange.** The playhead is now drawn while stopped
(with a grab tab) and can be dragged to set where the next play starts
*within* the selection, leaving the region itself intact. Stopping parks
the marker where it stopped rather than snapping to the start.

playheadT is a fraction of the *played* span, which stops being the
selection once a scrub offset exists — so every conversion goes through
absolute file time, the only frame the two share. Getting this wrong made
stop-after-scrub jump backwards.

**Selection transport bar.** Rewind / play-pause / stop / loop, attached
above the selection box. Pause resumes where it left off; loop restarts
from the top of the region rather than repeating whatever tail the last
play started from.

**Cursor flicker.** Twelve unconditional SetMouseCursor calls ran per
frame and the last one won. Two blocks in particular both ran every frame:
one set a cursor regardless of mouse position, and a second overrode it
only when the mouse was inside the spectrogram — so when a capture guard
had parked mousePos off-screen, the first block's stale choice stuck. That
is the fight between finger/pointer, resize/pointer and crosshair/pointer.
Handlers now record a prioritised request (active drag > hover hint >
default) and it is applied once at the end of the frame. The divider hint
is RESIZE_NS rather than the 4-way arrow while here.

The rewind glyph drew its bar and triangle with a gap between them and read
as a lone vertical bar; verified the fix by rendering it offscreen and
dumping pixels rather than eyeballing the geometry.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 15:56:33 -07:00
tyler cce96659b1 feat: menubar + icon rail, minimap, Blender-style navigation
A pass over the whole interface, driven by using it on a 5.7-hour capture.

**Layout.** The 320px sidebar of labelled widgets is now a 46px icon rail —
one column of square buttons, sized so it costs the spectrogram as little
width as possible — plus a menubar for one-shot actions. Menu items are
defined by naming a keymap entry, so an item reuses that binding's action,
gate and shortcut label and the two can't drift; items grey out under
exactly the conditions that make the shortcut a no-op. Settings that need
more than an on/off (FFT size, colours/levels, annotation kinds) open as
popouts beside the rail rather than widening it. Every toggle has exactly
one home: nothing is reachable from both the rail and a menu.

Icons are drawn from raylib primitives rather than an atlas or font
glyphs — the bundled font has no symbol coverage, and vector shapes stay
crisp at any UI scale with no assets to ship.

**Navigation.** Left-drag now pans and Ctrl+drag box-selects, with Tab
swapping which is bare (Ctrl always means "the other one", so either mode
does both). Previously a bare left-drag did three different things
depending on invisible state, with no cursor feedback; the cursor now
reports the active gesture. Wheeling a scrollbar pans that axis, or zooms
it with Shift.

**Minimap.** Whole-file thumbnail in the top-right with the current view
drawn on it; click or drag to scrub, corner handle switches between two
sizes. Rendered once per size into a cached texture and rebuilt only when
its content changes — panning and zooming just move the rectangle drawn on
top. The reduction is strided (each thumbnail cell samples at most 8x8),
because reducing every segment x bin meant ~1 G reads per rebuild and a
visible hitch on every overlay toggle.

**Fixes found along the way:**
- The timeline lane mapped events across the whole file while the
  spectrogram above it showed a zoomed window, so the two only lined up at
  full zoom-out and an event's tick sat nowhere near its burst. It is also
  properly toggleable now: the old flag only grew an always-present lane.
- Clicks preferred the spectrogram over the minimap. Input handling runs
  ~900 lines before the draw pass that computed the minimap's rect, so a
  press there started a pan AND a scrub — two handlers writing app.view in
  one frame. Geometry queries that input depends on now live outside the
  draw pass.
- Repainting during the background fill re-ran the full synchrosqueeze
  every 0.5 s. Zoomed out that is ~0.5 G bin-visits with four trig calls
  each, twice a second, for minutes — while showing almost nothing new,
  since folded segments land in columns already drawn. The interval now
  scales with how much work a repaint actually costs.
- IsUserInteracting() sweeps 512 key codes and was called three times a
  frame; memoized per frame.
- Frequency labels were drawn at a fixed offset wider than their gutter and
  overflowed into the rail. They are measured and right-aligned now, with
  one format chosen per axis so the column doesn't mix "3k" with "2.3k".
- The horizontal scrollbar is pinned to the window bottom; it used to sit
  mid-layout competing with the scope's divider, and the scope covered it
  outright at larger window sizes.
- The scope starts hidden — the spectrogram is the primary view.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 15:28:44 -07:00
tyler 82294844dd feat: hide control annotations by default, demote auto-crop notice to a toast
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
2026-08-12 14:17:05 -07:00
tyler 4c3c6a955a perf: unblock long-file loading; add collision detection and jump nav
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
2026-08-12 13:58:58 -07:00
tyler 8026d10547 fix: stop annotation labels overlapping, drop click-to-pin
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
2026-08-12 12:50:30 -07:00
tyler 8017954aa1 fix: render the spectrogram from the visible segment range
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
2026-08-12 12:50:16 -07:00
tyler 98e42b0a6a feat: report every annotation under the cursor, not just the topmost
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
2026-08-12 00:39:27 -07:00
tyler 5c3c88dc22 feat: scale time zoom by duration, decouple the two axes
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
2026-08-12 00:19:36 -07:00
tyler 0f9ad03fc5 fix: map scope grid and cursor through the visible time window
DrawScopeView's waveform envelope already drew only viewStart..viewEnd,
but TimeToX ignored both and mapped 0-1 across the full widget width. The
grid lines and the playback cursor were therefore laid out against the
whole signal while the trace beneath them showed a zoomed sub-range, so
the two drifted out of register the moment the view was zoomed or panned —
and out of register with the spectrogram directly above, which shares the
same time axis.

Map through the visible window in TimeToX, space the ten divisions across
that window rather than the whole signal, and keep the existing bounds
check so a cursor outside the current view is dropped instead of clamped
to an edge.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 00:19:14 -07:00
tyler c4687ce80d fix: track the playhead against the region actually playing
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
2026-08-12 00:19:02 -07:00
tyler 46e796cdeb fix: align playback and WAV export with the displayed frequency axis
Follows 81bab18, which fixed the same class of bug in the PNG export path.
sel.freq* are fractions of the *displayed* frequency axis (capped at
EffectiveMaxFreqHz), not of true Nyquist, but BuildSelectionAudio and
ExportSelectionWAV both scaled them against sampleRate/2. With a display
crop active this widened the bandpass by 1/DisplayFreqFraction(), so the
audio you heard (and the WAV you exported) covered a higher, wider band
than the box you drew.

Convert through EffectiveMaxFreqHz for the selection bounds; the filter
still reasons in true-Nyquist terms, which is what the separate `nyquist`
local is for. The "is this effectively full-band?" test likewise compares
against nyquist, so an uncropped selection still skips filtering.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8ZWfr5XZyyDttvkhJUgHN
2026-08-12 00:17:49 -07:00
tyler d35cc66ae6 docs: enumerate RELAY handshake and emergency subtypes in frame catalog
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:05:33 -07:00
tyler 81bab18ddd fix: align PNG export crop with displayed frequency axis
The spectrogram image spans the full Nyquist axis, but sel.freq* are
fractions of the displayed axis (capped at EffectiveMaxFreqHz). ExportPNG
mapped the selection straight onto the full image height, so when the
display max frequency was below Nyquist the export grabbed a band higher
in frequency than the box-select. Scale by DisplayFreqFraction() to match
the on-screen texture sub-sampling.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 14:56:27 -07:00
tyler c0f61d0472 feat: scrollbar thumb travel math + UI tweaks
- 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>
2026-06-06 21:21:11 -07:00
tyler 398be34aaf build: document system deps, add check-deps, auto-glob web modules
- README: rewrite Build section for the hand-written Makefile (make /
  make DEBUG=1 / run / test / bench). Add a "System dependencies" table
  with the X11+GL dev packages per distro (apt/dnf/pacman/zypper/apk),
  since a clone won't build without them and the error is otherwise
  cryptic. Fix stale ./bin/Debug paths to ./bin/Release.
- Makefile: add `make check-deps` — probes for the required X11/GL dev
  headers and prints the install command for the detected distro on
  failure (via /etc/os-release).
- build_web.sh: auto-discover app modules from src/*.c (drop the
  hardcoded APP_MODULES list that had to be hand-synced), matching the
  desktop Makefile. Excludes the desktop platform backends. Remove the
  stale rspektrum.make reference.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 21:19:23 -07:00
tyler 849306d65e build: replace premake with a hand-written Makefile; optimize FFT
Build system
- Add a single hand-written Makefile (GNU make + gcc, pure C). Builds
  raylib from vendored source and links rspektrum with no premake/lua.
  Targets: all/run/test/bench/clean; release default, DEBUG=1 for debug;
  ARCH overridable (defaults to -march=x86-64-v3).
- Remove premake entirely: rspektrum.make, raylib.make, build/premake5*
  binaries, build/premake5.lua, build/ecc/*. The generated top-level
  Makefile was gitignored, so hand-edits to it were silently lost.
- Vendor raylib src/ into the repo (was gitignored -> fresh clones could
  not build). Commit only src/ (~16MB); examples/projects stay local.
  Verified: a build from the git-tracked tree alone succeeds offline.
- Release flags bumped to -O3 -ffast-math with a portable arch baseline
  (x86-64-v3 = AVX2+FMA on x64, SSE2 on x86). Confirmed FMA/AVX codegen
  in fft.o.

FFT optimization (src/fft.c)
- Precompute twiddle factors and the bit-reversal permutation once per
  size, cached as a small plan table (FFTW's idea, lightweight). Removes
  the per-butterfly cexpf() and per-element bit-twiddling that dominated.
- 3.6x faster on the mlnl_samples.wav STFT workload (2048-pt, -O2 same
  flags both sides): 81us -> 22us per FFT. With the new -O3/-ffast-math/
  AVX2 release flags stacked: ~15us (5.5x vs the old -O2 baseline).
- Verified vs a double-precision reference DFT: 1e-6 relative error,
  round-trip 2.4e-7. Drop-in: same FFT() signature.

Tests/bench (bench/)
- fft_verify.c: FFT vs reference DFT + round-trip check (make test).
- fft_bench.c: times the real STFT workload (make bench).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 21:13:49 -07:00
tyler e900caad1d Add MIT license
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 20:10:43 -07:00
tyler 3b2e5517bf Update README.md 2026-06-06 03:08:38 +00:00
tyler 724956278d fix: bake UI font atlas at physical DPI size so text isn't skinny on standard-DPI
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>
2026-06-05 18:27:35 -07:00
tyler 83277e5086 fix: progressive full-res STFT fill never resumed after interaction
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>
2026-06-05 16:25:43 -07:00
tyler b72e1cef18 feat: scroll the sidebar controls with the mouse wheel when they overflow
The left-hand control panel is laid out top-to-bottom with a running y; with
annotations expanded or a short window, the bottom buttons (export, signal
info, about) ran off the bottom and were unreachable. Offset the content by a
sidebarScroll amount, measure the laid-out height, and let the wheel scroll it
(clamped) when the cursor is over the sidebar and no modal is open. No visible
scrollbar; the spectrogram's wheel-zoom already ignores the sidebar column so
the two never both fire.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:09:38 -07:00
tyler b95cafdf3b chore: drop unreferenced test WAV fixtures
The three test_tone_*.wav files are unused and regeneratable via
generate_test_tones.py; resources/test_announce_qpsk_275hz.wav was also
unreferenced. mlnl_samples.wav remains as the in-repo sample.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 15:59:59 -07:00
tyler 7916e8a24e docs+chore: add screenshot to README; drop committed export PNGs and junk
- README: embed resources/Screenshot.png under the intro
- remove accidentally-committed app export outputs (spectrogram_full.png,
  spectrogram_export.png) and gitignore them so they don't return
- remove unused resources/wabbit_alpha.png and stray .qwen/settings.json.orig

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 15:51:12 -07:00
tyler 5c3c452133 docs: rewrite README as a fresh project overview + usage guide
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 15:40:44 -07:00
tyler fb7bc5486e feat: true no-X headless --render (CPU spectrogram bitmap + overlay)
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>
2026-06-03 22:37:38 -07:00
tyler 95be6f6c22 docs: rewrite README to characterize rspektrum accurately
Replaces the stale Unity-port README (wrong controls, premake build,
missing features). Documents the mLink/mLnL focus, real keybindings,
make-based build, headless --render mode, and the Xvfb GUI-driving
primer. Consolidates the old SPECTROGRAM_README.md into README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-29 23:50:29 -07:00
tyler bb2f22bd0a docs: raylib lessons learned for desktop (non-game) apps
Captures the idle-CPU findings and patterns from the perf work:
event-driven idle, raylib's constant ~5% busy-wait, lazy audio
device, headless render recipe, and the warnings that bit us.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-29 23:12:18 -07:00
tyler f89e1b7eab perf: event-driven idle + lazy audio device for near-zero idle CPU
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>
2026-05-29 13:02:14 -07:00
tyler 2befb42d71 perf: throttle idle FPS and pause rendering when unfocused
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>
2026-05-29 12:37:38 -07:00
tyler ac262505c1 feat: headless PNG render, mLnL annotations, and per-frame sched offset
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>
2026-05-29 12:19:37 -07:00
tyler cef7619833 feat(web): proper viewport scaling, instant load, and file downloads
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>
2026-05-25 11:48:47 -07:00
tyler 6347eb172e fix(web): repair Emscripten build after module split + font move
The web build had bit-rotted since the last successful build (Apr 12):

- build_web.sh only compiled spectrogram.c + platform_web.c, but commit
  3a8f20b split the code into 9 modules — link failed with undefined
  symbols. Now compiles all app modules (kept in sync with rspektrum.make,
  swapping platform_linux -> platform_web).
- Dropped -DPLATFORM_WEB from the app-module compile/link: the platform
  refactor (b6942d8) added a `Platform` enum whose PLATFORM_WEB enumerator
  collides with the macro. Web behavior is selected by linking
  platform_web.c, not the macro, so the define was never needed by our code
  (raylib still gets it in its own build).
- Removed the stale `fonts/DejaVuSansMono.ttf` preload (font moved to
  resources/fonts/); resources@resources already bundles it and the runtime
  loads it relative to the resources dir.
- platform_web.c: include <errno.h> for ENOSYS (this stub had never compiled).
- build_web.sh: skip the slow raylib rebuild when libraylib.a already exists.

Verified: `./build_web.sh release` exits 0 and produces html/js/wasm/data;
font is packaged; all artifacts serve 200 via python http.server and the
wasm has valid magic bytes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 11:15:31 -07:00
tyler e8ed19d338 feat: spectrum-slice (PSD) panel + two-point marker/ruler tool
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>
2026-05-25 10:53:57 -07:00
tyler 542126261e feat: export selection to WAV (band-limited, time-cropped)
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>
2026-05-25 10:42:37 -07:00
tyler 9d21dbe82b improve: bandpass skirt width in Hz, not bins (consistent across selections)
The playback bandpass transition was freqPerBin*10 wide, and freqPerBin
depends on the FFT size, which is derived from the selection length — so
the same frequency band got a sharper or softer filter depending on how
long a region you selected. Set the skirt to ~20% of the passband (capped
at 100 Hz), floored at 3 FFT bins so it stays smooth at coarse resolution.
Now a given band sounds the same regardless of selection duration.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 10:31:23 -07:00
tyler ee9eac786c feat: live cursor readout (time / frequency / STFT level)
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>
2026-05-25 10:29:36 -07:00
tyler 26afc4b30e feat: frequency-aware selection stats (peak/center freq, occupied BW, SNR)
The selection readout was time-domain only — Energy/Peak/RMS/PAPR computed
from the whole-bandwidth waveform in the time span, ignoring the box's
frequency bounds entirely. The 2D box only measured one axis.

Add ComputeSpectralStats (stft.c): measures the boxed band from the STFT
magnitude (not the synchrosqueezed display buffer, which relocates energy)
and reports peak frequency, power-weighted centroid ("power center"),
occupied bandwidth (in-band span >3 dB over a median noise floor — robust
for both tones and noise-like bursts), and in-band SNR.

Also fold the two near-identical stats-panel blocks in render.c into one
DrawStatPanel + BuildSelectionStatLines helper so the live-drag and
committed-selection readouts can't drift.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 10:26:37 -07:00
tyler f833ed17a1 docs: AGENTS.md — headless run/see/drive playbook for raylib apps
Portable guide for an agent doing refactor/code-health work on a raylib
(or any GLFW/OpenGL) app: Xvfb + screenshot + pixel-diff loop, xdotool
key/mouse injection (incl. the press-release-must-span-frames gotcha),
determinism strategies for static apps vs continuously-animating games,
temp-keybinding state forcing, and a porting checklist for shot_input.sh.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 10:13:24 -07:00
tyler 05f9ddd3af test: headless input harness with mouse click/drag support
shot_input.sh launches the app under Xvfb and drives it with xdotool,
then screenshots for pixel-diff verification. Adds click/drag/rdrag
pseudo-actions that insert the frame gap raylib's button edge-detection
needs (a bare xdotool "click 1" is too fast and no-ops). Documents the
settled-capture timing (12s) and the 1280x800 viewport/sidebar bounds.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 09:41:39 -07:00
tyler 970d11e60e fix: new-file load resets full nav state (zoom out both axes, stop playback)
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>
2026-05-25 09:36:36 -07:00
tyler f91cae77e8 refactor: group viewport/zoom/pan state into a Viewport sub-struct
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>
2026-05-25 09:17:26 -07:00
tyler 8e4250ae63 refactor: group selection state into a Selection sub-struct + ClearSelection()
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>
2026-05-25 09:15:50 -07:00
tyler ab7a6bc71c ux: drop redundant 'Reset Sel' button; full-width 'Clear Selection'
Reset Sel advertised an 'R' key that was never bound and only set the
selection to the current view, overlapping Clear/Esc. Removed it and made
Clear a single full-width button labelled to match the Esc shortcut.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 09:06:14 -07:00
tyler 99c7d43637 refactor: table-driven keymap dispatch + auto-derived help list
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>
2026-05-25 09:05:37 -07:00
tyler 53f7fa6047 refactor: extract Clicked() + DrawPanelBox() sidebar widget helpers
Collapse the repeated 'CheckCollisionPointRec + IsMouseButtonPressed' click
test and the 'DrawRectangleRec + DrawRectangleLinesEx' panel chrome into two
helpers used across the sidebar buttons. Pure readability; render output is
pixel-identical (verified AE=0 vs baseline).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 08:59:08 -07:00
tyler c75e014b88 ui: stop the scope label colliding with the time-axis labels
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>
2026-05-25 02:07:53 -07:00
tyler dd0ad9506a refactor: centralize screen layout in ComputeLayout()
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>
2026-05-25 02:05:19 -07:00
tyler 487e3ad85b refactor: extract shared ComputeSegment for STFT passes
ComputeSTFTIncremental (overview, skipFactor-strided) and
ComputeNextHighResChunk (high-res fill) had ~50 lines of identical
per-segment code (windowing, FFT, bin fill for both the normal and
derivative spectra). Extract it into ComputeSegment() with a reusable
SegScratch buffer set (allocated once per pass, no per-segment malloc).
Each caller keeps only its own skip logic. Behavior-preserving — verified
the rendered spectrogram is unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 02:02:46 -07:00