Skip to content

Commit 5c8db67

Browse files
fix(camera): preserve landscape output on external macOS webcams (#116046)
* fix(camera): preserve landscape output on external macOS webcams After photo-session startup, replace an external camera's portrait format only with an advertised exact landscape counterpart using the same media subtype. Preserve built-in, Continuity, already-landscape, and unmatched formats; keep maxWidth as output-only sizing. Replace the shared iOS/macOS width-ranking proposal in PR #116046 with this bounded macOS repair. Add format-contract regressions and document the best-effort limit. Related: #113068; affected C310 confirmation is pending. Co-authored-by: Taksh <[email protected]> * fix(macos): start connectivity after app admission Keep passive dashboard, health, and menu reads from implicitly starting endpoint observation and control-channel recovery. AppDelegate already starts the coordinator explicitly after primary-app admission. * fix(macos): keep Talk phase updates from activating recovery --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 9458d8b commit 5c8db67

8 files changed

Lines changed: 138 additions & 10 deletions

File tree

‎apps/macos/Sources/OpenClaw/CameraCaptureService.swift‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,23 @@ actor CameraCaptureService {
7979

8080
session.startRunning()
8181
defer { session.stopRunning() }
82+
// The photo preset can choose a portrait format at startup on external webcams.
83+
// Select its landscape counterpart only after negotiation and before capturing.
84+
let formats = device.formats
85+
if let index = CameraDeviceResolver.landscapePhotoFormatIndex(
86+
deviceType: device.deviceType,
87+
activeFormat: device.activeFormat.formatDescription,
88+
formats: formats.map(\.formatDescription))
89+
{
90+
do {
91+
try device.lockForConfiguration()
92+
defer { device.unlockForConfiguration() }
93+
device.activeFormat = formats[index]
94+
} catch {
95+
self.logger.warning(
96+
"camera landscape format selection failed: \(error.localizedDescription, privacy: .public)")
97+
}
98+
}
8299
try await CameraCapturePipelineSupport.warmUpCaptureSession()
83100
await self.waitForExposureAndWhiteBalance(device: device)
84101
await self.sleepDelayMs(delayMs)

‎apps/macos/Sources/OpenClaw/CameraDeviceResolver.swift‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@ import AVFoundation
22

33
enum CameraDeviceResolver {
44
static func availableCameras() -> [AVCaptureDevice] {
5-
var types: [AVCaptureDevice.DeviceType] = [
5+
let types: [AVCaptureDevice.DeviceType] = [
66
.builtInWideAngleCamera,
77
.continuityCamera,
8+
.external,
89
]
9-
if let external = self.externalDeviceType() {
10-
types.append(external)
11-
}
1210
return AVCaptureDevice.DiscoverySession(
1311
deviceTypes: types,
1412
mediaType: .video,
@@ -19,10 +17,22 @@ enum CameraDeviceResolver {
1917
self.availableCameras().first { $0.uniqueID == deviceId }
2018
}
2119

22-
private static func externalDeviceType() -> AVCaptureDevice.DeviceType? {
23-
if #available(macOS 14.0, *) {
24-
return .external
20+
static func landscapePhotoFormatIndex(
21+
deviceType: AVCaptureDevice.DeviceType,
22+
activeFormat: CMFormatDescription,
23+
formats: [CMFormatDescription]) -> Int?
24+
{
25+
let activeSize = CMVideoFormatDescriptionGetDimensions(activeFormat)
26+
guard deviceType == .external, activeSize.width < activeSize.height else {
27+
return nil
28+
}
29+
let subtype = CMFormatDescriptionGetMediaSubType(activeFormat)
30+
// Repair portrait negotiation without choosing a different resolution or encoding.
31+
// Cameras without an exact landscape counterpart keep their negotiated format.
32+
return formats.firstIndex { format in
33+
let size = CMVideoFormatDescriptionGetDimensions(format)
34+
return size.width == activeSize.height && size.height == activeSize.width &&
35+
CMFormatDescriptionGetMediaSubType(format) == subtype
2536
}
26-
return AVCaptureDevice.DeviceType(rawValue: "AVCaptureDeviceTypeExternalUnknown")
2737
}
2838
}

‎apps/macos/Sources/OpenClaw/GatewayConnection.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1522,7 +1522,9 @@ extension GatewayConnection {
15221522
if let phase {
15231523
params["phase"] = AnyCodable(phase)
15241524
}
1525-
try? await self.requestVoid(method: .talkMode, params: params)
1525+
// Phase broadcasts report UI state; a failed notification must not start
1526+
// the Gateway or restart its tunnel. Talk startup owns that recovery.
1527+
_ = try? await self.request(method: Method.talkMode.rawValue, params: params, retryTransportFailures: false)
15261528
}
15271529

15281530
// MARK: - VoiceWake

‎apps/macos/Sources/OpenClaw/GatewayConnectivityCoordinator.swift‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ final class GatewayConnectivityCoordinator {
6060
},
6161
refresh: { await GatewayEndpointStore.shared.refresh() },
6262
log: { message in gatewayConnectivityLogger.error("\(message, privacy: .public)") })
63-
self.start()
6463
}
6564

6665
func start() {
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import AVFoundation
2+
import CoreMedia
3+
import Testing
4+
@testable import OpenClaw
5+
6+
struct CameraDeviceResolverTests {
7+
@Test func `external portrait photos select the transposed format with the same encoding`() throws {
8+
let portrait = try Self.format(width: 1080, height: 1920)
9+
let formats = try [
10+
Self.format(width: 1920, height: 1080, subtype: kCVPixelFormatType_422YpCbCr8_yuvs),
11+
Self.format(width: 3840, height: 2160),
12+
Self.format(width: 1920, height: 1080),
13+
]
14+
#expect(CameraDeviceResolver.landscapePhotoFormatIndex(
15+
deviceType: .external, activeFormat: portrait, formats: formats) == 2)
16+
}
17+
18+
@Test(arguments: [AVCaptureDevice.DeviceType.builtInWideAngleCamera, .continuityCamera])
19+
func `non-external cameras retain portrait formats`(deviceType: AVCaptureDevice.DeviceType) throws {
20+
#expect(try CameraDeviceResolver.landscapePhotoFormatIndex(
21+
deviceType: deviceType,
22+
activeFormat: Self.format(width: 1080, height: 1920),
23+
formats: [Self.format(width: 1920, height: 1080)]) == nil)
24+
}
25+
26+
@Test(arguments: [(1920, 1080), (1552, 1552), (1088, 1920)])
27+
func `landscape square and unmatched portrait formats remain unchanged`(width: Int32, height: Int32) throws {
28+
#expect(try CameraDeviceResolver.landscapePhotoFormatIndex(
29+
deviceType: .external,
30+
activeFormat: Self.format(width: width, height: height),
31+
formats: [
32+
Self.format(width: height, height: width, subtype: kCVPixelFormatType_422YpCbCr8_yuvs),
33+
Self.format(width: 1920, height: 1080),
34+
]) == nil)
35+
}
36+
37+
@Test func `external cameras without a matching encoding or format remain unchanged`() throws {
38+
let portrait = try Self.format(width: 1080, height: 1920)
39+
let wrongEncoding = try Self.format(width: 1920, height: 1080, subtype: kCVPixelFormatType_422YpCbCr8_yuvs)
40+
for formats in [[], [wrongEncoding]] {
41+
#expect(CameraDeviceResolver.landscapePhotoFormatIndex(
42+
deviceType: .external, activeFormat: portrait, formats: formats) == nil)
43+
}
44+
}
45+
46+
private static func format(
47+
width: Int32,
48+
height: Int32,
49+
subtype: FourCharCode = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange) throws -> CMFormatDescription
50+
{
51+
var description: CMVideoFormatDescription?
52+
let result = CMVideoFormatDescriptionCreate(
53+
allocator: kCFAllocatorDefault,
54+
codecType: subtype,
55+
width: width,
56+
height: height,
57+
extensions: nil,
58+
formatDescriptionOut: &description)
59+
#expect(result == noErr)
60+
return try #require(description)
61+
}
62+
}

‎apps/macos/Tests/OpenClawIPCTests/GatewayConnectionControlTests.swift‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,41 @@ private func assertConfigLookupCannotRecreateRoute(
252252
try await self.assertUncancelledFailureRecovers(CancellationError())
253253
}
254254

255+
@Test(arguments: [false, true], [false, true]) @MainActor
256+
func `Talk phase notifications preserve their payload without activating recovery`(
257+
enabled: Bool,
258+
failTransport: Bool) async throws
259+
{
260+
let requests = WebSocketMessageRecorder()
261+
try await self.withIsolatedRecoveryFixture { socket, message, sendIndex in
262+
guard sendIndex > 0,
263+
let id = GatewayWebSocketTestSupport.requestID(from: message),
264+
let data = Self.messageData(message),
265+
let frame = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
266+
else { return }
267+
if frame["method"] as? String == "talk.mode" {
268+
requests.append(message)
269+
if failTransport, requests.snapshot().count == 1 {
270+
throw URLError(.networkConnectionLost)
271+
}
272+
}
273+
socket.emitReceiveSuccess(.data(GatewayWebSocketTestSupport.okResponseData(id: id)))
274+
} operation: { connection, _ in
275+
let phase = enabled ? "speaking" : "idle"
276+
await connection.talkMode(enabled: enabled, phase: phase)
277+
278+
#expect(GatewayProcessManager.shared.status == .stopped)
279+
#expect(GatewayLaunchAgentManager.testingDaemonCommandCallsSnapshot().isEmpty)
280+
#expect(requests.snapshot().count == 1)
281+
let message = try #require(requests.snapshot().first)
282+
let data = try #require(Self.messageData(message))
283+
let frame = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
284+
let params = try #require(frame["params"] as? [String: Any])
285+
#expect(params["enabled"] as? Bool == enabled)
286+
#expect(params["phase"] as? String == phase)
287+
}
288+
}
289+
255290
@Test @MainActor
256291
func `gateway response errors never activate transport recovery`() async throws {
257292
try await self.withIsolatedRecoveryFixture { socket, message, sendIndex in

‎docs/nodes/camera.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ openclaw nodes camera clip --node <id> --no-audio
130130
- `camera.snap` waits `delayMs` (default 2000ms, clamped to `[0, 10000]`) after warm-up/exposure settle before capturing.
131131
- Photo payloads are recompressed to keep base64 under 5MB.
132132

133+
If a macOS external camera starts a photo session in portrait, OpenClaw selects an advertised landscape format with transposed dimensions and the same encoding, when one exists. Already-landscape, built-in, and Continuity Camera formats are unchanged. Without an exact counterpart, or if the camera cannot be reconfigured, capture keeps the negotiated format. `--max-width` still only limits the returned JPEG width; it does not choose a camera format.
134+
133135
### macOS physical PTZ
134136

135137
Physical PTZ is implemented by the Mac app for USB cameras that expose standard UVC absolute pan/tilt or zoom controls. It uses the same **Allow Camera** setting as capture. Other node platforms do not advertise these commands.

‎docs/nodes/talk.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ stopping Talk releases the camera and microphone tracks.
5454

5555
- Always-on overlay while Talk mode is enabled.
5656
- **Listening &rarr; Thinking &rarr; Speaking** phase transitions.
57+
- Phase notifications are best-effort: a failed update does not start the local Gateway or restart its tunnel. Starting Talk retains normal connection recovery.
5758
- On a short pause (silence window), the current transcript is sent.
5859
- Replies are written to WebChat (same as typing).
5960
- **Interrupt on speech** (default on): if the user talks while the assistant is speaking, playback stops and the interruption timestamp is noted for the next prompt.

0 commit comments

Comments
 (0)