Repository navigation
Gate source start on client state and accept any source format - #427
Conversation
The server now holds a reactivated source role until its client/state object arrives and flags a client/state that lacks it. request_start() queues the start and sends it once the role is released, the source object for the current activation was received and the client is available; request_stop(), a disconnect or the role's deactivation cancels a queued start. can_start exposes the same check, and a new Role.on_hold_released() hook lets the role send once its hold ends. A lenient server keeps starting a client whose initial client/state never carries the source object (spec PR 195); a strict server rejects it. The client SDK carries the source object in every client/state while the source role is active, so a player+source client reports it in its first state.
…/start resolve_av_format() falls back to PyAV's unnamed layout for channel counts without a named one. The source role decodes to 16, 24 or 32 bits via decoded_bit_depth() and announces that format; 8-bit PCM is widened to 16 bits. Only depths outside 1..32, and PCM depths that are not whole bytes, are flagged and refused. SourceBridge rejects at construction a remix PyAV cannot map, instead of failing on the first chunk.
SourceCapture discards PCM captured more than MAX_CAPTURE_BACKLOG_US (500 ms) ago before encoding it, and skips encoded frames whose capture time is that old, so a stall resumes from live capture instead of bursting stale audio. The encoder and the open input stream are kept; the server sees the gap in the timestamps.
send_source_signal() raises RuntimeError unless the client's source_support advertises the line_sense feature, so client/state never carries a signal the server was not told to expect.
capture_timestamp_us is on the client clock and marks when the first sample reached the input. The default, the time of the call, trails the capture by its latency and hides stall backlog, so callers with a capture clock should pass it.
24468c6 to
d8da8c3
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
Opus bit depths outside the required 1–32 range are currently accepted in source/v1.py.
Pull request overview
This PR gates source starts on valid client state, improves capture handling, and broadens source audio format support.
Changes:
- Queues starts until source state and availability requirements are met.
- Drops stale capture frames and updates source-state signaling.
- Supports broader channel counts and bit depths.
File summaries
| File | Reviewed changes |
|---|---|
tests/test_client_protocol_callbacks.py |
Tests source state and signal behavior |
tests/server/test_role_activation.py |
Tests activation gating |
tests/server/test_audio_format_utils.py |
Tests unnamed channel layouts |
tests/server/roles/source/test_v1.py |
Tests source lifecycle and formats |
tests/integration/test_source_loopback.py |
Updates source state setup |
tests/integration/test_source_end_to_end.py |
Tests queued source starts |
tests/client/test_source_capture.py |
Tests stale capture dropping |
tests/audio/test_codecs.py |
Tests decoder normalization |
tests/audio/test_bridge.py |
Tests channel-layout conversion |
aiosendspin/server/roles/source/v1.py |
Source gating and format validation |
aiosendspin/server/roles/base.py |
Adds the hold-release hook |
aiosendspin/server/connection.py |
Dispatches hold-release hooks |
aiosendspin/client/source.py |
Handles capture backlog trimming |
aiosendspin/client/connection.py |
Sends source state and gates signals |
aiosendspin/audio/source_bridge.py |
Validates channel remixing |
aiosendspin/audio/format.py |
Supports unnamed layouts |
aiosendspin/audio/codecs.py |
Normalizes decoded bit depths |
Review details
Suppressed comments (1)
aiosendspin/server/roles/source/v1.py:179
- Opus bypasses this range check, so
client-stream/startwithbit_depth=0or33is accepted even though S-9 requires 1–32 for every source codec; these values then reach the decoder. Apply the range check before the PCM-specific whole-byte check.
if source.codec is AudioCodec.PCM and source.bit_depth % 8:
# The PCM wire convention only packs whole-byte samples.
self._client.flag_noncompliance(
f"client-stream/start announced pcm bit_depth {source.bit_depth}, "
"which is not a whole number of bytes"
- Files reviewed: 17/17 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
🔵 Needs a closer look
Two moderate findings remain involving packed 24-bit remix sample counting and Opus bit-depth validation.
Review details
Suppressed comments (2)
aiosendspin/audio/source_bridge.py:123
- This validation probe feeds a packed 24-bit frame into
_convert_via, which computes its sample count from_in_av_stride(the 4-byte PyAV stride) before expanding packed s24; it therefore sees the probe as zero samples, and channel-remixing 24-bit sources can fail or truncate. Compute the input sample count from the packed_in_stridebefore conversion (and use that count when constructing the input frame).
self._build_resampler(rate=self._resampler_rate), bytes(self._in_stride)
aiosendspin/server/roles/source/v1.py:174
- This range check is skipped for Opus, so a
client-stream/startcan still announcebit_depth0 or 33 even though this change accepts only depths 1–32; validate the range for every codec before the PCM whole-byte check, while keeping Opus decoding at 16 bits.
if source.codec is not AudioCodec.OPUS and not 1 <= source.bit_depth <= 32:
self._client.flag_noncompliance(
f"client-stream/start announced unsupported bit_depth {source.bit_depth}"
)
return
- Files reviewed: 17/17 changed files
- Comments generated: 0 new
- Review effort level: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
Three moderate findings in source start availability handling remain unresolved.
Review details
Suppressed comments (3)
aiosendspin/server/roles/source/v1.py:302
- A queued
startcan remain stuck when availability is restored through the legacyplayer.statepath:PlayerV1Role.on_client_state()scheduleshandle_availability_change()asynchronously after this role'son_client_state()has already run, but thenew_availablebranch returns without retrying_send_queued_start(). Trigger the queued-start check when availability becomes true so the command is sent without requiring anotherclient/state.
def _send_queued_start(self) -> None:
"""Send the queued start command once `can_start` allows it."""
if not self._start_queued or not self.can_start:
return
aiosendspin/server/roles/source/v1.py:278
- This
_send_queued_start()runs before the legacy availability update for aclient/statewith no top-levelavailable:PlayerV1Role.on_client_state()scheduleshandle_availability_change()forplayer.state="external_source", so a queued source start can be sent while that same state makes the client unavailable. Account for the legacy player-state availability before evaluating the source start gate, or dispatch the availability update before source roles.
def on_client_state(self, payload: ClientStatePayload) -> None:
"""Send a queued start the state allows, and surface a line_sense signal change."""
source = payload.source
if source is not None:
self._source_state_received = True
self._send_queued_start()
aiosendspin/server/roles/source/v1.py:117
- This unconditional assignment treats an initial
client/statewith noavailablefield as sufficient to start; in lenient mode_client.availableremains its default or previously persistedTrue, so a queuedstartcan reach the wire even though the latest state did not reportavailable: trueas required by S-3. Keep the compatibility exception for a missingsourceobject, but also require an explicit initialavailable: true(or track that authorization separately) before allowing the queued start.
def on_initial_client_state(self, payload: ClientStatePayload) -> None: # noqa: ARG002
"""Record the initial client/state, which allows a start even without a source object."""
# A pre-#195 client may never send the source object. Only its initial client/state
# stands in, flagged by initial_state_deviations, which a strict server rejects.
self._source_state_received = True
- Files reviewed: 17/17 changed files
- Comments generated: 0 new
- Review effort level: Lite
Part of #386. One commit per item.
startonly after the source object has arrived, the client is available and the role is no longer held.request_start()now queues the request and sends it as soon as all three hold; nothing reaches the wire early.request_stop(), a disconnect or the role's deactivation cancels a queued start.can_startexposes the same check.Role.on_hold_released().client/statemissing the requiredsourceobject is flagged.sourceobject in everyclient/statewhile the role is active, so a player+source client includes it in its first state.SourceCapturedrops PCM and encoded frames captured more thanMAX_CAPTURE_BACKLOG_US(500 ms) ago, then continues from live capture without resendingclient-stream/start.capture_timestamp_us.client-stream/startaccepts any channel count ≥ 1 and any bit depth from 1 to 32.signalonly when it advertisedline_sense.SourceCapture.feed()docstring now covers the clock and default ofcapture_timestamp_us.Breaking
SendspinConnection.send_source_signal()now raisesRuntimeErrorunless the client advertisedsource@v1_support.features.line_sense. Before, it sent the signal anyway.Compatibility
sourceobject inclient/state.allow_noncompliant_clients=True) flags it and treats the client as startable once its initialclient/statehas arrived and it is available. This applies to the initial state only.DEPRECATED(spec-pr-195): the requirement to send a role's state object on activation comes from Foldstream/request-formatintoclient/statespec#195. Clarify activation and shared stream lifecycle requirements spec#274 only reworded that paragraph.SourceBridge/AsrcSourceBridgeraiseValueErrorwhen it is created, so Music Assistant's bridge will fail for those sources. Converting at the same channel count works.Deferred