Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 远程桌面画中画保持浏览时的缩放区域 (#5374)

Dash30f5d8c16b53
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopPresentationCrop.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopPresentationCrop.swift
new file mode 100644
index 0000000000..cc7b7553aa
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopPresentationCrop.swift
@@ -0,0 +1,100 @@
+import CoreGraphics
+import CoreVideo
+
+/// Keeps picture in picture on the desktop region the viewer was browsing.
+/// The inline layer draws the whole frame into the zoomed viewport rectangle;
+/// the system projection receives only the part visible through the view.
+enum RemoteDesktopPresentationCrop {
+ /// Visible part of the frame in normalized top-left coordinates, or nil
+ /// when the complete frame is on screen (fit, letterboxed or not yet laid out).
+ static func visibleRegion(viewport: CGRect, bounds: CGRect) -> CGRect? {
+ guard viewport.width > 0, viewport.height > 0, bounds.width > 0, bounds.height > 0,
+ [viewport.minX, viewport.minY, viewport.width, viewport.height].allSatisfy({ $0.isFinite })
+ else { return nil }
+ let visible = viewport.intersection(bounds)
+ guard !visible.isNull, visible.width > 0, visible.height > 0 else { return nil }
+ let region = CGRect(x: (visible.minX - viewport.minX) / viewport.width,
+ y: (visible.minY - viewport.minY) / viewport.height,
+ width: visible.width / viewport.width,
+ height: visible.height / viewport.height)
+ // Sub-point layout rounding at fit is not a zoom.
+ guard region.width < 0.995 || region.height < 0.995 else { return nil }
+ return region
+ }
+
+ /// Pixel rectangle aligned to 4:2:0 chroma samples, clamped to the frame.
+ static func pixelRect(region: CGRect, width: Int, height: Int) -> CGRect? {
+ guard width >= 2, height >= 2 else { return nil }
+ func span(_ start: CGFloat, _ end: CGFloat, _ limit: Int) -> (Int, Int) {
+ let lower = max(0, min(limit - 2, Int((start * CGFloat(limit)).rounded(.down)))) & ~1
+ var upper = min(limit, Int((end * CGFloat(limit)).rounded(.up)))
+ upper = max(lower + 2, upper + (upper - lower) % 2)
+ if upper > limit { upper -= 2 }
+ return (lower, upper - lower)
+ }
+ let (x, w) = span(region.minX, region.maxX, width)
+ let (y, h) = span(region.minY, region.maxY, height)
+ guard w >= 2, h >= 2 else { return nil }
+ return CGRect(x: x, y: y, width: w, height: h)
+ }
+}
+
+/// Copies the visible region of a decoded NV12 frame into a pooled buffer.
+/// Plain row copies keep colors identical to the inline picture.
+final class RemoteDesktopPresentationCropper {
+ private var pool: CVPixelBufferPool?
+ private var poolSize = CGSize.zero
+ private var poolFormat: OSType = 0
+
+ func reset() {
+ pool = nil
+ poolSize = .zero
+ poolFormat = 0
+ }
+
+ func crop(_ source: CVPixelBuffer, region: CGRect) -> CVPixelBuffer? {
+ let format = CVPixelBufferGetPixelFormatType(source)
+ guard format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ||
+ format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
+ CVPixelBufferGetPlaneCount(source) == 2,
+ let rect = RemoteDesktopPresentationCrop.pixelRect(region: region,
+ width: CVPixelBufferGetWidth(source), height: CVPixelBufferGetHeight(source))
+ else { return nil }
+ let x = Int(rect.minX), y = Int(rect.minY), width = Int(rect.width), height = Int(rect.height)
+ if pool == nil || poolSize != rect.size || poolFormat != format {
+ pool = nil
+ poolSize = rect.size
+ poolFormat = format
+ let attributes: [String: Any] = [
+ kCVPixelBufferPixelFormatTypeKey as String: format,
+ kCVPixelBufferWidthKey as String: width, kCVPixelBufferHeightKey as String: height,
+ kCVPixelBufferIOSurfacePropertiesKey as String: [:],
+ ]
+ CVPixelBufferPoolCreate(nil, nil, attributes as CFDictionary, &pool)
+ }
+ guard let pool else { return nil }
+ // No allocation threshold: AVKit may retain several projected frames, and a
+ // refused buffer would fall back to the whole desktop for that frame. The
+ // pool recycles buffers once AVKit releases them.
+ var output: CVPixelBuffer?
+ guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &output) == kCVReturnSuccess,
+ let output else { return nil }
+ CVPixelBufferLockBaseAddress(source, .readOnly)
+ defer { CVPixelBufferUnlockBaseAddress(source, .readOnly) }
+ CVPixelBufferLockBaseAddress(output, [])
+ defer { CVPixelBufferUnlockBaseAddress(output, []) }
+ // Luma is one byte per pixel; interleaved chroma is two bytes per two
+ // pixels on half the rows, so the same byte offset x selects its column.
+ for (plane, rows, firstRow) in [(0, height, y), (1, height / 2, y / 2)] {
+ guard let from = CVPixelBufferGetBaseAddressOfPlane(source, plane),
+ let to = CVPixelBufferGetBaseAddressOfPlane(output, plane) else { return nil }
+ let fromStride = CVPixelBufferGetBytesPerRowOfPlane(source, plane)
+ let toStride = CVPixelBufferGetBytesPerRowOfPlane(output, plane)
+ for row in 0..<rows {
+ memcpy(to.advanced(by: row * toStride), from.advanced(by: (firstRow + row) * fromStride + x), width)
+ }
+ }
+ CVBufferPropagateAttachments(source, output)
+ return output
+ }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift
index 461af9f039..06e7465f41 100644
--- a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift
@@ -71,6 +71,7 @@ final class RemoteDesktopVideoView: ExpoView, AVPictureInPictureControllerDelega
}
private var pool: CVPixelBufferPool?
private var poolSize = CGSize.zero
+ private let presentationCropper = RemoteDesktopPresentationCropper()
private var backgroundGeneration = 0
private var backgroundObserver: NSObjectProtocol?
private var foregroundObserver: NSObjectProtocol?
@@ -83,8 +84,8 @@ final class RemoteDesktopVideoView: ExpoView, AVPictureInPictureControllerDelega
isUserInteractionEnabled = false
display.videoGravity = .resizeAspect
presentationDisplay.videoGravity = .resizeAspect
- // AVKit keeps a stable viewport-sized projection of the same decoded frame.
- // The inline layer remains free to follow the viewer's pan/zoom rectangle.
+ // AVKit keeps a viewport-sized projection of the same decoded frame, limited
+ // to the region visible inline; the inline layer follows the pan/zoom rectangle.
addSubview(videoSurface)
canvas.backgroundColor = (backgroundColor ?? .systemBackground).cgColor
layer.addSublayer(canvas)
@@ -334,32 +335,46 @@ final class RemoteDesktopVideoView: ExpoView, AVPictureInPictureControllerDelega
backdropTime = 0
latestFrame = nil
pool = nil
+ presentationCropper.reset()
}
- @discardableResult private func render(_ frame: RTCVideoFrame, liveFrame: Bool = false) -> Bool {
- guard let buffer = pixelBuffer(frame) else { return false }
+ private func sampleBuffer(_ buffer: CVPixelBuffer) -> CMSampleBuffer? {
var format: CMVideoFormatDescription?
guard CMVideoFormatDescriptionCreateForImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: buffer, formatDescriptionOut: &format) == noErr,
- let format else { return false }
+ let format else { return nil }
var timing = CMSampleTimingInfo(duration: .invalid, presentationTimeStamp: CMClockGetTime(CMClockGetHostTimeClock()), decodeTimeStamp: .invalid)
var sample: CMSampleBuffer?
guard CMSampleBufferCreateReadyWithImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: buffer, formatDescription: format, sampleTiming: &timing, sampleBufferOut: &sample) == noErr,
- let sample else { return false }
+ let sample else { return nil }
// Live remote desktop has no seekable timeline; display every decoded frame
// immediately rather than accumulating latency behind presentation timestamps.
if let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true) {
let entry = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self)
CFDictionarySetValue(entry, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque())
}
+ return sample
+ }
+ /// The system projection follows the inline zoom: when the viewer is zoomed
+ /// in, PiP receives only the desktop region that was visible on screen.
+ private func presentationSample(_ buffer: CVPixelBuffer, inline sample: CMSampleBuffer) -> CMSampleBuffer {
+ guard pip != nil,
+ let region = RemoteDesktopPresentationCrop.visibleRegion(viewport: display.frame, bounds: bounds),
+ let cropped = presentationCropper.crop(buffer, region: region),
+ let projected = sampleBuffer(cropped) else { return sample }
+ return projected
+ }
+ @discardableResult private func render(_ frame: RTCVideoFrame, liveFrame: Bool = false) -> Bool {
+ guard let buffer = pixelBuffer(frame), let sample = sampleBuffer(buffer) else { return false }
if presentationDisplay.status == .failed {
playbackReady = false
presentationDisplay.flush()
}
let projected = presentationDisplay.isReadyForMoreMediaData
if projected {
- presentationDisplay.enqueue(sample)
+ presentationDisplay.enqueue(presentationSample(buffer, inline: sample))
if liveFrame { playbackReady = true; renderedFrames += 1 }
}
- // The second renderer shares the sample buffer; no second decode or copy.
+ // The inline renderer shares the decoded sample buffer; no second decode or
+ // copy. Only a zoomed system projection copies its visible region.
// Only the system projection consumes frames while inline is not visible.
let needsInline = inlineVisible && UIApplication.shared.applicationState == .active
var renderedInline = false
diff --git a/apps/mobile/scripts/fixtures/remote-desktop-presentation-crop.swift b/apps/mobile/scripts/fixtures/remote-desktop-presentation-crop.swift
new file mode 100644
index 0000000000..c1f7484986
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/remote-desktop-presentation-crop.swift
@@ -0,0 +1,72 @@
+import CoreGraphics
+import CoreVideo
+
+@main
+struct PresentationCropTests {
+ static func main() {
+ let bounds = CGRect(x: 0, y: 0, width: 400, height: 800)
+ // Fit and letterboxed layouts keep the whole frame, including rounding noise.
+ assert(RemoteDesktopPresentationCrop.visibleRegion(
+ viewport: CGRect(x: 0, y: 287.5, width: 400, height: 225), bounds: bounds) == nil)
+ assert(RemoteDesktopPresentationCrop.visibleRegion(
+ viewport: CGRect(x: -0.4, y: 0, width: 400.8, height: 800), bounds: bounds) == nil)
+ assert(RemoteDesktopPresentationCrop.visibleRegion(viewport: .zero, bounds: bounds) == nil)
+ assert(RemoteDesktopPresentationCrop.visibleRegion(
+ viewport: CGRect(x: 0, y: 0, width: 400, height: 225), bounds: .zero) == nil)
+ // A 4x zoom panned right/down keeps exactly the on-screen quarter.
+ let zoomed = RemoteDesktopPresentationCrop.visibleRegion(
+ viewport: CGRect(x: -800, y: -100, width: 1600, height: 900), bounds: bounds)!
+ assert(abs(zoomed.minX - 0.5) < 1e-9 && abs(zoomed.width - 0.25) < 1e-9)
+ assert(abs(zoomed.minY - 100.0 / 900) < 1e-9 && abs(zoomed.height - 800.0 / 900) < 1e-9)
+ // Pixel rects stay chroma aligned, even sized and inside the frame.
+ let rect = RemoteDesktopPresentationCrop.pixelRect(region: zoomed, width: 1920, height: 1080)!
+ assert(rect == CGRect(x: 960, y: 120, width: 480, height: 960))
+ let edge = RemoteDesktopPresentationCrop.pixelRect(
+ region: CGRect(x: 0.9993, y: 0.0003, width: 0.0007, height: 0.9997), width: 1921, height: 1081)!
+ assert(Int(edge.minX) % 2 == 0 && Int(edge.minY) % 2 == 0)
+ assert(Int(edge.width) % 2 == 0 && Int(edge.height) % 2 == 0 && edge.width >= 2)
+ assert(edge.maxX <= 1921 && edge.maxY <= 1081)
+
+ // Row copies select the same luma and chroma samples as the source.
+ var source: CVPixelBuffer?
+ let attributes = [kCVPixelBufferIOSurfacePropertiesKey as String: [:]] as CFDictionary
+ assert(CVPixelBufferCreate(nil, 64, 32, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
+ attributes, &source) == kCVReturnSuccess)
+ let input = source!
+ CVPixelBufferLockBaseAddress(input, [])
+ for plane in 0..<2 {
+ let base = CVPixelBufferGetBaseAddressOfPlane(input, plane)!.assumingMemoryBound(to: UInt8.self)
+ let stride = CVPixelBufferGetBytesPerRowOfPlane(input, plane)
+ for row in 0..<CVPixelBufferGetHeightOfPlane(input, plane) {
+ for column in 0..<64 { base[row * stride + column] = UInt8((row * 3 + column + plane * 100) & 0xff) }
+ }
+ }
+ CVPixelBufferUnlockBaseAddress(input, [])
+ let cropper = RemoteDesktopPresentationCropper()
+ let region = CGRect(x: 0.25, y: 0.5, width: 0.5, height: 0.25)
+ let output = cropper.crop(input, region: region)!
+ assert(CVPixelBufferGetWidth(output) == 32 && CVPixelBufferGetHeight(output) == 8)
+ assert(CVPixelBufferGetPixelFormatType(output) == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
+ CVPixelBufferLockBaseAddress(output, .readOnly)
+ let luma = CVPixelBufferGetBaseAddressOfPlane(output, 0)!.assumingMemoryBound(to: UInt8.self)
+ let lumaStride = CVPixelBufferGetBytesPerRowOfPlane(output, 0)
+ assert(luma[0] == UInt8((16 * 3 + 16) & 0xff))
+ assert(luma[7 * lumaStride + 31] == UInt8((23 * 3 + 47) & 0xff))
+ let chroma = CVPixelBufferGetBaseAddressOfPlane(output, 1)!.assumingMemoryBound(to: UInt8.self)
+ let chromaStride = CVPixelBufferGetBytesPerRowOfPlane(output, 1)
+ assert(chroma[0] == UInt8((8 * 3 + 16 + 100) & 0xff))
+ assert(chroma[3 * chromaStride + 31] == UInt8((11 * 3 + 47 + 100) & 0xff))
+ CVPixelBufferUnlockBaseAddress(output, .readOnly)
+ // Frames still retained by AVKit must not make the next crop fall back.
+ var retained = [output]
+ for _ in 0..<6 { retained.append(cropper.crop(input, region: region)!) }
+ assert(Set(retained.map { ObjectIdentifier($0) }).count == retained.count)
+ // A changed zoom reallocates; unsupported formats leave the frame uncropped.
+ let wider = cropper.crop(input, region: CGRect(x: 0, y: 0, width: 0.5, height: 0.5))!
+ assert(CVPixelBufferGetWidth(wider) == 32 && CVPixelBufferGetHeight(wider) == 16)
+ var rgb: CVPixelBuffer?
+ CVPixelBufferCreate(nil, 64, 32, kCVPixelFormatType_32BGRA, attributes, &rgb)
+ assert(cropper.crop(rgb!, region: region) == nil)
+ print("PASS: picture in picture keeps the visible zoom region with exact NV12 samples")
+ }
+}
diff --git a/apps/mobile/scripts/test-remote-desktop-presentation-crop.mjs b/apps/mobile/scripts/test-remote-desktop-presentation-crop.mjs
new file mode 100755
index 0000000000..88ad0037bd
--- /dev/null
+++ b/apps/mobile/scripts/test-remote-desktop-presentation-crop.mjs
@@ -0,0 +1,29 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const directory = mkdtempSync(join(tmpdir(), "cindy-presentation-crop-test-"));
+try {
+ const source = fileURLToPath(
+ new URL(
+ "../modules/cindy-remote-presentation/ios/RemoteDesktopPresentationCrop.swift",
+ import.meta.url,
+ ),
+ );
+ const fixture = fileURLToPath(
+ new URL(
+ "./fixtures/remote-desktop-presentation-crop.swift",
+ import.meta.url,
+ ),
+ );
+ const executable = join(directory, "presentation-crop-tests");
+ execFileSync("xcrun", ["swiftc", source, fixture, "-o", executable], {
+ stdio: "inherit",
+ });
+ execFileSync(executable, [], { stdio: "inherit" });
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.md
index 419f3fc9d0..2304cd2080 100644
--- a/docs/dev-rules/remote-desktop-connectivity.md
+++ b/docs/dev-rules/remote-desktop-connectivity.md
@@ -88,7 +88,12 @@ returning inline refreshes that state after the PiP stop completes. A cached old
frame alone does not make a reconnecting receiver ready for PiP.
Keep the AVKit sample-buffer projection at the native viewport's bounds, separate
from the inline layer's fitted/panned/zoomed rectangle. Both renderers share one
-decoded sample buffer; their readiness must not block each other. Only the system
+decoded sample buffer; their readiness must not block each other. When the viewer
+is zoomed in, only the projection's frame content follows the zoom: it receives
+the desktop region visible inline, copied from the decoded NV12 frame
+(`RemoteDesktopPresentationCrop`). The projection layer's geometry stays fixed, so
+PiP keeps the browsing zoom without moving the source; a fitted, unzoomed view
+passes the frame through unchanged. Only the system
projection receives frames while inline is hidden or the app is inactive. Restore
replays the latest frame into the inline renderer before completing the visible
source handoff. In physical-device A/B testing, a fitted or transformed source
@@ -134,6 +139,9 @@ and Light/Dark on a physical phone. Unit tests and simulator builds do not estab
background PiP acceptance. Roll out the Desktop signaling-loss fix with the native
phone build; older Desktop hosts may still stop media when signaling disconnects.
+Run `node apps/mobile/scripts/test-remote-desktop-presentation-crop.mjs` on macOS
+to check the PiP zoom region geometry, 4:2:0 alignment and NV12 row copies.
+
Run `node apps/mobile/scripts/test-remote-desktop-receiver.mjs` on macOS to
compile and execute the production receiver against test-only UIKit/WebRTC doubles.
It covers attempt isolation, late SDP/ICE/frame callbacks, idempotent stop,