Skip to content

Hand the player's PCM with its format on every write - #268

Merged
kahrendt merged 6 commits into
mainfrom
player-audio-format
Nov 17, 2026
Merged

kahrendt merged 6 commits into
mainfrom
player-audio-format

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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().

Adds on_audio_output(), which hands the PCM as a std::span<const uint8_t>
beside the AudioFormat of exactly those bytes, taken from the sync task's
decoder rather than from the stream/start the main loop applied, so audio
buffered before an updating stream/start keeps its own format (roles/
player/v1.md "stream/start"). bits_per_sample is the container depth, 24-bit
packed in 3 bytes. The library calls only on_audio_output(); its default
hands the bytes to on_audio_write(), which is deprecated and no longer pure.

Adds PlayerRole::stream_info(), a main-loop PlayerStreamInfo of what the
latest stream/start announced, codec included.
get_current_stream_params() and ServerPlayerStreamObject are deprecated for
removal in v0.11.0.

Pending underflow silence is dropped when a codec header changes the
format, since its bytes need not be whole frames of the new one.
The per-write format test covers the change's purpose and the deprecated
write's test covers the path the ESPHome hub uses until it moves. The
listener-form table, the same-format silence control and the container
depth test guarded nothing a realistic change could break.
The PCM layout, container depth and whole-frame rule live in the
integration guide's PlayerRoleListener section; the header keeps each
item's purpose and points there, internals keeps one sentence on where
the format comes from, and PlayerStreamInfo no longer repeats
AudioFormat's field docs.
@kahrendt
kahrendt marked this pull request as ready for review November 17, 2026 19:18
@kahrendt
kahrendt requested a max review from Copilot November 17, 2026 19:18

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

Queued old-format audio is accounted at the new sample rate, potentially triggering false synchronization corrections that drop valid audio or insert silence.

11 open issues
What changed in this PR

Continues the standard-view API migration by pairing each player PCM write with its own format, separate from main-loop stream announcements.

Changes:

  • Adds on_audio_output(), AudioFormat, and stream_info(), while retaining deprecated compatibility APIs.
  • Routes decoded audio and silence through format-aware output and migrates the PortAudio sink and examples.
  • Updates tests, build fixtures, and API/threading documentation.
File Description
tests/​test_player_role.cpp Tests per-write formats, format changes, and legacy forwarding.
tests/​test_client_teardown.cpp Migrates the discard listener to the new callback.
tests/​test_client_lifecycle.cpp Uses the new getter and output callback.
tests/​test_allocations.cpp Moves allocation-window tracking to the new callback.
tests/​lifecycle_test_fixtures.h Migrates the shared counting listener.
tests/​esp_idf/​main/​main.cpp Updates the ESP-IDF build fixture’s player listener.
src/​transfer_buffer.h Removes sink coupling and updates buffer usage documentation.
src/​transfer_buffer.cpp Removes listener-based audio transfer.
src/​sync_task.h Declares the format-aware sink writer.
src/​sync_task.cpp Labels audio and silence writes; clears stale-format pending silence.
src/​protocol.cpp Parses player fields into the internal parameter type.
src/​protocol_messages.h Uses internal player parameters in stream payloads.
src/​player_role.cpp Adds compatibility forwarding and stream-info publication.
src/​player_role_impl.h Stores new stream information alongside deprecated parameters.
src/​audio_types.h Defines internal parsed player stream parameters.
include/​sendspin/​player_role.h Exposes the new APIs and deprecates their predecessors.
include/​sendspin/​client.h Updates the listener documentation example.
examples/​tui_client/​tui.cpp Determines stream-panel availability from sample rate.
examples/​tui_client/​main.cpp Uses per-write formats for playback and display.
examples/​common/​portaudio_sink.h Accepts PCM spans with format metadata.
examples/​common/​portaudio_sink.cpp Drains queued audio before reopening for format changes.
examples/​basic_client/​main.cpp Migrates the output callback and sink wiring.
docs/​playback-sync.md Updates the callback name in the state-machine description.
docs/​internals.md Documents per-write format ownership and callback naming.
docs/​integration-guide.md Updates contracts, migration guidance, and examples.
docs/​conventions.md Updates the named sync-task callback.
CLAUDE.md Updates the player architecture summary.

Review effort: Max

Comment thread src/sync_task.cpp Resolved
Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread src/player_role.cpp Resolved
Comment thread docs/integration-guide.md Resolved
Comment thread src/player_role.cpp Resolved
Comment thread src/sync_task.cpp Resolved
Comment thread tests/test_player_role.cpp Resolved
… out of stream_info()

The PortAudio ring's clear() drops only what was written before it, so a same-format restart's
first writes survive the deferred clear; the sink reopens whenever it has no stream; stream_info()
is nullopt for a STREAM_START whose params a teardown replaced. Lists stream_info() in the state
snippet and fixes a stale test comment.

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

In-flight audio callbacks can replay frames or corrupt playback progress after a restart, while queued start events can lose stream information.

3 open issues
3 previously missed issues

In code that hasn't changed since last review

Medium severity Initialize both stream representations in the fixture

tests/​test_player_role.cpp:1322

This only updates the deprecated cache; the new main-loop stream_info remains empty and stream_active is false. Thus the fixture does not establish the advertised case where the main loop has applied the new stream before the old-format writes. Set up both main-loop representations consistently (or drain the starts) before exercising the writes, as required for fixtures by docs/conventions.md:290.

Low severity Drain queued old-format audio before reconfiguring output

docs/​integration-guide.md:244

The sample reconfigures the output as soon as the first new-format bytes arrive, but old-format bytes can still be queued in the output device. A backend that reopens or immediately changes format will discard or misinterpret those bytes, even though an in-place stream/start must retain the old audio. Please show or explicitly require draining the old-format queue before reconfiguration (returning zero and retrying if it cannot drain within the timeout), as the PortAudio sink does.

Low severity Document callback argument lifetimes and require copies

include/​sendspin/​player_role.h:113

Please state the lifetime of both arguments here. pcm points into a reused decode buffer or silence scratch, and format is a temporary created for this call; a sink that retains either for asynchronous playback will otherwise read overwritten data or a dangling reference. Consumers need to copy anything they keep after the callback returns.

11 resolved since last review

Review effort: Balanced

Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread examples/common/portaudio_sink.cpp Resolved
Comment thread src/player_role.cpp Resolved
Reverts the stream_info() resets: with START, END, START queued, the first START takes the second's
params, and the resets left the final stream reporting nullopt. A START left without its own params
keeps the previous ones, as the deprecated getter always has. Drops fixture lines nothing reads and
tells sinks to play out old-format audio before reopening in a new one.
@kahrendt
kahrendt merged commit 180b0e7 into main Nov 17, 2026
16 checks passed
@kahrendt
kahrendt deleted the player-audio-format branch November 17, 2026 20:31
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