Skip to content

Rust rewrite v1 skeleton: regulator-core + ratatui TUI - #1

Merged
borosf merged 20 commits into
masterfrom
vibe/rust-rewrite-6f034d
Nov 17, 2026
Merged

borosf merged 20 commits into
masterfrom
vibe/rust-rewrite-6f034d

Conversation

@borosf

@borosf borosf commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Summary

  • New Cargo workspace with two crates:
    • regulator-core: pure-Rust port of tg's timing algorithm — impulsive-noise suppression, FFT-based autocorrelation period detection (auto or fixed bph), waveform folding, beat error, and lift-angle amplitude estimation. No I/O, no platform deps.
    • regulator-tui: clean three-zone terminal UI (readout / waveform / status), live capture via cpal behind the optional audio feature, and a --demo mode driven by a synthetic watch signal so it runs with no hardware or audio stack.
  • Unit tests: synthetic watch generator verifies rate error, auto beat-rate detection, beat error, and rejection of silence (4/4 pass).
  • Original C code kept untouched as the GPLv2 reference; new README describes the rewrite, original moved to docs/original-readme.md.

Verification

  • cargo test — 4 passed
  • cargo build --no-default-features — clean (sandbox has no ALSA, so the cpal feature is verified by config only)
  • Demo analysis on synthetic 28800 bph signal: rate +13.5 s/d recovered vs +12 s/d injected, beat error ≈ 0

Notes

  • Amplitude estimation returns None on the synthetic signal (its pulse shape doesn't fully match a real tic/toc); shows as --- in the UI. Needs validation against real recordings.

Port of tg's timing algorithm (noise suppression, FFT autocorrelation
period detection, waveform folding, beat error, amplitude) to a pure-Rust
core crate with unit tests against a synthetic watch generator, plus a
clean three-zone terminal UI with cpal capture (optional feature) and a
--demo mode. Original C code kept as reference.

Co-authored-by: borosf <borosf@users.noreply.github.com>
…esample to 44.1 kHz mono

Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
…aching, egui GUI

- TimingResult fields are now Option: rate/amplitude/beat error report
  independently and blank out when not found
- Amplitude: direct impulse-duration measurement (region above 20% of the
  tic/toc peak) replacing tg's fragile escalating-threshold heuristic;
  validated at 264 deg vs 270 deg injected on the synthetic watch
- Period: parabolic interpolation of the autocorrelation peak for
  sub-sample resolution
- Analyzer caches FFT plans per length and reuses scratch buffers
- New regulator-gui crate: egui frontend with live plot, settings panel,
  demo/mic sources shared with the TUI
- TUI waveform renderer: proper scaling and tic/toc marker

Co-authored-by: borosf <borosf@users.noreply.github.com>
Real microphone noise can collapse the autocorrelation search window to
a==b or run it past the buffer end; tg's C loops handle this implicitly
but the Rust port sliced out of range. Guard the ranges, reject
right-edge peaks like the C code does, and make the frontends resilient
to a poisoned lock. Regression tests for the degenerate cases.

Co-authored-by: borosf <borosf@users.noreply.github.com>
- regulator-core::calibrate: CalibrationState ports tg's calibration
  (quartz watch ticking 1/s, phase drift fit over CAL_DATA_SIZE=900
  one-second samples); Analyzer applies the correction to rate
  (measured - calibration); validated on synthetic quartz: -15.2 s/d
  recovered for a +15 s/d fast clock
- GUI: calibrate button with live progress, calibration readout,
  calibration runs on mic input with sliding 4 s windows
- analyze_wav example: analyze any WAV recording, printing per-block
  results, for debugging against real recordings

Co-authored-by: borosf <borosf@users.noreply.github.com>
…d-trip tests

Co-authored-by: borosf <borosf@users.noreply.github.com>
…gorithm

Debugged against a real 18000 bph watch recording (previously: no signal,
+5000 s/d garbage):

- tg's default filter chain high-passes at FILTER_CUTOFF (3000 Hz) before
  analysis; without it, mains hum dominated the autocorrelation and the
  period detector failed on most blocks. Ported the biquad high-pass.
- Restored tg's exact amplitude algorithm (escalating-threshold scan for
  the pre-impulse build-up): measures 236-238 deg on the real recording
  where tg shows 272 deg. The earlier 20%-span variant was mistuned.
- Synthetic generator now models the escapement build-up (pre-hump) so
  the amplitude path works in demo mode; quartz mode keeps sharp clicks
  for calibration.

Results on the real recording: rate +40..+52 s/d (tg: +33), amplitude
237 deg (tg: 272), beat error ~0.1 ms, bph auto-detected 18000.

Co-authored-by: borosf <borosf@users.noreply.github.com>
- TimingResult now carries located tick events (fractional sample
  positions, tic/toc flag), extrapolated from the folded waveform peaks
  through the block at the detected period
- GUI: live Trace panel under the waveform - each tick plotted at its
  phase error over the last 60 s; rate error drifts as diagonal bands,
  beat error splits into tic/toc bands, noise is scatter
- Calibration refits on every new one-second sample once 60 points are
  collected and stops as soon as the confidence interval is under
  0.1 s/d, instead of always waiting for tg's full 900 s

Co-authored-by: borosf <borosf@users.noreply.github.com>
…eadout

- Strip chart is now the centerpiece and vertical like a timegrapher:
  time flows downward (newest at the bottom), horizontal axis is the
  phase error against the beat grid (+/-25 ms window, wrapping), tic
  green / toc magenta dashes, grid lines every 10 ms
- Layout per instrument UX: one large monospace rate readout at top
  (color-coded), secondary values (amp/be/lift/noise/cal) in a compact
  bottom strip, controls in a slim side panel, small waveform in the
  panel - no more three-equal-cards grid
- Beat rate dropdown extended to all standard rates 12000-43200;
  36000 bph covered by a new auto-detect test

Co-authored-by: borosf <borosf@users.noreply.github.com>
- During calibration the center panel becomes live feedback: collected
  (time, phase) samples plotted, progress counter, current estimate with
  its standard error, and a 'waiting for ticks' hint when no quartz
  signal is detected
- Calibrate button now switches from demo to mic automatically instead
  of silently doing nothing
- Lift angle is a typed DragValue (30-70) instead of a slider
- 'export chart' button writes the strip chart as SVG plus raw points as
  CSV (timestamped filenames in the working directory)
- Removed the license footer label

Co-authored-by: borosf <borosf@users.noreply.github.com>
The 900-sample quartz calibration exists because tg averages phase noise
against a wristwatch reference. But the sound card's clock error can be
measured directly against the NTP-disciplined system clock: regress the
cumulative captured sample count against batch arrival times
(regulator-core::ClockCal). This runs passively whenever the mic is on -
no watch, no mode, no user action - and converges within a few minutes;
the fit's standard error shrinks as batches accumulate and the
correction auto-applies once it is under 0.25 s/d (shown as 'cal auto'
in the strip). The quartz path remains available as an independent
check.

Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
…readout

- Events are now measured, not extrapolated: each expected tick position
  is searched in the prepared signal for the actual peak (rejected if it
  does not rise above the local noise floor), so the trace shows genuine
  per-tick scatter and drift instead of static stripes
- Mic ring buffer carries a monotonic sample counter, so window start
  times no longer oscillate when the buffer drains (the cause of the
  frozen, patternless chart); demo mode uses a running total too
- Clock calibration shows live while converging: 'cal +2.1 +-1.4' in
  amber in the bottom strip until it auto-applies as 'cal ... auto'

Co-authored-by: borosf <borosf@users.noreply.github.com>
…e draw

- Worker copies the 4 s window out of the ring buffer under the lock
  (sub-millisecond) and analyzes it unlocked, so the capture relay and
  UI never stall behind analysis
- One Analyzer is reused across iterations, keeping the FFT plan cache
  warm instead of rebuilding 350k-point plans every 200 ms
- Export button moved into the top readout bar; the egui panel added
  after CentralPanel is gone (panels must precede the central panel)
- draw_trace hoists the newest-timestamp lookup out of the per-point
  loop (was O(n^2) per frame)

Co-authored-by: borosf <borosf@users.noreply.github.com>
The clock-calibration block locked params a second time while the
outer guard was still held; std::sync::Mutex is not reentrant, so the
worker hung forever the moment the clock estimate first became
available (~2 s after the mic started), taking the UI with it. Reuse
the held guard instead.

Co-authored-by: borosf <borosf@users.noreply.github.com>
The clock-based estimate measures the sound card against the local
high-resolution timer, whose own drift is unknown and can be tens of
s/day on some hardware (observed: -31.9 vs tg's quartz -7.5, a ~28 ppm
local timer drift). It is no longer auto-applied: the bottom strip
shows it as 'clock ...' in gray, and a side-panel button lets the user
apply it explicitly. The quartz calibration remains the authoritative
correction, matching tg.

Co-authored-by: borosf <borosf@users.noreply.github.com>
- Quartz calibration accepts at +/-0.2 s/d confidence (tg gates at
  0.1), roughly halving convergence; the 900-sample count is only the
  worst-case cap, the early-exit fit typically finishes in a minute or
  two
- Calibration is a typed, editable field in the side panel: a value
  measured once (here or in tg) can be entered directly
- Settings (beat rate, lift angle, calibration, noise suppressor) now
  persist to %APPDATA%/regulator/config.txt and reload at startup, so
  calibration survives restarts; tg's startup 'auto cal' only catches
  device-forced rate mismatches and is ~0 in practice, so there was
  nothing faster to inherit

Co-authored-by: borosf <borosf@users.noreply.github.com>
…ME, CONTRIBUTING)

- Trace reworked to tg's orientation: time left-to-right, phase error
  vertical; SVG export matches.
- New branded JPEG result sheet (regulator-gui/src/sheet.rs) with a
  hand-drawn 5x7 bitmap font, readouts, trace and timestamp; exported
  alongside SVG/CSV. Unit-tested.
- snap_bph now includes 19800 and 43200 (auto mode previously snapped
  a 19800 bph watch to the wrong standard).
- Event location calls vmax once instead of twice per tick.
- README rewritten (GUI is the main frontend, TUI marked experimental),
  screenshot from the sheet renderer.
- CI (ubuntu+windows full, headless build), release workflow attaching
  GUI binaries on v* tags, CONTRIBUTING.md, bug report template.

Co-authored-by: borosf <borosf@users.noreply.github.com>
@borosf
borosf merged commit 154a4bb into master Nov 17, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant