Skip to content

Gate source start on client state and accept any source format - #427

Merged
chrisuthe merged 5 commits into
Sendspin:mainfrom
chrisuthe:chrisuthe/task/gate-source-start-on-client-state-and-accept-any
Sep 17, 2026
Merged

chrisuthe merged 5 commits into
Sendspin:mainfrom
chrisuthe:chrisuthe/task/gate-source-start-on-client-state-and-accept-any

Conversation

@chrisuthe

Copy link
Copy Markdown
Member

Part of #386. One commit per item.

  • S-3 – The server sends start only 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_start exposes the same check.
    • The source role now uses the activation-state hold from End removed roles before server/activate and gate re-added roles on client/state #417, plus one new base hook, Role.on_hold_released().
    • A client/state missing the required source object is flagged.
    • The client SDK now includes the source object in every client/state while the role is active, so a player+source client includes it in its first state.
  • S-7 – SourceCapture drops PCM and encoded frames captured more than MAX_CAPTURE_BACKLOG_US (500 ms) ago, then continues from live capture without resending client-stream/start.
    • The drop only works when callers pass capture_timestamp_us.
    • A frame the encoder was already holding can still span the gap; the encoder is deliberately not reset.
  • S-9 – client-stream/start accepts any channel count ≥ 1 and any bit depth from 1 to 32.
    • The stream is announced at 16, 24 or 32 bits, and 8-bit PCM is widened to 16.
    • Only PCM depths that are not whole bytes are flagged and refused.
    • Channel counts without a named layout use PyAV's unnamed layout.
  • S-10 – The client SDK sends signal only when it advertised line_sense.
  • S C – The SourceCapture.feed() docstring now covers the clock and default of capture_timestamp_us.

Breaking

  • SendspinConnection.send_source_signal() now raises RuntimeError unless the client advertised source@v1_support.features.line_sense. Before, it sent the signal anyway.

Compatibility

  • A client following an older spec revision may never send the source object in client/state.
  • For embedders: a source can now announce a channel count PyAV cannot downmix (9, 11, 13, 15, 17–23, 25+ channels). Converting such a source to a different channel count makes SourceBridge / AsrcSourceBridge raise ValueError when it is created, so Music Assistant's bridge will fail for those sources. Converting at the same channel count works.

Deferred

  • S-4, S-5, S-8 and S-12 move to new issues.
  • S-6 is tracked separately.
  • S-11 is left to the maintainers.

@chrisuthe chrisuthe added breaking-change Changes the public API or the protocol in a way that is not backwards compatible enhancement Improves an existing feature labels Sep 17, 2026
@chrisuthe
chrisuthe requested a lite review from Copilot September 17, 2026 01:15
@chrisuthe chrisuthe removed the enhancement Improves an existing feature label Sep 17, 2026
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.
@chrisuthe
chrisuthe force-pushed the chrisuthe/task/gate-source-start-on-client-state-and-accept-any branch from 24468c6 to d8da8c3 Compare September 17, 2026 01:17

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.

🔵 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/start with bit_depth=0 or 33 is 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.

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.

🔵 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_stride before 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/start can still announce bit_depth 0 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

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.

🔵 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 start can remain stuck when availability is restored through the legacy player.state path: PlayerV1Role.on_client_state() schedules handle_availability_change() asynchronously after this role's on_client_state() has already run, but the new_available branch returns without retrying _send_queued_start(). Trigger the queued-start check when availability becomes true so the command is sent without requiring another client/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 a client/state with no top-level available: PlayerV1Role.on_client_state() schedules handle_availability_change() for player.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/state with no available field as sufficient to start; in lenient mode _client.available remains its default or previously persisted True, so a queued start can reach the wire even though the latest state did not report available: true as required by S-3. Keep the compatibility exception for a missing source object, but also require an explicit initial available: 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

@chrisuthe
chrisuthe marked this pull request as ready for review September 17, 2026 02:11
@chrisuthe
chrisuthe merged commit 204a4e5 into Sendspin:main Sep 17, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking-change Changes the public API or the protocol in a way that is not backwards compatible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants