@appium/coresim 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ #include "sim_video_stream.h"
2
+
3
+ #import <CoreMedia/CoreMedia.h>
4
+ #import <CoreVideo/CoreVideo.h>
5
+ #import <IOSurface/IOSurface.h>
6
+ #import <VideoToolbox/VideoToolbox.h>
7
+
8
+ #include <algorithm>
9
+ #include <atomic>
10
+ #include <ctime>
11
+
12
+ #include "nserror_bridge.h"
13
+ #include "safe_dispatch.h"
14
+ #include "sim_screenshot.h"
15
+
16
+ namespace coresim {
17
+
18
+ namespace {
19
+
20
+ NSString* const kVideoStreamErrorDomain = @"com.appium.coresim.VideoStream";
21
+
22
+ NSError* MakeError(NSInteger code, NSString* message) {
23
+ return [NSError errorWithDomain:kVideoStreamErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : message}];
24
+ }
25
+
26
+ NSError* MakeStatusError(NSInteger code, NSString* what, OSStatus status) {
27
+ return MakeError(code, [NSString stringWithFormat:@"%@ (OSStatus %d)", what, static_cast<int>(status)]);
28
+ }
29
+
30
+ // CFAbsoluteTimeGetCurrent() is wall time — subject to backward NTP/manual clock corrections,
31
+ // which would violate VTCompressionSessionEncodeFrame's requirement of strictly increasing PTS.
32
+ // CLOCK_MONOTONIC_RAW never goes backward and isn't adjusted by NTP.
33
+ double MonotonicSeconds() {
34
+ struct timespec ts;
35
+ clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
36
+ return static_cast<double>(ts.tv_sec) + static_cast<double>(ts.tv_nsec) / 1e9;
37
+ }
38
+
39
+ void AppendAnnexB(std::vector<uint8_t>& out, const uint8_t* nal, size_t length) {
40
+ static const uint8_t kStartCode[4] = {0, 0, 0, 1};
41
+ out.insert(out.end(), kStartCode, kStartCode + 4);
42
+ out.insert(out.end(), nal, nal + length);
43
+ }
44
+
45
+ // VideoToolbox's compressed output is AVCC-framed (a 4-byte big-endian length prefix per NAL,
46
+ // no start codes) — rewrites it into Annex-B, matching VideoAccessUnit's documented wire format.
47
+ void AppendSampleBufferNALs(std::vector<uint8_t>& out, CMSampleBufferRef sampleBuffer) {
48
+ CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sampleBuffer);
49
+ if (block == nullptr) {
50
+ return;
51
+ }
52
+ size_t totalLength = CMBlockBufferGetDataLength(block);
53
+ if (totalLength == 0) {
54
+ return;
55
+ }
56
+ // CMBlockBufferGetDataPointer's pointer only covers the contiguous region starting at the given
57
+ // offset, which for a segmented buffer (multiple backing memory blocks — CoreMedia's documented
58
+ // contract, not just a VideoToolbox implementation detail) can be far shorter than totalLength;
59
+ // reading up to totalLength through it would run past that region. CopyDataBytes stitches
60
+ // segments together into a caller-owned, guaranteed-contiguous copy instead.
61
+ std::vector<uint8_t> data(totalLength);
62
+ if (CMBlockBufferCopyDataBytes(block, 0, totalLength, data.data()) != kCMBlockBufferNoErr) {
63
+ return;
64
+ }
65
+ const uint8_t* dataPointer = data.data();
66
+ size_t offset = 0;
67
+ while (offset + 4 <= totalLength) {
68
+ uint32_t nalLength = (static_cast<uint32_t>(dataPointer[offset]) << 24) |
69
+ (static_cast<uint32_t>(dataPointer[offset + 1]) << 16) |
70
+ (static_cast<uint32_t>(dataPointer[offset + 2]) << 8) | dataPointer[offset + 3];
71
+ offset += 4;
72
+ if (nalLength == 0 || offset + nalLength > totalLength) {
73
+ break;
74
+ }
75
+ AppendAnnexB(out, dataPointer + offset, nalLength);
76
+ offset += nalLength;
77
+ }
78
+ }
79
+
80
+ using ParameterSetAtIndexFn = OSStatus (*)(CMFormatDescriptionRef, size_t, const uint8_t**, size_t*, size_t*, int*);
81
+
82
+ void AppendParameterSets(std::vector<uint8_t>& out, CMFormatDescriptionRef format, ParameterSetAtIndexFn getAtIndex) {
83
+ size_t count = 0;
84
+ if (getAtIndex(format, 0, nullptr, nullptr, &count, nullptr) != noErr) {
85
+ return;
86
+ }
87
+ for (size_t i = 0; i < count; i++) {
88
+ const uint8_t* bytes = nullptr;
89
+ size_t size = 0;
90
+ if (getAtIndex(format, i, &bytes, &size, nullptr, nullptr) == noErr) {
91
+ AppendAnnexB(out, bytes, size);
92
+ }
93
+ }
94
+ }
95
+
96
+ } // namespace
97
+
98
+ class VideoStreamSession::Impl {
99
+ public:
100
+ Impl(id device, VideoStreamOptions options, std::function<void(VideoAccessUnit)> onAccessUnit,
101
+ std::function<void(NSError*)> onError, std::function<void()> onEnd)
102
+ : device_(device),
103
+ options_(options),
104
+ onAccessUnit_(std::move(onAccessUnit)),
105
+ onError_(std::move(onError)),
106
+ onEnd_(std::move(onEnd)) {
107
+ queue_ = dispatch_queue_create("com.appium.coresim.videoStream", DISPATCH_QUEUE_SERIAL);
108
+ }
109
+
110
+ ~Impl() { Stop(); }
111
+
112
+ void Start() {
113
+ NSError* error = nil;
114
+ id descriptor = ResolveCaptureDisplay(device_, options_.displayId, &error);
115
+ if (descriptor == nil) {
116
+ throw NSErrorException(error);
117
+ }
118
+ id surfaceObj = CurrentDisplaySurface(descriptor);
119
+ if (surfaceObj == nil) {
120
+ throw NSErrorException(MakeError(4, @"The device's display surface is not available yet"));
121
+ }
122
+ IOSurfaceRef surface = (__bridge IOSurfaceRef)surfaceObj;
123
+ // Set up synchronously (not lazily on the first Tick()) so a setup failure rejects Start()
124
+ // directly rather than only reaching onError, which the caller may not be listening for yet.
125
+ NSError* setupError = nil;
126
+ if (!SetUpSession(surface, &setupError)) {
127
+ throw NSErrorException(setupError);
128
+ }
129
+ // Must be set before EncodeSurface below — both it and HandleEncodedSample measure elapsed
130
+ // time from this.
131
+ startTime_ = MonotonicSeconds();
132
+ // Encode immediately rather than waiting for a *changed* seed on the first tick, or the
133
+ // stream would stay silent until the display changes again. running_ is set true before this
134
+ // call (not after), since VTCompressionSessionEncodeFrame's output callback can in principle
135
+ // fire on another thread before this one returns — HandleEncodedSample discards samples while
136
+ // running_ is false, which would otherwise silently drop the stream's very first (keyframe)
137
+ // access unit. A failure resets it and tears session_ down itself here, rather than going
138
+ // through Stop()/onEnd_ (see coresim.mm — onEnd_ firing this early would double-release its
139
+ // ThreadSafeFunctions).
140
+ running_ = true;
141
+ bool encoded = false;
142
+ try {
143
+ encoded = EncodeSurface(surface);
144
+ } catch (...) {
145
+ running_ = false;
146
+ VTCompressionSessionInvalidate(session_);
147
+ CFRelease(session_);
148
+ session_ = nullptr;
149
+ throw;
150
+ }
151
+ // Only commit the seed once a frame was actually submitted — a transient pixel-buffer
152
+ // creation failure (EncodeSurface returning false) otherwise leaves lastSeed_ at its default
153
+ // 0, so the first Tick() sees the real seed as "changed" and retries automatically instead of
154
+ // the stream going silent forever on a display that never changes again.
155
+ if (encoded) {
156
+ lastSeed_ = IOSurfaceGetSeed(surface);
157
+ }
158
+
159
+ double interval = 1.0 / std::max(options_.fps, 1.0);
160
+ dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_);
161
+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0),
162
+ static_cast<uint64_t>(interval * NSEC_PER_SEC),
163
+ static_cast<uint64_t>(interval * NSEC_PER_SEC / 10));
164
+ // `this` outlives the timer: Stop()/StopFromQueue() always drain or outrun it before `this`
165
+ // can be destroyed (see their comments below).
166
+ dispatch_source_set_event_handler(timer, ^{
167
+ Tick();
168
+ });
169
+ timer_ = timer;
170
+ dispatch_resume(timer_);
171
+ }
172
+
173
+ // Callable from any thread except `queue_` itself (would deadlock on the dispatch_sync below).
174
+ void Stop() {
175
+ if (!running_.exchange(false)) {
176
+ return; // idempotent
177
+ }
178
+ if (timer_ != nullptr) {
179
+ dispatch_source_cancel(timer_);
180
+ // Blocks until any in-flight Tick() finishes — by then running_ is already false, so it
181
+ // won't touch session_ again.
182
+ dispatch_sync(queue_, ^{
183
+ });
184
+ timer_ = nullptr;
185
+ }
186
+ TearDownSessionAndFireEnd();
187
+ }
188
+
189
+ void RequestKeyFrame() { forceKeyFrame_ = true; }
190
+
191
+ private:
192
+ // Same as Stop() minus the dispatch_sync barrier — only safe from within Tick() itself, already
193
+ // serialized on `queue_`; would race a concurrent Tick() from any other thread.
194
+ void StopFromQueue() {
195
+ if (!running_.exchange(false)) {
196
+ return; // idempotent — e.g. an external Stop() already won this race
197
+ }
198
+ if (timer_ != nullptr) {
199
+ dispatch_source_cancel(timer_);
200
+ timer_ = nullptr;
201
+ }
202
+ TearDownSessionAndFireEnd();
203
+ }
204
+
205
+ void TearDownSessionAndFireEnd() {
206
+ if (session_ != nullptr) {
207
+ // Flushes and blocks until every already-submitted frame's callback has returned — without
208
+ // this, a frame submitted just before Stop() could fire after onEnd_ releases the
209
+ // ThreadSafeFunctions below (a use-after-release; see CLAUDE.md).
210
+ VTCompressionSessionCompleteFrames(session_, kCMTimeInvalid);
211
+ VTCompressionSessionInvalidate(session_);
212
+ CFRelease(session_);
213
+ session_ = nullptr;
214
+ }
215
+ if (onEnd_) {
216
+ onEnd_();
217
+ }
218
+ }
219
+
220
+ void Tick() {
221
+ if (!running_) {
222
+ return;
223
+ }
224
+ if (pendingErrorTeardown_) {
225
+ // HandleEncodedSample (below) can run on VideoToolbox's own callback thread, where it's
226
+ // unsafe to tear down directly — StopFromQueue()/CompleteFrames() are only safe already
227
+ // serialized on `queue_` (here), and CompleteFrames specifically would deadlock waiting on
228
+ // its own still-executing callback. It sets this flag instead; picked up on the very next
229
+ // tick (queue_-serialized, safe) rather than via a raw cross-thread dispatch, since nothing
230
+ // here can outlive `this` the way a block captured on another thread otherwise could.
231
+ StopFromQueue();
232
+ return;
233
+ }
234
+ @autoreleasepool {
235
+ try {
236
+ // Re-resolved every tick (like CaptureScreenshot does), not cached once in Start(), so a
237
+ // deleted device or disconnected display surfaces a real error instead of Tick() quietly
238
+ // doing nothing forever.
239
+ NSError* resolveError = nil;
240
+ id descriptor = ResolveCaptureDisplay(device_, options_.displayId, &resolveError);
241
+ if (descriptor == nil) {
242
+ if (onError_) {
243
+ onError_(resolveError);
244
+ }
245
+ StopFromQueue();
246
+ return;
247
+ }
248
+ id surfaceObj = CurrentDisplaySurface(descriptor);
249
+ if (surfaceObj == nil) {
250
+ return; // transient — the connection may not have a frame ready yet, try again next tick
251
+ }
252
+ IOSurfaceRef surface = (__bridge IOSurfaceRef)surfaceObj;
253
+ uint32_t seed = IOSurfaceGetSeed(surface);
254
+ if (seed == lastSeed_) {
255
+ return; // unchanged since the last tick — mirrors CoreSimulator's own recorder, which
256
+ // only encodes a frame when the display actually changes (see CLAUDE.md)
257
+ }
258
+ // Only commit the new seed once EncodeSurface actually submits it — a transient failure
259
+ // (pixel-buffer creation) must leave lastSeed_ stale so the next tick retries this same
260
+ // frame instead of silently going quiet until the display changes again.
261
+ if (EncodeSurface(surface)) {
262
+ lastSeed_ = seed;
263
+ }
264
+ } catch (const std::exception& e) {
265
+ // Without this, an exception here (e.g. a dropped display-proxy connection) would escape
266
+ // this bare GCD timer handler uncaught and crash the whole process (see CLAUDE.md).
267
+ if (onError_) {
268
+ onError_(MakeError(3, [NSString stringWithFormat:@"Video stream encoding failed: %s", e.what()]));
269
+ }
270
+ StopFromQueue();
271
+ }
272
+ }
273
+ }
274
+
275
+ bool SetUpSession(IOSurfaceRef surface, NSError** error) {
276
+ int32_t width = static_cast<int32_t>(IOSurfaceGetWidth(surface));
277
+ int32_t height = static_cast<int32_t>(IOSurfaceGetHeight(surface));
278
+ CMVideoCodecType codecType =
279
+ options_.codec == VideoStreamCodec::kHEVC ? kCMVideoCodecType_HEVC : kCMVideoCodecType_H264;
280
+ OSStatus status = VTCompressionSessionCreate(kCFAllocatorDefault, width, height, codecType, nullptr, nullptr,
281
+ kCFAllocatorDefault, OutputCallback, this, &session_);
282
+ if (status != noErr) {
283
+ *error = MakeStatusError(1, @"Failed to create a VTCompressionSession", status);
284
+ return false;
285
+ }
286
+ // Clamped like Start()'s timer interval — an unvalidated 0 here would set MaxKeyFrameInterval
287
+ // to an out-of-spec value.
288
+ double fps = std::max(options_.fps, 1.0);
289
+ status = VTSessionSetProperty(session_, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
290
+ if (status == noErr) {
291
+ status = VTSessionSetProperty(session_, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse);
292
+ }
293
+ if (status == noErr) {
294
+ status = VTSessionSetProperty(session_, kVTCompressionPropertyKey_AverageBitRate,
295
+ (__bridge CFNumberRef) @(options_.bitrate));
296
+ }
297
+ if (status == noErr) {
298
+ status =
299
+ VTSessionSetProperty(session_, kVTCompressionPropertyKey_ExpectedFrameRate, (__bridge CFNumberRef) @(fps));
300
+ }
301
+ if (status == noErr) {
302
+ status = VTSessionSetProperty(session_, kVTCompressionPropertyKey_MaxKeyFrameInterval,
303
+ (__bridge CFNumberRef) @(static_cast<int>(fps * 2)));
304
+ }
305
+ if (status != noErr) {
306
+ *error = MakeStatusError(2, @"Failed to configure the VTCompressionSession", status);
307
+ VTCompressionSessionInvalidate(session_);
308
+ CFRelease(session_);
309
+ session_ = nullptr;
310
+ return false;
311
+ }
312
+ VTCompressionSessionPrepareToEncodeFrames(session_);
313
+ return true;
314
+ }
315
+
316
+ // Returns whether a frame was actually submitted to the encoder — false for a transient
317
+ // pixel-buffer creation failure the caller should retry, as opposed to a real encode failure
318
+ // (thrown, not returned, since that tears down the whole stream).
319
+ bool EncodeSurface(IOSurfaceRef surface) {
320
+ CVPixelBufferRef pixelBuffer = nullptr;
321
+ CVReturn cvStatus = CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, surface, nullptr, &pixelBuffer);
322
+ if (cvStatus != kCVReturnSuccess || pixelBuffer == nullptr) {
323
+ return false; // transient — try again next tick rather than tearing down the whole stream
324
+ }
325
+ CMTime pts = CMTimeMake(static_cast<int64_t>((MonotonicSeconds() - startTime_) * 1000000), 1000000);
326
+ NSDictionary* frameProperties = nil;
327
+ if (forceKeyFrame_.exchange(false)) {
328
+ frameProperties = @{(__bridge NSString*)kVTEncodeFrameOptionKey_ForceKeyFrame : @YES};
329
+ }
330
+ OSStatus status = VTCompressionSessionEncodeFrame(session_, pixelBuffer, pts, kCMTimeInvalid,
331
+ (__bridge CFDictionaryRef)frameProperties, nullptr, nullptr);
332
+ CVPixelBufferRelease(pixelBuffer);
333
+ if (status != noErr) {
334
+ throw std::runtime_error([[NSString stringWithFormat:@"VTCompressionSessionEncodeFrame failed (OSStatus %d)",
335
+ static_cast<int>(status)] UTF8String]);
336
+ }
337
+ return true;
338
+ }
339
+
340
+ static void OutputCallback(void* outputCallbackRefCon, void* /*sourceFrameRefCon*/, OSStatus status,
341
+ VTEncodeInfoFlags /*infoFlags*/, CMSampleBufferRef sampleBuffer) {
342
+ static_cast<Impl*>(outputCallbackRefCon)->HandleEncodedSample(status, sampleBuffer);
343
+ }
344
+
345
+ void HandleEncodedSample(OSStatus status, CMSampleBufferRef sampleBuffer) {
346
+ if (!running_) {
347
+ return;
348
+ }
349
+ if (status != noErr) {
350
+ // Only the first failure is reported — pendingErrorTeardown_ doubles as the report-once
351
+ // gate, since Tick() (the only place that consumes it) only ever needs to see it once too.
352
+ if (!pendingErrorTeardown_.exchange(true)) {
353
+ if (onError_) {
354
+ onError_(MakeStatusError(3, @"VideoToolbox reported an encoding failure", status));
355
+ }
356
+ }
357
+ return;
358
+ }
359
+ if (sampleBuffer == nullptr) {
360
+ return;
361
+ }
362
+ bool isKeyFrame = true;
363
+ CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, false);
364
+ if (attachments != nullptr && CFArrayGetCount(attachments) > 0) {
365
+ CFDictionaryRef attachment = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
366
+ isKeyFrame = !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
367
+ }
368
+
369
+ // From the sample's own presentation timestamp (as submitted in EncodeSurface), not a fresh
370
+ // wall-clock read here — this callback can fire well after encoding actually happened, and
371
+ // resampling "now" would report a later, jittery timestamp than when the frame was captured.
372
+ CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
373
+ VideoAccessUnit unit;
374
+ unit.isKeyFrame = isKeyFrame;
375
+ unit.sequence = sequence_++;
376
+ unit.timestampMicros = pts.timescale != 0 ? (pts.value * 1000000 / pts.timescale) : 0;
377
+ if (isKeyFrame) {
378
+ CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
379
+ if (format != nullptr) {
380
+ if (options_.codec == VideoStreamCodec::kHEVC) {
381
+ AppendParameterSets(unit.data, format, CMVideoFormatDescriptionGetHEVCParameterSetAtIndex);
382
+ } else {
383
+ AppendParameterSets(unit.data, format, CMVideoFormatDescriptionGetH264ParameterSetAtIndex);
384
+ }
385
+ }
386
+ }
387
+ AppendSampleBufferNALs(unit.data, sampleBuffer);
388
+ if (onAccessUnit_) {
389
+ onAccessUnit_(std::move(unit));
390
+ }
391
+ }
392
+
393
+ id device_;
394
+ VideoStreamOptions options_;
395
+ std::function<void(VideoAccessUnit)> onAccessUnit_;
396
+ std::function<void(NSError*)> onError_;
397
+ std::function<void()> onEnd_;
398
+
399
+ dispatch_queue_t queue_ = nullptr;
400
+ dispatch_source_t timer_ = nullptr;
401
+ VTCompressionSessionRef session_ = nullptr;
402
+ uint32_t lastSeed_ = 0;
403
+ // VideoToolbox's output callback isn't documented as single-threaded, so this is read-modify-
404
+ // written atomically rather than assuming HandleEncodedSample never runs concurrently.
405
+ std::atomic<uint64_t> sequence_{0};
406
+ double startTime_ = 0;
407
+ std::atomic<bool> running_{false};
408
+ // Set by HandleEncodedSample (possibly off queue_) on an encoder failure, consumed by the next
409
+ // Tick() (on queue_) — see both for why teardown can't just happen inline there.
410
+ std::atomic<bool> pendingErrorTeardown_{false};
411
+ std::atomic<bool> forceKeyFrame_{false};
412
+ };
413
+
414
+ VideoStreamSession::VideoStreamSession(id device, VideoStreamOptions options,
415
+ std::function<void(VideoAccessUnit)> onAccessUnit,
416
+ std::function<void(NSError*)> onError, std::function<void()> onEnd)
417
+ : impl_(std::make_unique<Impl>(device, options, std::move(onAccessUnit), std::move(onError), std::move(onEnd))) {}
418
+
419
+ VideoStreamSession::~VideoStreamSession() = default;
420
+
421
+ void VideoStreamSession::Start() { impl_->Start(); }
422
+
423
+ void VideoStreamSession::Stop() { impl_->Stop(); }
424
+
425
+ void VideoStreamSession::RequestKeyFrame() { impl_->RequestKeyFrame(); }
426
+
427
+ } // namespace coresim
@@ -49,6 +49,8 @@ import {
49
49
  setContentSize,
50
50
  setIncreaseContrast,
51
51
  } from './commands/ui.js';
52
+ import {isVideoRecording, startVideoRecording, stopVideoRecording} from './commands/video-recording.js';
53
+ import {startVideoStream} from './commands/video-stream.js';
52
54
  import {getWebInspectorSocket} from './commands/webinspector.js';
53
55
  // Bare re-imports so `declare module './native-simctl.js'` augmentations in the command modules
54
56
  // (which add their methods to NativeSimctl's type) reach downstream consumers' emitted .d.ts
@@ -68,6 +70,8 @@ import './commands/process.js';
68
70
  import './commands/screenshot.js';
69
71
  import './commands/spawn.js';
70
72
  import './commands/ui.js';
73
+ import './commands/video-recording.js';
74
+ import './commands/video-stream.js';
71
75
  import './commands/webinspector.js';
72
76
  import {NativeSimUnavailableError} from './errors.js';
73
77
  import type {
@@ -247,6 +251,12 @@ Object.assign(NativeSimctl.prototype, {
247
251
  getScreenshot,
248
252
  getDisplays,
249
253
 
254
+ // video recording
255
+ startVideoRecording,
256
+ stopVideoRecording,
257
+ isVideoRecording,
258
+ startVideoStream,
259
+
250
260
  // webinspector
251
261
  getWebInspectorSocket,
252
262
 
package/src/types.ts CHANGED
@@ -128,6 +128,54 @@ export interface ScreenshotOptions {
128
128
  quality?: number;
129
129
  }
130
130
 
131
+ /** Options for `NativeSimctl.startVideoRecording`. */
132
+ export interface VideoRecordingOptions {
133
+ /**
134
+ * Which display to record, by `id` from `getDisplays()`. Defaults to the primary display
135
+ * (falling back to the first renderable display if none is primary, e.g. tvOS).
136
+ */
137
+ displayId?: string;
138
+ /** Video codec — `'h264'` (default) or `'hevc'`. */
139
+ codec?: 'h264' | 'hevc';
140
+ /**
141
+ * For a non-rectangular display (e.g. a Dynamic Island cutout): `'ignored'` (default) saves the
142
+ * unmasked framebuffer, `'black'` renders the mask black, `'alpha'` is not supported and
143
+ * behaves like `'black'`.
144
+ */
145
+ mask?: 'ignored' | 'alpha' | 'black';
146
+ }
147
+
148
+ /** Options for `NativeSimctl.startVideoStream`. */
149
+ export interface VideoStreamOptions {
150
+ /**
151
+ * Which display to stream, by `id` from `getDisplays()`. Defaults to the primary display
152
+ * (falling back to the first renderable display if none is primary, e.g. tvOS).
153
+ */
154
+ displayId?: string;
155
+ /** Video codec — `'h264'` (default) or `'hevc'`. */
156
+ codec?: 'h264' | 'hevc';
157
+ /**
158
+ * Max frames/sec to poll the framebuffer at — an unchanged frame is never re-encoded, so this
159
+ * is an upper bound, not a guarantee. Must be >= 1. Defaults to 15.
160
+ */
161
+ fps?: number;
162
+ /** Target average bitrate, in bits/sec. Defaults to 2,000,000 (2 Mbps). */
163
+ bitrate?: number;
164
+ }
165
+
166
+ /**
167
+ * One encoded frame from `VideoStream.accessUnits()` — Annex-B NAL units. A keyframe's `data` has
168
+ * parameter sets (SPS/PPS, or VPS/SPS/PPS for HEVC) prepended, so it's self-decodable alone.
169
+ */
170
+ export interface VideoAccessUnit {
171
+ data: Buffer;
172
+ isKeyFrame: boolean;
173
+ /** Monotonically increasing per stream, starting at 0. */
174
+ sequence: number;
175
+ /** Microseconds since the stream started. */
176
+ timestampMicros: number;
177
+ }
178
+
131
179
  /**
132
180
  * Options for `NativeSimctl.spawnProcess`, passed through to CoreSimulator's
133
181
  * `spawnWithPath:options:terminationQueue:terminationHandler:error:`. Only keys confirmed
@@ -230,6 +278,24 @@ export interface NativeSpawnResult {
230
278
  */
231
279
  export type NativeSpawnExitCallback = (code: number | null, signal: number | null) => void;
232
280
 
281
+ /** Raw shape of an access unit as the native addon delivers it — see {@link VideoAccessUnit}. */
282
+ export interface NativeVideoAccessUnit {
283
+ data: Buffer;
284
+ isKeyFrame: boolean;
285
+ sequence: number;
286
+ timestampMicros: number;
287
+ }
288
+
289
+ export type NativeVideoAccessUnitCallback = (unit: NativeVideoAccessUnit) => void;
290
+ export type NativeVideoErrorCallback = (err: Error) => void;
291
+
292
+ /** A live encoder session, wrapped by `coresim.mm`'s `NativeVideoStream` — what `NativeDeviceHandle.startVideoStream()` resolves to. */
293
+ export interface NativeVideoStreamHandle {
294
+ stop(): Promise<void>;
295
+ /** Forces the next encoded frame to be a keyframe — trivial in-memory flag, so synchronous. */
296
+ requestKeyFrame(): void;
297
+ }
298
+
233
299
  /** A `SimDevice`, wrapped by `coresim.mm`'s `NativeDevice` — what `NativeSimctl`'s `_findDevice()` resolves to. */
234
300
  export interface NativeDeviceHandle {
235
301
  // Trivial in-memory accessors — kept synchronous on the native side (see coresim.mm), never a
@@ -278,6 +344,16 @@ export interface NativeDeviceHandle {
278
344
  getWebInspectorSocket(): Promise<string>;
279
345
  screenshot(options?: {format?: 'png' | 'jpeg'; displayId?: string; quality?: number}): Promise<Buffer>;
280
346
  getDisplays(): Promise<SimDisplayInfo[]>;
347
+ startVideoRecording(
348
+ outputFile: string,
349
+ options?: {displayId?: string; codec?: 'h264' | 'hevc'; mask?: 'ignored' | 'alpha' | 'black'},
350
+ ): Promise<void>;
351
+ stopVideoRecording(): Promise<void>;
352
+ startVideoStream(
353
+ options: {displayId?: string; codec?: 'h264' | 'hevc'; fps?: number; bitrate?: number} | undefined,
354
+ onAccessUnit: NativeVideoAccessUnitCallback,
355
+ onError: NativeVideoErrorCallback,
356
+ ): Promise<NativeVideoStreamHandle>;
281
357
  spawn(path: string, options: SpawnOptions | undefined, onExit: NativeSpawnExitCallback): Promise<NativeSpawnResult>;
282
358
  }
283
359