Skip to content

Add AirPlay, Picture in Picture, and VS Code development support - #101

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
ab1ackb3rry:feature/airplay-vscode-support
Jul 25, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
ab1ackb3rry:feature/airplay-vscode-support

Conversation

@ab1ackb3rry

@ab1ackb3rry ab1ackb3rry commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds AirPlay and iOS Picture in Picture (PiP) playback support to Silo's AVPlayer routes (Native Player HLS/Direct and SiloPlayer loopback). Reconciles externally initiated pause/play events (from system PiP and AirPlay remotes) with Silo's internal play-intent tracking. Fixes transport state mismatch that caused playback to resume immediately after user pause.

Picture in Picture Support

What Works

  • Auto-start PiP: When swiping to home, iOS automatically enters PiP if the app was playing (standard AVKit behavior).
  • Manual toggle: PiP button in mobile player top strip.
  • Transport controls: Play/pause from the floating window are properly routed through Silo's backend.
  • AirPlay + PiP coexistence: PiP remains active while AirPlay routes work independently.
  • Background playback: PiP continues playing when the app is backgrounded; normal pause policy applies only when PiP ends or fails to start.
  • Skip intervals: Quick-skip forward/backward (configured via Now Playing metadata) work in PiP.

Known Limitations

  • No scrubbing/timeline: iOS AVKit's playerLayer content source does not provide a draggable timeline in PiP. Only play/pause and skip intervals are available. Full timeline seeking requires returning to the full-screen player and using Silo's scrubber.
  • Silo-rendered subtitles do not appear in PiP: Text overlays are rendered by Silo's subtitle system and are only visible on the main player display, not in the system PiP window.
  • Not available on compatibility (PlayerCore) route: The sample-buffer playback route would require a custom sample-buffer PiP content source; not yet implemented.

AirPlay Support

  • iPhone/iPad to Apple TV or receiver: Playback is delivered to the receiver via HLS stream from the SiloPlayer loopback server.
  • Automatic URL swap: When AirPlay activates, the loopback item URL is reloaded with the device's LAN IPv4 address so the receiver can reach the stream. On AirPlay end, the URL reverts to localhost for phone playback.
  • Fixes for IPv6/cellular networks: Previously, all loopback playback was forced through LAN addressing and failed on networks without a private IPv4 address. Now local playback defaults to localhost and only upgrades when needed.

Changes Made

  1. AVPlayerBackend: Added external playback state reconciliation; loopback URL swaps on AirPlay activation/end; unified transport-state policy to treat externally paused AVPlayer as user intent.
  2. PictureInPictureCoordinator: New singleton managing AVPictureInPictureController lifecycle; coordinates background pause policy on PiP stop/failure; binds lifecycle to player session.
  3. LoopbackSegmentServer: Loopback URLs default to 127.0.0.1 for local playback; LAN address only generated when explicitly requested for AirPlay.
  4. PlayerViewModel: Background scene-phase handler now gives automatic PiP a 1-second grace window before pausing.
  5. AirPlayRoutePicker, MobilePlayerControls: PiP button added; route picker wired to pin controls while sheet is open.
  6. ApplePlaybackRouteCapabilities: PiP and AirPlay marked as validationRequired on AVPlayer routes.

Testing

  • Focused XCTest coverage for loopback startup recovery and segment server ranges (IPv4 validation).
  • Full iOS, tvOS, macOS builds pass.
  • Transport-state reconciliation prevents feedback loops between watchdog and external pause/play.

Blockers and Notes

  • Timeline scrubbing in PiP is not possible under iOS AVKit's architecture for playerLayer content sources. This is a system limitation, not a Silo implementation gap.

Summary by CodeRabbit

  • New Features

    • Added an in-player AirPlay device picker and Picture-in-Picture controls.
    • Enabled local-network (LAN) streaming with session-scoped, token-protected access links.
    • Updated player routing to better support seamless AirPlay handoff and PiP playback state.
  • Documentation

    • Expanded VS Code setup instructions, including tasks for generating projects, building, and running tests.
  • Bug Fixes

    • Improved play/pause reconciliation for AirPlay and PiP, plus safer PiP attach/detach across lifecycle changes.
    • Refined background behavior to reduce premature pausing during PiP transitions.
  • Tests

    • Added coverage for LAN URL privacy, token authorization, and route recovery behavior.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Quick104, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 900864b7-41d5-4752-a9c0-7abdd787eb84

📥 Commits

Reviewing files that changed from the base of the PR and between 154d9fe and b90671e.

📒 Files selected for processing (4)
  • docs/tvos-player/05-route-capability-matrix.md
  • iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift
📝 Walkthrough

Walkthrough

The PR adds tokenized local-network loopback playback for AirPlay, PiP lifecycle handling, updated route capability metadata and controls, and a complete VS Code workflow for Xcode project generation, builds, tests, and debugging.

Changes

AirPlay playback

Layer / File(s) Summary
Tokenized local-network delivery
iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift, iosApp/Tests/LoopbackSegmentServerRangeTests.swift
Adds exposure modes, session-token authorization, private IPv4 discovery, reachable resource URLs, external-client gating, and coverage for LAN URL behavior.
Playback route integration
iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift, iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift
Enables external playback, switches loopback URLs for external devices, reconciles transport intents, redacts access tokens in logs, and tests recovery behavior.
PiP and lifecycle integration
iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift, iosApp/iosApp/Screens/Player/PlayerViewModel.swift, iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerSurface.swift
Adds PiP coordination, player-layer binding, background grace handling, external-playback callbacks, and lifecycle cleanup.
Route capability and picker integration
iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift, iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift, iosApp/iosApp/Screens/Player/iOS/*, docs/tvos-player/05-route-capability-matrix.md
Updates capability states and validation gates, adds PiP and AirPlay controls, and records AirPlay validation results.

VS Code workflow

Layer / File(s) Summary
VS Code project workflow
.vscode/*, .gitignore, README.md
Adds workspace recommendations, Sweetpad settings, Xcode generation/build/test tasks, LLDB launch configuration, setup instructions, and generated-file ignores.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PlayerControls
  participant AVPlayerBackend
  participant LoopbackSegmentServer
  participant AppleTV
  PlayerControls->>AVPlayerBackend: select AirPlay route
  AVPlayerBackend->>LoopbackSegmentServer: start local-network server
  LoopbackSegmentServer-->>AVPlayerBackend: return tokenized playlist URL
  AVPlayerBackend->>AppleTV: provide external playback URL
  AppleTV->>LoopbackSegmentServer: request tokenized HLS resources
  LoopbackSegmentServer-->>AppleTV: authorize and serve resources
Loading

Possibly related PRs

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main additions: AirPlay, Picture in Picture, and VS Code development support.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.vscode/settings.json:
- Around line 21-24: Declare the Node.js prerequisite for the SweetPad BSP
configuration: in .vscode/settings.json lines 21-24, retain the SweetPad
provider settings only if the required Node.js runtime is available; in
README.md lines 100-106, document installing and verifying a supported Node.js
version, or document configuring an alternative BSP provider instead.

In @.vscode/tasks.json:
- Around line 131-136: Update the iosTestDestination input in the tasks
configuration to remove the unavailable hard-coded iPhone 17 Pro default.
Require the user to provide an installed simulator destination, or derive the
default from simulators available in the local Xcode environment.

In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift`:
- Around line 388-395: Update isPrivateIPv4Address to reject any address whose
four parsed octets are outside 0...255, before applying the private-range
checks. In iosApp/Tests/LoopbackSegmentServerRangeTests.swift lines 27-34, add
cases covering invalid numeric octets such as 999 and -1, verifying they return
false.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3f24eed3-a9ca-4210-a00b-48eb5db4498c

📥 Commits

Reviewing files that changed from the base of the PR and between d49d805 and 2b69ae9.

📒 Files selected for processing (15)
  • .gitignore
  • .vscode/extensions.json
  • .vscode/launch.json
  • .vscode/settings.json
  • .vscode/tasks.json
  • README.md
  • docs/tvos-player/05-route-capability-matrix.md
  • iosApp/Tests/LoopbackSegmentServerRangeTests.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Player/iOS/AirPlayRoutePicker.swift
  • iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift

Comment thread .vscode/settings.json Resolved
Comment thread .vscode/tasks.json Resolved
…loopback playback

- AirPlay: Swap loopback item URL from 127.0.0.1 to device LAN address only when external playback activates; restore to loopback on end. Fixes playback failure on cellular/IPv6-only networks.
- PiP transport: Reconcile externally initiated pause/play (from PiP or AirPlay remotes) into Silo's play-intent latch. Prevents watchdog from resuming paused playback. Adds transport-state policy to distinguish unexpected pauses from intentional ones.
- PiP lifecycle: Bind failed/stopped callbacks to background pause policy with 1s grace window for automatic PiP startup. Closes race where background transition paused during PiP willStart.
- Controls: Add PiP button to mobile player top strip; wire AirPlay route picker to pin controls while sheet is open.
- Capabilities: Mark PiP and AirPlay as validationRequired on AVPlayer routes (HLS, Direct, Loopback).
- IPv4: Validate octet ranges in LAN address check; add focused test.
- Note: PiP has no draggable timeline — iOS AVKit's playerLayer content source only supports play/pause and skip intervals. Full scrubbing requires returning to full-screen player.
@ab1ackb3rry ab1ackb3rry changed the title Add AirPlay and VS Code development support Add AirPlay, Picture in Picture, and VS Code development support Jul 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift (1)

20-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Isolate PictureInPictureCoordinator to the main actor.

All current coordinator access and mutations occur in UI/view/UIKit paths, so annotating this shared UI-owned singleton with @MainActor enforces the intended execution context and prepares it for Swift 6 strict concurrency. The existing DispatchQueue.main.async hop can be replaced with the main-actor hop, since isPossible is currently written from a DispatchQueue.main.async closure that could become a shared-state read elsewhere.

♻️ Suggested change
 `@Observable`
+@MainActor
 final class PictureInPictureCoordinator {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift` around
lines 20 - 52, Annotate the PictureInPictureCoordinator class and its shared
singleton with `@MainActor` so all coordinator state and UI interactions are
isolated to the main actor. Update the existing DispatchQueue.main.async
mutation of isPossible to use a main-actor-compatible hop, preserving the
current asynchronous update behavior.
iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift (1)

27-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a plain stored property for the singleton coordinator.

PictureInPictureCoordinator.shared is owned by the app, not by MobilePlayerControls. SwiftUI still tracks accesses to its @Observable state from a plain property, so private let pictureInPicture = PictureInPictureCoordinator.shared expresses ownership without changing behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift` at line 27,
Replace the `@State` wrapper on pictureInPicture in MobilePlayerControls with a
plain private let stored property initialized from
PictureInPictureCoordinator.shared, preserving the existing coordinator access
and behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift`:
- Around line 369-370: In makeRouteRequirements, set
keepsPictureInPictureDisabledUntilValidated and
keepsExternalPlaybackDisabledUntilValidated to true. Preserve the
compatibility-route gating behavior so .playerCoreDirect reports the
corresponding unsupported capabilities in decisionTrace and degradation notes.

In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift`:
- Line 1788: Update the reload log in the loopback item reload flow to avoid
interpolating the full tokenized itemURL. Log only the URL’s host and port, or
use an equivalent redacted path representation, while preserving the existing
reason and player timing fields.
- Around line 926-932: Update the URL-resolution failure path in the AirPlay
handoff method containing the resourceURL guard to call the existing reportError
mechanism, as handleFirstSegmentReady does, before returning. Preserve the
logger and ensure the receiver-facing failure is surfaced instead of silently
leaving the loopback URL active.

---

Nitpick comments:
In `@iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift`:
- Line 27: Replace the `@State` wrapper on pictureInPicture in
MobilePlayerControls with a plain private let stored property initialized from
PictureInPictureCoordinator.shared, preserving the existing coordinator access
and behavior.

In `@iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift`:
- Around line 20-52: Annotate the PictureInPictureCoordinator class and its
shared singleton with `@MainActor` so all coordinator state and UI interactions
are isolated to the main actor. Update the existing DispatchQueue.main.async
mutation of isPossible to use a main-actor-compatible hop, preserving the
current asynchronous update behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 625aee21-e033-4418-9a14-77cb8b9fa054

📥 Commits

Reviewing files that changed from the base of the PR and between 2b69ae9 and 3954d22.

📒 Files selected for processing (11)
  • iosApp/Tests/LoopbackSegmentServerRangeTests.swift
  • iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerSurface.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Player/iOS/AirPlayRoutePicker.swift
  • iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift
  • iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • iosApp/Tests/LoopbackSegmentServerRangeTests.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift

Comment on lines +369 to +370
keepsPictureInPictureDisabledUntilValidated: false,
keepsExternalPlaybackDisabledUntilValidated: false,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect how the two requirement flags are consumed by the capability matrix.
fd -t f 'ApplePlaybackRouteCapabilities.swift' iosApp --exec rg -n -C6 'keepsPictureInPictureDisabledUntilValidated|keepsExternalPlaybackDisabledUntilValidated' {}
rg -n -C4 'keepsPictureInPictureDisabledUntilValidated|keepsExternalPlaybackDisabledUntilValidated' --type=swift iosApp | head -80

Repository: Silo-Server/silo-apple

Length of output: 9318


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== ApplePlaybackRoutePlanner outline =="
ast-grep outline iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift --view compact || true

echo
echo "== ApplePlaybackRoutePlanner relevant sections =="
sed -n '320,380p' iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift | cat -n -v
sed -n '240,325p' iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift | cat -n -v

echo
echo "== Route requirements references =="
rg -n -C8 'BlockingReason|degradationNotes|blockingReasons|routeCapabilities|PlaybackRouteRequirements|keepsPictureInPictureDisabledUntilValidated|keepsExternalPlaybackDisabledUntilValidated' --type=swift iosApp/iosApp/Screens/Player | sed -n '1,220p'

echo
echo "== PictureInPictureCoordinator docs references =="
rg -n -C8 'PictureInPictureCoordinator|has no PiP|no PiP support|Picture in Picture|pictureInPicture' --type=swift iosApp/iosApp | sed -n '1,260p'

echo
echo "== MobilePlayerControls AVPlayer gate == "
rg -n -C8 'avPlayerBackend|MobilePlayerControls' --type=swift iosApp/iosApp | sed -n '1,220p'

Repository: Silo-Server/silo-apple

Length of output: 50378


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Route capabilities definitions =="
sed -n '1,230p' iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift | cat -n -v

echo
echo "== MobilePlayerControls outer gating/constraints =="
sed -n '90,165p' iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift | cat -n -v

echo
echo "== Execution plan usage of route requirements/trace/degradation warnings =="
rg -n -C4 'requirements:|decisionTrace:|degradationWarnings|degradationNotes|blockingReasons|summaryTokens|keepsPictureInPictureDisabledUntilValidated|keepsExternalPlaybackDisabledUntilValidated' --type=swift iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift | sed -n '1,260p'

Repository: Silo-Server/silo-apple

Length of output: 42055


Keep the compatibility-route PiP/AirPlay unsupport flags true in makeRouteRequirements.

With both flags set to false, .playerCoreDirect stops adding pip_disabled_until_validated/external_playback_disabled_until_validated to decisionTrace and stops emitting its unsupported degradation notes, even though .playerCoreDirect's capabilities remain unsuported/unclaimed. That leaves the compatibility-route decision trace/gating report without the unsupported capabilities that the fallback path is meant to expose.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swift` around lines
369 - 370, In makeRouteRequirements, set
keepsPictureInPictureDisabledUntilValidated and
keepsExternalPlaybackDisabledUntilValidated to true. Preserve the
compatibility-route gating behavior so .playerCoreDirect reports the
corresponding unsupported capabilities in decisionTrace and degradation notes.

Comment on lines +926 to +932
guard let url = server.resourceURL(
for: playlistName,
reachableFromExternalDevice: active
) else {
Self.logger.error("AirPlay handoff could not determine a reachable local network address")
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Silent failure leaves the receiver playing an unreachable URL.

When the LAN address can't be resolved during a handoff, the item keeps the 127.0.0.1 URL, which the AirPlay receiver cannot fetch — the user sees an indefinite stall with only an OS log entry. handleFirstSegmentReady surfaces the same condition via reportError (Line 2084); consider doing the same here for consistency.

🛠️ Proposed change
         ) else {
             Self.logger.error("AirPlay handoff could not determine a reachable local network address")
+            if active {
+                reportError("AirPlay handoff could not determine a reachable local network address.")
+            }
             return
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
guard let url = server.resourceURL(
for: playlistName,
reachableFromExternalDevice: active
) else {
Self.logger.error("AirPlay handoff could not determine a reachable local network address")
return
}
guard let url = server.resourceURL(
for: playlistName,
reachableFromExternalDevice: active
) else {
Self.logger.error("AirPlay handoff could not determine a reachable local network address")
if active {
reportError("AirPlay handoff could not determine a reachable local network address.")
}
return
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift` around
lines 926 - 932, Update the URL-resolution failure path in the AirPlay handoff
method containing the resourceURL guard to call the existing reportError
mechanism, as handleFirstSegmentReady does, before returning. Preserve the
logger and ensure the receiver-facing failure is surfaced instead of silently
leaving the loopback URL active.

Eight findings from the PR review, all in the player code.

Transport reconciliation read any AVPlayer `timeControlStatus` transition
as a receiver/PiP command while a handoff was live. The `.initial` KVO
delivery, pre-roll, seeks, buffer underruns, and EOF all park the player
at rate 0 for reasons of their own; each would have latched
`isUserPaused`, and every loopback stall-recovery path is gated on
`!isUserPaused`, so a stall could wedge the session outright.
`AVPlayerSystemTransportIntent.resolve` now takes the full context and
only acts on transitions nothing else explains.

AirPlay video hands the receiver a URL and none of the asset's HTTP
headers, so Native Player routes — whose stream URLs authenticate with an
`Authorization` header against `/api/v1/...` behind `RequireAuth` — would
have 401'd on the TV. External playback is now applied per strategy: on
for the iOS loopback route and header-less assets (offline downloads),
off elsewhere, with the route picker hidden to match.

Also:

- Redact the loopback server's per-session access token in player logs.
  It sits in the URL path, and `DiagnosticsRedactor` preserves paths, so
  it was reaching diagnostics bundles verbatim.
- Recover instead of stalling when no LAN address resolves for a handoff:
  playback returns to the device with a notice, at startup and mid-session.
- Refuse off-device connections to the segment server until a handoff is
  actually live, and advertise only Wi-Fi/Ethernet RFC1918 addresses —
  no link-local, VPN, or cellular.
- Owner-guard the PiP teardown in `PlayerViewModel.cleanup()` so a late
  close cannot kill a newer session's PiP binding.
- Suppress the engagement-ended pause when PiP stops as part of a
  user-initiated restore, which can land while the scene still reads as
  backgrounded.

Verified on mac-builder: iOS/tvOS/macOS build clean, 737 iOS tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift`:
- Around line 398-401: Make external playback asset/auth-mode aware in
ApplePlaybackRouteCapabilities.swift at lines 398-401, so header-less/local
assets can expose the route picker while authenticated assets remain
unsupported; alternatively introduce the corresponding asset-specific capability
variant. Align the HLS capability state and note at lines 327-330 with the same
behavior, removing the local-download exception if the route remains universally
unsupported. Update docs/tvos-player/05-route-capability-matrix.md lines 43 and
68-74 to match the runtime behavior and retain the header-less asset claim only
when the picker and playback path support it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ed995c3b-259d-4169-b520-e25cabf2972b

📥 Commits

Reviewing files that changed from the base of the PR and between 3954d22 and 154d9fe.

📒 Files selected for processing (9)
  • docs/tvos-player/05-route-capability-matrix.md
  • iosApp/Tests/LoopbackSegmentServerRangeTests.swift
  • iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift
  • iosApp/iosApp/Screens/Player/iOS/PictureInPictureCoordinator.swift
🚧 Files skipped from review as they are similar to previous changes (4)
  • iosApp/iosApp/Screens/Player/iOS/MobilePlayerControls.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift

Quick104 and others added 2 commits July 25, 2026 15:06
The header check I added missed the source proxy. `prepareSourceProxy`
runs for every direct-play plan on both the loopback and native-direct
engines, and rewrites the stream URL to the on-device cache proxy at
127.0.0.1 *with the headers dropped* — so `headers.isEmpty` read a
proxied native-direct session as receiver-fetchable and offered AirPlay
for a URL that means nothing on an Apple TV.

Ask the real question instead: can a receiver fetch this URL on its own?
Header-authenticated URLs and loopback hosts both fail; `file://` assets
pass, since AVPlayer streams those to the receiver itself rather than
handing over the URL.

Verified on mac-builder: iOS/tvOS/macOS build clean, 738 iOS tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The runtime enables AirPlay per asset, so a flat "unsupported" on the
native-direct route contradicted itself for offline downloads — and that
label is what the player's own route status row shows while the picker is
visible. Documentation only: `externalPlayback.state` feeds a status row
and a degradation note, never the picker, which reads the runtime
`supportsExternalPlayback`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Quick104
Quick104 merged commit 14d5e35 into Silo-Server:main Jul 25, 2026
1 check 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.

2 participants