Skip to content

Order visualizer stream callbacks against frames and hand spectrum bins as a span - #266

Merged
kahrendt merged 6 commits into
mainfrom
visualizer-stream-info
Nov 17, 2026
Merged

kahrendt merged 6 commits into
mainfrom
visualizer-stream-info

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Third step of moving the public API to standard view types (after #260, #261), and the visualizer half of Sendspin/spec#307. on_spectrum() handed a std::vector, and on_visualizer_stream_start() a struct holding one; an in-place stream/start recalled the buffered frames, which #307 says the client keeps; and the main-loop stream callbacks were unordered against the drain thread's frame callbacks, so a frame could arrive after on_visualizer_stream_end(). Part of Sendspin/backlog#92.

Migration:

Deprecated Replacement
on_spectrum(int64_t, const std::vector<uint16_t>&) on_spectrum_bins(int64_t, std::span<const uint16_t>, const VisualizerSpectrumConfig&)
on_visualizer_stream_start(const ServerVisualizerStreamObject&) on_visualizer_stream_started(const VisualizerStream&)

config is the configuration the frame was received under; size the display from bins.size(). VisualizerStream (4 bytes) is the admitted stream: served types, tracks_downbeats, rate_max. A start whose notice a later start overwrote before it fired is folded into that later one. Overriding a deprecated callback draws no warning, so search for the old names and mark overrides override.

Change

  • In-place start: updates the negotiated types and bin count without recalling buffered or held frames. Spectrum length and the downbeat bit are fitted on the protocol task at arrival, so the drain thread decodes with no configuration and the decode atomics go.
  • Ordering, modeled on the player's on_stream_start()/on_stream_end() against on_audio_write(): every start, end, clear and teardown takes a lifecycle ordinal stamped into each frame's item header. The drain thread holds a frame until the main loop has acknowledged its ordinal (dropped as late at its lag bound), and the main loop holds an end or clear until the drain thread reports it is past it. All stream callbacks stay on the main loop. A long run of in-place starts pulls the boundary and the drain thread's reported position along, so the 16-bit ordinals stay in range; a late frame's 20 ms bound counts from its display time.
  • Start notice: a latest-wins Inbox slot replaces the config slot and its topic. A start or clear the full event ring drops is acknowledged where it is lost, costing ordering, not delivery.
  • The tui example and the integration guide (visualizer section, threading table, the Deprecated String API section now "Deprecated API") use the new API; internals.md gains "Visualizer Stream Events".
  • The visualizer tests in test_client_lifecycle.cpp name the private members they reach in their own comments; tests/CMakeLists.txt points there (a follow-up applies this to the other tests and the conventions).

Tests

  • Handshake table: frames wait for the events queued before them, across folded starts, a clear behind a superseded start, dropped starts and clears, a full held-event queue, ordinal wraparound, and a run of updates past half the ordinal range (with the drain thread reporting and stuck in a callback); late frames waiting for their notice are dropped past the bound.
  • Lifecycle: no frame callback after its stream's end or clear (stream/end, clear, deactivation, connection loss, with a callback in flight); a frame after a fresh start, update or clear waits for its notice; stop() ends a wait; an in-place start keeps held and listed frames, each frame decoding with its own bin count; both spectrum forms (new first, identical bins and config).
  • The first-spectrum-frame alloc window stays at 0 with both forms overridden. Mutants caught include the acknowledgement wait removed, an end or clear fired without waiting, a superseded start firing, no lost-event fallback, a plain <= in place of the wrap-safe compare, and a skipped or reordered deprecated call.
  • TSan runs of the visualizer tests (20 repeats) were clean; builds checked: -DENABLE_WERROR=ON with examples, and an ESP-IDF esp32s3 build with no deprecation warnings. Not run on hardware.

…ns as a span

Adds on_spectrum_bins(), which hands the bins as a std::span with the
spectrum configuration the frame was received under, and
on_visualizer_stream_started(), which hands a 4-byte VisualizerStream
describing the admitted stream. on_spectrum(), on_visualizer_stream_start()
and ServerVisualizerStreamObject are deprecated for removal in v0.11.0; the
library calls each new callback before its deprecated form.

An in-place stream/start keeps the buffered and held frames, and each frame
is fitted to the stream it arrived in on the protocol task, so the drain
thread decodes without configuration (roles/visualizer/v1.md "stream/start").

The lifecycle callbacks stay on the main loop and are ordered against the
drain thread's frame callbacks the way the player's are against
on_audio_write(): a frame waits for the notice of the stream it arrived in,
and an end or clear waits until the drain thread is past it. A start whose
notice a later start overwrote is folded into that one, and a lost event
costs ordering, not delivery.
StartNotice's stream gains an initializer for -Wmissing-field-initializers,
held_events' overflow check compares against Inbox::EVENT_CAPACITY instead
of the static capacity() through the instance, and take_start_notice() and
recall_frames() are const.
The visualizer tests in test_client_lifecycle.cpp state the private
members they reach, and why, in their own comments; the CMakeLists entry
keeps main's text, drops the visualizer's retired catch_up_teardown()
step and points at those comments.
@kahrendt
kahrendt marked this pull request as ready for review November 17, 2026 16:05
@kahrendt
kahrendt requested a max review from Copilot November 17, 2026 16:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Long-running in-place updates can break lifecycle comparisons and drop current frames, while acknowledgement timing can allow delivery beyond the 20 ms lag bound.

5 open issues
What changed in this PR

Continues the standard-view API migration for visualizer data and coordinates main-loop stream callbacks with drain-thread frame delivery.

Changes:

  • Adds span-based spectrum and compact stream callbacks, retaining deprecated compatibility forms.
  • Preserves buffered frames during in-place stream updates and introduces lifecycle acknowledgement tracking.
  • Updates the TUI example, documentation, and unit, lifecycle, and allocation coverage.
File Description
tests/​test_visualizer_role.cpp Covers payload fitting, stream updates, and lifecycle handshakes.
tests/​test_client_lifecycle.cpp Adds callback compatibility and stream/frame ordering scenarios.
tests/​test_allocations.cpp Checks both spectrum callback forms remain allocation-free.
tests/​README.md Updates visualizer test coverage descriptions.
tests/​lifecycle_test_fixtures.h Migrates the shared listener to the new stream callback.
tests/​CMakeLists.txt Updates private-access documentation for lifecycle tests.
src/​visualizer_role.cpp Implements frame fitting, lifecycle coordination, and dual callback dispatch.
src/​visualizer_role_impl.h Defines start notices, held events, and handshake state.
src/​inbox.h Adds visualizer topics and reports event-push failures.
src/​inbound_ring.h Updates frame-stamp documentation for lifecycle ordinals.
src/​client.cpp Routes visualizer events through the deferred role drain.
include/​sendspin/​visualizer_role.h Exposes view-based callbacks and deprecates older forms.
examples/​tui_client/​main.cpp Uses the new callbacks and sizes spectrum data per frame.
docs/​internals.md Documents visualizer lifecycle channels and event ordering.
docs/​integration-guide.md Explains callback contracts, migration, and threading behavior.

Review effort: Max

Comment thread src/visualizer_role.cpp Resolved
Comment thread src/visualizer_role.cpp Resolved
Comment thread src/visualizer_role.cpp Resolved
Comment thread src/visualizer_role.cpp Resolved
Comment thread tests/CMakeLists.txt Resolved
A run of more than half the ordinal range of updating stream/starts moved
no boundary, so every later frame read as stale and an end stopped waiting
for the drain thread. Each update now pulls boundary_ordinal up to a
quarter range behind its ordinal, and the main loop pulls drain_passed up
the same way as it judges each held event.

visualizer_delivery_wait_us() now takes whether the frame is acknowledged
and is asked again on every pass, so a late frame's 20 ms bound counts from
its display time, and an acknowledgement after the cutoff drops the frame
instead of delivering it.

Also names every COMMAND_ACK writer and corrects comments that still said
frames reach the drain thread verbatim and the stream payload reaches the
main loop.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/visualizer_role.cpp Resolved
Comment thread src/visualizer_role.cpp Resolved
A start whose notice a later start replaced fired and acknowledged
nothing, so a long enough run of them left acked_ordinal so far behind
that a new frame read as acknowledged before any notice described it. A
superseded start now acknowledges through ORDINAL_TRAIL before its own
ordinal, where every frame is already stale.

The ORDINAL_TRAIL comment also states the accepted limit both ways: a
frame callback blocked through more than half the range of events, with
the main loop behind, can leave an end held or let it fire early.
@kahrendt
kahrendt merged commit fab9280 into main Nov 17, 2026
16 checks passed
@kahrendt
kahrendt deleted the visualizer-stream-info branch November 17, 2026 17:46
kahrendt added a commit that referenced this pull request Nov 17, 2026
## Summary

The comment beside each `-fno-access-control` flag in
`tests/CMakeLists.txt` named every private
member its file reaches and why. Several had grown into long prose
(about 120 lines for
`test_client_lifecycle.cpp`) that repeated what the tests already said.
#266 moved the visualizer
tests' notes into the tests; this applies that to every file and writes
the rule down.

## Change

- `docs/conventions.md`: a test file names each private member it
reaches, and why, once: a reach
several of its tests share at the top of the file or on their fixture,
any other in the comment
of the test or helper that takes it. The CMake comment says only that
the file compiles with the
  flag and names what it reaches.
- `docs/conventions.md` (Documentation): each fact has one home, at the
code that owns it; a copy
elsewhere is a pointer, and only where the site would mislead without
it.
- The test-standards and docs-sync skills check both; `CLAUDE.md`
summarizes the first.
- 13 test files: each note moved to its one home, merged with the
existing comments; the CMake
comments shrink to two lines each. Comment text drops by about 1,190
words overall.
- Reaches the old notes missed are named (for example
`send_transport_frame()`,
`chunk_is_unplayably_late()`, `InboundDropLog::dropped_`, `config_`),
and stale "see
  CMakeLists" include comments are dropped.

## Tests

- Comment-only in `tests/*.cpp`: with comments stripped, every changed
file matches `main`.
- A script checked that every member the old CMake notes named is still
named in its file's
comments; the only names dropped are public or no longer reached (for
example
  `process_binary_message()` in `test_encrypted_lifecycle.cpp`).
kahrendt added a commit that referenced this pull request Nov 17, 2026
## Summary

Next step of the public API move to standard view types (after #260,
#261, #266). The player handed PCM through `on_audio_write(uint8_t*,
size_t, uint32_t)` and left the consumer to read its format from
`get_current_stream_params()`, a value the main loop applies when it
drains a `stream/start`. ESPHome reads that getter on the sync thread
for every write: a data race, and wrong across an updating
`stream/start`, since the main loop switches it while audio buffered in
the old format is still being written (roles/player/v1.md
"stream/start"). Each write now carries the format of exactly its own
bytes. Part of Sendspin/backlog#92.

**Migration:**

| Deprecated | Replacement |
|---|---|
| `PlayerRoleListener::on_audio_write(uint8_t*, size_t, uint32_t)` |
`on_audio_output(std::span<const uint8_t>, const AudioFormat&,
uint32_t)` |
| `PlayerRole::get_current_stream_params()` |
`PlayerRole::stream_info()`, main loop only, for what the stream
announced (codec included); each write's `AudioFormat` for the PCM
itself |
| `ServerPlayerStreamObject` | `PlayerStreamInfo` |

`AudioFormat` is the sample rate, channels and container depth (8, 16,
24 or 32; 24-bit packed in 3 bytes, odd depths reported at the next
multiple of 8 with their samples in the top bits). The return value is
unchanged: bytes written, whole frames. Overriding `on_audio_write()`
draws no warning, so search for the name and mark overrides `override`.

## Change

- **Dispatch:** the sync task calls only `on_audio_output()` (its return
value counts bytes, so both forms cannot run); its default hands the
bytes to `on_audio_write()`, now non-pure. A listener overriding neither
plays nothing, and the sync task retries after its usual back-off rather
than spinning. `on_audio_output()` becomes pure in v0.11.0.
- **Format per write:** silence and decoded audio both go through
`SyncTask::write_to_sink()`, which labels each write from the sync
task's own decoded stream info. `TransferBuffer` no longer holds a
listener. Pending underflow silence is dropped when a codec header
changes the format, since its bytes need not be whole frames of the new
one.
- **`stream_info()`:** a main-loop `PlayerStreamInfo` (codec, sample
rate, channels, announced depth), or `nullopt` while no stream is
active. The stream parse moves to an internal `PlayerStreamParams`.
- The examples, the integration guide (player section, threading table,
Deprecated API) and internals use the new API; the PortAudio sink
reopens on a format change after its old audio plays out.

## Tests

- `PlayerAudioOutput.EachWriteCarriesTheFormatOfItsOwnBytes`: across an
updating PCM `stream/start` (44.1 kHz stereo 16-bit to 48 kHz mono
24-bit), each write, silence included, carries the format of its own
bytes, though the main loop has already applied the update, and no
partial frame of leftover silence goes out.
- `PlayerAudioOutput.TheDeprecatedWriteStillReceivesTheAudio`: a
listener still on `on_audio_write()`, as the ESPHome hub is, gets the
audio through the forward.
- The FLAC `stream/start` and first-codec-header allocation windows stay
at 0 with a listener overriding `on_audio_output()`.
- Builds checked: GCC 16 `-DENABLE_WERROR=ON` with tests and examples,
clang-tidy, and an ESP-IDF esp32s3 build with no deprecation warnings.
The sync task's static stack bound is unchanged (5,088 B). Not run on
hardware; the ESPHome hub needs a follow-up to move to
`on_audio_output()`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants