Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ final class RendererAttachmentCoordinator: NSObject {
/// Configuration bundle derived from live settings and passed into the renderer pipeline.
struct Configuration {
var upscalingEnabled: Bool
var lowLatencyMode: Bool
var frameProbeEnabled: Bool
var hdrEnabled: Bool
var floorBehavior: RenderLadderFloorBehavior
Expand All @@ -61,6 +62,7 @@ final class RendererAttachmentCoordinator: NSObject {
}
return Self(
upscalingEnabled: settingsStore.stream.upscalingEnabled,
lowLatencyMode: settingsStore.stream.lowLatencyMode,
frameProbeEnabled: settingsStore.diagnostics.frameProbe,
hdrEnabled: settingsStore.stream.hdrEnabled,
floorBehavior: floorBehavior,
Expand Down Expand Up @@ -121,9 +123,11 @@ final class RendererAttachmentCoordinator: NSObject {
private var sampleRendererSnapshot: StreamSurfaceModel.RendererTelemetrySnapshot = .cleared
private var metalRendererSnapshot: StreamSurfaceModel.RendererTelemetrySnapshot = .cleared
private var upscalingEnabled = true
private var lowLatencyMode = true
private var floorBehavior: RenderLadderFloorBehavior = .sampleFloor
private var lastAppliedTrackIdentity: ObjectIdentifier?
private var lastAppliedUpscalingEnabled: Bool?
private var lastAppliedLowLatencyMode: Bool?
private var lastAppliedFloorBehavior: RenderLadderFloorBehavior?
private var lastAppliedFrameProbeEnabled: Bool?
private var lastAppliedContainerBounds: CGSize?
Expand Down Expand Up @@ -263,6 +267,7 @@ final class RendererAttachmentCoordinator: NSObject {
hasReportedRendererDecodeFailure = false
lastAppliedTrackIdentity = nil
lastAppliedUpscalingEnabled = nil
lastAppliedLowLatencyMode = nil
lastAppliedFloorBehavior = nil
lastAppliedFrameProbeEnabled = nil
lastAppliedContainerBounds = nil
Expand All @@ -273,6 +278,7 @@ final class RendererAttachmentCoordinator: NSObject {
private func applyConfiguration(_ configuration: Configuration) {
callbacks = configuration.callbacks
upscalingEnabled = configuration.upscalingEnabled
lowLatencyMode = configuration.lowLatencyMode
floorBehavior = configuration.floorBehavior
setFrameProbeEnabled(configuration.frameProbeEnabled)
sampleBufferRenderer.hdrEnabled = configuration.hdrEnabled
Expand Down Expand Up @@ -536,7 +542,8 @@ final class RendererAttachmentCoordinator: NSObject {
targetW: target.width,
targetH: target.height,
upscalingEnabled: upscalingEnabled,
floorBehavior: floorBehavior
floorBehavior: floorBehavior,
lowLatencyMode: lowLatencyMode
)
let planChanged = ladderPlan != nextPlan
ladderPlan = nextPlan
Expand Down Expand Up @@ -618,6 +625,7 @@ final class RendererAttachmentCoordinator: NSObject {
let trackChanged = attachedTrack !== newTrack
let frameProbeChanged = lastAppliedFrameProbeEnabled != frameProbeEnabled
let settingsChanged = lastAppliedUpscalingEnabled != upscalingEnabled
|| lastAppliedLowLatencyMode != lowLatencyMode
|| lastAppliedFloorBehavior != floorBehavior
|| frameProbeChanged
|| lastAppliedContainerBounds != containerBounds
Expand All @@ -640,6 +648,7 @@ final class RendererAttachmentCoordinator: NSObject {
guard trackChanged || settingsChanged else { return }
lastAppliedTrackIdentity = newTrack.map(ObjectIdentifier.init)
lastAppliedUpscalingEnabled = upscalingEnabled
lastAppliedLowLatencyMode = lowLatencyMode
lastAppliedFloorBehavior = floorBehavior
lastAppliedFrameProbeEnabled = frameProbeEnabled
lastAppliedContainerBounds = containerBounds
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,14 @@ final class MetalVideoRenderer: NSObject, RTCVideoRenderer, MTKViewDelegate, @un
var outputTexture: MTLTexture?
var outputSize: MTLSize = MTLSize(width: 0, height: 0, depth: 1)
#if canImport(MetalFX)
var spatialScaler: (any MTLFXSpatialScaler)?
/// Untyped storage: MTLFXSpatialScaler is tvOS 27.1+ in the current SDK and
/// stored properties can't carry availability.
var spatialScalerStorage: AnyObject?
@available(tvOS 27.1, *)
var spatialScaler: (any MTLFXSpatialScaler)? {
get { spatialScalerStorage as? any MTLFXSpatialScaler }
set { spatialScalerStorage = newValue }
}
var spatialScalerOutputTexture: MTLTexture?
var spatialScalerInputSize: MTLSize = MTLSize(width: 0, height: 0, depth: 1)
var spatialScalerOutputSize: MTLSize = MTLSize(width: 0, height: 0, depth: 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ extension MetalVideoRenderer {

let presentationTexture: MTLTexture
#if canImport(MetalFX)
if let spatialScaler, let spatialScalerOutputTexture {
if #available(tvOS 27.1, *), let spatialScaler, let spatialScalerOutputTexture {
spatialScaler.colorTexture = outputTexture
spatialScaler.outputTexture = spatialScalerOutputTexture
spatialScaler.encode(commandBuffer: commandBuffer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ extension MetalVideoRenderer {

guard let requestedRung else {
mtkView.drawableSize = CGSize(width: sourceWidth, height: sourceHeight)
spatialScaler = nil
spatialScalerStorage = nil
spatialScalerOutputTexture = nil
spatialScalerInputSize = MTLSize(width: 0, height: 0, depth: 1)
spatialScalerOutputSize = MTLSize(width: 0, height: 0, depth: 1)
Expand All @@ -52,7 +52,7 @@ extension MetalVideoRenderer {
switch requestedRung {
case .passthrough:
mtkView.drawableSize = CGSize(width: sourceWidth, height: sourceHeight)
spatialScaler = nil
spatialScalerStorage = nil
spatialScalerOutputTexture = nil
spatialScalerInputSize = MTLSize(width: 0, height: 0, depth: 1)
spatialScalerOutputSize = MTLSize(width: 0, height: 0, depth: 1)
Expand All @@ -67,7 +67,7 @@ extension MetalVideoRenderer {
processingOutputHeight = targetHeight
default:
mtkView.drawableSize = CGSize(width: sourceWidth, height: sourceHeight)
spatialScaler = nil
spatialScalerStorage = nil
spatialScalerOutputTexture = nil
spatialScalerInputSize = MTLSize(width: 0, height: 0, depth: 1)
spatialScalerOutputSize = MTLSize(width: 0, height: 0, depth: 1)
Expand All @@ -81,11 +81,18 @@ extension MetalVideoRenderer {
|| targetHeight != spatialScalerOutputSize.height
|| sourceWidth != spatialScalerInputSize.width
|| sourceHeight != spatialScalerInputSize.height
|| spatialScaler == nil
|| spatialScalerStorage == nil
else {
return
}

guard #available(tvOS 27.1, *) else {
spatialScalerStorage = nil
spatialScalerOutputTexture = nil
notifyCandidateFailedIfNeeded(requestedRung, reason: "MetalFX spatial scaler requires tvOS 27.1")
return
}

let descriptor = MTLFXSpatialScalerDescriptor()
descriptor.inputWidth = sourceWidth
descriptor.inputHeight = sourceHeight
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,29 @@ public struct StreamStateResponse: Codable, Sendable, Equatable {
self.state = state
self.errorDetails = errorDetails
}

private enum CodingKeys: String, CodingKey {
case state
case errorDetails
}

private struct LenientErrorDetails: Decodable {
let code: String?
let message: String?
}

/// The server sends `"errorDetails":{"code":null,"message":null}` on healthy
/// sessions; treat a null code as "no error" instead of failing the decode.
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
state = try container.decode(String.self, forKey: .state)
if let details = try container.decodeIfPresent(LenientErrorDetails.self, forKey: .errorDetails),
let code = details.code {
errorDetails = ErrorDetails(code: code, message: details.message ?? "")
} else {
errorDetails = nil
}
}
}

public struct SdpExchangeResponse: Codable, Sendable, Equatable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,26 @@ struct CloudLibraryProductDetailTests {
#expect(summary.unlockPercent == 35)
}
}

@Suite("StreamStateResponse")
struct StreamStateResponseTests {

@Test func nullErrorDetailsDecodesAsNoError() throws {
let json = #"{"state":"Provisioned","detailedSessionState":0,"errorDetails":{"code":null,"message":null}}"#
let decoded = try JSONDecoder().decode(StreamStateResponse.self, from: Data(json.utf8))
#expect(decoded.state == "Provisioned")
#expect(decoded.errorDetails == nil)
}

@Test func populatedErrorDetailsDecode() throws {
let json = #"{"state":"Failed","errorDetails":{"code":"ConsoleUnavailable","message":"Console is offline"}}"#
let decoded = try JSONDecoder().decode(StreamStateResponse.self, from: Data(json.utf8))
#expect(decoded.errorDetails == .init(code: "ConsoleUnavailable", message: "Console is offline"))
}

@Test func missingErrorDetailsDecodesAsNoError() throws {
let json = #"{"state":"ReadyToConnect"}"#
let decoded = try JSONDecoder().decode(StreamStateResponse.self, from: Data(json.utf8))
#expect(decoded.errorDetails == nil)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,15 @@ actor StreamingRuntime {
)
}
} else {
try await streamSession.waitUntilReady()
// xHome sessions go Provisioning -> Provisioned without passing through
// ReadyToConnect, so accept either; if the server does ask for the
// /connect auth step, perform it the same way the cloud path does.
let initialHomeState = try await streamSession.waitUntilReadyOrProvisioned()
if initialHomeState == .readyToConnect,
let connectUserToken = msaUserToken, !connectUserToken.isEmpty {
try await streamSession.sendMSALAuth(userToken: connectUserToken)
try await streamSession.waitUntilProvisioned()
}
await notifyLifecycle(.readyToConnect)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,60 @@ struct StreamingSessionTests {
#expect(requests.contains(where: { $0.httpMethod == "DELETE" && $0.url?.path.hasSuffix("/test-session") == true }))
}

@MainActor
@Test
func homeConnect_acceptsProvisionedStateWithNullErrorDetails() async {
// Real xHome sessions go Provisioning -> Provisioned (never ReadyToConnect)
// and report an all-null errorDetails object while healthy.
let bridge = RecordingBridge(
offerSDP: makeLocalOfferSDP(),
localCandidates: [
IceCandidatePayload(
candidate: "a=end-of-candidates",
sdpMLineIndex: 0,
sdpMid: "0"
)
],
connectionState: .connected
)
let client = makeClient(
responses: [
.json(statusCode: 200, pathSuffix: "/play", body: [
"sessionPath": "v5/sessions/home/test-session",
"sessionId": "session-provisioned",
"state": "Provisioning"
]),
.json(statusCode: 200, pathSuffix: "/state", body: [
"state": "Provisioned",
"detailedSessionState": 0,
"errorDetails": ["code": NSNull(), "message": NSNull()]
]),
.json(statusCode: 200, pathSuffix: "/sdp", body: [
"sdp": makeRemoteAnswerSDP()
]),
.empty(statusCode: 204, pathSuffix: "/ice"),
.json(statusCode: 200, pathSuffix: "/ice", body: [
"iceCandidates": [
[
"candidate": "a=candidate:2 1 udp 2122260223 20.0.0.1 6000 typ host",
"sdpMLineIndex": 0,
"sdpMid": "0"
]
]
]),
.empty(statusCode: 200, pathSuffix: "/test-session")
]
)
let session = StreamingSession(apiClient: client, bridge: bridge)

await session.connect(type: .home, targetId: "console-1")

#expect(session.lifecycle == .connected)
#expect(bridge.didSetRemoteDescription == true)

await session.disconnect()
}

@MainActor
@Test
func cloudConnect_missingMSATokenFailsBeforeWebRTCStarts() async {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public struct LiveUpscaleCapabilityProbe: UpscaleCapabilityProbing {

public func supportsMetal4FXSpatial(device: any MTLDevice) -> Bool {
#if canImport(MetalFX)
if #available(tvOS 26, macOS 26, *) {
if #available(tvOS 27.1, macOS 26, *) {
let supported = MTLFXSpatialScalerDescriptor.supportsMetal4FX(device)
log.debug("Metal4FX spatial supported: \(supported)")
return supported
Expand Down Expand Up @@ -88,9 +88,12 @@ public struct LiveUpscaleCapabilityProbe: UpscaleCapabilityProbing {

public func supportsMetalFXSpatial(device: any MTLDevice) -> Bool {
#if canImport(MetalFX)
let supported = MTLFXSpatialScalerDescriptor.supportsDevice(device)
log.debug("MetalFX spatial supported: \(supported)")
return supported
if #available(tvOS 27.1, macOS 26, *) {
let supported = MTLFXSpatialScalerDescriptor.supportsDevice(device)
log.debug("MetalFX spatial supported: \(supported)")
return supported
}
return false
#else
return false
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ public struct RenderLadderPlanner: Sendable {
targetW: Int,
targetH: Int,
upscalingEnabled: Bool,
floorBehavior: RenderLadderFloorBehavior
floorBehavior: RenderLadderFloorBehavior,
lowLatencyMode: Bool = false
) -> RenderLadderPlan {
let sourceDimensions = RenderLadderDimensions(
width: max(1, sourceW),
Expand Down Expand Up @@ -127,7 +128,8 @@ public struct RenderLadderPlanner: Sendable {
sourceW: sourceDimensions.width,
sourceH: sourceDimensions.height,
targetW: desiredProcessingTarget.width,
targetH: desiredProcessingTarget.height
targetH: desiredProcessingTarget.height,
excludeFrameInterpolation: lowLatencyMode
)

let floorRung: RenderLadderRung = floorBehavior == .metalFloor && device != nil ? .passthrough : .sampleBuffer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ public struct UpscaleCapabilityResolver: Sendable {
sourceW: Int,
sourceH: Int,
targetW: Int,
targetH: Int
targetH: Int,
excludeFrameInterpolation: Bool = false
) -> UpscaleCandidateResolution {
guard sourceW > 0, sourceH > 0, targetW > 0, targetH > 0 else {
return invalidDimensionsResolution()
Expand Down Expand Up @@ -105,14 +106,20 @@ public struct UpscaleCapabilityResolver: Sendable {
candidates: &candidates,
skippedRungReasons: &skippedRungReasons
)
appendFrameInterpolationCandidate(
sourceW: sourceW,
sourceH: sourceH,
targetW: targetW,
targetH: targetH,
candidates: &candidates,
skippedRungReasons: &skippedRungReasons
)
if excludeFrameInterpolation {
// LLFI buffers a frame (~33 ms at 60 fps); never trade that latency for upscaling
// when the user has asked for low latency.
skippedRungReasons["llfi"] = "excluded: low latency mode adds no buffered-frame upscalers"
} else {
appendFrameInterpolationCandidate(
sourceW: sourceW,
sourceH: sourceH,
targetW: targetW,
targetH: targetH,
candidates: &candidates,
skippedRungReasons: &skippedRungReasons
)
}
appendMetalCandidate(
device: device,
candidate: .metalFXSpatial,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ struct MockUpscaleCapabilityProbe: UpscaleCapabilityProbing {
#expect(result == .vtFrameInterpolation)
}

@Test func llfiExcludedInLowLatencyMode() {
let resolver = makeResolver(MockUpscaleCapabilityProbe(vtFrameInterpolation: true, metalFX: true))
let resolution = resolver.resolveCandidateResolution(
device: device, sourceW: 1920, sourceH: 1080, targetW: 3840, targetH: 2160,
excludeFrameInterpolation: true
)
#expect(!resolution.candidates.contains(.vtFrameInterpolation))
#expect(resolution.candidates.first == .metalFXSpatial)
#expect(resolution.skippedRungReasons["llfi"] != nil)
}

@Test func llsrBeatsLLFIOnTrueTwoXTarget() {
let resolver = makeResolver(MockUpscaleCapabilityProbe(scaleFactors: [2.0], vtFrameInterpolation: true))
let result = resolver.resolve(device: device, sourceW: 1920, sourceH: 1080, targetW: 3840, targetH: 2160)
Expand Down
Loading