@windowkit/appkit 0.31.0 → 0.33.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.
- package/README.md +103 -5
- package/binding.gyp +3 -1
- package/index.js +5 -2
- package/package.json +2 -2
- package/prebuilds/darwin-arm64/calayers.node +0 -0
- package/prebuilds/darwin-x64/calayers.node +0 -0
- package/src/addon.mm +5 -0
- package/src/capture.mm +265 -53
- package/src/displaystream.mm +775 -0
- package/src/permissions.mm +64 -3
- package/src/systemaudio.mm +876 -0
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
// @windowkit/appkit displaystream.mm — a display or a window as a stream of
|
|
2
|
+
// frames, for a renderer's screen sharing (react-x11's
|
|
3
|
+
// design/architecture/media-capture.md, `getDisplayMedia`): ScreenCaptureKit's
|
|
4
|
+
// SCStream (macOS 14), shown on a layer of its own, its frames handed over
|
|
5
|
+
// only on request — what a camera is, with the screen behind it.
|
|
6
|
+
//
|
|
7
|
+
// The windows there are to share — Screen Recording decides what is listed:
|
|
8
|
+
//
|
|
9
|
+
// - screenCaptureWindows(cb): cb([{ id, title, app: { name, bundleId, pid },
|
|
10
|
+
// x, y, width, height, active }]), the windows on screen at the normal
|
|
11
|
+
// level that are big enough to mean something, frontmost first, in points
|
|
12
|
+
// with a top-left origin; `id` is the window number captureScreenshot and
|
|
13
|
+
// openDisplayStream take. cb({ error, name }) where the list could not be
|
|
14
|
+
// had: NotAllowedError without the grant.
|
|
15
|
+
//
|
|
16
|
+
// A stream:
|
|
17
|
+
//
|
|
18
|
+
// - openDisplayStream({ display?, window?, width?, height?, frameRate?,
|
|
19
|
+
// cursor? }) -> { id, layer }: a display (a CGDirectDisplayID; the main
|
|
20
|
+
// display without either) or one window, answered at once; the stream
|
|
21
|
+
// starts on a queue of its own, and `display-started { id, width, height,
|
|
22
|
+
// frameRate }` or `display-error { id, name, message }` says how that went,
|
|
23
|
+
// `name` Media Capture's: NotAllowedError without Screen Recording,
|
|
24
|
+
// NotFoundError for a display or a window that is not there,
|
|
25
|
+
// NotSupportedError before macOS 14, NotReadableError otherwise. The frames
|
|
26
|
+
// are the source's own pixels, scaled to fit `width` x `height` with its
|
|
27
|
+
// aspect kept where one is asked; at `frameRate` at most (30 if not said),
|
|
28
|
+
// and only when something changed: a still screen sends none. `layer`
|
|
29
|
+
// shows the newest, filling its bounds.
|
|
30
|
+
// - displayStreamFrames(id, on): while on, `display-frame { id, width,
|
|
31
|
+
// height, format: 'BGRA', planes, strides, time }`, copies, in sRGB, `time`
|
|
32
|
+
// seconds on the capture clock. The newest only, as a camera's.
|
|
33
|
+
// - displayStreamCopyFrame(id, surface) -> { width, height, time, written }
|
|
34
|
+
// | null: cameraCopyFrame's contract.
|
|
35
|
+
// - displayStreamConfigure(id, { width?, height?, frameRate? }): the stream
|
|
36
|
+
// at another size or rate, without stopping — what is not said stays as it
|
|
37
|
+
// is — answered by `display-configured { id, width, height, frameRate }`,
|
|
38
|
+
// or `display-configured { id, error, name }` where it was refused, the
|
|
39
|
+
// stream running as it was.
|
|
40
|
+
// - event `display-muted { id, muted }`: the window minimized, hidden or on
|
|
41
|
+
// another space — no frames until it is back — and `display-ended { id,
|
|
42
|
+
// name?, message? }`: the window closed, the display went, the user stopped
|
|
43
|
+
// it from the menu bar's sharing indicator (`name` NotAllowedError then).
|
|
44
|
+
// A closed window is said within a second of going. closeDisplayStream(id).
|
|
45
|
+
//
|
|
46
|
+
// Frames arrive on ScreenCaptureKit's queue and cross to JS the way a
|
|
47
|
+
// camera's do (capture.mm's Deliver).
|
|
48
|
+
|
|
49
|
+
#include <napi.h>
|
|
50
|
+
#import <Cocoa/Cocoa.h>
|
|
51
|
+
#import <CoreMedia/CoreMedia.h>
|
|
52
|
+
#import <CoreVideo/CoreVideo.h>
|
|
53
|
+
#import <QuartzCore/QuartzCore.h>
|
|
54
|
+
#import <ScreenCaptureKit/ScreenCaptureKit.h>
|
|
55
|
+
#include <os/lock.h>
|
|
56
|
+
#include <pthread.h>
|
|
57
|
+
|
|
58
|
+
#include <atomic>
|
|
59
|
+
#include <cmath>
|
|
60
|
+
#include <memory>
|
|
61
|
+
#include <string>
|
|
62
|
+
#include <vector>
|
|
63
|
+
|
|
64
|
+
#include "channel.h"
|
|
65
|
+
|
|
66
|
+
// capture.mm: one count of capture ids, one way to JS
|
|
67
|
+
double CALNextCaptureId();
|
|
68
|
+
bool CALCaptureDeliver(dispatch_block_t block);
|
|
69
|
+
// video.mm
|
|
70
|
+
bool CALPixelBufferToBGRA(Napi::Env env, const char* verb, CVPixelBufferRef pb, uint8_t* dst,
|
|
71
|
+
size_t dstStride);
|
|
72
|
+
bool CALVideoTargetBitmap(Napi::Value v, uint8_t** data, size_t* width, size_t* height,
|
|
73
|
+
size_t* bytesPerRow);
|
|
74
|
+
// backend.mm
|
|
75
|
+
void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep);
|
|
76
|
+
|
|
77
|
+
static void Send(CALEvent ev) {
|
|
78
|
+
auto held = std::make_shared<CALEvent>(std::move(ev));
|
|
79
|
+
CALCaptureDeliver(^{
|
|
80
|
+
if (CALListening()) CALEmit(std::move(*held));
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static bool OptNum(Napi::Value obj, const char* k, double* out) {
|
|
85
|
+
if (!obj.IsObject()) return false;
|
|
86
|
+
Napi::Object o = obj.As<Napi::Object>();
|
|
87
|
+
if (!o.Has(k)) return false;
|
|
88
|
+
Napi::Value v = o.Get(k);
|
|
89
|
+
if (!v.IsNumber()) return false;
|
|
90
|
+
double d = v.As<Napi::Number>().DoubleValue();
|
|
91
|
+
if (!std::isfinite(d)) return false;
|
|
92
|
+
*out = d;
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
static bool OptBool(Napi::Value obj, const char* k, bool* out) {
|
|
97
|
+
if (!obj.IsObject()) return false;
|
|
98
|
+
Napi::Object o = obj.As<Napi::Object>();
|
|
99
|
+
if (!o.Has(k)) return false;
|
|
100
|
+
Napi::Value v = o.Get(k);
|
|
101
|
+
if (!v.IsBoolean()) return false;
|
|
102
|
+
*out = v.As<Napi::Boolean>().Value();
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
static void StreamError(double sid, const char* name, NSString* message) {
|
|
107
|
+
CALEvent ev("display-error");
|
|
108
|
+
ev.Num("id", sid).Str("name", name).Str("message", message.UTF8String ?: "");
|
|
109
|
+
Send(std::move(ev));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Media Capture's name for what ScreenCaptureKit said. */
|
|
113
|
+
static const char* NameOf(NSError* error) API_AVAILABLE(macos(12.3)) {
|
|
114
|
+
if (!error) return "NotReadableError";
|
|
115
|
+
if ([error.domain isEqualToString:SCStreamErrorDomain]) {
|
|
116
|
+
switch (error.code) {
|
|
117
|
+
case SCStreamErrorUserDeclined:
|
|
118
|
+
case SCStreamErrorUserStopped:
|
|
119
|
+
return "NotAllowedError";
|
|
120
|
+
case SCStreamErrorNoDisplayList:
|
|
121
|
+
case SCStreamErrorNoWindowList:
|
|
122
|
+
case SCStreamErrorAttemptToStartStreamState:
|
|
123
|
+
return "NotReadableError";
|
|
124
|
+
default:
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return "NotReadableError";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// a stream
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
API_AVAILABLE(macos(12.3))
|
|
136
|
+
@interface CALDisplayStream : NSObject <SCStreamOutput, SCStreamDelegate>
|
|
137
|
+
@property(nonatomic) double sid;
|
|
138
|
+
@property(atomic, strong) SCStream* stream;
|
|
139
|
+
@property(atomic, strong) CALayer* layer;
|
|
140
|
+
@property(nonatomic, strong) dispatch_queue_t queue;
|
|
141
|
+
@property(atomic) BOOL closed;
|
|
142
|
+
- (void)endedWith:(NSError*)error;
|
|
143
|
+
// the stream's queue's: the source's size in pixels, and what it runs at
|
|
144
|
+
@property(nonatomic) double sourceWidth, sourceHeight, width, height, rate;
|
|
145
|
+
@property(nonatomic) BOOL cursor;
|
|
146
|
+
// the window streamed, or 0 for a display
|
|
147
|
+
@property(nonatomic) double windowID;
|
|
148
|
+
@end
|
|
149
|
+
|
|
150
|
+
@implementation CALDisplayStream {
|
|
151
|
+
os_unfair_lock _lock;
|
|
152
|
+
CVPixelBufferRef _latest; // for a copy; retained
|
|
153
|
+
double _latestTime;
|
|
154
|
+
uint64_t _latestSeq, _copiedSeq;
|
|
155
|
+
CVPixelBufferRef _pending; // for JS, while on its way; retained
|
|
156
|
+
double _pendingTime;
|
|
157
|
+
bool _scheduled;
|
|
158
|
+
std::atomic<bool> _frames;
|
|
159
|
+
bool _suspended; // the stream's queue's
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
- (instancetype)init {
|
|
163
|
+
if ((self = [super init])) {
|
|
164
|
+
_lock = OS_UNFAIR_LOCK_INIT;
|
|
165
|
+
_frames = false;
|
|
166
|
+
}
|
|
167
|
+
return self;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
- (void)dealloc {
|
|
171
|
+
if (_latest) CVPixelBufferRelease(_latest);
|
|
172
|
+
if (_pending) CVPixelBufferRelease(_pending);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The stream's queue. ScreenCaptureKit suspends a window's stream for two
|
|
176
|
+
// reasons it does not tell apart — the window minimized, hidden or on
|
|
177
|
+
// another space, and the window gone — and says nothing more either way: no
|
|
178
|
+
// error, no stop, no frame. So a suspension is a mute, and the window is
|
|
179
|
+
// looked for while it lasts: one the window server no longer lists ends the
|
|
180
|
+
// stream.
|
|
181
|
+
- (void)suspend {
|
|
182
|
+
if (_suspended || self.closed) return;
|
|
183
|
+
_suspended = true;
|
|
184
|
+
[self sendMuted:true];
|
|
185
|
+
[self lookForWindow];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
- (void)resume {
|
|
189
|
+
if (!_suspended) return;
|
|
190
|
+
_suspended = false;
|
|
191
|
+
[self sendMuted:false];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
- (void)sendMuted:(bool)muted {
|
|
195
|
+
CALEvent ev("display-muted");
|
|
196
|
+
ev.Num("id", self.sid).Bool("muted", muted);
|
|
197
|
+
Send(std::move(ev));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
- (void)lookForWindow {
|
|
201
|
+
if (!_suspended || self.closed || self.windowID == 0) return;
|
|
202
|
+
CFArrayRef list = CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, (CGWindowID)self.windowID);
|
|
203
|
+
bool there = list && CFArrayGetCount(list) > 0;
|
|
204
|
+
if (list) CFRelease(list);
|
|
205
|
+
if (!there) {
|
|
206
|
+
[self endedWith:nil];
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
__weak CALDisplayStream* weak = self;
|
|
210
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), self.queue, ^{
|
|
211
|
+
[weak lookForWindow];
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
- (void)setFramesOn:(bool)on {
|
|
216
|
+
_frames = on;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
- (CVPixelBufferRef)takeNewest:(double*)time {
|
|
220
|
+
os_unfair_lock_lock(&_lock);
|
|
221
|
+
CVPixelBufferRef pb = nullptr;
|
|
222
|
+
if (_latest && _latestSeq != _copiedSeq) {
|
|
223
|
+
pb = CVPixelBufferRetain(_latest);
|
|
224
|
+
*time = _latestTime;
|
|
225
|
+
_copiedSeq = _latestSeq;
|
|
226
|
+
}
|
|
227
|
+
os_unfair_lock_unlock(&_lock);
|
|
228
|
+
return pb;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ScreenCaptureKit's queue: a frame, which is news only when it is complete —
|
|
232
|
+
// an idle frame says nothing changed, and carries no picture of its own.
|
|
233
|
+
- (void)stream:(SCStream*)stream
|
|
234
|
+
didOutputSampleBuffer:(CMSampleBufferRef)sample
|
|
235
|
+
ofType:(SCStreamOutputType)type {
|
|
236
|
+
if (type != SCStreamOutputTypeScreen || self.closed) return;
|
|
237
|
+
if (!CMSampleBufferIsValid(sample)) return;
|
|
238
|
+
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sample, false);
|
|
239
|
+
if (!attachments || CFArrayGetCount(attachments) == 0) return;
|
|
240
|
+
NSDictionary* info = (__bridge NSDictionary*)CFArrayGetValueAtIndex(attachments, 0);
|
|
241
|
+
NSNumber* status = info[SCStreamFrameInfoStatus];
|
|
242
|
+
if (!status) return;
|
|
243
|
+
switch ((SCFrameStatus)status.integerValue) {
|
|
244
|
+
case SCFrameStatusSuspended:
|
|
245
|
+
[self suspend];
|
|
246
|
+
return;
|
|
247
|
+
case SCFrameStatusStopped:
|
|
248
|
+
[self endedWith:nil];
|
|
249
|
+
return;
|
|
250
|
+
case SCFrameStatusComplete:
|
|
251
|
+
[self resume];
|
|
252
|
+
break;
|
|
253
|
+
default:
|
|
254
|
+
// idle (nothing changed), blank, started: no picture of their own
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
CVPixelBufferRef pb = CMSampleBufferGetImageBuffer(sample);
|
|
258
|
+
if (!pb) return;
|
|
259
|
+
double time = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sample));
|
|
260
|
+
|
|
261
|
+
// the layer shows it: its own transaction, actions off, so a frame is a
|
|
262
|
+
// flip and not a crossfade
|
|
263
|
+
IOSurfaceRef surface = CVPixelBufferGetIOSurface(pb);
|
|
264
|
+
CALayer* layer = self.layer;
|
|
265
|
+
if (surface && layer) {
|
|
266
|
+
CALNameSurfaceSRGB(surface, true);
|
|
267
|
+
id contents = (__bridge id)surface;
|
|
268
|
+
[CATransaction begin];
|
|
269
|
+
[CATransaction setDisableActions:YES];
|
|
270
|
+
layer.contents = contents;
|
|
271
|
+
[CATransaction commit];
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
bool schedule = false;
|
|
275
|
+
os_unfair_lock_lock(&_lock);
|
|
276
|
+
if (_latest) CVPixelBufferRelease(_latest);
|
|
277
|
+
_latest = CVPixelBufferRetain(pb);
|
|
278
|
+
_latestTime = time;
|
|
279
|
+
_latestSeq++;
|
|
280
|
+
if (_frames.load()) {
|
|
281
|
+
if (_pending) CVPixelBufferRelease(_pending);
|
|
282
|
+
_pending = CVPixelBufferRetain(pb);
|
|
283
|
+
_pendingTime = time;
|
|
284
|
+
schedule = !_scheduled;
|
|
285
|
+
_scheduled = true;
|
|
286
|
+
}
|
|
287
|
+
os_unfair_lock_unlock(&_lock);
|
|
288
|
+
if (!schedule) return;
|
|
289
|
+
__weak CALDisplayStream* weak = self;
|
|
290
|
+
if (!CALCaptureDeliver(^{
|
|
291
|
+
CALDisplayStream* s = weak;
|
|
292
|
+
if (s) [s sendPending];
|
|
293
|
+
})) {
|
|
294
|
+
os_unfair_lock_lock(&_lock);
|
|
295
|
+
_scheduled = false;
|
|
296
|
+
os_unfair_lock_unlock(&_lock);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Where JS is: the frame waiting, as the event — the newest by now.
|
|
301
|
+
- (void)sendPending {
|
|
302
|
+
os_unfair_lock_lock(&_lock);
|
|
303
|
+
CVPixelBufferRef pb = _pending;
|
|
304
|
+
double time = _pendingTime;
|
|
305
|
+
_pending = nullptr;
|
|
306
|
+
_scheduled = false;
|
|
307
|
+
os_unfair_lock_unlock(&_lock);
|
|
308
|
+
if (!pb) return;
|
|
309
|
+
if (self.closed || !_frames.load() || !CALListening() ||
|
|
310
|
+
CVPixelBufferGetPixelFormatType(pb) != kCVPixelFormatType_32BGRA) {
|
|
311
|
+
CVPixelBufferRelease(pb);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
|
|
315
|
+
size_t bpr = CVPixelBufferGetBytesPerRow(pb);
|
|
316
|
+
size_t rows = CVPixelBufferGetHeight(pb);
|
|
317
|
+
NSData* plane = [NSData dataWithBytes:CVPixelBufferGetBaseAddress(pb) length:bpr * rows];
|
|
318
|
+
double width = (double)CVPixelBufferGetWidth(pb), height = (double)rows;
|
|
319
|
+
CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
|
|
320
|
+
CVPixelBufferRelease(pb);
|
|
321
|
+
double stride = (double)bpr;
|
|
322
|
+
CALEvent ev("display-frame");
|
|
323
|
+
ev.Num("id", self.sid)
|
|
324
|
+
.Num("width", width)
|
|
325
|
+
.Num("height", height)
|
|
326
|
+
.Str("format", "BGRA")
|
|
327
|
+
.Num("time", time)
|
|
328
|
+
.Handle("planes",
|
|
329
|
+
^Napi::Value(Napi::Env env) {
|
|
330
|
+
Napi::Array a = Napi::Array::New(env, 1);
|
|
331
|
+
a.Set((uint32_t)0, Napi::Buffer<uint8_t>::Copy(env, (const uint8_t*)plane.bytes, plane.length));
|
|
332
|
+
return a;
|
|
333
|
+
})
|
|
334
|
+
.Handle("strides", ^Napi::Value(Napi::Env env) {
|
|
335
|
+
Napi::Array a = Napi::Array::New(env, 1);
|
|
336
|
+
a.Set((uint32_t)0, stride);
|
|
337
|
+
return a;
|
|
338
|
+
});
|
|
339
|
+
ev.FoldBy(self.sid);
|
|
340
|
+
CALEmit(std::move(ev));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// The stream stopped of its own accord: the window closed, the display went,
|
|
344
|
+
// or the user stopped the sharing from the menu bar.
|
|
345
|
+
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {
|
|
346
|
+
[self endedWith:error];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
- (void)endedWith:(NSError*)error {
|
|
350
|
+
if (self.closed) return;
|
|
351
|
+
self.closed = YES;
|
|
352
|
+
[self dropFrames];
|
|
353
|
+
CALEvent ev("display-ended");
|
|
354
|
+
ev.Num("id", self.sid);
|
|
355
|
+
if (error) {
|
|
356
|
+
ev.Str("name", NameOf(error)).Str("message", error.localizedDescription.UTF8String ?: "");
|
|
357
|
+
}
|
|
358
|
+
Send(std::move(ev));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
- (void)dropFrames {
|
|
362
|
+
_frames = false;
|
|
363
|
+
os_unfair_lock_lock(&_lock);
|
|
364
|
+
if (_latest) CVPixelBufferRelease(_latest);
|
|
365
|
+
if (_pending) CVPixelBufferRelease(_pending);
|
|
366
|
+
_latest = _pending = nullptr;
|
|
367
|
+
os_unfair_lock_unlock(&_lock);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
- (void)stop {
|
|
371
|
+
self.closed = YES;
|
|
372
|
+
[self dropFrames];
|
|
373
|
+
SCStream* stream = self.stream;
|
|
374
|
+
self.stream = nil;
|
|
375
|
+
if (stream) [stream stopCaptureWithCompletionHandler:^(NSError*) {}];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
@end
|
|
379
|
+
|
|
380
|
+
static NSMutableDictionary<NSNumber*, id>* gStreams;
|
|
381
|
+
|
|
382
|
+
static NSObject* StreamsLock() {
|
|
383
|
+
static NSObject* lock;
|
|
384
|
+
static dispatch_once_t once;
|
|
385
|
+
dispatch_once(&once, ^{
|
|
386
|
+
lock = [NSObject new];
|
|
387
|
+
});
|
|
388
|
+
return lock;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
static CALDisplayStream* StreamFor(double sid) API_AVAILABLE(macos(12.3)) {
|
|
392
|
+
@synchronized(StreamsLock()) {
|
|
393
|
+
return gStreams[@(sid)];
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
static void Forget(double sid) {
|
|
398
|
+
@synchronized(StreamsLock()) {
|
|
399
|
+
[gStreams removeObjectForKey:@(sid)];
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// The size frames come at: the source's pixels, or fitted into what was
|
|
404
|
+
// asked with the aspect kept — a width alone or a height alone sets the
|
|
405
|
+
// other by the aspect. Even numbers, which every encoder downstream wants.
|
|
406
|
+
static void FitSize(double sw, double sh, double w, double h, size_t* outW, size_t* outH) {
|
|
407
|
+
double fw = sw, fh = sh;
|
|
408
|
+
if (w > 0 || h > 0) {
|
|
409
|
+
double scale = 1e9;
|
|
410
|
+
if (w > 0) scale = std::min(scale, w / sw);
|
|
411
|
+
if (h > 0) scale = std::min(scale, h / sh);
|
|
412
|
+
fw = sw * scale;
|
|
413
|
+
fh = sh * scale;
|
|
414
|
+
}
|
|
415
|
+
*outW = std::max<size_t>(2, (size_t)llround(fw / 2) * 2);
|
|
416
|
+
*outH = std::max<size_t>(2, (size_t)llround(fh / 2) * 2);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// What a stream runs at, as ScreenCaptureKit takes it: BGRA in sRGB, which
|
|
420
|
+
// is what a layer shows and an encoder reads without asking.
|
|
421
|
+
static SCStreamConfiguration* ConfigFor(CALDisplayStream* s) API_AVAILABLE(macos(14.0)) {
|
|
422
|
+
SCStreamConfiguration* config = [SCStreamConfiguration new];
|
|
423
|
+
config.width = (size_t)s.width;
|
|
424
|
+
config.height = (size_t)s.height;
|
|
425
|
+
config.minimumFrameInterval = CMTimeMake(1000, (int32_t)llround(s.rate * 1000));
|
|
426
|
+
config.pixelFormat = kCVPixelFormatType_32BGRA;
|
|
427
|
+
config.colorSpaceName = kCGColorSpaceSRGB;
|
|
428
|
+
config.showsCursor = s.cursor;
|
|
429
|
+
config.queueDepth = 5;
|
|
430
|
+
config.ignoreShadowsSingleWindow = YES;
|
|
431
|
+
return config;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
struct StreamAsk {
|
|
435
|
+
bool hasDisplay = false, hasWindow = false, cursor = true;
|
|
436
|
+
double display = 0, window = 0, width = 0, height = 0, rate = 30;
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
static void StreamStarted(CALDisplayStream* s, SCStream* stream, NSError* error) API_AVAILABLE(macos(14.0)) {
|
|
440
|
+
if (s.closed) {
|
|
441
|
+
// closed while it started: `stop` may have run before there was a stream
|
|
442
|
+
if (!error) [stream stopCaptureWithCompletionHandler:^(NSError*) {}];
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
if (error) {
|
|
446
|
+
s.closed = YES;
|
|
447
|
+
s.stream = nil;
|
|
448
|
+
StreamError(s.sid, NameOf(error), error.localizedDescription ?: @"the stream did not start");
|
|
449
|
+
Forget(s.sid);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
CALEvent ev("display-started");
|
|
453
|
+
ev.Num("id", s.sid).Num("width", s.width).Num("height", s.height).Num("frameRate", s.rate);
|
|
454
|
+
Send(std::move(ev));
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// On the stream's queue, which `stop` runs on too, so a close lands before
|
|
458
|
+
// the stream is made or after it, never between: the filter for what was
|
|
459
|
+
// asked, out of what ScreenCaptureKit listed, and the stream started on it.
|
|
460
|
+
static void MakeStream(CALDisplayStream* s, StreamAsk ask, SCShareableContent* content, NSError* error)
|
|
461
|
+
API_AVAILABLE(macos(14.0)) {
|
|
462
|
+
if (s.closed) return;
|
|
463
|
+
if (error || !content) {
|
|
464
|
+
bool declined = error.code == SCStreamErrorUserDeclined;
|
|
465
|
+
StreamError(s.sid, declined ? "NotAllowedError" : "NotReadableError",
|
|
466
|
+
declined ? @"Screen Recording is not allowed for this app (Privacy & Security › Screen Recording)"
|
|
467
|
+
: (error.localizedDescription ?: @"the screen could not be listed"));
|
|
468
|
+
Forget(s.sid);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
SCContentFilter* filter = nil;
|
|
472
|
+
if (ask.hasWindow) {
|
|
473
|
+
for (SCWindow* w in content.windows) {
|
|
474
|
+
if (w.windowID == (CGWindowID)ask.window) {
|
|
475
|
+
filter = [[SCContentFilter alloc] initWithDesktopIndependentWindow:w];
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
} else {
|
|
480
|
+
CGDirectDisplayID want = ask.hasDisplay ? (CGDirectDisplayID)ask.display : CGMainDisplayID();
|
|
481
|
+
for (SCDisplay* d in content.displays) {
|
|
482
|
+
if (d.displayID == want) {
|
|
483
|
+
filter = [[SCContentFilter alloc] initWithDisplay:d excludingWindows:@[]];
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
if (!filter) {
|
|
489
|
+
StreamError(s.sid, "NotFoundError", ask.hasWindow ? @"there is no such window" : @"there is no such display");
|
|
490
|
+
Forget(s.sid);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
double scale = filter.pointPixelScale;
|
|
494
|
+
s.sourceWidth = filter.contentRect.size.width * scale;
|
|
495
|
+
s.sourceHeight = filter.contentRect.size.height * scale;
|
|
496
|
+
size_t w = 0, h = 0;
|
|
497
|
+
FitSize(s.sourceWidth, s.sourceHeight, ask.width, ask.height, &w, &h);
|
|
498
|
+
s.width = (double)w;
|
|
499
|
+
s.height = (double)h;
|
|
500
|
+
s.rate = ask.rate > 0 ? std::min(ask.rate, 120.0) : 30;
|
|
501
|
+
s.cursor = ask.cursor;
|
|
502
|
+
s.windowID = ask.hasWindow ? ask.window : 0;
|
|
503
|
+
SCStream* stream = [[SCStream alloc] initWithFilter:filter configuration:ConfigFor(s) delegate:s];
|
|
504
|
+
NSError* addError = nil;
|
|
505
|
+
if (![stream addStreamOutput:s type:SCStreamOutputTypeScreen sampleHandlerQueue:s.queue error:&addError]) {
|
|
506
|
+
StreamError(s.sid, "NotReadableError", addError.localizedDescription ?: @"the stream took no output");
|
|
507
|
+
Forget(s.sid);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
s.stream = stream;
|
|
511
|
+
[stream startCaptureWithCompletionHandler:^(NSError* startError) {
|
|
512
|
+
StreamStarted(s, stream, startError);
|
|
513
|
+
}];
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
static void StartStream(CALDisplayStream* s, StreamAsk ask) API_AVAILABLE(macos(14.0)) {
|
|
517
|
+
[SCShareableContent getShareableContentExcludingDesktopWindows:NO
|
|
518
|
+
onScreenWindowsOnly:!ask.hasWindow
|
|
519
|
+
completionHandler:^(SCShareableContent* content, NSError* error) {
|
|
520
|
+
dispatch_async(s.queue, ^{
|
|
521
|
+
MakeStream(s, ask, content, error);
|
|
522
|
+
});
|
|
523
|
+
}];
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
static Napi::Value OpenDisplayStream(const Napi::CallbackInfo& info) {
|
|
527
|
+
Napi::Env env = info.Env();
|
|
528
|
+
Napi::Value opts = info.Length() > 0 ? info[0] : env.Undefined();
|
|
529
|
+
StreamAsk ask;
|
|
530
|
+
ask.hasDisplay = OptNum(opts, "display", &ask.display);
|
|
531
|
+
ask.hasWindow = OptNum(opts, "window", &ask.window);
|
|
532
|
+
OptNum(opts, "width", &ask.width);
|
|
533
|
+
OptNum(opts, "height", &ask.height);
|
|
534
|
+
OptNum(opts, "frameRate", &ask.rate);
|
|
535
|
+
OptBool(opts, "cursor", &ask.cursor);
|
|
536
|
+
double sid = CALNextCaptureId();
|
|
537
|
+
Napi::Object out = Napi::Object::New(env);
|
|
538
|
+
out.Set("id", sid);
|
|
539
|
+
if (@available(macOS 14.0, *)) {
|
|
540
|
+
CALDisplayStream* s = [CALDisplayStream new];
|
|
541
|
+
s.sid = sid;
|
|
542
|
+
s.queue = dispatch_queue_create("appkit.displaystream", DISPATCH_QUEUE_SERIAL);
|
|
543
|
+
@synchronized(StreamsLock()) {
|
|
544
|
+
if (!gStreams) gStreams = [NSMutableDictionary dictionary];
|
|
545
|
+
gStreams[@(sid)] = s;
|
|
546
|
+
}
|
|
547
|
+
CALayer* (^make)(void) = ^CALayer* {
|
|
548
|
+
CALayer* layer = [CALayer layer];
|
|
549
|
+
layer.contentsGravity = kCAGravityResize;
|
|
550
|
+
s.layer = layer;
|
|
551
|
+
return layer;
|
|
552
|
+
};
|
|
553
|
+
if (pthread_main_np()) {
|
|
554
|
+
void* retained = (void*)CFBridgingRetain(make());
|
|
555
|
+
out.Set("layer", Napi::External<void>::New(env, retained, [](Napi::Env, void* d) { CFRelease(d); }));
|
|
556
|
+
} else {
|
|
557
|
+
CALHandle* handle = CALNewHandle();
|
|
558
|
+
out.Set("layer", CALWrapHandle(env, handle, false));
|
|
559
|
+
CALOnUI(^{ handle->object_ = make(); });
|
|
560
|
+
}
|
|
561
|
+
dispatch_async(s.queue, ^{
|
|
562
|
+
if (!s.closed) StartStream(s, ask);
|
|
563
|
+
});
|
|
564
|
+
} else {
|
|
565
|
+
StreamError(sid, "NotSupportedError", @"streaming the screen needs macOS 14 (ScreenCaptureKit)");
|
|
566
|
+
}
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
static Napi::Value DisplayStreamFrames(const Napi::CallbackInfo& info) {
|
|
571
|
+
Napi::Env env = info.Env();
|
|
572
|
+
if (!info[0].IsNumber()) {
|
|
573
|
+
Napi::TypeError::New(env, "displayStreamFrames(id, on): id is the number openDisplayStream answered")
|
|
574
|
+
.ThrowAsJavaScriptException();
|
|
575
|
+
return env.Undefined();
|
|
576
|
+
}
|
|
577
|
+
if (@available(macOS 14.0, *)) {
|
|
578
|
+
CALDisplayStream* s = StreamFor(info[0].As<Napi::Number>().DoubleValue());
|
|
579
|
+
[s setFramesOn:info.Length() > 1 && info[1].ToBoolean().Value()];
|
|
580
|
+
}
|
|
581
|
+
return env.Undefined();
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
static Napi::Value DisplayStreamCopyFrame(const Napi::CallbackInfo& info) {
|
|
585
|
+
Napi::Env env = info.Env();
|
|
586
|
+
if (!info[0].IsNumber()) {
|
|
587
|
+
Napi::TypeError::New(env, "displayStreamCopyFrame(id, surface): id is the number openDisplayStream answered")
|
|
588
|
+
.ThrowAsJavaScriptException();
|
|
589
|
+
return env.Undefined();
|
|
590
|
+
}
|
|
591
|
+
uint8_t* data;
|
|
592
|
+
size_t sw, sh, bpr;
|
|
593
|
+
if (!CALVideoTargetBitmap(info[1], &data, &sw, &sh, &bpr)) return env.Undefined();
|
|
594
|
+
if (@available(macOS 14.0, *)) {
|
|
595
|
+
CALDisplayStream* s = StreamFor(info[0].As<Napi::Number>().DoubleValue());
|
|
596
|
+
double time = 0;
|
|
597
|
+
CVPixelBufferRef pb = [s takeNewest:&time];
|
|
598
|
+
if (!pb) return env.Null();
|
|
599
|
+
size_t w = CVPixelBufferGetWidth(pb), h = CVPixelBufferGetHeight(pb);
|
|
600
|
+
Napi::Object out = Napi::Object::New(env);
|
|
601
|
+
out.Set("width", (double)w);
|
|
602
|
+
out.Set("height", (double)h);
|
|
603
|
+
out.Set("time", time);
|
|
604
|
+
bool fits = w == sw && h == sh;
|
|
605
|
+
bool ok = !fits || CALPixelBufferToBGRA(env, "displayStreamCopyFrame", pb, data, bpr);
|
|
606
|
+
CVPixelBufferRelease(pb);
|
|
607
|
+
if (!ok) return env.Undefined();
|
|
608
|
+
out.Set("written", fits);
|
|
609
|
+
return out;
|
|
610
|
+
}
|
|
611
|
+
return env.Null();
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
static Napi::Value DisplayStreamConfigure(const Napi::CallbackInfo& info) {
|
|
615
|
+
Napi::Env env = info.Env();
|
|
616
|
+
if (!info[0].IsNumber()) {
|
|
617
|
+
Napi::TypeError::New(env, "displayStreamConfigure(id, opts): id is the number openDisplayStream answered")
|
|
618
|
+
.ThrowAsJavaScriptException();
|
|
619
|
+
return env.Undefined();
|
|
620
|
+
}
|
|
621
|
+
double sid = info[0].As<Napi::Number>().DoubleValue();
|
|
622
|
+
Napi::Value opts = info.Length() > 1 ? info[1] : env.Undefined();
|
|
623
|
+
double width = 0, height = 0, rate = 0;
|
|
624
|
+
bool hasWidth = OptNum(opts, "width", &width);
|
|
625
|
+
bool hasHeight = OptNum(opts, "height", &height);
|
|
626
|
+
bool sized = hasWidth || hasHeight;
|
|
627
|
+
bool paced = OptNum(opts, "frameRate", &rate) && rate > 0;
|
|
628
|
+
if (@available(macOS 14.0, *)) {
|
|
629
|
+
CALDisplayStream* s = StreamFor(sid);
|
|
630
|
+
if (!s) return env.Undefined();
|
|
631
|
+
dispatch_async(s.queue, ^{
|
|
632
|
+
SCStream* stream = s.stream;
|
|
633
|
+
if (s.closed || !stream) return;
|
|
634
|
+
if (sized) {
|
|
635
|
+
size_t w = 0, h = 0;
|
|
636
|
+
FitSize(s.sourceWidth, s.sourceHeight, width, height, &w, &h);
|
|
637
|
+
s.width = (double)w;
|
|
638
|
+
s.height = (double)h;
|
|
639
|
+
}
|
|
640
|
+
if (paced) s.rate = std::min(rate, 120.0);
|
|
641
|
+
double w = s.width, h = s.height, r = s.rate;
|
|
642
|
+
[stream updateConfiguration:ConfigFor(s)
|
|
643
|
+
completionHandler:^(NSError* error) {
|
|
644
|
+
CALEvent ev("display-configured");
|
|
645
|
+
ev.Num("id", sid);
|
|
646
|
+
if (error) {
|
|
647
|
+
ev.Str("name", NameOf(error)).Str("error", error.localizedDescription.UTF8String ?: "");
|
|
648
|
+
} else {
|
|
649
|
+
ev.Num("width", w).Num("height", h).Num("frameRate", r);
|
|
650
|
+
}
|
|
651
|
+
Send(std::move(ev));
|
|
652
|
+
}];
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
return env.Undefined();
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
static Napi::Value CloseDisplayStream(const Napi::CallbackInfo& info) {
|
|
659
|
+
Napi::Env env = info.Env();
|
|
660
|
+
if (!info[0].IsNumber()) return env.Undefined();
|
|
661
|
+
double sid = info[0].As<Napi::Number>().DoubleValue();
|
|
662
|
+
if (@available(macOS 14.0, *)) {
|
|
663
|
+
CALDisplayStream* s = StreamFor(sid);
|
|
664
|
+
if (!s) return env.Undefined();
|
|
665
|
+
Forget(sid);
|
|
666
|
+
// no frame shown or sent after this, whatever is on its way
|
|
667
|
+
s.closed = YES;
|
|
668
|
+
dispatch_async(s.queue, ^{
|
|
669
|
+
[s stop];
|
|
670
|
+
});
|
|
671
|
+
CALOnUI(^{
|
|
672
|
+
s.layer.contents = nil;
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
return env.Undefined();
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// ---------------------------------------------------------------------------
|
|
679
|
+
// the windows
|
|
680
|
+
// ---------------------------------------------------------------------------
|
|
681
|
+
|
|
682
|
+
struct WindowInfo {
|
|
683
|
+
double id, x, y, w, h, pid;
|
|
684
|
+
bool active;
|
|
685
|
+
std::string title, app, bundleId;
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
static CALValueBlock WindowsError(const char* name, NSString* message) {
|
|
689
|
+
std::string n = name, m = message.UTF8String ?: "";
|
|
690
|
+
return ^Napi::Value(Napi::Env env) {
|
|
691
|
+
Napi::Object o = Napi::Object::New(env);
|
|
692
|
+
o.Set("error", m);
|
|
693
|
+
o.Set("name", n);
|
|
694
|
+
return o;
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
static Napi::Value ScreenCaptureWindows(const Napi::CallbackInfo& info) {
|
|
699
|
+
Napi::Env env = info.Env();
|
|
700
|
+
Napi::Value last = info.Length() ? info[info.Length() - 1] : env.Undefined();
|
|
701
|
+
if (!last.IsFunction()) {
|
|
702
|
+
Napi::TypeError::New(env, "screenCaptureWindows(cb): expected a callback").ThrowAsJavaScriptException();
|
|
703
|
+
return env.Undefined();
|
|
704
|
+
}
|
|
705
|
+
CALTsfn tsfn = CALReplyTo(env, last.As<Napi::Function>(), "appkit:screenCaptureWindows");
|
|
706
|
+
if (@available(macOS 14.0, *)) {
|
|
707
|
+
[SCShareableContent
|
|
708
|
+
getShareableContentExcludingDesktopWindows:YES
|
|
709
|
+
onScreenWindowsOnly:YES
|
|
710
|
+
completionHandler:^(SCShareableContent* content, NSError* error) {
|
|
711
|
+
if (error || !content) {
|
|
712
|
+
bool declined = error.code == SCStreamErrorUserDeclined;
|
|
713
|
+
CALReply(tsfn, WindowsError(declined ? "NotAllowedError" : "NotReadableError",
|
|
714
|
+
declined ? @"Screen Recording is not allowed for this app "
|
|
715
|
+
@"(Privacy & Security › Screen Recording)"
|
|
716
|
+
: (error.localizedDescription ?: @"the windows could not be listed")));
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
auto list = std::make_shared<std::vector<WindowInfo>>();
|
|
720
|
+
for (SCWindow* w in content.windows) {
|
|
721
|
+
// the normal level, and big enough to be a window a person
|
|
722
|
+
// would pick: not a menu bar item, a tooltip or a shadow
|
|
723
|
+
if (w.windowLayer != 0) continue;
|
|
724
|
+
CGRect f = w.frame;
|
|
725
|
+
if (f.size.width < 40 || f.size.height < 40) continue;
|
|
726
|
+
SCRunningApplication* a = w.owningApplication;
|
|
727
|
+
WindowInfo one;
|
|
728
|
+
one.id = (double)w.windowID;
|
|
729
|
+
one.x = f.origin.x;
|
|
730
|
+
one.y = f.origin.y; // a window's frame has its origin top-left
|
|
731
|
+
one.w = f.size.width;
|
|
732
|
+
one.h = f.size.height;
|
|
733
|
+
one.pid = a ? (double)a.processID : 0;
|
|
734
|
+
one.active = w.isActive;
|
|
735
|
+
one.title = w.title.UTF8String ?: "";
|
|
736
|
+
one.app = a.applicationName.UTF8String ?: "";
|
|
737
|
+
one.bundleId = a.bundleIdentifier.UTF8String ?: "";
|
|
738
|
+
list->push_back(one);
|
|
739
|
+
}
|
|
740
|
+
CALReply(tsfn, ^Napi::Value(Napi::Env env) {
|
|
741
|
+
Napi::Array arr = Napi::Array::New(env, list->size());
|
|
742
|
+
for (size_t i = 0; i < list->size(); i++) {
|
|
743
|
+
const WindowInfo& w = (*list)[i];
|
|
744
|
+
Napi::Object o = Napi::Object::New(env);
|
|
745
|
+
o.Set("id", w.id);
|
|
746
|
+
o.Set("title", w.title);
|
|
747
|
+
Napi::Object app = Napi::Object::New(env);
|
|
748
|
+
app.Set("name", w.app);
|
|
749
|
+
app.Set("bundleId", w.bundleId);
|
|
750
|
+
app.Set("pid", w.pid);
|
|
751
|
+
o.Set("app", app);
|
|
752
|
+
o.Set("x", w.x);
|
|
753
|
+
o.Set("y", w.y);
|
|
754
|
+
o.Set("width", w.w);
|
|
755
|
+
o.Set("height", w.h);
|
|
756
|
+
o.Set("active", w.active);
|
|
757
|
+
arr.Set((uint32_t)i, o);
|
|
758
|
+
}
|
|
759
|
+
return arr;
|
|
760
|
+
});
|
|
761
|
+
}];
|
|
762
|
+
} else {
|
|
763
|
+
CALReply(tsfn, WindowsError("NotSupportedError", @"listing windows needs macOS 14 (ScreenCaptureKit)"));
|
|
764
|
+
}
|
|
765
|
+
return env.Undefined();
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
void InitDisplayStream(Napi::Env env, Napi::Object exports) {
|
|
769
|
+
exports.Set("screenCaptureWindows", Napi::Function::New(env, ScreenCaptureWindows));
|
|
770
|
+
exports.Set("openDisplayStream", Napi::Function::New(env, OpenDisplayStream));
|
|
771
|
+
exports.Set("displayStreamFrames", Napi::Function::New(env, DisplayStreamFrames));
|
|
772
|
+
exports.Set("displayStreamCopyFrame", Napi::Function::New(env, DisplayStreamCopyFrame));
|
|
773
|
+
exports.Set("displayStreamConfigure", Napi::Function::New(env, DisplayStreamConfigure));
|
|
774
|
+
exports.Set("closeDisplayStream", Napi::Function::New(env, CloseDisplayStream));
|
|
775
|
+
}
|