From 930ea6c3fd2396e129557b41f65d4efd672b0883 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 16 Oct 2026 11:54:02 +0200 Subject: [PATCH 1/3] docs(adr): 0031 a physical iPhone streams through CoreDevice's media stream, behind a screen-source seam --- ...-coredevice-behind-a-screen-source-seam.md | 192 ++++++ .../adr/0031-device-stream-poc/README.md | 45 ++ .../Sources/HEVCReceiver.swift | 284 ++++++++ .../Sources/MediaBridge.h | 16 + .../Sources/MediaBridge.m | 85 +++ .../Sources/MediaDiagnostics.swift | 55 ++ .../Sources/NetworkMirror.swift | 187 ++++++ .../0031-device-stream-poc/Sources/main.swift | 613 ++++++++++++++++++ .../arm64-apple-macos.swiftinterface | 149 +++++ .../arm64-apple-macos.swiftinterface | 72 ++ .../arm64-apple-macos.swiftinterface | 23 + .../arm64-apple-macos.swiftinterface | 26 + .../adr/0031-device-stream-poc/build.sh | 20 + .../findings/device-preparation.md | 24 + .../findings/entitlements.md | 57 ++ .../findings/hevc-artifacts.md | 29 + .../proof/usb-packets.stats.json | 13 + .../proof/wifi-packets.stats.json | 13 + docs/internal/adr/README.md | 1 + 19 files changed, 1904 insertions(+) create mode 100644 docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md create mode 100644 docs/internal/adr/0031-device-stream-poc/README.md create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/HEVCReceiver.swift create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.h create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.m create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/MediaDiagnostics.swift create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/NetworkMirror.swift create mode 100644 docs/internal/adr/0031-device-stream-poc/Sources/main.swift create mode 100644 docs/internal/adr/0031-device-stream-poc/Stubs/CoreDevice.swiftmodule/arm64-apple-macos.swiftinterface create mode 100644 docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceMediaStreamSupport.swiftmodule/arm64-apple-macos.swiftinterface create mode 100644 docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceProtocols.swiftmodule/arm64-apple-macos.swiftinterface create mode 100644 docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceTypes.swiftmodule/arm64-apple-macos.swiftinterface create mode 100755 docs/internal/adr/0031-device-stream-poc/build.sh create mode 100644 docs/internal/adr/0031-device-stream-poc/findings/device-preparation.md create mode 100644 docs/internal/adr/0031-device-stream-poc/findings/entitlements.md create mode 100644 docs/internal/adr/0031-device-stream-poc/findings/hevc-artifacts.md create mode 100644 docs/internal/adr/0031-device-stream-poc/proof/usb-packets.stats.json create mode 100644 docs/internal/adr/0031-device-stream-poc/proof/wifi-packets.stats.json diff --git a/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md new file mode 100644 index 000000000..8b2b2f319 --- /dev/null +++ b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md @@ -0,0 +1,192 @@ +# 0031. A physical iPhone streams through CoreDevice's media stream, behind a screen-source seam + +- **Status:** Proposed +- **Date:** 2026-10-16 +- **Issue:** [#617](https://github.com/callstackincubator/simlock/issues/617), task [#619](https://github.com/callstackincubator/simlock/issues/619) +- **Supersedes:** nothing. Builds on the stream module as it is, and on + [ADR 0022](0022-a-physical-device-is-a-second-device-type-the-core-knows.md)'s + physical iPhone (USB, enrolled by UDID). +- **Evidence:** [`0031-device-stream-poc/`](0031-device-stream-poc/), a + proof of concept that mirrors a USB iPhone with this design. Its + `README.md` and `findings/` say what was tried and what was measured. + +## Context + +A lease on a simulator streams its screen: `simlock-screen-capture` (Swift, +in `vendor/screen-capture/`) reads the simulator's framebuffer, encodes +H.264 and writes simlock's frame envelope on stdout. The iOS driver runs it +and the stream module serves the bytes. A lease on a physical iPhone gets +`415 STREAM_NOT_SUPPORTED`. + +Apple offers two ways to see an iPhone's screen from a Mac. + +- **DeviceHub, Xcode 27's device window.** It asks CoreDevice, a private + framework in `/Library/Developer/PrivateFrameworks`, to start a media + stream. The iPhone then sends RTP video over the paired tunnel. That + works over USB and Wi-Fi. DeviceHub hands the stream to `avconferenced`, + which draws it into a layer. `avconferenced` refuses any client without + the restricted entitlement `com.apple.videoconference.allow-conferencing`. + A third-party binary that claims it is killed before `main` + (`findings/entitlements.md`). +- **QuickTime.** CoreMediaIO's `kCMIOHardwarePropertyAllowScreenCaptureDevices` + shows a USB iPhone as an `AVCaptureDevice`. The API is public. It works + over USB only, and the process must hold the Camera permission, which a + person grants in a dialog on that Mac. + +The PoC proved a third path. It drives DeviceHub's negotiation itself +(CoreDevice's `startMediaStream`, and AVConference's negotiator object for +the offer and answer). Then it receives the RTP packets on its own socket +and decodes the HEVC in its own process with VideoToolbox. Nothing goes +through `avconferenced`, so no entitlement is needed, and no Camera +permission either. It streamed over USB and over Wi-Fi +(`proof/usb-packets.stats.json`, `proof/wifi-packets.stats.json`). + +The price: + +- CoreDevice ships no Swift interface. The PoC calls it through + hand-written `.swiftinterface` stubs (`Stubs/`). They match CoreDevice + 642.x (Xcode 27), checked on 642.16. Another major version may rename or + drop what they declare. +- DeviceHub's default HEVC settings produced torn pictures in a decoder of + our own. The PoC overrides the negotiator's HEVC feature string, and + turns off long-term reference pictures, inside its own process. That + fixed it (`findings/hevc-artifacts.md`). +- Without DeviceHub running, CoreDevice does not load the iPhone's + services. The PoC takes a usage assertion, as DeviceHub does + (`findings/device-preparation.md`). + +## Decision + +### 1. A physical iPhone's screen comes from CoreDevice's media stream, decoded by simlock + +The capture asks CoreDevice for the iPhone's media stream. It negotiates +through AVConference's negotiator object, receives the RTP packets on the +socket CoreDevice shares with it, and decodes the HEVC with VideoToolbox. +It never uses `avconferenced`, never claims a restricted entitlement, and +never asks for the Camera permission. + +```mermaid +sequenceDiagram + participant D as iOS driver + participant P as simlock-device-capture + participant C as CoreDevice (coredeviced) + participant I as iPhone + D->>P: start + P->>P: CoreDevice major is not 642: exit with the reason + P->>C: usage assertion, then startMediaStream(offer) + C->>I: start the screen stream + C-->>P: answer, shared socket + I-->>P: RTP / HEVC + P->>P: decode, encode H.264 + P-->>D: frames on stdout, meta first + D->>P: stdin closed + P->>C: stopMediaStream(its own stream id), release the assertion +``` + +### 2. The iPhone has its own program, sharing a library with the simulator's + +`vendor/screen-capture/` becomes one Swift package with: + +- a library target: the encoders, the scaler, the frame envelope writer, + the stdin and signal lifecycle, and the `ScreenSource` seam (§3); +- `simlock-screen-capture`: the simulator source, as today; +- `simlock-device-capture`: the CoreDevice source, the only target that + links CoreDevice and its stubs. + +A CoreDevice change can then never stop a simulator stream. macOS refuses +to start a program whose linked frameworks no longer match, before its own +code runs. Only the iPhone program carries that risk. + +```mermaid +flowchart LR + subgraph pkg["vendor/screen-capture"] + L["library: encoder, scaler, envelope, lifecycle, ScreenSource"] + S["simlock-screen-capture"] --> L + P["simlock-device-capture"] --> L + end + S --> SIM["simulator framebuffer"] + P --> CD["CoreDevice 642.x (private)"] + P -.later.-> QT["CoreMediaIO (public)"] +``` + +### 3. A screen source is one shape, with two implementations now and a third named + +A `ScreenSource` starts on a device id and hands decoded pictures +(`CVPixelBuffer`) to the shared encode loop. It stops on request. It +reports a failure as one line of text. A source delivers at least 5 +pictures a second while it runs, repeating its last one when the screen +is still, as the simulator source does today. A still screen then never +looks like a dead capture to the stream's silence limit. + +The two implementations are the simulator framebuffer and CoreDevice. +CoreMediaIO, the QuickTime path, is the named third. It would replace +CoreDevice inside `simlock-device-capture` if CoreDevice's private API +stops being usable. That change touches no TypeScript: the driver runs the +same program with the same arguments. + +### 4. CoreDevice major 642 only, and a mismatch is a reason, not a crash + +`simlock-device-capture` weak-links the private frameworks. Before it +calls into them, it reads CoreDevice's `CFBundleShortVersionString`. + +- Major `642`: it goes on. +- Anything else, or no CoreDevice: it writes one log line and exits with a + non-zero code, before it touches the iPhone. The line says that physical + iPhone streams need Xcode 27 (CoreDevice 642.x) and names the version it + found. The viewer gets that line in a 503. + +`pnpm build` builds `simlock-device-capture` only on a Mac whose CoreDevice +major is 642. Elsewhere it is skipped, and a physical iPhone's stream +answers 503 saying so. Moving to a new major means checking the stubs on +it and changing the pin, in one change. + +### 5. HEVC is decoded and re-encoded as H.264 + +The iPhone sends HEVC. The program decodes it and encodes H.264 with the +same encoder the simulator program uses. The frame envelope, the console's +decoder and every browser stay as they are. The cost is one decode and one +encode per picture on the worker, both in VideoToolbox. + +### 6. The program changes only what it started + +- It stops only the media stream it started, by that stream's id. It never + stops all streams, so DeviceHub or Xcode showing the same iPhone keeps + its own. +- It releases its usage assertion on every way out: stop, error, the + stream ending, and an assertion that CoreDevice invalidates. +- The negotiator overrides named in Context are made in its own process, before + it builds its offer. No system file and no other process is changed. + +## Consequences + +- Physical iPhone streams need Xcode 27 on the worker, and a simlock built + on such a Mac. A worker on another Xcode answers 503 with the reason. +- Each new Xcode major costs a check of the stubs against it, and a pin + change. Until then, iPhone streams on that Xcode are off; simulator + streams are not affected. +- `vendor/screen-capture/` gains code that is ours (the CoreDevice source, + the stubs, the RTP receiver) next to serve-sim's. Its `NOTICE.md` + records which is which. The HEVC feature string comes from the MIT + `idevice` project and is credited there. +- A worker pays an HEVC decode and an H.264 encode per streamed iPhone. +- The stream module, the frame envelope, the HTTP API and the console do + not change. + +## Alternatives considered + +- **QuickTime's CoreMediaIO path now.** Public and stable. Rejected for + now: the PoC never confirmed sustained frames on it (its log shows a 0x0 + format at start), and it needs the Camera permission granted by a person + in a dialog on each worker. It stays the named replacement (§3). +- **DeviceHub's own path through `avconferenced`.** Rejected: it needs a + restricted entitlement Apple does not grant to third parties. +- **One program with two sources.** Rejected: the iPhone source would link + the private frameworks, so a CoreDevice change would also stop simulator + streams on that Mac. +- **Pass HEVC to the browser.** Rejected: the console, the envelope's + `codec` and every viewer would change, and not every browser decodes + HEVC. +- **Pin the exact version 642.16.** Rejected: every Xcode patch update would + turn iPhone streams off until someone re-checks the stubs. Apple builds + these frameworks with library evolution, so a minor version keeps their + calls. diff --git a/docs/internal/adr/0031-device-stream-poc/README.md b/docs/internal/adr/0031-device-stream-poc/README.md new file mode 100644 index 000000000..706114c42 --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/README.md @@ -0,0 +1,45 @@ +# DeviceStreamPoC + +A third-party macOS app that mirrors a physical iPhone and sends touches to it, built by +reverse-engineering what Xcode 27's **DeviceHub.app** does under the hood. + +Requirements: macOS 26, Xcode 27 (CoreDevice 642.x), an iPhone paired with Xcode and connected over USB. + +```bash +./build.sh +open build/DeviceStreamPoC.app +``` + +Pick the iPhone, press **Start mirror**, allow Camera access when asked (iOS screen-capture devices are +treated as cameras by TCC), then click / drag / two-finger-scroll on the video to touch the device. +A drag that starts within 3% of an edge is sent as an edge gesture (bottom edge = home gesture). + +## How DeviceHub works + +| Concern | Framework | Notes | +| --- | --- | --- | +| Shell | `DeviceHub.app` → `DeviceKit.framework` | DeviceHub only instantiates `DeviceKit.DeviceManagementWindow()`. | +| Discovery / control | `CoreDevice.framework` (`/Library/Developer/PrivateFrameworks`) | Client of `coredeviced`; devices reached over the RemotePairing tunnel (`remotepairingd`), USB or Wi‑Fi. Entry: `CoreDeviceService.sharedConnection` → `DeviceManager` → `RemoteDevice`. | +| Video | `CoreDeviceMediaStreamSupport.framework` + private `AVConference` | `MediaStreamSession.makeVideoStream(withConfiguration: .receiveMirroredPrimary(layer:timeout:))` negotiates `com.apple.coredevice.feature.startmediastream` with an `AVCMediaStreamNegotiator` offer, gets a socket pair on the tunnel, and `avconferenced` renders the decoded video into the CALayer (`AVCRemoteVideoClient`). Frames never enter the client process. | +| Touch / keys | `CoreDevice` HID capabilities + `UniversalHID.framework` | Legacy digitizer: `RemoteDevice.getImplementation(for: CapabilityStaticMember())` → `HIDDigitizer.send(pointOne:…)` (`IndigoHIDDigitizer`, normalized 0…1 coordinates). Newer path: `UniversalHIDService` virtual HID services + HID reports. | + +## What a third-party app can and cannot use + +* **Works without entitlements**: everything in CoreDevice — discovery, device/display info, screenshots + (`CaptureScreenshotCapability`), and the remote HID digitizer (verified: taps, drags, edge gestures). +* **Gated**: the AVConference video path. `avconferenced` rejects `vcMediaStreamSetSessionConfig` unless the + client holds `com.apple.videoconference.allow-conferencing`, a restricted entitlement; AMFI refuses to load a + non-Apple binary that claims it. The "Try CoreDevice media stream" button reproduces the refusal. +* **Public substitute for video**: CoreMediaIO `kCMIOHardwarePropertyAllowScreenCaptureDevices` exposes a + USB-connected iPhone as a muxed `AVCaptureDevice` (what QuickTime Player uses). This app renders it with + `AVCaptureVideoPreviewLayer` and maps clicks back through `captureDevicePointConverted(fromLayerPoint:)`. + +## Layout + +* `Sources/main.swift` — the app (AppKit): CoreMediaIO capture, CoreDevice discovery, digitizer input, the media-stream experiment. +* `Stubs/*.swiftmodule/*.swiftinterface` — hand-written Swift interfaces for the private frameworks (they ship none). The frameworks are built with library evolution, so calls go through stable dispatch thunks; declarations must match the real signatures/manglings (see comments). +* `Tools/listdevices.swift`, `Tools/tap.swift` — CLI checks. `tap x y [x2 y2]` taps or swipes in normalized coordinates; `EDGE=bottom` makes it an edge gesture. +* `build.sh`, `Info.plist`, `entitlements.plist` (the entitlement experiment; not applied by default). + +Environment switches for testing: `AUTOSTART=`, `AUTOTAP=x,y` (device space) or +`AUTOTAP=view:fx,fy` (fraction of the video view), `LOGFILE=`. diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/HEVCReceiver.swift b/docs/internal/adr/0031-device-stream-poc/Sources/HEVCReceiver.swift new file mode 100644 index 000000000..d4c8e48be --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/HEVCReceiver.swift @@ -0,0 +1,284 @@ +import Foundation +import VideoToolbox + +// Single-stream receiver with bounded packet reordering. Loss discards the whole access unit. +// HEVC RTP payloads follow RFC 7798 (single NAL, AP and FU, without DONL). +final class HEVCRTPReceiver { + var onAccessUnit: ([Data], UInt32) -> Void = { _, _ in } + var onLoss: () -> Void = {} + private var pending: [UInt16:(data:Data,arrival:TimeInterval)] = [:] + private var nextExpected: UInt16? + private let reorderDelay: TimeInterval = 0.025 + private(set) var reorderedPackets = 0 + private(set) var latePackets = 0 + private(set) var lossEvents = 0 + private var sequence: UInt16? + private var timestamp: UInt32? + private var fragment = Data() + private var nals: [Data] = [] + private var damaged = false + private var unitBytes = 0 + private(set) var source: UInt32? + private(set) var received: UInt32 = 0 + private(set) var highest: UInt32 = 0 + private var base: UInt32 = 0 + private var previousExpected: UInt32 = 0 + private var previousReceived: UInt32 = 0 + private var lastSR: UInt32 = 0 + private var lastSRTime: TimeInterval = 0 + private var transit: Double? + private var jitter = 0.0 + private let maxUnitBytes = 8 * 1024 * 1024 + static func u16(_ b: [UInt8], _ i: Int) -> UInt16 { UInt16(b[i]) << 8 | UInt16(b[i+1]) } + static func u32(_ b: [UInt8], _ i: Int) -> UInt32 { UInt32(u16(b,i)) << 16 | UInt32(u16(b,i+2)) } + static func word(_ n: UInt32) -> [UInt8] { [UInt8(truncatingIfNeeded:n >> 24),UInt8(truncatingIfNeeded:n >> 16),UInt8(truncatingIfNeeded:n >> 8),UInt8(truncatingIfNeeded:n)] } + private func lose() { fragment.removeAll(keepingCapacity:true); nals.removeAll(keepingCapacity:true); unitBytes=0; damaged=true; lossEvents+=1; onLoss() } + func receive(_ data: Data) { + let bytes=Array(data.prefix(12)) + guard bytes.count>=12,bytes[0]>>6==2 else {return} + // RTCP has its own sequence space and must never enter the RTP reorder buffer. + guard bytes[1]&127==100 else {receiveOrdered(data);return} + let sender=Self.u32(bytes,8) + guard source==nil || source==sender else {return} + if source==nil {source=sender} + let seq=Self.u16(bytes,2) + if nextExpected==nil {nextExpected=seq} + guard let expected=nextExpected else {return} + let distance=Int16(bitPattern:seq &- expected) + guard distance>=0 else {latePackets+=1;return} + guard pending[seq]==nil else {return} + if distance>0 {reorderedPackets+=1} + pending[seq]=(data,ProcessInfo.processInfo.systemUptime) + flushPending() + } + func flushPending() { + while let expected=nextExpected { + if let packet=pending.removeValue(forKey:expected) { + nextExpected=expected &+ 1 + receiveOrdered(packet.data) + continue + } + guard !pending.isEmpty else {return} + let oldest=pending.values.map(\.arrival).min()! + guard pending.count>=256 || ProcessInfo.processInfo.systemUptime-oldest>=reorderDelay else {return} + // The gap is now real; receiveOrdered will invalidate the affected access unit. + nextExpected=pending.keys.min { ($0 &- expected)<($1 &- expected) } + } + } + private func receiveOrdered(_ data: Data) { + let b=Array(data) + guard b.count>=4, b[0]>>6==2 else {return} + if b[1]>=192 && b[1]<=223 { + var offset=0 + while offset+4<=b.count { + let length=(Int(Self.u16(b,offset+2))+1)*4 + guard length>=4,offset+length<=b.count else {return} + if b[offset+1]==200, length>=28 { + let sender=Self.u32(b,offset+4) + if source==nil || source==sender { + lastSR=(Self.u32(b,offset+8)<<16)|(Self.u32(b,offset+12)>>16) + lastSRTime=ProcessInfo.processInfo.systemUptime + } + } + offset+=length + } + return + } + guard b.count>=12, b[1]&127==100 else {return} + let sender=Self.u32(b,8) + guard source==nil || source==sender else {return} + source=sender + let seq=Self.u16(b,2), ts=Self.u32(b,4) + var offset=12+Int(b[0]&15)*4 + guard offset<=b.count else {return} + if b[0]&16 != 0 { + guard offset+4<=b.count else {return} + offset+=4+Int(Self.u16(b,offset+2))*4 + } + var end=b.count + if b[0]&32 != 0 { + let pad=Int(b.last!) + guard pad>0,pad<=end-offset else {return} + end-=pad + } + guard offset+2<=end else {return} + var sequenceGap=false + if let previous=sequence { + let distance=Int16(bitPattern:seq &- previous) + guard distance>0 else {return} // Ignore duplicates. + highest &+= UInt32(distance) + if distance != 1 { sequenceGap=true } + } else { highest=UInt32(seq); base=highest } + sequence=seq; received &+= 1 + // Differences avoid unsigned timestamp wrap during long sessions. + let now=ProcessInfo.processInfo.systemUptime + let currentTransit=now*90000-Double(ts) + if let old=transit { let delta=abs(currentTransit-old); if delta<900000 {jitter+=(delta-jitter)/16} } + transit=currentTransit + if timestamp != ts { + if timestamp != nil && (!nals.isEmpty || !fragment.isEmpty) { lossEvents+=1;onLoss() } + nals.removeAll(keepingCapacity:true);fragment.removeAll(keepingCapacity:true);unitBytes=0;damaged=false;timestamp=ts + } + // Apply loss AFTER the timestamp reset: a gap may include the first slices of this frame. + if sequenceGap {lose()} + let payload=Array(b[offset..>1)&63 + if !damaged { + switch kind { + case 0..<48: + if !fragment.isEmpty {lose()} else {append(Data(payload))} + case 48: + var i=2 + while i=2,i+length<=payload.count else {lose();break} + append(Data(payload[i..=4 else {lose();return} + let fu=payload[2] + if fu&128 != 0 { + if !fragment.isEmpty {lose();return} + fragment=Data([(payload[0]&129)|((fu&63)<<1),payload[1]]) + } + guard !fragment.isEmpty else {lose();return} + guard fragment.count+payload.count-3<=maxUnitBytes else {lose();return} + fragment.append(contentsOf:payload.dropFirst(3)) + if fu&64 != 0 {let nal=fragment;fragment.removeAll(keepingCapacity:true);append(nal)} + default: lose() + } + } + if b[1]&128 != 0 { + if !fragment.isEmpty {lose()} + // A complete picture must include its first slice, including when joining mid-stream. + let slices=nals.filter { ($0[$0.startIndex]>>1)&63 < 32 } + if !slices.isEmpty && !slices.contains(where: {$0.count>=3 && $0[$0.startIndex+2]&128 != 0}) {lose()} + if !damaged && !nals.isEmpty {onAccessUnit(nals,ts)} + nals.removeAll(keepingCapacity:true);unitBytes=0 + } + } + private func append(_ nal:Data) { + guard unitBytes+nal.count<=maxUnitBytes else {lose();return} + nals.append(nal);unitBytes+=nal.count + } + func report(receiver: UInt32, requestKeyframe: Bool = false, bye: Bool = false) -> Data { + let w=Self.word + var b:[UInt8] + if let source { + let expected=highest &- base &+ 1 + let interval=expected &- previousExpected + let got=received &- previousReceived + let lost=max(Int64(expected)-Int64(received),0) + let fraction=interval>0 ? min(255,max(0,(Int64(interval)-Int64(got))*256/Int64(interval))):0 + let total=UInt32(min(lost,0x7fffff)) + let delay=lastSR==0 ? 0:UInt32(min((ProcessInfo.processInfo.systemUptime-lastSRTime)*65536,Double(UInt32.max))) + b=[0x81,201,0,7]+w(receiver)+w(source)+[UInt8(fraction),UInt8(truncatingIfNeeded:total>>16),UInt8(truncatingIfNeeded:total>>8),UInt8(truncatingIfNeeded:total)]+w(highest)+w(UInt32(jitter))+w(lastSR)+w(delay) + previousExpected=expected;previousReceived=received + } else {b=[0x80,201,0,1]+w(receiver)} + let name=Array("DeviceStreamPoC".utf8) + var chunk=w(receiver)+[1,UInt8(name.count)]+name+[0] + while chunk.count%4 != 0 {chunk.append(0)} + b += [0x81,202,0,UInt8(chunk.count/4)]+chunk + if requestKeyframe,let source {b += [0x81,206,0,2]+w(receiver)+w(source)} + if bye {b += [0x81,203,0,1]+w(receiver)} + return Data(b) + } +} + +final class HEVCDecoder { + private let useHardware:Bool + var onConfiguration:(String)->Void = {_ in} + init(useHardware:Bool = false) {self.useHardware=useHardware} + private var parameterSets: [UInt8:Data] = [:] + private var format: CMVideoFormatDescription? + private var session: VTDecompressionSession? + private(set) var needsKeyframe=true + private var discardLeadingPictures=false + private(set) var decoded=0 + private(set) var submitted=0 + private(set) var decoderDropped=0 + private(set) var waitingForKeyframe=0 + private(set) var accessUnits=0 + var onFrame: (CVPixelBuffer) -> Void = {_ in} + var onFailure: (String) -> Void = {_ in} + deinit { if let session {VTDecompressionSessionInvalidate(session)} } + func invalidateReferences() { + needsKeyframe=true + if let session {VTDecompressionSessionInvalidate(session)} + session=nil + } + func decode(_ nals:[Data], timestamp:UInt32) { + accessUnits+=1 + var picture=[Data](), randomAccess=false, changed=false, sliceTypes=[UInt8]() + for nal in nals { + guard nal.count>=2 else {continue} + let type=(nal[nal.startIndex]>>1)&63 + if (32...34).contains(type) { + if parameterSets[type] != nal {parameterSets[type]=nal;changed=true} + } else {picture.append(nal);if type<32 {sliceTypes.append(type)};if (16...21).contains(type) {randomAccess=true}} + } + if changed {if let session {VTDecompressionSessionInvalidate(session)};session=nil;format=nil;needsKeyframe=true} + guard !sliceTypes.isEmpty else {return} + guard !needsKeyframe || randomAccess else {waitingForKeyframe+=1;return} + // RASL pictures following an open-GOP recovery point may reference the discarded past. + if discardLeadingPictures && sliceTypes.contains(where: {$0==8 || $0==9}) {return} + if needsKeyframe && randomAccess {discardLeadingPictures=true} + else if sliceTypes.contains(where: {$0<6}) {discardLeadingPictures=false} + do { + if session==nil {try configure()} + guard let session,let format else {return} + var bytes=Data() + for nal in picture {bytes.append(contentsOf:HEVCRTPReceiver.word(UInt32(nal.count)));bytes.append(nal)} + var block:CMBlockBuffer? + try check(CMBlockBufferCreateWithMemoryBlock(allocator:kCFAllocatorDefault,memoryBlock:nil,blockLength:bytes.count,blockAllocator:kCFAllocatorDefault,customBlockSource:nil,offsetToData:0,dataLength:bytes.count,flags:0,blockBufferOut:&block),"block allocation") + guard let block else {return} + try bytes.withUnsafeBytes {raw in try check(CMBlockBufferReplaceDataBytes(with:raw.baseAddress!,blockBuffer:block,offsetIntoDestination:0,dataLength:bytes.count),"block copy")} + var timing=CMSampleTimingInfo(duration:.invalid,presentationTimeStamp:CMTime(value:Int64(timestamp),timescale:90000),decodeTimeStamp:.invalid) + var size=bytes.count,sample:CMSampleBuffer? + try check(CMSampleBufferCreateReady(allocator:kCFAllocatorDefault,dataBuffer:block,formatDescription:format,sampleCount:1,sampleTimingEntryCount:1,sampleTimingArray:&timing,sampleSizeEntryCount:1,sampleSizeArray:&size,sampleBufferOut:&sample),"compressed sample") + guard let sample else {return} + // CoreMedia assumes sync samples unless NotSync is explicitly set. P/B pictures + // depend on decoded references; never describe them as random-access points. + if let attachments=CMSampleBufferGetSampleAttachmentsArray(sample,createIfNecessary:true) { + let dictionary=unsafeBitCast(CFArrayGetValueAtIndex(attachments,0),to:CFMutableDictionary.self) + let depends = randomAccess ? kCFBooleanFalse! : kCFBooleanTrue! + CFDictionarySetValue(dictionary,Unmanaged.passUnretained(kCMSampleAttachmentKey_NotSync).toOpaque(),Unmanaged.passUnretained(depends).toOpaque()) + CFDictionarySetValue(dictionary,Unmanaged.passUnretained(kCMSampleAttachmentKey_DependsOnOthers).toOpaque(),Unmanaged.passUnretained(depends).toOpaque()) + } + submitted+=1 + // Synchronous callback: decoded frames and reference state stay on the receiver queue. + var outputError:OSStatus=0 + var gotImage=false + let status=VTDecompressionSessionDecodeFrame(session,sampleBuffer:sample,flags:[],infoFlagsOut:nil) { [self] status,_,image,_,_ in + outputError=status + if status==0,let image {gotImage=true;decoded+=1;needsKeyframe=false;onFrame(image)} + } + try check(status,"decode submission");try check(outputError,"decode output") + if !gotImage {decoderDropped+=1} + } catch {invalidateReferences();onFailure(error.localizedDescription)} + } + private func check(_ status:OSStatus,_ operation:String) throws { + if status != 0 {throw NSError(domain:"HEVCDecoder",code:Int(status),userInfo:[NSLocalizedDescriptionKey:"\(operation): \(status)"])} + } + private func configure() throws { + guard let vps=parameterSets[32],let sps=parameterSets[33],let pps=parameterSets[34] else {return} + let status=vps.withUnsafeBytes {v in sps.withUnsafeBytes {s in pps.withUnsafeBytes {p in + let pointers=[v.bindMemory(to:UInt8.self).baseAddress!,s.bindMemory(to:UInt8.self).baseAddress!,p.bindMemory(to:UInt8.self).baseAddress!] + return CMVideoFormatDescriptionCreateFromHEVCParameterSets(allocator:kCFAllocatorDefault,parameterSetCount:3,parameterSetPointers:pointers,parameterSetSizes:[vps.count,sps.count,pps.count],nalUnitHeaderLength:4,extensions:nil,formatDescriptionOut:&format) + }}} + try check(status,"HEVC format") + guard let format else {return} + // Explicit decoder selection makes transport/assembly identical in both modes. + var specification:[CFString:Any]=[kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder:useHardware] + if useHardware {specification[kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder]=true} + try check(VTDecompressionSessionCreate(allocator:kCFAllocatorDefault,formatDescription:format,decoderSpecification:specification as CFDictionary,imageBufferAttributes:[kCVPixelBufferIOSurfacePropertiesKey:[:]] as CFDictionary,outputCallback:nil,decompressionSessionOut:&session),"decoder creation") + if let session { + VTSessionSetProperty(session,key:kVTDecompressionPropertyKey_RealTime,value:kCFBooleanTrue) + var actualHardware:CFTypeRef? + let status=VTSessionCopyProperty(session,key:kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder,allocator:kCFAllocatorDefault,valueOut:&actualHardware) + if status==0,let enabled=actualHardware as? Bool { + onConfiguration("HEVC decoder: \(enabled ? "hardware" : "software") (requested \(useHardware ? "hardware" : "software"))") + } else {onConfiguration("HEVC decoder requested \(useHardware ? "hardware" : "software"); backend query status \(status)")} + } + } +} diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.h b/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.h new file mode 100644 index 000000000..c6a1c7adb --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.h @@ -0,0 +1,16 @@ +#import +NSObject * _Nullable probeNegotiator(NSDictionary * _Nonnull options, NSInteger mode); +NSData * _Nullable probeOffer(NSObject * _Nonnull negotiator); +NSDictionary * _Nullable probeAnswer(NSObject * _Nonnull negotiator, NSData * _Nonnull answer); + +NSString * _Nullable probeBind(NSString * _Nonnull remoteIP); +unsigned short probePort(void); +NSData * _Nullable probeReceive(int milliseconds); +void probeClose(void); + + + +#import +void probeAdopt(xpc_object_t _Nonnull sockets); + +BOOL probeSend(NSData * _Nonnull packet); diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.m b/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.m new file mode 100644 index 000000000..b33a61081 --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/MediaBridge.m @@ -0,0 +1,85 @@ +#import "MediaBridge.h" +#import +#import +@interface NSObject (AVCProbe) +- (id)initWithMode:(NSInteger)mode options:(NSDictionary*)options error:(NSError**)error; +- (id)offer; +- (BOOL)setAnswer:(NSData*)answer withError:(NSError**)error; +- (id)generateMediaStreamConfigurationWithError:(NSError**)error; +- (id)dictionary; +@end +#import +// LTRP was disabled during the artifact investigation. It did not fix the corruption; +// preserve that setting while changing the independent HEVC capability advertisement. +// No system framework is modified: these hooks affect only this demo process. +static IMP originalScreenFeatures; +static NSDictionary *screenDecoderFeatures(id self, SEL selector) { + NSDictionary *original=((NSDictionary *(*)(id,SEL))originalScreenFeatures)(self,selector); + NSMutableDictionary *features=[original mutableCopy]; + // Payload 100 is HEVC; preserve H.264 and every other negotiated setting. + // DeviceHub advertises FLS;VRAE:0;SW:1;. The idevice receiver documents tearing + // with that preset and uses this alternative for its standalone HEVC decoder: + // https://docs.rs/idevice/latest/src/idevice/services/core_device/display_stream/negotiation.rs.html + if(features[@100]) features[@100]=@"FLS;MS:-1;LF:-1;LTR;CABAC;POS:0;EOD:1;HTS:2;RR:3;AR:16/9,5/8;XR:16/9,5/8;"; + return features; +} +static BOOL ltrpDisabled(id self,SEL _cmd) { return NO; } +static void disableLTRPGetter(const char *className) { + Method m=class_getInstanceMethod(NSClassFromString(@(className)),@selector(ltrpEnabled)); + if(!m) {NSLog(@"negotiator: %s has no ltrpEnabled",className);return;} + method_setImplementation(m,(IMP)ltrpDisabled); +} +static BOOL installNegotiatorHooks(void) { + static dispatch_once_t once; + static BOOL installed=NO; + dispatch_once(&once,^{ + Class settings=NSClassFromString(@"AVCMediaStreamNegotiatorSettingsCoreDeviceScreenSharing"); + Method features=class_getInstanceMethod(settings,@selector(featureListString)); + if(!features) {NSLog(@"negotiator: HEVC capability setting unavailable");return;} + originalScreenFeatures=method_setImplementation(features,(IMP)screenDecoderFeatures); + installed=YES; + NSLog(@"negotiator: standalone-decoder HEVC capabilities enabled"); + if(getenv("KEEP_LTRP")) {NSLog(@"negotiator: KEEP_LTRP set, leaving LTRP enabled");return;} + // The offer is built inside -initWithMode:options:error: from the settings preset + // (AVCMediaStreamNegotiatorSettingsCoreDeviceScreenSharing) and the local configuration, + // so both getters are overridden before the negotiator is created. + disableLTRPGetter("AVCMediaStreamNegotiatorSettings"); + disableLTRPGetter("VCMediaNegotiatorLocalConfiguration"); + NSLog(@"negotiator: LTRP disabled for the offer"); + }); + return installed; +} +NSObject *probeNegotiator(NSDictionary *options, NSInteger mode) { + dlopen("/System/Library/PrivateFrameworks/AVConference.framework/AVConference",RTLD_NOW); + if(!installNegotiatorHooks()) return nil; + NSError *e=nil; id n=[(NSObject*)[NSClassFromString(@"AVCMediaStreamNegotiator") alloc] initWithMode:mode options:options error:&e]; + if(e) NSLog(@"negotiator error: %@",e); return n; +} +NSData *probeOffer(NSObject *n){ id o=[n offer]; NSLog(@"offer class=%@",[o class]); return [o isKindOfClass:NSData.class]?o:nil; } +NSDictionary *probeAnswer(NSObject*n,NSData*a){NSError*e=nil; if(![n setAnswer:a withError:&e]){NSLog(@"answer error: %@",e);return nil;}id c=[n generateMediaStreamConfigurationWithError:&e]; if(e)NSLog(@"config error: %@",e);return [c dictionary];} + +#import +#import +#import +#import +#import +static int rx=-1; +static unsigned short rxPort=0; +NSString *probeBind(NSString *remoteIP) { + int route=socket(AF_INET6,SOCK_DGRAM,0); struct sockaddr_in6 dst={0},src={0}; dst.sin6_len=sizeof(dst);dst.sin6_family=AF_INET6;dst.sin6_port=htons(9); + if(inet_pton(AF_INET6,remoteIP.UTF8String,&dst.sin6_addr)!=1){close(route);return nil;} + if(connect(route,(struct sockaddr*)&dst,sizeof(dst))!=0){perror("route connect");close(route);return nil;} + socklen_t len=sizeof(src);getsockname(route,(struct sockaddr*)&src,&len);close(route); + char ip[INET6_ADDRSTRLEN];inet_ntop(AF_INET6,&src.sin6_addr,ip,sizeof(ip)); + rx=socket(AF_INET6,SOCK_DGRAM,0);src.sin6_port=0; + if(bind(rx,(struct sockaddr*)&src,sizeof(src))!=0){perror("receiver bind");probeClose();return nil;} + len=sizeof(src);getsockname(rx,(struct sockaddr*)&src,&len);rxPort=ntohs(src.sin6_port); + int sz=4*1024*1024;setsockopt(rx,SOL_SOCKET,SO_RCVBUF,&sz,sizeof(sz));return @(ip); +} +unsigned short probePort(void){return rxPort;} +NSData *probeReceive(int milliseconds){struct pollfd p={rx,POLLIN,0};if(poll(&p,1,milliseconds)<=0)return nil;unsigned char b[65536];ssize_t n=recv(rx,b,sizeof(b),0);return n>0?[NSData dataWithBytes:b length:n]:nil;} +void probeClose(void){if(rx>=0)close(rx);rx=-1;} + +void probeAdopt(xpc_object_t sockets){char*d=xpc_copy_description(sockets);fprintf(stderr,"SOCKETS %s\n",d);free(d);xpc_dictionary_apply(sockets,^bool(const char*k,xpc_object_t v){if(xpc_get_type(v)==XPC_TYPE_FD){int fd=xpc_fd_dup(v);int t=0;socklen_t n=sizeof(t);getsockopt(fd,SOL_SOCKET,SO_TYPE,&t,&n);fprintf(stderr,"FD key=%s type=%d\n",k,t);if(rx<0){rx=fd;int sz=4*1024*1024;setsockopt(rx,SOL_SOCKET,SO_RCVBUF,&sz,sizeof(sz));}else close(fd);}return true;});} + +BOOL probeSend(NSData *packet) { return send(rx, packet.bytes, packet.length, 0) == (ssize_t)packet.length; } diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/MediaDiagnostics.swift b/docs/internal/adr/0031-device-stream-poc/Sources/MediaDiagnostics.swift new file mode 100644 index 000000000..a03ea6cce --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/MediaDiagnostics.swift @@ -0,0 +1,55 @@ +import Foundation +import VideoToolbox +import ImageIO + +// Temporary bounded evidence for the user-driven artifact investigation. +// All methods run on the receiver queue; nothing is uploaded. +final class MediaDiagnostics { + private let directory:URL + private var packets=Data(), elementary=Data() + private let began=ProcessInfo.processInfo.systemUptime + private let limit=16*1024*1024 + private var saved=false + private var frames=0 + private var enabled:Bool + init(hardware:Bool) { + enabled=ProcessInfo.processInfo.environment["DISABLE_MEDIA_DIAGNOSTICS"] != "1" + directory=Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("work/media-diagnostics/\(Int(Date().timeIntervalSince1970))-\(hardware ? "hardware" : "software")-\(UUID().uuidString.prefix(6))") + if enabled { + do {try FileManager.default.createDirectory(at:directory,withIntermediateDirectories:true) + log("Diagnostics: saving first 8 seconds locally to \(directory.path)") + } catch {enabled=false;log("Diagnostics: \(error.localizedDescription)")} + } + } + func receive(_ packet:Data) { + guard enabled,!saved else {return} + if ProcessInfo.processInfo.systemUptime-began>=8 || packets.count+packet.count+4>limit {finish();return} + packets.append(contentsOf:HEVCRTPReceiver.word(UInt32(packet.count)));packets.append(packet) + } + func accessUnit(_ nals:[Data]) { + guard enabled,!saved else {return} + let size=nals.reduce(0){$0+$1.count+4} + guard elementary.count+size<=limit else {finish();return} + for nal in nals {elementary.append(contentsOf:[0,0,0,1]);elementary.append(nal)} + } + func decoded(_ pixel:CVPixelBuffer) { + guard enabled,!saved else {return} + frames+=1 + guard frames==1 || frames==60 || frames==180 else {return} + var image:CGImage? + let status=VTCreateCGImageFromCVPixelBuffer(pixel,options:nil,imageOut:&image) + guard status==0,let image,let destination=CGImageDestinationCreateWithURL(directory.appendingPathComponent("decoded-\(frames).png") as CFURL,"public.png" as CFString,1,nil) else {return} + CGImageDestinationAddImage(destination,image,nil) + if !CGImageDestinationFinalize(destination) {log("Diagnostics: could not save decoded frame")} + } + func finish() { + guard enabled,!saved else {return};saved=true + do { + try packets.write(to:directory.appendingPathComponent("received.rtpdump")) + try elementary.write(to:directory.appendingPathComponent("assembled.hevc")) + log("Diagnostics: saved \(packets.count) packet bytes and \(elementary.count) HEVC bytes") + } catch {log("Diagnostics: \(error.localizedDescription)")} + packets=Data();elementary=Data() + } +} diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/NetworkMirror.swift b/docs/internal/adr/0031-device-stream-poc/Sources/NetworkMirror.swift new file mode 100644 index 000000000..2795ed295 --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/NetworkMirror.swift @@ -0,0 +1,187 @@ +import AppKit +import AVFoundation +import CoreDevice +import Network + +private final class LatestVideoFrame: @unchecked Sendable { + private let lock=NSLock() + private var pixel:CVPixelBuffer? + private var scheduled=false + func submit(_ image:CVPixelBuffer, present:@escaping @MainActor (CVPixelBuffer)->Void) { + lock.lock();pixel=image + let enqueue = !scheduled + scheduled=true;lock.unlock() + guard enqueue else {return} + DispatchQueue.main.async { [self] in + lock.lock();let image=pixel;pixel=nil;scheduled=false;lock.unlock() + if let image {present(image)} + } + } +} + +@MainActor +final class NetworkMirror { + private(set) var layer: AVSampleBufferDisplayLayer? + private(set) var videoSize: CGSize? + private var task: Task? + private var receiverTask: Task? + private var generation=UUID() + private var displayed=0 + + func start(device:RemoteDevice,into host:CALayer,useHardware:Bool,onPrepared:@escaping @MainActor () async -> Void,onState:@escaping(String)->Void,onFinished:@escaping()->Void) { + guard task==nil else {return} + let display=AVSampleBufferDisplayLayer() + display.videoGravity = .resizeAspect + display.frame=host.bounds + host.addSublayer(display);layer=display + generation=UUID();let run=generation + displayed=0 + task=Task { [self] in + var token:UInt32? + var usageAssertion:DeviceUsageAssertion? + var stage="preparing device services" + defer { + probeClose() + receiverTask=nil;task=nil + usageAssertion?.releaseAssertion() + if usageAssertion != nil {log("Device preparation: usage assertion released")} + if generation==run {layer?.removeFromSuperlayer();layer=nil;videoSize=nil} + onFinished() + } + do { + onState("Preparing device connection and developer services…") + log("Device preparation: requesting CoreDevice services, device information, trusted discovery and secure networking") + let requirements=UsageAssertionRequirements(deviceStates:[ + .developerModeEnabledIfRequired, + .coreDeviceServicesLoaded, + .extendedDeviceInfoLoaded, + .remoteServiceDiscoveryTrustedConnectivityAvailable, + .secureNetworkingAvailable + ],capabilities:[]) + usageAssertion=try await device.acquireDeviceUsageAssertion(withReason:"DeviceStreamPoC screen mirroring",requirements:requirements) + try Task.checkCancellation() + usageAssertion?.registerInvalidationHandler(invokingOnQueue:.main) { [weak self] error in + // Explicit release on Stop is expected; report unexpected service loss. + guard let error else {return} + Task { @MainActor [weak self] in + guard let self,self.generation==run,self.task != nil else {return} + log("Device preparation: usage assertion invalidated: \(error)") + onState("Device connection lost: \(error.localizedDescription)") + self.stop() + } + } + log("Device preparation: services ready; usage assertion held for this mirror session") + await onPrepared() + try Task.checkCancellation() + stage="querying media support" + var options=MediaStreamHelper.getNegotiatorOptions(for:device.deviceInfo) + options[DeviceMediaStream.kAVCMediaStreamOptionClientName]="CoreDeviceScreenSharing" + options[DeviceMediaStream.kAVCMediaStreamOptionClientSessionID]=UUID() + options["avcMediaStreamOptionCallID"]=UUID().uuidString + guard let negotiator=probeNegotiator(options,5),let offer=probeOffer(negotiator) else {throw failure("Could not create the media offer")} + let support=try await device.mediaStreamSupportInfo + try Task.checkCancellation() + guard let tunnel=device.deviceInfo.tunnelIPAddressString,let local=probeBind(tunnel) else {throw failure("No paired device tunnel is available")} + stage="starting media stream" + let response=try await device.startMediaStream(with:.init(timeout:15,type:.video,direction:.output,negotiatorOffer:offer,clientSupportedFeatures:support.client.supportedFeatures,receiverIP:local,receiverPort:probePort(),options:options.compactMapValues{CodableValue($0)})) + token=UInt32(exactly:response.connection.streamConfig.StreamInputID) + stage="configuring media receiver" + try Task.checkCancellation() + guard let config=probeAnswer(negotiator,response.negotiatorAnswer), (config["vcMediaStreamSRTPCipherSuite"] as? NSNumber)?.intValue==0 else {throw failure("Unsupported encrypted media configuration")} + // Read numeric configuration through Encodable, avoiding guessed Swift struct layout. + let json=try JSONSerialization.jsonObject(with:JSONEncoder().encode(response.connection)) as? [String:Any] + let streamConfig=json?["streamConfig"] as? [String:Any] + let summary=["IsltrpEnabled","KeyFrameInterval","VideoStreamMode","Framerate","RxCodecFeatureListString"].map { "\($0)=\(streamConfig?[$0] ?? "?")" }.joined(separator:" ") + log("Network mirror: negotiated stream config: \(summary)") + guard let localSSRC=(streamConfig?["RemoteSSRC"] as? NSNumber)?.uint32Value, + let source=IPv6Address(local),let destination=IPv6Address(response.connection.sender.ipv6Address) else {throw failure("Invalid negotiated endpoints")} + probeClose() + try NetworkUtils.withSharedSocketDictionary(sourceAddress:source,port:response.connection.receiver.port,remoteAddress:destination,remotePort:response.connection.sender.port) {probeAdopt($0)} + log("Network mirror: started over \(device.deviceInfo.transportType?.description ?? "tunnel"); local HEVC decoder, no conferencing entitlement") + onState("Connected — waiting for video…") + let worker=Task.detached(priority:.userInitiated) { [weak self] in + let parser=HEVCRTPReceiver(),decoder=HEVCDecoder(useHardware:useHardware) + let latestFrame=LatestVideoFrame() + let diagnostics=MediaDiagnostics(hardware:useHardware) + defer {diagnostics.finish()} + var lastPLI=0.0,lastReport=0.0,lastPacket=ProcessInfo.processInfo.systemUptime + var keyframeRequests=0 + var packets=0,bytes=0,lastStats=lastPacket + let began=lastPacket + decoder.onConfiguration={message in log(message)} + parser.onLoss={decoder.invalidateReferences()} + decoder.onFailure={message in log("HEVC: \(message)")} + // Retain only the latest decoded frame. Never wait on AppKit from the socket reader. + decoder.onFrame={pixel in + diagnostics.decoded(pixel) + latestFrame.submit(pixel) { [weak self] image in self?.present(image,run:run,onState:onState) } + } + parser.onAccessUnit={nals,ts in diagnostics.accessUnit(nals);decoder.decode(nals,timestamp:ts)} + defer {_ = probeSend(parser.report(receiver:localSSRC,bye:true))} + while !Task.isCancelled { + if let data=probeReceive(5) {packets+=1;bytes+=data.count;lastPacket=ProcessInfo.processInfo.systemUptime;diagnostics.receive(data);parser.receive(data)} + parser.flushPending() + let now=ProcessInfo.processInfo.systemUptime + let pli=decoder.needsKeyframe && parser.source != nil && now-lastPLI>=0.5 + if now-lastReport>=1 || pli { + guard probeSend(parser.report(receiver:localSSRC,requestKeyframe:pli)) else {throw Self.failure("Media socket closed while sending RTCP")} + lastReport=now + if pli {keyframeRequests+=1;lastPLI=now} + } + if now-lastStats>=5 { + log("Network mirror: \(decoder.decoded) decoded frames, \(packets) datagrams, \(bytes) bytes, \(Int(now-began))s; loss=\(parser.lossEvents), reordered=\(parser.reorderedPackets), late=\(parser.latePackets), keyframe requests=\(keyframeRequests), units=\(decoder.accessUnits), submitted=\(decoder.submitted), decoder dropped=\(decoder.decoderDropped), waiting=\(decoder.waitingForKeyframe)") + lastStats=now + } + if now-lastPacket>10 {throw Self.failure("No media received for 10 seconds. Check that the device is awake and reachable.")} + if now-began>10 && decoder.decoded==0 {throw Self.failure("Packets arrived but no HEVC frame could be decoded")} + } + log("Network mirror: receiver stopped after \(decoder.decoded) decoded frames") + } + receiverTask=worker + stage="receiving video" + try await worker.value + } catch is CancellationError {log("Network mirror: cancelled")} + catch {log("Network mirror failed while \(stage): \(error)");onState("Failed while \(stage): \(error.localizedDescription)")} + if let token { + // Stop only this session; never stop unrelated DeviceHub streams. + do {_ = try await device.stopMediaStream(with:.init(stopAll:false,identifiers:[token]));log("Network mirror: remote stop requested (\(token))")} + catch {log("Network mirror: remote stop failed: \(error)")} + } + } + } + private func present(_ pixel:CVPixelBuffer,run:UUID,onState:(String)->Void) { + guard generation==run,let layer else {return} + var format:CMVideoFormatDescription? + guard CMVideoFormatDescriptionCreateForImageBuffer(allocator:kCFAllocatorDefault,imageBuffer:pixel,formatDescriptionOut:&format)==0,let format else {return} + var timing=CMSampleTimingInfo(duration:.invalid,presentationTimeStamp:CMTime(value:Int64(displayed),timescale:60),decodeTimeStamp:.invalid) + var sample:CMSampleBuffer? + guard CMSampleBufferCreateReadyWithImageBuffer(allocator:kCFAllocatorDefault,imageBuffer:pixel,formatDescription:format,sampleTiming:&timing,sampleBufferOut:&sample)==0,let sample else {return} + if let attachments=CMSampleBufferGetSampleAttachmentsArray(sample,createIfNecessary:true) { + let dictionary=unsafeBitCast(CFArrayGetValueAtIndex(attachments,0),to:CFMutableDictionary.self) + CFDictionarySetValue(dictionary,Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(),Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()) + } + if layer.status == .failed {log("Preview: \(layer.error?.localizedDescription ?? "display failed")");layer.flush()} + if layer.isReadyForMoreMediaData {layer.enqueue(sample);displayed+=1} + let size=CGSize(width:CVPixelBufferGetWidth(pixel),height:CVPixelBufferGetHeight(pixel)) + if videoSize != size || displayed==1 { + videoSize=size + log("Network mirror: first decoded/displayed frame \(Int(size.width))×\(Int(size.height))") + onState("Mirroring over CoreDevice — \(Int(size.width))×\(Int(size.height)) HEVC. Click or drag to touch.") + } + } + func layout(in host:CALayer) {layer?.frame=host.bounds} + func normalizedPoint(_ point:CGPoint,in bounds:CGRect)->CGPoint? { + guard layer != nil,let size=videoSize else {return nil} + let scale=min(bounds.width/size.width,bounds.height/size.height) + let rect=CGRect(x:(bounds.width-size.width*scale)/2,y:(bounds.height-size.height*scale)/2,width:size.width*scale,height:size.height*scale) + guard rect.contains(point) else {return nil} + return CGPoint(x:(point.x-rect.minX)/rect.width,y:1-(point.y-rect.minY)/rect.height) + } + func stop() { + generation=UUID() + task?.cancel();receiverTask?.cancel() + layer?.removeFromSuperlayer();layer=nil;videoSize=nil + } + nonisolated private static func failure(_ message:String)->NSError {NSError(domain:"NetworkMirror",code:1,userInfo:[NSLocalizedDescriptionKey:message])} + private func failure(_ message:String)->NSError {Self.failure(message)} +} diff --git a/docs/internal/adr/0031-device-stream-poc/Sources/main.swift b/docs/internal/adr/0031-device-stream-poc/Sources/main.swift new file mode 100644 index 000000000..e863cab6a --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Sources/main.swift @@ -0,0 +1,613 @@ +// DeviceStreamPoC — a third-party macOS app that mirrors a physical iPhone and sends touches to it. +// +// Findings behind this design (see README.md): +// • Device discovery, display info and HID input come from Xcode's private CoreDevice.framework +// (client of coredeviced / the remotepairingd tunnel). Both work without special entitlements. +// • The video path DeviceHub uses (CoreDeviceMediaStreamSupport → AVConference) is gated by the +// restricted entitlement com.apple.videoconference.allow-conferencing, so it is kept here only +// as an optional experiment ("Try CoreDevice media stream"). +// • Default video uses a custom CoreDevice RTP receiver and local VideoToolbox decoding. +// • The USB fallback uses the public QuickTime path: CoreMediaIO's +// kCMIOHardwarePropertyAllowScreenCaptureDevices exposes a USB-connected iPhone as an +// AVCaptureDevice (muxed audio+video), rendered with AVCaptureVideoPreviewLayer. +// • Clicks on the preview are converted to normalized (0…1) coordinates and sent through +// CoreDevice's remote HID digitizer (com.apple.coredevice.feature.remote.hid.digitizer). +// +// The private frameworks ship no Swift interfaces, so ../Stubs holds hand-written .swiftinterface +// files that mirror their ABI (they are built with library evolution → stable dispatch thunks). + +import AppKit +import AVFoundation +import CoreMediaIO +import QuartzCore +import CoreDevice +import CoreDeviceProtocols +import CoreDeviceTypes +import CoreDeviceMediaStreamSupport + +// MARK: - Logging + +let logFileHandle: FileHandle? = { + let path = ProcessInfo.processInfo.environment["LOGFILE"] ?? Bundle.main.bundleURL + .deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("work/demo-app.log").path + FileManager.default.createFile(atPath: path, contents: nil) + return FileHandle(forWritingAtPath: path) +}() + +func log(_ message: String) { + let stamp = ISO8601DateFormatter().string(from: Date()) + let line = "[\(stamp)] \(message)" + print(line) + fflush(stdout) + if let logFileHandle { logFileHandle.seekToEndOfFile(); logFileHandle.write((line + "\n").data(using: .utf8)!) } + DispatchQueue.main.async { AppDelegate.shared?.appendLog(message) } +} + +// MARK: - Touch injection (CoreDevice remote HID digitizer) + +@MainActor +final class TouchInjector { + private var digitizer: (any HIDDigitizer)? + private(set) var isReady = false + + func connect(device: RemoteDevice) async { + let member = CapabilityStaticMember() + guard device.supports(member) else { + log("HID: device does not report the remote HID digitizer capability") + return + } + do { + let impl = try await device.getImplementation(for: member) + digitizer = impl + isReady = true + log("HID: digitizer implementation ready (\(type(of: impl)))") + } catch { + log("HID: failed to get digitizer implementation: \(error)") + } + } + + /// `point` is normalized: (0,0) top-left of the device screen, (1,1) bottom-right. + func send(_ eventType: DigitizerEventType, at point: CGPoint, edge: DigitizerEdge = .none) { + guard let digitizer else { return } + let p = DigitizerPoint(x: Double(min(max(point.x, 0), 1)), y: Double(min(max(point.y, 0), 1))) + do { + try digitizer.send(pointOne: p, pointTwo: nil, eventType: eventType, edge: edge, target: .mainScreen) + if eventType == .end { digitizer.sendBarrier() } + } catch { + log("HID: send failed: \(error)") + } + } + + func disconnect() { + digitizer = nil + isReady = false + } +} + +// MARK: - QuickTime-style screen capture (CoreMediaIO + AVFoundation) + +@MainActor +final class ScreenCapture: NSObject { + private var session: AVCaptureSession? + private(set) var previewLayer: AVCaptureVideoPreviewLayer? + private(set) var device: AVCaptureDevice? + private var connectObserver: NSObjectProtocol? + + static func enableScreenCaptureDevices() { + var address = CMIOObjectPropertyAddress( + mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices), + mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal), + mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMain)) + var allow: UInt32 = 1 + let status = CMIOObjectSetPropertyData(CMIOObjectID(kCMIOObjectSystemObject), &address, 0, nil, + UInt32(MemoryLayout.size), &allow) + log("CMIO: kCMIOHardwarePropertyAllowScreenCaptureDevices = 1 (status \(status))") + } + + /// iOS screen devices show up as external muxed devices whose uniqueID is the device UDID. + static func captureDevices() -> [AVCaptureDevice] { + let discovery = AVCaptureDevice.DiscoverySession(deviceTypes: [.external], mediaType: nil, position: .unspecified) + return discovery.devices.filter { $0.hasMediaType(.muxed) || $0.hasMediaType(.video) } + } + + static func findDevice(udid: String?, name: String?) -> AVCaptureDevice? { + let devices = captureDevices() + for d in devices { log("CMIO: capture device '\(d.localizedName)' uniqueID=\(d.uniqueID) model=\(d.modelID) muxed=\(d.hasMediaType(.muxed))") } + if let udid, let d = devices.first(where: { $0.uniqueID.caseInsensitiveCompare(udid) == .orderedSame }) { return d } + if let name, let d = devices.first(where: { $0.localizedName == name }) { return d } + return devices.first(where: { $0.modelID.localizedCaseInsensitiveContains("iOS") }) + } + + func start(udid: String?, name: String?, into hostLayer: CALayer, completion: @escaping (Result) -> Void) { + ScreenCapture.enableScreenCaptureDevices() + // The screen device is published asynchronously after the property flips; wait for it. + if let device = ScreenCapture.findDevice(udid: udid, name: name) { + attach(device: device, into: hostLayer, completion: completion) + return + } + log("CMIO: iPhone screen capture device not published yet, waiting for AVCaptureDeviceWasConnected…") + connectObserver = NotificationCenter.default.addObserver(forName: AVCaptureDevice.wasConnectedNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + guard let self, self.session == nil, let device = ScreenCapture.findDevice(udid: udid, name: name) else { return } + self.attach(device: device, into: hostLayer, completion: completion) + } + } + DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self] in + guard let self, self.session == nil else { return } + completion(.failure(NSError(domain: "DeviceStreamPoC", code: 1, userInfo: [NSLocalizedDescriptionKey: "No iPhone screen-capture device appeared. Is the iPhone connected over USB and unlocked (Trust This Computer)?"]))) + } + } + + private func attach(device: AVCaptureDevice, into hostLayer: CALayer, completion: @escaping (Result) -> Void) { + if let connectObserver { NotificationCenter.default.removeObserver(connectObserver); self.connectObserver = nil } + AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in + Task { @MainActor in + guard let self else { return } + guard granted else { + completion(.failure(NSError(domain: "DeviceStreamPoC", code: 2, userInfo: [NSLocalizedDescriptionKey: "Camera access denied (needed for iOS screen capture devices)."]))) + return + } + do { + let session = AVCaptureSession() + session.beginConfiguration() + let input = try AVCaptureDeviceInput(device: device) + guard session.canAddInput(input) else { throw NSError(domain: "DeviceStreamPoC", code: 3, userInfo: [NSLocalizedDescriptionKey: "Cannot add capture input"]) } + session.addInput(input) + session.commitConfiguration() + let preview = AVCaptureVideoPreviewLayer(session: session) + preview.videoGravity = .resizeAspect + preview.backgroundColor = NSColor.black.cgColor + preview.frame = hostLayer.bounds + hostLayer.addSublayer(preview) + self.previewLayer = preview + self.session = session + self.device = device + session.startRunning() + let dims = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription) + log("CMIO: capturing '\(device.localizedName)' \(dims.width)x\(dims.height) via AVCaptureSession") + completion(.success(())) + } catch { + completion(.failure(error)) + } + } + } + } + + /// Size of the incoming video frames (pixels), used to map clicks to normalized device coordinates. + var videoSize: CGSize? { + guard let device else { return nil } + let d = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription) + guard d.width > 0, d.height > 0 else { return nil } + return CGSize(width: Int(d.width), height: Int(d.height)) + } + + func layout(in hostLayer: CALayer) { + previewLayer?.frame = hostLayer.bounds + } + + func stop() { + if let connectObserver { NotificationCenter.default.removeObserver(connectObserver); self.connectObserver = nil } + session?.stopRunning() + previewLayer?.removeFromSuperlayer() + previewLayer = nil + session = nil + device = nil + } +} + +// MARK: - Optional experiment: DeviceHub's own video path (needs com.apple.videoconference.allow-conferencing) + +@MainActor +final class MediaStreamExperiment { + private var session: MediaStreamSession? + private var stream: (any VideoStream)? + private var task: Task? + + func start(device: RemoteDevice, layer: CALayer, onStateChange: @escaping (String) -> Void) { + let session = MediaStreamSession(clientSessionID: UUID()) + self.session = session + task = Task { [weak self] in + do { + let configuration: VideoStreamConfiguration = .receiveMirroredPrimary(layer: layer, timeout: 30) + log("MediaStream: makeVideoStream(.receiveMirroredPrimary)") + let stream = try await session.makeVideoStream(withConfiguration: configuration, fromRemoteDevice: device) + await MainActor.run { self?.stream = stream } + let events = try await stream.activate() + onStateChange("CoreDevice media stream active — waiting for first frame…") + for try await event in events { + switch event { + case .receivedFirstFrame: log("MediaStream: receivedFirstFrame"); onStateChange("CoreDevice media stream: streaming") + case .remoteVideoAttributesChanged(let a): log("MediaStream: attributes ratio=\(a.ratio) rect=\(a.contentsRect)") + case .receivedLastDecodedFrame(let d): log("MediaStream: last decoded frame \(d.count) bytes") + @unknown default: break + } + } + onStateChange("CoreDevice media stream ended") + } catch { + log("MediaStream: error \(error)") + onStateChange("CoreDevice media stream failed: \(error.localizedDescription)") + } + } + } + + func stop() { + task?.cancel(); task = nil + let s = stream; stream = nil + Task { await s?.invalidate() } + } +} + +// MARK: - Device screen view (hosts the preview layer, forwards mouse input as touches) + +final class DeviceScreenView: NSView { + /// Maps a point in this view's coordinates to normalized device coordinates (0…1, y down). + var mapPoint: (CGPoint) -> CGPoint? = { _ in nil } + var onTouch: (DigitizerEventType, CGPoint, DigitizerEdge) -> Void = { _, _, _ in } + var onLayout: (CALayer) -> Void = { _ in } + private var tracking = false + private var gestureEdge: DigitizerEdge = .none + + /// Starting a drag within 3% of a screen edge marks it as an edge gesture (home, Control Center, back…). + private func edge(for p: CGPoint) -> DigitizerEdge { + if p.y >= 0.97 { return .bottom } + if p.y <= 0.03 { return .top } + if p.x <= 0.03 { return .left } + if p.x >= 0.97 { return .right } + return .none + } + private var panOrigin: CGPoint? // view-space origin of a scroll-wheel pan + private var panOffset = CGPoint.zero // accumulated scroll delta in view points + + override init(frame: NSRect) { + super.init(frame: frame) + wantsLayer = true + layer?.backgroundColor = NSColor.black.cgColor + layer?.masksToBounds = true + } + required init?(coder: NSCoder) { fatalError() } + + override func layout() { + super.layout() + if let layer { onLayout(layer) } + } + + func normalizedPoint(forViewPoint p: CGPoint) -> CGPoint? { + guard let n = mapPoint(p), n.x >= 0, n.x <= 1, n.y >= 0, n.y <= 1 else { return nil } + return n + } + private func normalizedPoint(for event: NSEvent) -> CGPoint? { + normalizedPoint(forViewPoint: convert(event.locationInWindow, from: nil)) + } + + // Click / drag → tap / pan. + override func mouseDown(with event: NSEvent) { + guard let p = normalizedPoint(for: event) else { return } + tracking = true + gestureEdge = edge(for: p) + onTouch(.start, p, gestureEdge) + } + override func mouseDragged(with event: NSEvent) { + guard tracking, let p = normalizedPoint(for: event) else { return } + onTouch(.position, p, gestureEdge) + } + override func mouseUp(with event: NSEvent) { + guard tracking else { return } + tracking = false + onTouch(.end, normalizedPoint(for: event) ?? CGPoint(x: 0.5, y: 0.5), gestureEdge) + } + + // Two-finger scroll → synthesized one-finger pan starting under the cursor. + override func scrollWheel(with event: NSEvent) { + let local = convert(event.locationInWindow, from: nil) + switch event.phase { + case .began: + panOrigin = local; panOffset = .zero + if let p = normalizedPoint(forViewPoint: local) { gestureEdge = edge(for: p); onTouch(.start, p, gestureEdge) } + case .changed: + guard let origin = panOrigin else { return } + // Natural scrolling: content follows the fingers, like a touch drag. + panOffset.x += event.scrollingDeltaX + panOffset.y -= event.scrollingDeltaY // AppKit y is up; scrollingDeltaY > 0 means fingers moved down… content down + if let p = normalizedPoint(forViewPoint: CGPoint(x: origin.x + panOffset.x, y: origin.y + panOffset.y)) { onTouch(.position, p, gestureEdge) } + case .ended, .cancelled: + guard let origin = panOrigin else { return } + let end = CGPoint(x: origin.x + panOffset.x, y: origin.y + panOffset.y) + onTouch(.end, normalizedPoint(forViewPoint: end) ?? normalizedPoint(forViewPoint: origin) ?? CGPoint(x: 0.5, y: 0.5), gestureEdge) + panOrigin = nil + default: + // Non-gesture wheel (mouse): one short flick per event. + guard panOrigin == nil, let start = normalizedPoint(forViewPoint: local) else { return } + let end = CGPoint(x: local.x + event.scrollingDeltaX * 4, y: local.y - event.scrollingDeltaY * 4) + onTouch(.start, start, .none) + onTouch(.position, normalizedPoint(forViewPoint: end) ?? start, .none) + onTouch(.end, normalizedPoint(forViewPoint: end) ?? start, .none) + } + } +} + +// MARK: - App + +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate { + static var shared: AppDelegate? + + private var window: NSWindow! + private var devicePopup: NSPopUpButton! + private var startButton: NSButton! + private var stopButton: NSButton! + private var experimentButton: NSButton! + private var statusLabel: NSTextField! + private var logView: NSTextView! + private var screenView: DeviceScreenView! + private var aspectConstraint: NSLayoutConstraint? + + private var manager: DeviceManager! + private var devices: [RemoteDevice] = [] + private let capture = ScreenCapture() + private let networkMirror = NetworkMirror() + private var usbButton: NSButton! + private var softwareDecoderButton: NSButton! + private let touch = TouchInjector() + private let experiment = MediaStreamExperiment() + + func applicationDidFinishLaunching(_ notification: Notification) { + AppDelegate.shared = self + buildUI() + connectToCoreDevice() + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } + func applicationWillTerminate(_ notification: Notification) { stopAll() } + + // MARK: UI + + private func buildUI() { + window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 780), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, defer: false) + window.title = "DeviceStreamPoC — USB / Wi-Fi mirror" + window.center() + + let content = NSView() + window.contentView = content + + devicePopup = NSPopUpButton(frame: .zero, pullsDown: false) + startButton = NSButton(title: "Start mirror", target: self, action: #selector(startTapped)) + startButton.keyEquivalent = "\r" + stopButton = NSButton(title: "Stop", target: self, action: #selector(stopTapped)) + stopButton.isEnabled = false + experimentButton = NSButton(title: "Try CoreDevice media stream", target: self, action: #selector(experimentTapped)) + usbButton = NSButton(title: "USB fallback", target: self, action: #selector(usbTapped)) + softwareDecoderButton = NSButton(checkboxWithTitle: "Software HEVC", target: nil, action: nil) + softwareDecoderButton.state = .on + softwareDecoderButton.toolTip = "Use the software decoder. Change while stopped to compare with hardware decoding." + let refreshButton = NSButton(title: "Refresh devices", target: self, action: #selector(refreshTapped)) + + statusLabel = NSTextField(labelWithString: "Connecting to CoreDevice service…") + statusLabel.lineBreakMode = .byTruncatingTail + + screenView = DeviceScreenView(frame: .zero) + screenView.mapPoint = { [weak self] viewPoint in + guard let self else {return nil} + if self.networkMirror.layer != nil {return self.networkMirror.normalizedPoint(viewPoint,in:self.screenView.bounds)} + guard let preview = self.capture.previewLayer, let host = self.screenView.layer else {return nil} + // View coords == root-layer coords for a layer-backed (non-flipped) NSView; the preview layer + // knows its aspect-fit video rect and converts to capture-device space (0…1, origin top-left). + let layerPoint = host.convert(viewPoint, to: preview) + let p = preview.captureDevicePointConverted(fromLayerPoint: layerPoint) + // On macOS the conversion keeps the layer's y-up convention; the digitizer wants y-down. + return CGPoint(x: p.x, y: 1 - p.y) + } + screenView.onLayout = { [weak self] layer in self?.capture.layout(in: layer); self?.networkMirror.layout(in: layer) } + screenView.onTouch = { [weak self] type, point, edge in + guard let self else { return } + self.touch.send(type, at: point, edge: edge) + if type != .position { + log(String(format: "HID: %@ at (%.3f, %.3f)%@", type == .start ? "touch down" : "touch up", point.x, point.y, edge == .none ? "" : " [edge gesture]")) + } + } + + let scroll = NSScrollView() + scroll.hasVerticalScroller = true + scroll.borderType = .bezelBorder + logView = NSTextView() + logView.isEditable = false + logView.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular) + logView.autoresizingMask = [.width] + logView.isVerticallyResizable = true + logView.textContainer?.widthTracksTextView = true + scroll.documentView = logView + + let toolbar = NSStackView(views: [devicePopup, refreshButton, startButton, stopButton, usbButton, softwareDecoderButton]) + toolbar.orientation = .horizontal + toolbar.spacing = 8 + + for v in [toolbar, statusLabel, screenView, scroll] as [NSView] { + v.translatesAutoresizingMaskIntoConstraints = false + content.addSubview(v) + } + + NSLayoutConstraint.activate([ + toolbar.topAnchor.constraint(equalTo: content.topAnchor, constant: 12), + toolbar.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 12), + statusLabel.topAnchor.constraint(equalTo: toolbar.bottomAnchor, constant: 8), + statusLabel.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 12), + statusLabel.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -12), + screenView.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 8), + screenView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 12), + screenView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -12), + screenView.widthAnchor.constraint(lessThanOrEqualTo: content.widthAnchor, multiplier: 0.6), + scroll.topAnchor.constraint(equalTo: screenView.topAnchor), + scroll.leadingAnchor.constraint(equalTo: screenView.trailingAnchor, constant: 12), + scroll.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -12), + scroll.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -12), + scroll.widthAnchor.constraint(greaterThanOrEqualToConstant: 280), + ]) + setAspect(9.0 / 19.5) + + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + private func setAspect(_ widthOverHeight: CGFloat) { + aspectConstraint?.isActive = false + aspectConstraint = screenView.widthAnchor.constraint(equalTo: screenView.heightAnchor, multiplier: widthOverHeight) + aspectConstraint?.priority = .defaultHigh + aspectConstraint?.isActive = true + } + + func appendLog(_ line: String) { + guard let logView else { return } + logView.textStorage?.append(NSAttributedString(string: line + "\n", attributes: [ + .font: NSFont.monospacedSystemFont(ofSize: 11, weight: .regular), + .foregroundColor: NSColor.textColor, + ])) + logView.scrollToEndOfDocument(nil) + } + + private func setStatus(_ text: String) { statusLabel.stringValue = text } + + // MARK: CoreDevice + + private func connectToCoreDevice() { + manager = DeviceManager(serviceConnection: CoreDeviceService.sharedConnection) + log("CoreDevice: DeviceManager created from CoreDeviceService.sharedConnection") + refreshDevices() + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in + guard let self else { return } + self.refreshDevices() + // AUTOSTART= starts the mirror without clicking (used for testing). + if let wanted = ProcessInfo.processInfo.environment["AUTOSTART"], + let index = self.devices.firstIndex(where: { ($0.deviceInfo.name ?? "").localizedCaseInsensitiveContains(wanted) }) { + self.devicePopup.selectItem(at: index) + self.startTapped() + } + } + } + + private func refreshDevices() { + devices = manager.allDevices() + devicePopup.removeAllItems() + for device in devices { + let info = device.deviceInfo + devicePopup.addItem(withTitle: "\(info.name ?? device.description) — \(info.marketingName ?? info.productType ?? "") [\(info.transportType?.description ?? "?")]") + } + if devices.isEmpty { + devicePopup.addItem(withTitle: "No devices") + setStatus("No devices reported by CoreDevice yet (pair the device in Xcode first).") + } else { + setStatus("\(devices.count) device(s). Pick one and press Start mirror.") + } + log("CoreDevice: allDevices() -> \(devices.count)") + for device in devices { + let info = device.deviceInfo + log(" • \(info.name ?? "?") udid=\(info.udid ?? "?") type=\(info.deviceType?.description ?? "?") transport=\(info.transportType?.description ?? "?")") + } + } + + private var selectedDevice: RemoteDevice? { + let index = devicePopup.indexOfSelectedItem + return index >= 0 && index < devices.count ? devices[index] : nil + } + + @objc private func refreshTapped() { refreshDevices() } + + @objc private func startTapped() { + guard startButton.isEnabled, let device = selectedDevice, let layer = screenView.layer else {return} + startButton.isEnabled=false;usbButton.isEnabled=false;devicePopup.isEnabled=false;stopButton.isEnabled=true + setStatus("Starting USB / Wi-Fi mirror…") + softwareDecoderButton.isEnabled=false + networkMirror.start(device:device,into:layer,useHardware:softwareDecoderButton.state == .off,onPrepared:{ [weak self] in + guard let self else {return} + await self.touch.connect(device:device) + },onState:{ [weak self] state in + guard let self else {return} + self.setStatus(state) + if let size=self.networkMirror.videoSize {self.setAspect(size.width/size.height)} + },onFinished:{ [weak self] in + guard let self else {return} + self.startButton.isEnabled=true;self.usbButton.isEnabled=true;self.devicePopup.isEnabled=true;self.stopButton.isEnabled=false + self.touch.disconnect() + self.softwareDecoderButton.isEnabled=true + }) + } + + @objc private func usbTapped() { + guard let device = selectedDevice, let layer = screenView.layer else { return } + startButton.isEnabled = false + usbButton.isEnabled = false + devicePopup.isEnabled = false + stopButton.isEnabled = true + let info = device.deviceInfo + setStatus("Starting screen capture for \(info.name ?? "device")…") + + // 1. Video: QuickTime-style CoreMediaIO screen capture device (USB). + capture.start(udid: info.udid, name: info.name, into: layer) { [weak self] result in + guard let self else { return } + switch result { + case .success: + if let size = self.capture.videoSize { self.setAspect(size.width / size.height) } + self.setStatus("Mirroring \(info.name ?? "device") — click or drag on the video to touch the device.") + if let auto = ProcessInfo.processInfo.environment["AUTOTAP"] { + // AUTOTAP=x,y (normalized) sends one tap after the video is up (used for testing). + let isView = auto.hasPrefix("view:") + let parts = auto.replacingOccurrences(of: "view:", with: "").split(separator: ",").compactMap { Double($0) } + if parts.count == 2 { + DispatchQueue.main.asyncAfter(deadline: .now() + 2) { + var p = CGPoint(x: parts[0], y: parts[1]) + if isView { + let b = self.screenView.bounds + let vp = CGPoint(x: b.width * parts[0], y: b.height * parts[1]) + guard let mapped = self.screenView.normalizedPoint(forViewPoint: vp) else { log("HID: AUTOTAP view point \(vp) is outside the video"); return } + log(String(format: "HID: AUTOTAP view (%.0f, %.0f) of %.0fx%.0f -> device (%.3f, %.3f)", vp.x, vp.y, b.width, b.height, mapped.x, mapped.y)) + p = mapped + } + self.touch.send(.start, at: p) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { + self.touch.send(.end, at: p) + log(String(format: "HID: AUTOTAP sent at (%.3f, %.3f)", p.x, p.y)) + } + } + } + } + case .failure(let error): + self.setStatus("Video: \(error.localizedDescription)") + log("CMIO: \(error)") + } + } + + // 2. Input: CoreDevice remote HID digitizer (works over USB and Wi‑Fi). + Task { await touch.connect(device: device) } + } + + @objc private func stopTapped() { + let wasNetwork = networkMirror.layer != nil + stopAll() + startButton.isEnabled = !wasNetwork + usbButton.isEnabled = !wasNetwork + devicePopup.isEnabled = !wasNetwork + stopButton.isEnabled = false + setStatus("Stopped") + } + + @objc private func experimentTapped() { + guard let device = selectedDevice, let layer = screenView.layer else { return } + experiment.start(device: device, layer: layer) { [weak self] state in + Task { @MainActor in self?.setStatus(state) } + } + } + + private func stopAll() { + networkMirror.stop() + capture.stop() + touch.disconnect() + experiment.stop() + } +} + +let app = NSApplication.shared +let delegate = MainActor.assumeIsolated { AppDelegate() } +app.delegate = delegate +app.setActivationPolicy(.regular) +app.run() diff --git a/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDevice.swiftmodule/arm64-apple-macos.swiftinterface b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDevice.swiftmodule/arm64-apple-macos.swiftinterface new file mode 100644 index 000000000..dfd64f8fe --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDevice.swiftmodule/arm64-apple-macos.swiftinterface @@ -0,0 +1,149 @@ +// swift-interface-format-version: 1.0 +// swift-compiler-version: Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1) +// swift-module-flags: -target arm64-apple-macos26.0 -enable-library-evolution -swift-version 5 -module-name CoreDevice +// Hand-written stub for /Library/Developer/PrivateFrameworks/CoreDevice.framework (client side of coredeviced). +import Swift +import Foundation +import Dispatch +import CoreDeviceTypes +import CoreDeviceProtocols + +public protocol CoreDeviceServiceConnection { +} + +public struct CoreDeviceService { + public static var sharedConnection: any CoreDevice.CoreDeviceServiceConnection { get } +} + +public class DeviceManager { + public init(serviceConnection: any CoreDevice.CoreDeviceServiceConnection) + final public func allDevices() -> [CoreDevice.RemoteDevice] +} + +public class RemoteDevice { + final public var id: Foundation.UUID { get } + final public var description: Swift.String { get } + public var deviceInfo: CoreDeviceProtocols.DeviceInfo { get } + final public var displayInfo: CoreDeviceTypes.DisplayInfo { get async throws } + final public func getDisplayInfo(completingOn: Dispatch.DispatchQueue?, completion: @escaping (Swift.Result) -> Swift.Void) + public func supports(_ member: CoreDevice.CapabilityStaticMember) -> Swift.Bool where Cap : CoreDevice.DeviceCapability + public func getImplementation(for member: CoreDevice.CapabilityStaticMember) async throws -> Cap.ProtocolType where Cap : CoreDevice.DeviceCapability + public func supportsFeature(identifiedBy: Swift.String) -> Swift.Bool +} + +// ---- Capability system + legacy remote HID digitizer (com.apple.coredevice.feature.remote.hid.digitizer) ---- + +public struct Capability : Swift.Hashable { + public static func == (lhs: CoreDevice.Capability, rhs: CoreDevice.Capability) -> Swift.Bool + public func hash(into hasher: inout Swift.Hasher) + public var hashValue: Swift.Int { get } +} + +public protocol DeviceCapability { + associatedtype ProtocolType + associatedtype ImplType + static var capability: CoreDevice.Capability { get } +} + +public struct CapabilityStaticMember { + public init() +} + +public struct DigitizerPoint { + public init(x: Swift.Double, y: Swift.Double) + public var x: Swift.Double { get } + public var y: Swift.Double { get } +} + +public enum DigitizerEventType { + case start + case position + case end +} + +public enum DigitizerEdge { + case none + case top + case left + case right + case bottom +} + +public enum DigitizerTarget { + case mainScreen + case display1 + case display2 + case display3 + case display4 + case display5 + case display6 + case display7 + case display8 + case display9 + case display10 +} + +public protocol HIDDigitizer { + func send(pointOne: CoreDevice.DigitizerPoint, pointTwo: CoreDevice.DigitizerPoint?, eventType: CoreDevice.DigitizerEventType, edge: CoreDevice.DigitizerEdge, target: CoreDevice.DigitizerTarget) throws + func sendBarrier() +} + +public struct DigitizerHIDCapability : CoreDevice.DeviceCapability { + public typealias ProtocolType = any CoreDevice.HIDDigitizer + public typealias ImplType = Swift.Never + public static var capability: CoreDevice.Capability { get } +} + +public enum CodableValue { public init?(_ value: Any) } +public struct MediaStreamHelper { public static func getNegotiatorOptions(for: CoreDeviceProtocols.DeviceInfo) -> [String: Any] } +public struct DeviceMediaStream { + public static var kAVCMediaStreamOptionClientName: String { get } + public static var kAVCMediaStreamOptionClientSessionID: String { get } + public enum StreamType { case audio; case video } + public enum Direction { case input; case output } + public struct SupportInfo { public var supportedFeatures: UInt64 { get }; public var description: String { get } } + public struct SupportInfoResponse { public var client: SupportInfo { get }; public var device: SupportInfo { get }; public var common: SupportInfo { get } } + public struct StartRequest { + public init(timeout: UInt, type: StreamType, direction: Direction, negotiatorOffer: Foundation.Data, clientSupportedFeatures: UInt64, receiverIP: String?, receiverPort: UInt16?, options: [String: CodableValue]) + } + public struct StartResponse : Encodable { public var connection: ConnectionInfo { get }; public var negotiatorAnswer: Foundation.Data { get }; public func encode(to: any Encoder) throws } + public struct ConnectionInfo : Encodable { public var receiver: NetworkInfo { get }; public var sender: NetworkInfo { get }; public var streamConfig: MediaStreamConfig { get }; public func encode(to: any Encoder) throws } + public struct NetworkInfo { public var ipv6Address: String { get }; public var port: UInt16 { get } } + public struct MediaStreamConfig { public var StreamInputID: Int { get } } + public struct StopRequest { public init(stopAll: Bool, identifiers: [UInt32]?) } + public struct StopResponse : Encodable { public func encode(to: any Encoder) throws } +} +extension RemoteDevice { + public var mediaStreamSupportInfo: DeviceMediaStream.SupportInfoResponse { get async throws } + public func startMediaStream(with: DeviceMediaStream.StartRequest) async throws -> DeviceMediaStream.StartResponse + public func stopMediaStream(with: DeviceMediaStream.StopRequest) async throws -> DeviceMediaStream.StopResponse +} + +import Network +import XPC +public struct NetworkUtils { + public static func withSharedSocketDictionary(sourceAddress: Network.IPv6Address, port: UInt16, remoteAddress: Network.IPv6Address, remotePort: UInt16, body: (XPC.xpc_object_t) throws -> A) throws -> A +} + +// DeviceKit's device interaction model acquires these states before media/HID use. +// Signatures verified against the installed CoreDevice 642.x binary and DeviceKit imports. +public struct AssertableDeviceState : Swift.Hashable { + public static var developerModeEnabledIfRequired: CoreDevice.AssertableDeviceState { get } + public static var coreDeviceServicesLoaded: CoreDevice.AssertableDeviceState { get } + public static var extendedDeviceInfoLoaded: CoreDevice.AssertableDeviceState { get } + public static var remoteServiceDiscoveryTrustedConnectivityAvailable: CoreDevice.AssertableDeviceState { get } + public static var secureNetworkingAvailable: CoreDevice.AssertableDeviceState { get } + public static func == (lhs: CoreDevice.AssertableDeviceState, rhs: CoreDevice.AssertableDeviceState) -> Swift.Bool + public func hash(into hasher: inout Swift.Hasher) + public var hashValue: Swift.Int { get } +} +public struct UsageAssertionRequirements { + public init(deviceStates: Swift.Set, capabilities: Swift.Set) +} +public class DeviceUsageAssertion { + public func releaseAssertion() + public func registerInvalidationHandler(invokingOnQueue: Dispatch.DispatchQueue?, handler: @escaping (Swift.Error?) -> Swift.Void) +} +extension RemoteDevice { + public func acquireDeviceUsageAssertion(withReason: Swift.String, requirements: CoreDevice.UsageAssertionRequirements) async throws -> CoreDevice.DeviceUsageAssertion +} diff --git a/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceMediaStreamSupport.swiftmodule/arm64-apple-macos.swiftinterface b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceMediaStreamSupport.swiftmodule/arm64-apple-macos.swiftinterface new file mode 100644 index 000000000..e03891877 --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceMediaStreamSupport.swiftmodule/arm64-apple-macos.swiftinterface @@ -0,0 +1,72 @@ +// swift-interface-format-version: 1.0 +// swift-compiler-version: Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1) +// swift-module-flags: -target arm64-apple-macos26.0 -enable-library-evolution -swift-version 5 -module-name CoreDeviceMediaStreamSupport +// Hand-written stub for CoreDevice.framework/Frameworks/CoreDeviceMediaStreamSupport.framework. +import Swift +import Foundation +import CoreGraphics +import QuartzCore +import _Concurrency +import CoreDevice + +public enum MediaStreamDirection { + case send + case receive +} + +public protocol MediaStreamConfiguration { + var direction: CoreDeviceMediaStreamSupport.MediaStreamDirection { get } +} + +public struct VideoStreamReceiveConfiguration { + public var direction: CoreDeviceMediaStreamSupport.MediaStreamDirection { get } + public var resolution: CoreGraphics.CGSize { get } +} + +public struct VideoStreamSendConfiguration { + public var direction: CoreDeviceMediaStreamSupport.MediaStreamDirection { get } + public var resolution: CoreGraphics.CGSize { get } +} + +public enum VideoStreamConfiguration { + case send(CoreDeviceMediaStreamSupport.VideoStreamSendConfiguration) + case receive(CoreDeviceMediaStreamSupport.VideoStreamReceiveConfiguration) + public static func receiveMirroredPrimary(layer: QuartzCore.CALayer, timeout: Swift.UInt) -> CoreDeviceMediaStreamSupport.VideoStreamConfiguration + public static func receiveMirroredDisplayByIdentifier(_ displayID: Swift.UInt32, layer: QuartzCore.CALayer, timeout: Swift.UInt) -> CoreDeviceMediaStreamSupport.VideoStreamConfiguration + public static func receiveVirtualExternal(layer: QuartzCore.CALayer, resolution: CoreGraphics.CGSize, timeout: Swift.UInt) -> CoreDeviceMediaStreamSupport.VideoStreamConfiguration + public var direction: CoreDeviceMediaStreamSupport.MediaStreamDirection { get } +} + +public struct VideoStreamAttributes { + public var contentsRect: CoreGraphics.CGRect { get } + public var ratio: CoreGraphics.CGSize { get } + public var scaleFactor: Swift.Float { get } +} + +public enum VideoStreamEvent { + case receivedFirstFrame + case receivedLastDecodedFrame(Foundation.Data) + case remoteVideoAttributesChanged(CoreDeviceMediaStreamSupport.VideoStreamAttributes) +} + +public protocol MediaStreamProtocol : _Concurrency.Actor { + associatedtype Event + associatedtype Configuration + var configuration: Self.Configuration { get } + func activate() async throws -> _Concurrency.AsyncThrowingStream + func invalidate() async +} + +public protocol VideoStream : CoreDeviceMediaStreamSupport.MediaStreamProtocol where Self.Event == CoreDeviceMediaStreamSupport.VideoStreamEvent, Self.Configuration == CoreDeviceMediaStreamSupport.VideoStreamConfiguration { + func requestLastDecodedFrame() async +} + +public actor MediaStreamSession { + public init(clientSessionID: Foundation.UUID) + public var clientSessionID: Foundation.UUID { get } +} + +// Declared in an extension upstream (no dispatch thunk is exported for it). +extension CoreDeviceMediaStreamSupport.MediaStreamSession { + public func makeVideoStream(withConfiguration: CoreDeviceMediaStreamSupport.VideoStreamConfiguration, fromRemoteDevice: CoreDevice.RemoteDevice) async throws -> any CoreDeviceMediaStreamSupport.VideoStream +} diff --git a/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceProtocols.swiftmodule/arm64-apple-macos.swiftinterface b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceProtocols.swiftmodule/arm64-apple-macos.swiftinterface new file mode 100644 index 000000000..53d7109fc --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceProtocols.swiftmodule/arm64-apple-macos.swiftinterface @@ -0,0 +1,23 @@ +// swift-interface-format-version: 1.0 +// swift-compiler-version: Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1) +// swift-module-flags: -target arm64-apple-macos26.0 -enable-library-evolution -swift-version 5 -module-name CoreDeviceProtocols +// Hand-written stub for the CoreDeviceProtocols module (symbols live in CoreDevice.framework). +import Swift +import Foundation +import CoreDeviceTypes + +public enum DeviceType { + public var description: Swift.String { get } + public var rawValue: Swift.String { get } +} + +public struct DeviceInfo { + public var name: Swift.String? { get } + public var udid: Swift.String? { get } + public var identifier: Foundation.UUID { get } + public var deviceType: CoreDeviceProtocols.DeviceType? { get } + public var transportType: CoreDeviceTypes.TransportType? { get } + public var productType: Swift.String? { get } + public var marketingName: Swift.String? { get } + public var tunnelIPAddressString: Swift.String? { get } +} diff --git a/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceTypes.swiftmodule/arm64-apple-macos.swiftinterface b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceTypes.swiftmodule/arm64-apple-macos.swiftinterface new file mode 100644 index 000000000..c679cbabb --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/Stubs/CoreDeviceTypes.swiftmodule/arm64-apple-macos.swiftinterface @@ -0,0 +1,26 @@ +// swift-interface-format-version: 1.0 +// swift-compiler-version: Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1) +// swift-module-flags: -target arm64-apple-macos26.0 -enable-library-evolution -swift-version 5 -module-name CoreDeviceTypes -module-abi-name CoreDevice +// Hand-written stub. Mirrors the ABI of the "CoreDevice"-mangled shared types that live in +// CoreDeviceUtilities.framework / CoreDevice.framework (no .swiftinterface ships with Xcode). +import Swift +import Foundation +import CoreGraphics + +public enum TransportType { + public var description: Swift.String { get } + public var rawValue: Swift.String { get } +} + +public struct Display { + public var displayId: Swift.UInt32 { get } + public var name: Swift.String { get } + public var primary: Swift.Bool { get } + public var nativeSize: CoreGraphics.CGSize { get } + public var bounds: CoreGraphics.CGRect { get } + public var uniqueId: Swift.String? { get } +} + +public struct DisplayInfo { + public var displays: [CoreDeviceTypes.Display] { get } +} diff --git a/docs/internal/adr/0031-device-stream-poc/build.sh b/docs/internal/adr/0031-device-stream-poc/build.sh new file mode 100755 index 000000000..26bef6dcc --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/build.sh @@ -0,0 +1,20 @@ +#!/bin/zsh +# Builds DeviceStreamPoC.app next to this script. Requires Xcode 27 (CoreDevice 642.x) on macOS 26. +set -euo pipefail +cd "$(dirname "$0")" +PF=/Library/Developer/PrivateFrameworks +APP=build/DeviceStreamPoC.app +rm -rf build && mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp Info.plist "$APP/Contents/Info.plist" +xcrun clang -fobjc-arc -c Sources/MediaBridge.m -o build/MediaBridge.o +# why: the private enum stubs intentionally omit cases. Optimizing clients can treat +# them as uninhabited (CodableValue traps in Dictionary.compactMapValues). +# Keep this reverse-engineering demo unoptimized, like the proven CLI probe. +xcrun swiftc -Onone -g -I Stubs -module-cache-path build/module-cache -import-objc-header Sources/MediaBridge.h \ + -o "$APP/Contents/MacOS/DeviceStreamPoC" \ + Sources/*.swift build/MediaBridge.o \ + "$PF/CoreDevice.framework/Versions/A/CoreDevice" \ + "$PF/CoreDeviceUtilities.framework/Versions/A/CoreDeviceUtilities" \ + "$PF/CoreDevice.framework/Versions/A/Frameworks/CoreDeviceMediaStreamSupport.framework/Versions/A/CoreDeviceMediaStreamSupport" +codesign --force --sign - "$APP" +echo "built $APP" diff --git a/docs/internal/adr/0031-device-stream-poc/findings/device-preparation.md b/docs/internal/adr/0031-device-stream-poc/findings/device-preparation.md new file mode 100644 index 000000000..c40d6376f --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/findings/device-preparation.md @@ -0,0 +1,24 @@ +# Device preparation — 2026-10-16 + +User confirmed the HEVC capability correction resolved video corruption. +New symptom: mediaStreamSupportInfo fails with remoteService XPC unavailable and +HID capabilities are missing until DeviceHub runs. This occurs before streaming. + +Installed DeviceKit imports RemoteDevice.acquireDeviceUsageAssertion(withReason: +requirements:), the corresponding requirements/state types, and releaseAssertion. +Disassembly of DeviceInteractionModel around 0x4a8a10 builds the state set from +getters developerModeEnabledIfRequired, coreDeviceServicesLoaded, +extendedDeviceInfoLoaded and remoteServiceDiscoveryTrustedConnectivityAvailable, +then conditionally inserts secureNetworkingAvailable at 0x4a8a5c. +The demo targets physical devices and requests all five. + +The assertion is awaited before media support, negotiation options and tunnel IP +are read. HID setup also waits. The local reference holds the assertion through +remote stream stop; defer releases it on success, failure and cancellation. A +successful acquisition followed by cancellation is also released. Unexpected +assertion invalidation cancels the stream. Error logs identify the failing stage. +No global disconnect or release of other apps' assertions is performed. + +No live test performed, per user request. Build and launch only. User should test +with DeviceHub fully closed and a fresh device connection. Backup files are in +work/pre-device-preparation. No entitlement or system protection changes. diff --git a/docs/internal/adr/0031-device-stream-poc/findings/entitlements.md b/docs/internal/adr/0031-device-stream-poc/findings/entitlements.md new file mode 100644 index 000000000..5922ee97d --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/findings/entitlements.md @@ -0,0 +1,57 @@ +# DeviceStreamPoC entitlement investigation + +Date: 15 October 2026. Host: macOS 26.6.1 (25G76), arm64; System Integrity Protection enabled. Installed DeviceHub reports version 27.0, build 255.2.6.6. + +## Conclusion + +There is no ordinary local signing fix identified for `com.apple.videoconference.allow-conferencing`. It is a restricted entitlement on this machine. Adding it produces a valid code signature but prevents the process from launching. Making it legitimate would require authorization from Apple, not merely an Apple Development or Developer ID certificate. No public capability or request route for this particular entitlement was found. + +This does not prove that every possible video implementation is blocked. It establishes that the current AVConference implementation cannot be enabled simply by changing the PoC's signing flags. + +## Evidence + +1. The current `build.sh` signs ad hoc and does not apply `entitlements.plist`. Inspection confirms that the app currently carries no entitlements. That is intentional: applying the experimental entitlement would make it unlaunchable. +2. The actual `DeviceHub.app/Contents/MacOS/DeviceHub` executable contains the conferencing entitlement. Inspect that executable explicitly: inspecting the app bundle selects `DevicesTrampoline`, which has an empty entitlement dictionary. +3. Existing system logs from 14:10:25 and 14:10:29 Europe/Warsaw show `avconferenced` rejecting `vcMediaStreamSetSessionConfig` with `entitlementStatus=2`. This is a daemon-side authorization failure. It is separate from Camera consent and from the PoC's Swift interface declarations. +4. A fresh minimal C program that only prints a marker was packaged into four separate app bundles and signed ad hoc. It has no dependency on CoreDevice, AVConference, the phone, or the Swift stubs. + +| Probe | codesign and strict verification | Execution | +| --- | --- | --- | +| Empty entitlements | Both passed | Reached main; exit 0 | +| Ordinary camera entitlement | Both passed | Reached main; exit 0 | +| Conferencing entitlement | Both passed | SIGKILL before main | +| Conferencing entitlement + Hardened Runtime | Both passed | SIGKILL before main | + +The two failing probes produced AMFI error -424 at 14:51:49 Europe/Warsaw: “The file is adhoc signed but contains restricted entitlements”. Kernel logs also recorded fatal code-signature validation failures. The control probes show why generic AMFI warnings about ad-hoc signatures should not themselves be mistaken for the fatal cause. + +Probe source, entitlement plists, app bundles and machine-readable results are in `work/entitlement-audit/`. The probes were executed outside the agent sandbox; no system protection was changed. + +## What might make the entitlement usable + +Apple would have to authorize its use for this app through an applicable signing/provisioning arrangement, if Apple offers one. Restricted entitlements in third-party macOS apps require authorization in a provisioning profile. A developer certificate alone does not grant arbitrary entitlement keys. Apple's published macOS capability list does not list this conferencing entitlement. Asking Apple Developer Technical Support about availability is reasonable, but approval should not be assumed. + +Root execution, Camera permission, changing the bundle identifier, notarization, or adding a sandbox exception are not substitutes for entitlement authorization. No paid signing identity or Apple-issued profile granting this entitlement was tested or available as evidence in this investigation. + +The report's statement that disabling SIP and AMFI is the only route is too absolute. It omits possible Apple authorization and implementations that avoid this daemon. It also does not demonstrate that changing those protections would resolve every subsequent streaming check. No protection changes, injection, or patches to Apple binaries were attempted. + +## Product paths + +- **Existing USB implementation:** the project already contains CoreMediaIO/AVCaptureSession video capture plus CoreDevice HID input. The pasted report predates that code. Existing app logs show the muxed iOS device being selected, capture starting and HID events being sent. The log reports an initial format of 0x0, so this inspection alone does not establish frame quality or sustained video delivery. I did not retest the phone UI. +- **Custom receiver research:** the installed CoreDevice binary exports `RemoteDevice.startMediaStream(with:)`, `stopMediaStream(with:)`, stream support queries, and negotiation helpers. CoreDeviceMediaStreamSupport then constructs AVConference streams. This identifies a plausible separation point: negotiate through CoreDevice, receive the transport independently, and decode/render in our process. It would require reconstructing the negotiation and transport contract, codec framing and any encryption/feedback. Symbols and successful negotiation do not prove usable packets are obtainable without further privileges. No custom receiver was built in this investigation. + +For Wi-Fi video, a bounded next experiment is to prove that a standalone, unentitled client can obtain and receive the negotiated media transport without constructing an AVConference video stream. Only after that succeeds should work proceed to codec decoding and rendering. This changes the video implementation; it does not grant the restricted entitlement. + +## Limits of the original report + +An observed authorization failure does not establish that it is the only gate. Similarly, a few successful CoreDevice operations do not establish that everything in CoreDevice is unrestricted. Swift library evolution helps ABI resilience, but does not promise compatibility for hand-written declarations of private APIs across Xcode releases. + +The stubs also expose `requestLastDecodedFrame()` and `receivedLastDecodedFrame(Data)`, so the statement that frames never enter the client process should be limited to the normal remote-layer rendering path; these declarations alone do not verify the optional frame-copy behavior. + +## Sources + +- [Apple TN3125: Inside Code Signing — Provisioning Profiles](https://developer.apple.com/documentation/technotes/tn3125-inside-code-signing-provisioning-profiles), especially Entitlements on macOS and The how. +- [Apple: Supported capabilities (macOS)](https://developer.apple.com/help/account/reference/supported-capabilities-macos/). +- [Apple DTS: entitlement categories](https://developer.apple.com/forums/thread/735356). +- Local project source, signed executable metadata, installed framework exported symbols, existing app/system logs, and fresh isolated signing probes described above. + +The app source, build script, app signature and system security configuration were left unchanged. This investigation added only this report and files under `work/entitlement-audit/`. diff --git a/docs/internal/adr/0031-device-stream-poc/findings/hevc-artifacts.md b/docs/internal/adr/0031-device-stream-poc/findings/hevc-artifacts.md new file mode 100644 index 000000000..57e61a26d --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/findings/hevc-artifacts.md @@ -0,0 +1,29 @@ +# HEVC motion artifact investigation — 2026-10-16 + +The user reports corruption during scrolling/transitions with both decoder modes. +The captured native `decoded-180.png` is already corrupt before preview rendering. +The 1792084498-software-A95E74 capture contains 234 complete pictures (one IDR, +233 P pictures). Independent reconstruction of its raw RTP records exactly matches +all 2,791,594 bytes of assembled.hevc. There are no RTP sequence gaps. Runtime +counters also show no decoder drops. The capture has no long-term references in +its SPS; disabling LTRP did not resolve the issue. Earlier sample metadata and +presentation timing corrections also did not resolve it. + +Current candidate: change the HEVC capability advertisement. Local runtime +inspection confirmed that CoreDevice screen settings expose featureListString as +a dictionary keyed by RTP payload number: 100 -> FLS;VRAE:0;SW:1; and +123 -> FLS;SW:1;. The idevice implementation explicitly reports screen tearing +with the default HEVC feature string and uses an alternative. The demo now wraps +the existing screen settings getter, changing only key 100. This changes the +negotiator's own local state before offer creation, keeping it consistent with +its outgoing offer. H.264 settings and the existing LTRP setting are preserved. + +Reference: https://docs.rs/idevice/latest/src/idevice/services/core_device/display_stream/negotiation.rs.html + +This is a candidate fix, not a confirmed root cause. No phone interaction or live +stream test was performed. Build and launch only; user verifies scrolling and +transitions. The log records the negotiated codec string and bounded local +captures remain enabled. If it persists, compare the next negotiated string and +native decoded frames before choosing another change. + +Rollback source: work/pre-hevc-capabilities/MediaBridge.m diff --git a/docs/internal/adr/0031-device-stream-poc/proof/usb-packets.stats.json b/docs/internal/adr/0031-device-stream-poc/proof/usb-packets.stats.json new file mode 100644 index 000000000..ffd72c197 --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/proof/usb-packets.stats.json @@ -0,0 +1,13 @@ +{ + "datagrams": 1278, + "timestamps": 583, + "nal_32": 1, + "nal_33": 1, + "nal_34": 1, + "marker_packets": 582, + "nal_20": 1, + "nal_1": 581, + "non_video_datagrams": 10, + "incomplete_tail": 1, + "hevc_bytes": 1282468 +} diff --git a/docs/internal/adr/0031-device-stream-poc/proof/wifi-packets.stats.json b/docs/internal/adr/0031-device-stream-poc/proof/wifi-packets.stats.json new file mode 100644 index 000000000..052502f0b --- /dev/null +++ b/docs/internal/adr/0031-device-stream-poc/proof/wifi-packets.stats.json @@ -0,0 +1,13 @@ +{ + "datagrams": 1312, + "timestamps": 583, + "nal_32": 1, + "nal_33": 1, + "nal_34": 1, + "marker_packets": 582, + "nal_20": 1, + "nal_1": 581, + "non_video_datagrams": 10, + "incomplete_tail": 1, + "hevc_bytes": 1045203 +} diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index 884b53535..c9a06faaf 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -69,3 +69,4 @@ the status is stale. | [0028](0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md) | The uplink carries byte channels beside its messages, and small messages go first | Accepted | | [0029](0029-host-load-is-an-optional-module-whose-readings-ride-on-status.md) | Host load is an optional module whose readings ride on status | Accepted | | [0030](0030-optional-modules-share-one-contract-and-load-only-when-turned-on.md) | Optional modules share one contract and load only when turned on | Accepted — not yet implemented | +| [0031](0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md) | A physical iPhone streams through CoreDevice's media stream, behind a screen-source seam | Proposed | From 49001f4254b318658ed9383d0c11845e397a82e9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 16 Oct 2026 11:59:47 +0200 Subject: [PATCH 2/3] docs(adr): 0031 accepted, not yet implemented --- ...ne-streams-through-coredevice-behind-a-screen-source-seam.md | 2 +- docs/internal/adr/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md index 8b2b2f319..1693a0ee4 100644 --- a/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md +++ b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md @@ -1,6 +1,6 @@ # 0031. A physical iPhone streams through CoreDevice's media stream, behind a screen-source seam -- **Status:** Proposed +- **Status:** Accepted — not yet implemented - **Date:** 2026-10-16 - **Issue:** [#617](https://github.com/callstackincubator/simlock/issues/617), task [#619](https://github.com/callstackincubator/simlock/issues/619) - **Supersedes:** nothing. Builds on the stream module as it is, and on diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index c9a06faaf..89bd80ebb 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -69,4 +69,4 @@ the status is stale. | [0028](0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md) | The uplink carries byte channels beside its messages, and small messages go first | Accepted | | [0029](0029-host-load-is-an-optional-module-whose-readings-ride-on-status.md) | Host load is an optional module whose readings ride on status | Accepted | | [0030](0030-optional-modules-share-one-contract-and-load-only-when-turned-on.md) | Optional modules share one contract and load only when turned on | Accepted — not yet implemented | -| [0031](0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md) | A physical iPhone streams through CoreDevice's media stream, behind a screen-source seam | Proposed | +| [0031](0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md) | A physical iPhone streams through CoreDevice's media stream, behind a screen-source seam | Accepted — not yet implemented | From 12f9114433297a00f663def957ce3cd5b83142c0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 16 Oct 2026 12:08:06 +0200 Subject: [PATCH 3/3] docs(adr): 0031 the program alone enforces the CoreDevice pin; the build only tries --- ...s-through-coredevice-behind-a-screen-source-seam.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md index 1693a0ee4..9e4656ebe 100644 --- a/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md +++ b/docs/internal/adr/0031-a-physical-iphone-streams-through-coredevice-behind-a-screen-source-seam.md @@ -135,10 +135,12 @@ calls into them, it reads CoreDevice's `CFBundleShortVersionString`. iPhone streams need Xcode 27 (CoreDevice 642.x) and names the version it found. The viewer gets that line in a 503. -`pnpm build` builds `simlock-device-capture` only on a Mac whose CoreDevice -major is 642. Elsewhere it is skipped, and a physical iPhone's stream -answers 503 saying so. Moving to a new major means checking the stubs on -it and changing the pin, in one change. +The program is the one place that enforces the pin. `pnpm build` tries to +build `simlock-device-capture` on every Mac and copies it when it builds. +When it does not build, the build warns and goes on, and a physical +iPhone's stream answers 503 saying the program is missing. A program built +on a Mac with another major refuses at run time, as above. Moving to a new +major means checking the stubs on it and changing the pin, in one change. ### 5. HEVC is decoded and re-encoded as H.264