@windowkit/appkit 0.30.2 → 0.32.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/src/capture.mm ADDED
@@ -0,0 +1,1944 @@
1
+ // @windowkit/appkit capture.mm — cameras, microphones, speakers, an audio
2
+ // out and screenshots, for a renderer's media capture (react-x11's
3
+ // design/architecture/media-capture.md): the devices AVFoundation and
4
+ // CoreAudio know, a camera shown on a layer of its own with its frames handed
5
+ // over only on request, a microphone and every output on one voice-processing
6
+ // audio engine, and ScreenCaptureKit's screenshots.
7
+ //
8
+ // Devices — no authorization asked, nothing prompts:
9
+ //
10
+ // - captureDevices() -> [{ id, kind: 'camera'|'microphone'|'speaker', name,
11
+ // isDefault, groupId?, position?, formats? }], or the same through
12
+ // captureDevices(cb) from a queue of its own: cameras and microphones from
13
+ // AVCaptureDevice's discovery (`id` is the uniqueID, which for a microphone
14
+ // is CoreAudio's device UID), speakers from CoreAudio. A camera's
15
+ // `formats` are [{ width, height, minFrameRate, maxFrameRate }].
16
+ // - event `capture-devices` whenever a device comes or goes or a default
17
+ // input or output changes. Watched from the first captureDevices() on.
18
+ //
19
+ // A camera:
20
+ //
21
+ // - openCamera(deviceId | null, { width, height, frameRate }) -> { id, layer,
22
+ // width, height, frameRate, format, range, colorSpace }: the device's
23
+ // format nearest the size asked (a YCbCr one where it has one, so nothing
24
+ // converts) and the rate clamped to it, answered at once; the session
25
+ // starts on a queue of its own, and `camera-started { id }` or
26
+ // `camera-error { id, name, message }` says how that went, `name` Media
27
+ // Capture's: NotAllowedError, NotFoundError, NotReadableError. `layer` is
28
+ // an AVCaptureVideoPreviewLayer — a layer handle every layer verb takes —
29
+ // filling its bounds (the renderer fits the picture) and never mirrored.
30
+ // - cameraFrames(id, on): while on, `camera-frame { id, width, height,
31
+ // format, range, colorSpace, planes, strides, time }`, the planes copies
32
+ // of the camera's own (NV12 on every Mac camera seen), `time` seconds on the
33
+ // capture clock. The newest frame only: one that arrives while the last is
34
+ // still on its way replaces it.
35
+ // - cameraCopyFrame(id, surface) -> { width, height, time, written } | null:
36
+ // playerCopyFrame's contract — the newest frame into a 2D surface in the
37
+ // layer's colours, null when none is newer than the last one copied.
38
+ // - events `camera-muted { id, muted }` (the session interrupted: another
39
+ // app took the camera) and `camera-ended { id }` (unplugged, or a runtime
40
+ // error). closeCamera(id).
41
+ //
42
+ // The audio: one AVAudioEngine for every microphone and every output, so an
43
+ // echo-cancelled microphone has what is played as its reference (react-x11's
44
+ // design record §3) — while one is open, voice processing is on for the
45
+ // engine's input and output both, and every output plays through it.
46
+ //
47
+ // - openMicrophone(deviceId | null, { sampleRate, channels, echoCancellation,
48
+ // noiseSuppression, autoGainControl }) -> { id, sampleRate, channels,
49
+ // echoCancellation, noiseSuppression, autoGainControl, latency }:
50
+ // resampled and mixed down here to the rate and count asked. The switches
51
+ // answered are what was asked; `microphone-started { id, … }` carries what
52
+ // the engine actually did — voice processing engaged or not — and
53
+ // `microphone-error { id, name, message }` what went wrong. Then
54
+ // `audio-input { id, sampleRate, channels: [Float32Array], frames, time,
55
+ // dropped? }` every 10 ms, nothing dropped short of two seconds waiting.
56
+ // One input device at a time: the engine has one input. closeMicrophone(id).
57
+ // - openAudioOutput({ sampleRate, channels, deviceId }) -> { id, sampleRate,
58
+ // channels, latency }; audioOutputWrite(id, [Float32Array]) -> frames
59
+ // queued; audioOutputState(id) -> { currentTime, queued, latency }, the
60
+ // time in seconds the device has played since the first write;
61
+ // closeAudioOutput(id). Silence where the queue runs dry. One output device
62
+ // for the engine: the first output's `deviceId` picks it.
63
+ //
64
+ // The screen:
65
+ //
66
+ // - captureScreenshot({ display, window, rect, cursor }, cb): one picture
67
+ // through ScreenCaptureKit (macOS 14), cb({ width, height, scale, data })
68
+ // with `data` straight RGBA in sRGB, or cb({ error, name }) — NotAllowedError
69
+ // without the Screen Recording grant, NotSupportedError before macOS 14.
70
+ // `rect` is in points of the display; `display` a CGDirectDisplayID,
71
+ // `window` a window number.
72
+ // - screenCaptureDisplays() -> [{ id, name, x, y, width, height, scale }],
73
+ // points, top-left origin; through a callback off the main thread.
74
+ //
75
+ // Everything that arrives on a queue of AVFoundation's or CoreAudio's
76
+ // crosses to JS one way: straight into the channel where threaded mode has
77
+ // it open, and otherwise through a threadsafe function of the main thread's,
78
+ // where pump mode's listener is called (CALEmit is the main thread's then).
79
+
80
+ #include <napi.h>
81
+ #import <AVFoundation/AVFoundation.h>
82
+ #import <AudioToolbox/AudioToolbox.h>
83
+ #import <Cocoa/Cocoa.h>
84
+ #import <CoreAudio/CoreAudio.h>
85
+ #import <CoreMedia/CoreMedia.h>
86
+ #import <CoreVideo/CoreVideo.h>
87
+ #import <ScreenCaptureKit/ScreenCaptureKit.h>
88
+ #include <os/lock.h>
89
+ #include <pthread.h>
90
+
91
+ #include <atomic>
92
+ #include <cmath>
93
+ #include <memory>
94
+ #include <string>
95
+ #include <vector>
96
+
97
+ #include "channel.h"
98
+
99
+ // video.mm
100
+ bool CALPixelBufferToBGRA(Napi::Env env, const char* verb, CVPixelBufferRef pb, uint8_t* dst,
101
+ size_t dstStride);
102
+ bool CALVideoTargetBitmap(Napi::Value v, uint8_t** data, size_t* width, size_t* height,
103
+ size_t* bytesPerRow);
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // crossing to JS
107
+ // ---------------------------------------------------------------------------
108
+
109
+ struct Delivery {
110
+ dispatch_block_t block;
111
+ };
112
+
113
+ static void CallJsDelivery(Napi::Env env, Napi::Function, void*, Delivery* d) {
114
+ if ((napi_env)env == nullptr || !CALCanCallIntoJS(env)) {
115
+ delete d;
116
+ return;
117
+ }
118
+ d->block();
119
+ delete d;
120
+ CALRaiseUncaughtIfPending(env);
121
+ }
122
+
123
+ using DeliveryTsfn = Napi::TypedThreadSafeFunction<void, Delivery, CallJsDelivery>;
124
+ static std::atomic<CALTsfn*> gDeliver{nullptr};
125
+
126
+ // `block` where it may emit: here, with threaded mode's channel open or on
127
+ // the main thread; on the main thread's JS loop otherwise. False when it
128
+ // could not be sent — the environment is ending — and it will never run.
129
+ static bool Deliver(dispatch_block_t block) {
130
+ if (CALChannelOpen() || pthread_main_np()) {
131
+ block();
132
+ return true;
133
+ }
134
+ CALTsfn* t = gDeliver.load();
135
+ if (!t) return false;
136
+ Delivery* d = new Delivery{block};
137
+ bool queued = t->Use(false, [d](napi_threadsafe_function f) {
138
+ return DeliveryTsfn(f).NonBlockingCall(d);
139
+ });
140
+ if (!queued) delete d;
141
+ return queued;
142
+ }
143
+
144
+ static void Send(CALEvent ev) {
145
+ auto held = std::make_shared<CALEvent>(std::move(ev));
146
+ Deliver(^{
147
+ if (CALListening()) CALEmit(std::move(*held));
148
+ });
149
+ }
150
+
151
+ static NSString* Str(Napi::Value v) {
152
+ if (!v.IsString()) return nil;
153
+ return [NSString stringWithUTF8String:v.As<Napi::String>().Utf8Value().c_str()];
154
+ }
155
+
156
+ static bool OptNum(Napi::Value obj, const char* k, double* out) {
157
+ if (!obj.IsObject()) return false;
158
+ Napi::Object o = obj.As<Napi::Object>();
159
+ if (!o.Has(k)) return false;
160
+ Napi::Value v = o.Get(k);
161
+ if (!v.IsNumber()) return false;
162
+ double d = v.As<Napi::Number>().DoubleValue();
163
+ if (!std::isfinite(d)) return false;
164
+ *out = d;
165
+ return true;
166
+ }
167
+
168
+ static bool OptBool(Napi::Value obj, const char* k, bool* out) {
169
+ if (!obj.IsObject()) return false;
170
+ Napi::Object o = obj.As<Napi::Object>();
171
+ if (!o.Has(k)) return false;
172
+ Napi::Value v = o.Get(k);
173
+ if (!v.IsBoolean()) return false;
174
+ *out = v.As<Napi::Boolean>().Value();
175
+ return true;
176
+ }
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // devices
180
+ // ---------------------------------------------------------------------------
181
+
182
+ static NSArray<AVCaptureDevice*>* Cameras() {
183
+ NSMutableArray<AVCaptureDeviceType>* types =
184
+ [NSMutableArray arrayWithObject:AVCaptureDeviceTypeBuiltInWideAngleCamera];
185
+ if (@available(macOS 14.0, *)) {
186
+ [types addObject:AVCaptureDeviceTypeExternal];
187
+ // Continuity Camera only where the app said it wants it: AVFoundation
188
+ // logs a warning for every discovery that asks without the key
189
+ if ([NSBundle.mainBundle objectForInfoDictionaryKey:@"NSCameraUseContinuityCameraDeviceType"]) {
190
+ [types addObject:AVCaptureDeviceTypeContinuityCamera];
191
+ }
192
+ } else {
193
+ #pragma clang diagnostic push
194
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
195
+ [types addObject:AVCaptureDeviceTypeExternalUnknown];
196
+ #pragma clang diagnostic pop
197
+ }
198
+ return [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:types
199
+ mediaType:AVMediaTypeVideo
200
+ position:AVCaptureDevicePositionUnspecified]
201
+ .devices;
202
+ }
203
+
204
+ static NSArray<AVCaptureDevice*>* Microphones() {
205
+ NSMutableArray<AVCaptureDeviceType>* types = [NSMutableArray array];
206
+ if (@available(macOS 14.0, *)) {
207
+ [types addObject:AVCaptureDeviceTypeMicrophone];
208
+ [types addObject:AVCaptureDeviceTypeExternal];
209
+ } else {
210
+ #pragma clang diagnostic push
211
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
212
+ [types addObject:AVCaptureDeviceTypeBuiltInMicrophone];
213
+ [types addObject:AVCaptureDeviceTypeExternalUnknown];
214
+ #pragma clang diagnostic pop
215
+ }
216
+ return [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:types
217
+ mediaType:AVMediaTypeAudio
218
+ position:AVCaptureDevicePositionUnspecified]
219
+ .devices;
220
+ }
221
+
222
+ static AudioObjectPropertyAddress Address(AudioObjectPropertySelector sel,
223
+ AudioObjectPropertyScope scope = kAudioObjectPropertyScopeGlobal) {
224
+ return {sel, scope, kAudioObjectPropertyElementMain};
225
+ }
226
+
227
+ static NSString* DeviceUID(AudioDeviceID dev) {
228
+ CFStringRef uid = nullptr;
229
+ UInt32 size = sizeof(uid);
230
+ AudioObjectPropertyAddress a = Address(kAudioDevicePropertyDeviceUID);
231
+ if (AudioObjectGetPropertyData(dev, &a, 0, nullptr, &size, &uid) != noErr || !uid) return nil;
232
+ return (__bridge_transfer NSString*)uid;
233
+ }
234
+
235
+ static NSString* DeviceName(AudioDeviceID dev) {
236
+ CFStringRef name = nullptr;
237
+ UInt32 size = sizeof(name);
238
+ AudioObjectPropertyAddress a = Address(kAudioObjectPropertyName);
239
+ if (AudioObjectGetPropertyData(dev, &a, 0, nullptr, &size, &name) != noErr || !name) return @"";
240
+ return (__bridge_transfer NSString*)name;
241
+ }
242
+
243
+ static AudioDeviceID DefaultDevice(bool input) {
244
+ AudioDeviceID dev = kAudioObjectUnknown;
245
+ UInt32 size = sizeof(dev);
246
+ AudioObjectPropertyAddress a = Address(input ? kAudioHardwarePropertyDefaultInputDevice
247
+ : kAudioHardwarePropertyDefaultOutputDevice);
248
+ AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, nullptr, &size, &dev);
249
+ return dev;
250
+ }
251
+
252
+ static AudioDeviceID DeviceForUID(NSString* uid) {
253
+ if (!uid.length) return kAudioObjectUnknown;
254
+ AudioDeviceID dev = kAudioObjectUnknown;
255
+ CFStringRef cf = (__bridge CFStringRef)uid;
256
+ AudioValueTranslation t = {&cf, sizeof(cf), &dev, sizeof(dev)};
257
+ UInt32 size = sizeof(t);
258
+ AudioObjectPropertyAddress a = Address(kAudioHardwarePropertyDeviceForUID);
259
+ if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, nullptr, &size, &t) != noErr) {
260
+ return kAudioObjectUnknown;
261
+ }
262
+ return dev;
263
+ }
264
+
265
+ // An engine makes an aggregate device of its own for the default device
266
+ // (`CADefaultDeviceAggregate-<pid>`), and voice processing another: private
267
+ // to this process, and no device a person would pick — but CoreAudio lists
268
+ // them, and AVFoundation says one was connected.
269
+ static bool IsPrivate(NSString* uid) {
270
+ return [uid hasPrefix:@"CADefaultDeviceAggregate"] || [uid hasPrefix:@"VPAUAggregateAudioDevice"];
271
+ }
272
+
273
+ static bool IsHidden(AudioDeviceID dev) {
274
+ UInt32 hidden = 0, size = sizeof(hidden);
275
+ AudioObjectPropertyAddress a = Address(kAudioDevicePropertyIsHidden);
276
+ if (AudioObjectGetPropertyData(dev, &a, 0, nullptr, &size, &hidden) == noErr && hidden) return true;
277
+ return IsPrivate(DeviceUID(dev));
278
+ }
279
+
280
+ static bool HasStreams(AudioDeviceID dev, bool input) {
281
+ UInt32 size = 0;
282
+ AudioObjectPropertyAddress a = Address(
283
+ kAudioDevicePropertyStreams, input ? kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput);
284
+ return AudioObjectGetPropertyDataSize(dev, &a, 0, nullptr, &size) == noErr && size > 0;
285
+ }
286
+
287
+ static std::vector<AudioDeviceID> AudioDevices() {
288
+ UInt32 size = 0;
289
+ AudioObjectPropertyAddress a = Address(kAudioHardwarePropertyDevices);
290
+ if (AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &a, 0, nullptr, &size) != noErr) return {};
291
+ std::vector<AudioDeviceID> devs(size / sizeof(AudioDeviceID));
292
+ if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, nullptr, &size, devs.data()) != noErr) {
293
+ return {};
294
+ }
295
+ return devs;
296
+ }
297
+
298
+ static dispatch_queue_t AudioQueue();
299
+
300
+ // What CoreAudio has that a listing shows: every device a person could pick,
301
+ // and the two defaults. CoreAudio says its device list changed when an engine
302
+ // starts as much as when a headset is plugged in; only a change in this is
303
+ // news.
304
+ static NSString* AudioSignature() {
305
+ NSMutableArray<NSString*>* parts = [NSMutableArray array];
306
+ for (AudioDeviceID dev : AudioDevices()) {
307
+ if (IsHidden(dev)) continue;
308
+ NSString* uid = DeviceUID(dev);
309
+ if (uid) [parts addObject:uid];
310
+ }
311
+ [parts addObject:DeviceUID(DefaultDevice(true)) ?: @"-"];
312
+ [parts addObject:DeviceUID(DefaultDevice(false)) ?: @"-"];
313
+ return [parts componentsJoinedByString:@"\n"];
314
+ }
315
+
316
+ // From the first listing on: the devices coming and going, and the defaults
317
+ // moving, said as `capture-devices`.
318
+ static void WatchDevices() {
319
+ static dispatch_once_t once;
320
+ dispatch_once(&once, ^{
321
+ void (^changed)(void) = ^{
322
+ Send(CALEvent("capture-devices"));
323
+ };
324
+ __block NSString* audio = AudioSignature();
325
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
326
+ [nc addObserverForName:AVCaptureDeviceWasConnectedNotification
327
+ object:nil
328
+ queue:nil
329
+ usingBlock:^(NSNotification* n) {
330
+ AVCaptureDevice* d = n.object;
331
+ if (![d isKindOfClass:AVCaptureDevice.class] || !IsPrivate(d.uniqueID)) changed();
332
+ }];
333
+ [nc addObserverForName:AVCaptureDeviceWasDisconnectedNotification
334
+ object:nil
335
+ queue:nil
336
+ usingBlock:^(NSNotification* n) {
337
+ AVCaptureDevice* d = n.object;
338
+ if (![d isKindOfClass:AVCaptureDevice.class] || !IsPrivate(d.uniqueID)) changed();
339
+ }];
340
+ for (AudioObjectPropertySelector sel :
341
+ {kAudioHardwarePropertyDevices, kAudioHardwarePropertyDefaultInputDevice,
342
+ kAudioHardwarePropertyDefaultOutputDevice}) {
343
+ AudioObjectPropertyAddress a = Address(sel);
344
+ AudioObjectAddPropertyListenerBlock(kAudioObjectSystemObject, &a, AudioQueue(),
345
+ ^(UInt32, const AudioObjectPropertyAddress*) {
346
+ NSString* now = AudioSignature();
347
+ if ([now isEqualToString:audio]) return;
348
+ audio = now;
349
+ changed();
350
+ });
351
+ }
352
+ });
353
+ }
354
+
355
+ static const char* PositionOf(AVCaptureDevice* d) {
356
+ if (@available(macOS 14.0, *)) {
357
+ if ([d.deviceType isEqualToString:AVCaptureDeviceTypeExternal]) return "external";
358
+ }
359
+ switch (d.position) {
360
+ case AVCaptureDevicePositionFront:
361
+ return "front";
362
+ case AVCaptureDevicePositionBack:
363
+ return "back";
364
+ default:
365
+ return d.transportType == 'bltn' ? "front" : "unspecified";
366
+ }
367
+ }
368
+
369
+ struct FormatInfo {
370
+ double width, height, minFrameRate, maxFrameRate;
371
+ };
372
+
373
+ struct DeviceInfo {
374
+ std::string id, kind, name, position, groupId;
375
+ bool isDefault = false;
376
+ std::vector<FormatInfo> formats;
377
+ };
378
+
379
+ // The devices there are, as plain data: on any thread.
380
+ static std::vector<DeviceInfo> ListDevices() {
381
+ std::vector<DeviceInfo> list;
382
+ NSString* defaultCamera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo].uniqueID;
383
+ NSString* defaultInput = DeviceUID(DefaultDevice(true));
384
+ NSString* defaultOutput = DeviceUID(DefaultDevice(false));
385
+ NSArray<AVCaptureDevice*>* cameras = Cameras();
386
+ NSArray<AVCaptureDevice*>* microphones = Microphones();
387
+ // a camera and a microphone that are one piece of hardware share a model
388
+ NSMutableDictionary<NSString*, NSNumber*>* models = [NSMutableDictionary dictionary];
389
+ for (AVCaptureDevice* d in [cameras arrayByAddingObjectsFromArray:microphones]) {
390
+ if (!d.modelID.length) continue;
391
+ models[d.modelID] = @(models[d.modelID].intValue + 1);
392
+ }
393
+ auto base = [&](AVCaptureDevice* d, const char* kind) {
394
+ DeviceInfo info;
395
+ info.id = d.uniqueID.UTF8String;
396
+ info.kind = kind;
397
+ info.name = d.localizedName.UTF8String ?: "";
398
+ if (d.modelID.length && models[d.modelID].intValue > 1) info.groupId = d.modelID.UTF8String;
399
+ return info;
400
+ };
401
+ for (AVCaptureDevice* d in cameras) {
402
+ DeviceInfo info = base(d, "camera");
403
+ info.isDefault = [d.uniqueID isEqualToString:defaultCamera];
404
+ info.position = PositionOf(d);
405
+ NSMutableSet<NSString*>* seen = [NSMutableSet set];
406
+ for (AVCaptureDeviceFormat* fmt in d.formats) {
407
+ CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(fmt.formatDescription);
408
+ double lo = INFINITY, hi = 0;
409
+ for (AVFrameRateRange* r in fmt.videoSupportedFrameRateRanges) {
410
+ lo = fmin(lo, r.minFrameRate);
411
+ hi = fmax(hi, r.maxFrameRate);
412
+ }
413
+ if (!std::isfinite(lo)) lo = hi;
414
+ NSString* key = [NSString stringWithFormat:@"%dx%d@%g-%g", dim.width, dim.height, lo, hi];
415
+ if ([seen containsObject:key]) continue;
416
+ [seen addObject:key];
417
+ info.formats.push_back({(double)dim.width, (double)dim.height, lo, hi});
418
+ }
419
+ list.push_back(info);
420
+ }
421
+ for (AVCaptureDevice* d in microphones) {
422
+ if (IsPrivate(d.uniqueID)) continue;
423
+ DeviceInfo info = base(d, "microphone");
424
+ info.isDefault = [d.uniqueID isEqualToString:defaultInput];
425
+ list.push_back(info);
426
+ }
427
+ for (AudioDeviceID dev : AudioDevices()) {
428
+ if (IsHidden(dev) || !HasStreams(dev, false)) continue;
429
+ NSString* uid = DeviceUID(dev);
430
+ if (!uid) continue;
431
+ DeviceInfo info;
432
+ info.id = uid.UTF8String;
433
+ info.kind = "speaker";
434
+ info.name = DeviceName(dev).UTF8String ?: "";
435
+ info.isDefault = [uid isEqualToString:defaultOutput];
436
+ list.push_back(info);
437
+ }
438
+ return list;
439
+ }
440
+
441
+ static Napi::Value DevicesValue(Napi::Env env, const std::vector<DeviceInfo>& list) {
442
+ Napi::Array out = Napi::Array::New(env, list.size());
443
+ for (size_t i = 0; i < list.size(); i++) {
444
+ const DeviceInfo& d = list[i];
445
+ Napi::Object o = Napi::Object::New(env);
446
+ o.Set("id", d.id);
447
+ o.Set("kind", d.kind);
448
+ o.Set("name", d.name);
449
+ o.Set("isDefault", d.isDefault);
450
+ if (!d.position.empty()) o.Set("position", d.position);
451
+ if (!d.groupId.empty()) o.Set("groupId", d.groupId);
452
+ if (d.kind == "camera") {
453
+ Napi::Array formats = Napi::Array::New(env, d.formats.size());
454
+ for (size_t f = 0; f < d.formats.size(); f++) {
455
+ Napi::Object one = Napi::Object::New(env);
456
+ one.Set("width", d.formats[f].width);
457
+ one.Set("height", d.formats[f].height);
458
+ one.Set("minFrameRate", d.formats[f].minFrameRate);
459
+ one.Set("maxFrameRate", d.formats[f].maxFrameRate);
460
+ formats.Set((uint32_t)f, one);
461
+ }
462
+ o.Set("formats", formats);
463
+ }
464
+ out.Set((uint32_t)i, o);
465
+ }
466
+ return out;
467
+ }
468
+
469
+ // captureDevices() answers at once; captureDevices(cb) lists on a queue of
470
+ // its own and answers through cb — the first listing of a process loads
471
+ // AVFoundation's camera plug-ins, 100 ms to over a second, which a UI thread
472
+ // should not wait out.
473
+ static Napi::Value CaptureDevices(const Napi::CallbackInfo& info) {
474
+ Napi::Env env = info.Env();
475
+ WatchDevices();
476
+ if (info.Length() && info[info.Length() - 1].IsFunction()) {
477
+ CALTsfn tsfn = CALReplyTo(env, info[info.Length() - 1].As<Napi::Function>(), "appkit:captureDevices");
478
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
479
+ auto list = std::make_shared<std::vector<DeviceInfo>>(ListDevices());
480
+ CALReply(tsfn, ^Napi::Value(Napi::Env e) { return DevicesValue(e, *list); });
481
+ });
482
+ return env.Undefined();
483
+ }
484
+ return DevicesValue(env, ListDevices());
485
+ }
486
+
487
+ // ---------------------------------------------------------------------------
488
+ // cameras
489
+ // ---------------------------------------------------------------------------
490
+
491
+ @interface CALCamera : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate>
492
+ @property(nonatomic) double cid;
493
+ @property(nonatomic, strong) AVCaptureDevice* device;
494
+ @property(nonatomic, strong) AVCaptureDeviceFormat* format;
495
+ @property(nonatomic) double frameRate;
496
+ @property(nonatomic, strong) AVCaptureSession* session;
497
+ @property(nonatomic, strong) AVCaptureVideoDataOutput* output;
498
+ @property(nonatomic, strong) AVCaptureVideoPreviewLayer* layer;
499
+ @property(nonatomic, strong) dispatch_queue_t queue;
500
+ @property(nonatomic, strong) NSMutableArray* notes;
501
+ @property(nonatomic) BOOL closed;
502
+ @end
503
+
504
+ @implementation CALCamera {
505
+ os_unfair_lock _lock;
506
+ CVPixelBufferRef _latest; // for a copy; retained
507
+ double _latestTime;
508
+ uint64_t _latestSeq, _copiedSeq;
509
+ CVPixelBufferRef _pending; // for JS, while on its way; retained
510
+ double _pendingTime;
511
+ bool _scheduled;
512
+ std::atomic<bool> _frames;
513
+ }
514
+
515
+ - (instancetype)init {
516
+ if ((self = [super init])) {
517
+ _lock = OS_UNFAIR_LOCK_INIT;
518
+ _frames = false;
519
+ }
520
+ return self;
521
+ }
522
+
523
+ - (void)dealloc {
524
+ if (_latest) CVPixelBufferRelease(_latest);
525
+ if (_pending) CVPixelBufferRelease(_pending);
526
+ }
527
+
528
+ - (void)setFramesOn:(bool)on {
529
+ _frames = on;
530
+ }
531
+
532
+ // The newest frame, if newer than the last one copied: retained, or null.
533
+ - (CVPixelBufferRef)takeNewest:(double*)time {
534
+ os_unfair_lock_lock(&_lock);
535
+ CVPixelBufferRef pb = nullptr;
536
+ if (_latest && _latestSeq != _copiedSeq) {
537
+ pb = CVPixelBufferRetain(_latest);
538
+ *time = _latestTime;
539
+ _copiedSeq = _latestSeq;
540
+ }
541
+ os_unfair_lock_unlock(&_lock);
542
+ return pb;
543
+ }
544
+
545
+ - (void)captureOutput:(AVCaptureOutput*)output
546
+ didOutputSampleBuffer:(CMSampleBufferRef)sample
547
+ fromConnection:(AVCaptureConnection*)connection {
548
+ CVPixelBufferRef pb = CMSampleBufferGetImageBuffer(sample);
549
+ if (!pb) return;
550
+ double time = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sample));
551
+ bool schedule = false;
552
+ os_unfair_lock_lock(&_lock);
553
+ if (_latest) CVPixelBufferRelease(_latest);
554
+ _latest = CVPixelBufferRetain(pb);
555
+ _latestTime = time;
556
+ _latestSeq++;
557
+ if (_frames.load()) {
558
+ if (_pending) CVPixelBufferRelease(_pending);
559
+ _pending = CVPixelBufferRetain(pb);
560
+ _pendingTime = time;
561
+ schedule = !_scheduled;
562
+ _scheduled = true;
563
+ }
564
+ os_unfair_lock_unlock(&_lock);
565
+ if (!schedule) return;
566
+ __weak CALCamera* weak = self;
567
+ if (!Deliver(^{
568
+ CALCamera* c = weak;
569
+ if (c) [c sendPending];
570
+ })) {
571
+ os_unfair_lock_lock(&_lock);
572
+ _scheduled = false;
573
+ os_unfair_lock_unlock(&_lock);
574
+ }
575
+ }
576
+
577
+ // Where JS is: the frame waiting, as the event — the newest by now, since a
578
+ // frame that arrived while this was on its way replaced the one that sent it.
579
+ - (void)sendPending {
580
+ os_unfair_lock_lock(&_lock);
581
+ CVPixelBufferRef pb = _pending;
582
+ double time = _pendingTime;
583
+ _pending = nullptr;
584
+ _scheduled = false;
585
+ os_unfair_lock_unlock(&_lock);
586
+ if (!pb) return;
587
+ if (self.closed || !_frames.load() || !CALListening()) {
588
+ CVPixelBufferRelease(pb);
589
+ return;
590
+ }
591
+ OSType type = CVPixelBufferGetPixelFormatType(pb);
592
+ const char* format = nullptr;
593
+ bool full = false;
594
+ switch (type) {
595
+ case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
596
+ full = true;
597
+ [[fallthrough]];
598
+ case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
599
+ format = "NV12";
600
+ break;
601
+ case kCVPixelFormatType_32BGRA:
602
+ format = "BGRA";
603
+ full = true;
604
+ break;
605
+ default:
606
+ CVPixelBufferRelease(pb);
607
+ return;
608
+ }
609
+ #pragma clang diagnostic push
610
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
611
+ CFTypeRef matrix = CVBufferGetAttachment(pb, kCVImageBufferYCbCrMatrixKey, nullptr);
612
+ #pragma clang diagnostic pop
613
+ const char* colorSpace =
614
+ matrix && CFEqual(matrix, kCVImageBufferYCbCrMatrix_ITU_R_601_4) ? "bt601" : "bt709";
615
+ CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
616
+ size_t count = CVPixelBufferIsPlanar(pb) ? CVPixelBufferGetPlaneCount(pb) : 1;
617
+ NSMutableArray<NSData*>* planes = [NSMutableArray array];
618
+ std::vector<double> strides;
619
+ for (size_t i = 0; i < count; i++) {
620
+ bool planar = CVPixelBufferIsPlanar(pb);
621
+ const void* base = planar ? CVPixelBufferGetBaseAddressOfPlane(pb, i) : CVPixelBufferGetBaseAddress(pb);
622
+ size_t bpr = planar ? CVPixelBufferGetBytesPerRowOfPlane(pb, i) : CVPixelBufferGetBytesPerRow(pb);
623
+ size_t rows = planar ? CVPixelBufferGetHeightOfPlane(pb, i) : CVPixelBufferGetHeight(pb);
624
+ [planes addObject:[NSData dataWithBytes:base length:bpr * rows]];
625
+ strides.push_back((double)bpr);
626
+ }
627
+ double width = (double)CVPixelBufferGetWidth(pb), height = (double)CVPixelBufferGetHeight(pb);
628
+ CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
629
+ CVPixelBufferRelease(pb);
630
+ CALEvent ev("camera-frame");
631
+ ev.Num("id", self.cid)
632
+ .Num("width", width)
633
+ .Num("height", height)
634
+ .Str("format", format)
635
+ .Str("range", full ? "full" : "video")
636
+ .Str("colorSpace", colorSpace)
637
+ .Num("time", time)
638
+ .Handle("planes",
639
+ ^Napi::Value(Napi::Env env) {
640
+ Napi::Array a = Napi::Array::New(env, planes.count);
641
+ for (NSUInteger i = 0; i < planes.count; i++) {
642
+ NSData* d = planes[i];
643
+ a.Set((uint32_t)i, Napi::Buffer<uint8_t>::Copy(env, (const uint8_t*)d.bytes, d.length));
644
+ }
645
+ return a;
646
+ })
647
+ .Handle("strides", ^Napi::Value(Napi::Env env) {
648
+ Napi::Array a = Napi::Array::New(env, strides.size());
649
+ for (size_t i = 0; i < strides.size(); i++) a.Set((uint32_t)i, strides[i]);
650
+ return a;
651
+ });
652
+ // threaded mode: a frame queued behind another of this camera's replaces it
653
+ ev.FoldBy(self.cid);
654
+ CALEmit(std::move(ev));
655
+ }
656
+
657
+ - (void)stop {
658
+ self.closed = YES;
659
+ _frames = false;
660
+ for (id note in self.notes) [NSNotificationCenter.defaultCenter removeObserver:note];
661
+ self.notes = nil;
662
+ [self.output setSampleBufferDelegate:nil queue:nil];
663
+ if (self.session.isRunning) [self.session stopRunning];
664
+ os_unfair_lock_lock(&_lock);
665
+ if (_latest) CVPixelBufferRelease(_latest);
666
+ if (_pending) CVPixelBufferRelease(_pending);
667
+ _latest = _pending = nullptr;
668
+ os_unfair_lock_unlock(&_lock);
669
+ }
670
+
671
+ @end
672
+
673
+ static NSMutableDictionary<NSNumber*, CALCamera*>* gCameras;
674
+ static std::atomic<uint32_t> gNextCapture{0};
675
+
676
+ static CALCamera* CameraFor(double cid) {
677
+ @synchronized([CALCamera class]) {
678
+ return gCameras[@(cid)];
679
+ }
680
+ }
681
+
682
+ static bool IsYCbCr420(AVCaptureDeviceFormat* f) {
683
+ FourCharCode sub = CMFormatDescriptionGetMediaSubType(f.formatDescription);
684
+ return sub == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ||
685
+ sub == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
686
+ }
687
+
688
+ // The format nearest the size asked, YCbCr first, and the rate it can run
689
+ // nearest the one asked. Nothing asked: the largest no bigger than 1280x720.
690
+ static AVCaptureDeviceFormat* ChooseFormat(AVCaptureDevice* d, double w, double h, double rate,
691
+ double* chosenRate) {
692
+ AVCaptureDeviceFormat* best = nil;
693
+ double bestScore = INFINITY;
694
+ for (AVCaptureDeviceFormat* f in d.formats) {
695
+ CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(f.formatDescription);
696
+ double score;
697
+ if (w > 0 || h > 0) {
698
+ double aw = w > 0 ? w : dim.width, ah = h > 0 ? h : dim.height;
699
+ score = fabs(dim.width - aw) / aw + fabs(dim.height - ah) / ah;
700
+ } else {
701
+ bool fits = dim.width <= 1280 && dim.height <= 720;
702
+ score = fits ? 1.0 / (1.0 + (double)dim.width * dim.height) : 10 + (double)dim.width * dim.height;
703
+ }
704
+ double hi = 0;
705
+ for (AVFrameRateRange* r in f.videoSupportedFrameRateRanges) hi = fmax(hi, r.maxFrameRate);
706
+ if (rate > 0 && hi + 0.01 < rate) score += 0.5 * (rate - hi) / rate;
707
+ if (!IsYCbCr420(f)) score += 100;
708
+ if (score < bestScore) {
709
+ bestScore = score;
710
+ best = f;
711
+ }
712
+ }
713
+ if (best) {
714
+ double lo = INFINITY, hi = 0;
715
+ for (AVFrameRateRange* r in best.videoSupportedFrameRateRanges) {
716
+ lo = fmin(lo, r.minFrameRate);
717
+ hi = fmax(hi, r.maxFrameRate);
718
+ }
719
+ double want = rate > 0 ? rate : fmin(30, hi);
720
+ *chosenRate = fmin(hi, fmax(std::isfinite(lo) ? lo : want, want));
721
+ }
722
+ return best;
723
+ }
724
+
725
+ // The frame duration `f` runs `rate` at, from the range of its own that holds
726
+ // the rate — and at a range's ends, that range's own duration exactly. A
727
+ // duration worked out from the rate is rounded to its timescale: 1/30 s in
728
+ // microseconds is 33333 µs, 30.0003 frames a second, and AVFoundation throws
729
+ // for a rate a hair past the format's fastest rather than clamping it.
730
+ static CMTime FrameDuration(AVCaptureDeviceFormat* f, double rate) {
731
+ AVFrameRateRange* best = nil;
732
+ double nearest = INFINITY;
733
+ for (AVFrameRateRange* r in f.videoSupportedFrameRateRanges) {
734
+ double off = rate < r.minFrameRate ? r.minFrameRate - rate
735
+ : rate > r.maxFrameRate ? rate - r.maxFrameRate
736
+ : 0;
737
+ if (off < nearest) {
738
+ nearest = off;
739
+ best = r;
740
+ }
741
+ }
742
+ if (!best) return kCMTimeInvalid;
743
+ if (rate >= best.maxFrameRate - 1e-3) return best.minFrameDuration;
744
+ if (rate <= best.minFrameRate + 1e-3) return best.maxFrameDuration;
745
+ CMTime d = CMTimeMakeWithSeconds(1.0 / rate, 1000000);
746
+ if (CMTimeCompare(d, best.minFrameDuration) < 0) return best.minFrameDuration;
747
+ if (CMTimeCompare(d, best.maxFrameDuration) > 0) return best.maxFrameDuration;
748
+ return d;
749
+ }
750
+
751
+ static void CameraError(double cid, const char* name, NSString* message) {
752
+ Send(std::move(CALEvent("camera-error").Num("id", cid).Str("name", name).Str("message", message.UTF8String)));
753
+ }
754
+
755
+ static void StartSession(CALCamera* c);
756
+
757
+ // On the camera's queue: the session put together and started.
758
+ static void StartCamera(CALCamera* c) {
759
+ double cid = c.cid;
760
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
761
+ if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
762
+ CameraError(cid, "NotAllowedError", @"the camera is not allowed for this app (Privacy & Security › Camera)");
763
+ return;
764
+ }
765
+ if (status == AVAuthorizationStatusNotDetermined) {
766
+ // asked here so a request that comes back no is a NotAllowedError and not
767
+ // a session that delivers nothing; the session starts once it says yes
768
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
769
+ completionHandler:^(BOOL granted) {
770
+ dispatch_async(c.queue, ^{
771
+ if (c.closed) return;
772
+ if (!granted) {
773
+ CameraError(cid, "NotAllowedError",
774
+ @"the camera was not allowed — by the user, or by "
775
+ @"macOS for a process it does not take for an app");
776
+ return;
777
+ }
778
+ StartCamera(c);
779
+ });
780
+ }];
781
+ return;
782
+ }
783
+ // AVFoundation reports a configuration it will not take by throwing, on
784
+ // this queue, where nothing above would catch it and the process ends: it
785
+ // is the open's error instead, and the app goes on
786
+ @try {
787
+ StartSession(c);
788
+ } @catch (NSException* e) {
789
+ CameraError(cid, "NotReadableError",
790
+ [NSString stringWithFormat:@"the camera could not be configured: %@", e.reason ?: e.name]);
791
+ }
792
+ }
793
+
794
+ // On the camera's queue, allowed: the input, the output, the format and the
795
+ // rate, then the session running.
796
+ static void StartSession(CALCamera* c) {
797
+ double cid = c.cid;
798
+ NSError* err = nil;
799
+ AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:c.device error:&err];
800
+ if (!input) {
801
+ CameraError(cid, "NotReadableError", err.localizedDescription ?: @"the camera could not be opened");
802
+ return;
803
+ }
804
+ AVCaptureSession* s = c.session;
805
+ [s beginConfiguration];
806
+ if (![s canAddInput:input]) {
807
+ [s commitConfiguration];
808
+ CameraError(cid, "NotReadableError", @"the camera could not be added to a capture session");
809
+ return;
810
+ }
811
+ [s addInput:input];
812
+ AVCaptureVideoDataOutput* out = [AVCaptureVideoDataOutput new];
813
+ out.alwaysDiscardsLateVideoFrames = YES;
814
+ // the format's own layout, so nothing is converted on the way
815
+ FourCharCode sub = CMFormatDescriptionGetMediaSubType(c.format.formatDescription);
816
+ out.videoSettings = @{
817
+ (id)kCVPixelBufferPixelFormatTypeKey : @(IsYCbCr420(c.format) ? sub : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
818
+ };
819
+ [out setSampleBufferDelegate:c queue:c.queue];
820
+ if ([s canAddOutput:out]) [s addOutput:out];
821
+ c.output = out;
822
+ [s commitConfiguration];
823
+ if ([c.device lockForConfiguration:&err]) {
824
+ @try {
825
+ c.device.activeFormat = c.format;
826
+ CMTime d = FrameDuration(c.format, c.frameRate);
827
+ if (CMTIME_IS_VALID(d)) {
828
+ c.device.activeVideoMinFrameDuration = d;
829
+ c.device.activeVideoMaxFrameDuration = d;
830
+ }
831
+ } @finally {
832
+ [c.device unlockForConfiguration];
833
+ }
834
+ }
835
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
836
+ __weak CALCamera* weak = c;
837
+ c.notes = [NSMutableArray array];
838
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionWasInterruptedNotification
839
+ object:s
840
+ queue:nil
841
+ usingBlock:^(NSNotification*) {
842
+ Send(std::move(CALEvent("camera-muted").Num("id", cid).Bool("muted", true)));
843
+ }]];
844
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionInterruptionEndedNotification
845
+ object:s
846
+ queue:nil
847
+ usingBlock:^(NSNotification*) {
848
+ Send(std::move(CALEvent("camera-muted").Num("id", cid).Bool("muted", false)));
849
+ }]];
850
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionRuntimeErrorNotification
851
+ object:s
852
+ queue:nil
853
+ usingBlock:^(NSNotification*) {
854
+ CALCamera* cam = weak;
855
+ if (!cam || cam.closed) return;
856
+ Send(std::move(CALEvent("camera-ended").Num("id", cid)));
857
+ }]];
858
+ [c.notes addObject:[nc addObserverForName:AVCaptureDeviceWasDisconnectedNotification
859
+ object:c.device
860
+ queue:nil
861
+ usingBlock:^(NSNotification*) {
862
+ CALCamera* cam = weak;
863
+ if (!cam || cam.closed) return;
864
+ Send(std::move(CALEvent("camera-ended").Num("id", cid)));
865
+ }]];
866
+ [s startRunning];
867
+ if (c.closed) return;
868
+ if (!s.isRunning) {
869
+ CameraError(cid, "NotReadableError", @"the capture session did not start — the camera may be in use");
870
+ return;
871
+ }
872
+ CMTime ran = c.device.activeVideoMinFrameDuration;
873
+ double rate = CMTIME_IS_VALID(ran) && ran.value > 0 ? (double)ran.timescale / ran.value : c.frameRate;
874
+ Send(std::move(CALEvent("camera-started").Num("id", cid).Num("frameRate", rate)));
875
+ }
876
+
877
+ static Napi::Value OpenCamera(const Napi::CallbackInfo& info) {
878
+ Napi::Env env = info.Env();
879
+ Napi::Value opts = info.Length() > 1 ? info[1] : env.Undefined();
880
+ double w = 0, h = 0, rate = 0;
881
+ OptNum(opts, "width", &w);
882
+ OptNum(opts, "height", &h);
883
+ OptNum(opts, "frameRate", &rate);
884
+ NSString* uid = Str(info[0]);
885
+ AVCaptureDevice* device =
886
+ uid ? [AVCaptureDevice deviceWithUniqueID:uid] : [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
887
+ double cid = (double)(++gNextCapture);
888
+ Napi::Object out = Napi::Object::New(env);
889
+ out.Set("id", cid);
890
+ if (!device || ![device hasMediaType:AVMediaTypeVideo]) {
891
+ CameraError(cid, "NotFoundError", uid ? [NSString stringWithFormat:@"there is no camera %@", uid]
892
+ : @"there is no camera");
893
+ return out;
894
+ }
895
+ double chosenRate = 30;
896
+ AVCaptureDeviceFormat* format = ChooseFormat(device, w, h, rate, &chosenRate);
897
+ if (!format) {
898
+ CameraError(cid, "NotReadableError", @"the camera lists no format to capture in");
899
+ return out;
900
+ }
901
+ CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
902
+ FourCharCode sub = CMFormatDescriptionGetMediaSubType(format.formatDescription);
903
+ CFTypeRef matrix = CMFormatDescriptionGetExtension(format.formatDescription,
904
+ kCMFormatDescriptionExtension_YCbCrMatrix);
905
+ out.Set("width", (double)dim.width);
906
+ out.Set("height", (double)dim.height);
907
+ out.Set("frameRate", chosenRate);
908
+ out.Set("format", "NV12");
909
+ out.Set("range", sub == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange ? "full" : "video");
910
+ out.Set("colorSpace",
911
+ matrix && CFEqual(matrix, kCMFormatDescriptionYCbCrMatrix_ITU_R_601_4) ? "bt601" : "bt709");
912
+
913
+ CALCamera* c = [CALCamera new];
914
+ c.cid = cid;
915
+ c.device = device;
916
+ c.format = format;
917
+ c.frameRate = chosenRate;
918
+ c.session = [AVCaptureSession new];
919
+ c.queue = dispatch_queue_create("appkit.camera", DISPATCH_QUEUE_SERIAL);
920
+ @synchronized([CALCamera class]) {
921
+ if (!gCameras) gCameras = [NSMutableDictionary dictionary];
922
+ gCameras[@(cid)] = c;
923
+ }
924
+ AVCaptureVideoPreviewLayer* (^make)(void) = ^AVCaptureVideoPreviewLayer* {
925
+ AVCaptureVideoPreviewLayer* layer = [AVCaptureVideoPreviewLayer layerWithSession:c.session];
926
+ layer.videoGravity = AVLayerVideoGravityResize;
927
+ AVCaptureConnection* conn = layer.connection;
928
+ if (conn.isVideoMirroringSupported) {
929
+ conn.automaticallyAdjustsVideoMirroring = NO;
930
+ conn.videoMirrored = NO;
931
+ }
932
+ c.layer = layer;
933
+ return layer;
934
+ };
935
+ if (pthread_main_np()) {
936
+ void* retained = (void*)CFBridgingRetain(make());
937
+ out.Set("layer", Napi::External<void>::New(env, retained, [](Napi::Env, void* d) { CFRelease(d); }));
938
+ } else {
939
+ CALHandle* handle = CALNewHandle();
940
+ out.Set("layer", CALWrapHandle(env, handle, false));
941
+ CALOnUI(^{ handle->object_ = make(); });
942
+ }
943
+ dispatch_async(c.queue, ^{
944
+ if (!c.closed) StartCamera(c);
945
+ });
946
+ return out;
947
+ }
948
+
949
+ static Napi::Value CameraFrames(const Napi::CallbackInfo& info) {
950
+ Napi::Env env = info.Env();
951
+ if (!info[0].IsNumber()) {
952
+ Napi::TypeError::New(env, "cameraFrames(id, on): id is the number openCamera answered")
953
+ .ThrowAsJavaScriptException();
954
+ return env.Undefined();
955
+ }
956
+ CALCamera* c = CameraFor(info[0].As<Napi::Number>().DoubleValue());
957
+ [c setFramesOn:info.Length() > 1 && info[1].ToBoolean().Value()];
958
+ return env.Undefined();
959
+ }
960
+
961
+ static Napi::Value CameraCopyFrame(const Napi::CallbackInfo& info) {
962
+ Napi::Env env = info.Env();
963
+ if (!info[0].IsNumber()) {
964
+ Napi::TypeError::New(env, "cameraCopyFrame(id, surface): id is the number openCamera answered")
965
+ .ThrowAsJavaScriptException();
966
+ return env.Undefined();
967
+ }
968
+ uint8_t* data;
969
+ size_t sw, sh, bpr;
970
+ if (!CALVideoTargetBitmap(info[1], &data, &sw, &sh, &bpr)) return env.Undefined();
971
+ CALCamera* c = CameraFor(info[0].As<Napi::Number>().DoubleValue());
972
+ double time = 0;
973
+ CVPixelBufferRef pb = [c takeNewest:&time];
974
+ if (!pb) return env.Null();
975
+ size_t w = CVPixelBufferGetWidth(pb), h = CVPixelBufferGetHeight(pb);
976
+ Napi::Object out = Napi::Object::New(env);
977
+ out.Set("width", (double)w);
978
+ out.Set("height", (double)h);
979
+ out.Set("time", time);
980
+ bool fits = w == sw && h == sh;
981
+ bool ok = !fits || CALPixelBufferToBGRA(env, "cameraCopyFrame", pb, data, bpr);
982
+ CVPixelBufferRelease(pb);
983
+ if (!ok) return env.Undefined();
984
+ out.Set("written", fits);
985
+ return out;
986
+ }
987
+
988
+ static Napi::Value CloseCamera(const Napi::CallbackInfo& info) {
989
+ Napi::Env env = info.Env();
990
+ if (!info[0].IsNumber()) return env.Undefined();
991
+ double cid = info[0].As<Napi::Number>().DoubleValue();
992
+ CALCamera* c;
993
+ @synchronized([CALCamera class]) {
994
+ c = gCameras[@(cid)];
995
+ [gCameras removeObjectForKey:@(cid)];
996
+ }
997
+ if (!c) return env.Undefined();
998
+ c.closed = YES;
999
+ dispatch_async(c.queue, ^{ [c stop]; });
1000
+ CALOnUI(^{ c.layer.session = nil; });
1001
+ return env.Undefined();
1002
+ }
1003
+
1004
+ // ---------------------------------------------------------------------------
1005
+ // audio: one engine, its input and its outputs
1006
+ // ---------------------------------------------------------------------------
1007
+
1008
+ // A ring of planar float samples, one writer and one reader — the render
1009
+ // thread at one end, so neither end takes a lock.
1010
+ class Ring {
1011
+ public:
1012
+ Ring(size_t channels, size_t capacity) : channels_(channels), cap_(capacity) {
1013
+ data_.resize(channels * capacity);
1014
+ }
1015
+ size_t channels() const { return channels_; }
1016
+ size_t available() const { return w_.load(std::memory_order_acquire) - r_.load(std::memory_order_acquire); }
1017
+ // what fitted
1018
+ size_t write(const float* const* src, size_t frames) {
1019
+ size_t w = w_.load(std::memory_order_relaxed), r = r_.load(std::memory_order_acquire);
1020
+ size_t room = cap_ - (w - r);
1021
+ size_t n = frames < room ? frames : room;
1022
+ for (size_t c = 0; c < channels_; c++) {
1023
+ float* dst = &data_[c * cap_];
1024
+ const float* s = src[c < channels_ ? c : 0];
1025
+ for (size_t i = 0; i < n; i++) dst[(w + i) % cap_] = s ? s[i] : 0;
1026
+ }
1027
+ w_.store(w + n, std::memory_order_release);
1028
+ return n;
1029
+ }
1030
+ size_t read(float* const* dst, size_t frames) {
1031
+ size_t r = r_.load(std::memory_order_relaxed), w = w_.load(std::memory_order_acquire);
1032
+ size_t n = frames < w - r ? frames : w - r;
1033
+ for (size_t c = 0; c < channels_; c++) {
1034
+ const float* src = &data_[c * cap_];
1035
+ for (size_t i = 0; i < n; i++) dst[c][i] = src[(r + i) % cap_];
1036
+ }
1037
+ r_.store(r + n, std::memory_order_release);
1038
+ return n;
1039
+ }
1040
+ void clear() { r_.store(w_.load()); }
1041
+
1042
+ private:
1043
+ size_t channels_, cap_;
1044
+ std::vector<float> data_;
1045
+ std::atomic<size_t> w_{0}, r_{0};
1046
+ };
1047
+
1048
+ @interface CALMicrophone : NSObject
1049
+ @property(nonatomic) double mid;
1050
+ @property(nonatomic) double sampleRate;
1051
+ @property(nonatomic) AVAudioChannelCount channels;
1052
+ @property(nonatomic) BOOL echoCancellation, noiseSuppression, autoGainControl;
1053
+ @property(nonatomic, strong) NSString* deviceUID;
1054
+ @property(nonatomic, strong) AVAudioConverter* converter;
1055
+ @property(nonatomic, strong) AVAudioFormat* format;
1056
+ @property(nonatomic) BOOL started;
1057
+ @end
1058
+
1059
+ @implementation CALMicrophone {
1060
+ @public
1061
+ std::vector<std::vector<float>> pending; // converted, not yet a 10 ms chunk
1062
+ double sent; // frames sent, for `time`
1063
+ std::shared_ptr<std::atomic<int>> inflight;
1064
+ std::atomic<int> dropped;
1065
+ }
1066
+ @end
1067
+
1068
+ @interface CALOutput : NSObject
1069
+ @property(nonatomic) double oid;
1070
+ @property(nonatomic) double sampleRate;
1071
+ @property(nonatomic) AVAudioChannelCount channels;
1072
+ @property(nonatomic, strong) AVAudioSourceNode* node;
1073
+ @end
1074
+
1075
+ @implementation CALOutput {
1076
+ @public
1077
+ std::unique_ptr<Ring> ring;
1078
+ std::atomic<uint64_t> played; // frames the render thread pulled since the first write
1079
+ std::atomic<bool> begun;
1080
+ }
1081
+ @end
1082
+
1083
+ // The audio queue's, and touched nowhere else: the engine and everything
1084
+ // wired to it. The two things other threads need from it are kept apart —
1085
+ // the outputs, which JS opens and closes, under their own lock
1086
+ // (`OutputsNow`), and the latency `audioOutputState` reports, published as
1087
+ // a number — since a strong pointer the queue reassigns while JS reads it is
1088
+ // a use after free, and a dictionary JS mutates while the queue enumerates it
1089
+ // is a corrupted heap: both were seen, as a crash in an unrelated allocation.
1090
+ static AVAudioEngine* gEngine;
1091
+ static AVAudioSinkNode* gSink;
1092
+ static std::unique_ptr<Ring> gInputRing; // the input's samples, from the render thread
1093
+ static AVAudioFormat* gInputFormat;
1094
+ static dispatch_source_t gDrain;
1095
+ // APPKIT_DEBUG_AUDIO=1: what the engine does, on stderr — its rebuilds and
1096
+ // why, voice processing engaging or not, the input's format, each start and
1097
+ // its error, configuration changes, and once a second what the input gave and
1098
+ // what reached JS. For a machine the audio cannot be watched on otherwise.
1099
+ static const bool gDebugAudio = [] {
1100
+ const char* v = getenv("APPKIT_DEBUG_AUDIO");
1101
+ return v && *v && strcmp(v, "0") != 0;
1102
+ }();
1103
+ #define AUDIO_LOG(...) \
1104
+ do { \
1105
+ if (gDebugAudio) { \
1106
+ fprintf(stderr, "@windowkit/appkit audio: " __VA_ARGS__); \
1107
+ fputc('\n', stderr); \
1108
+ } \
1109
+ } while (0)
1110
+ static std::atomic<uint64_t> gSinkFrames{0}; // frames the input gave, from the render thread
1111
+ static uint64_t gChunksSent = 0; // the audio queue's
1112
+ static double gLastReport = 0;
1113
+ // configuration changes lately, for the loop guard
1114
+ static std::vector<double> gChanges;
1115
+ static BOOL gVoice;
1116
+ // Voice processing would not start on this input — some Bluetooth headsets'
1117
+ // microphones, -10875 from the engine — so the microphone runs without it
1118
+ // until the input changes or every microphone closes.
1119
+ static BOOL gVoiceRefused;
1120
+ static NSString* gInputUID;
1121
+ static NSMutableDictionary<NSNumber*, CALMicrophone*>* gMics;
1122
+ static id gConfigNote;
1123
+ static std::atomic<double> gOutputLatency{0};
1124
+
1125
+ // JS's and the queue's alike, only ever under @synchronized([CALOutput class]).
1126
+ static NSMutableDictionary<NSNumber*, CALOutput*>* gOutputs;
1127
+ static NSString* gOutputUID;
1128
+
1129
+ // The outputs open now and the device the first of them named: a copy, taken
1130
+ // under the lock, which the queue works from.
1131
+ static NSArray<CALOutput*>* OutputsNow(NSString** uid) {
1132
+ @synchronized([CALOutput class]) {
1133
+ if (uid) *uid = gOutputUID;
1134
+ return gOutputs.allValues ?: @[];
1135
+ }
1136
+ }
1137
+
1138
+ static dispatch_queue_t AudioQueue() {
1139
+ static dispatch_queue_t q;
1140
+ static dispatch_once_t once;
1141
+ dispatch_once(&once, ^{ q = dispatch_queue_create("appkit.audio", DISPATCH_QUEUE_SERIAL); });
1142
+ return q;
1143
+ }
1144
+
1145
+ static void SetUnitDevice(AudioUnit unit, NSString* uid) {
1146
+ AudioDeviceID dev = DeviceForUID(uid);
1147
+ if (!unit || dev == kAudioObjectUnknown) return;
1148
+ AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &dev,
1149
+ sizeof(dev));
1150
+ }
1151
+
1152
+ static void DrainInput();
1153
+ static void SafeRewire();
1154
+ static void Rewire();
1155
+
1156
+ // The engine taken down, and what was wired to it forgotten, so the next
1157
+ // Rewire builds a new one from what is open.
1158
+ static void TearDownEngine() {
1159
+ if (gEngine) [gEngine stop];
1160
+ if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
1161
+ gConfigNote = nil;
1162
+ if (gDrain) dispatch_source_cancel(gDrain);
1163
+ gDrain = nil;
1164
+ gEngine = nil;
1165
+ gSink = nil;
1166
+ gInputRing.reset();
1167
+ gVoice = NO;
1168
+ gInputUID = nil;
1169
+ gOutputLatency = 0;
1170
+ for (CALOutput* o in OutputsNow(nullptr)) o.node = nil;
1171
+ for (CALMicrophone* m in gMics.allValues) m.converter = nil;
1172
+ }
1173
+
1174
+ static void MicrophoneError(double mid, const char* name, NSString* message) {
1175
+ Send(std::move(
1176
+ CALEvent("microphone-error").Num("id", mid).Str("name", name).Str("message", message.UTF8String)));
1177
+ }
1178
+
1179
+ // On the audio queue: the engine wired for what is open now — its input
1180
+ // while a microphone is, voice processing while an echo-cancelled one is,
1181
+ // every output a source node into the mixer — and running while anything is.
1182
+ // Changing whether there is an input or voice processing stops the engine
1183
+ // first: neither can change on a running one.
1184
+ static void Rewire() {
1185
+ bool wantInput = gMics.count > 0;
1186
+ bool wantVoice = false;
1187
+ NSString* wantUID = nil;
1188
+ for (CALMicrophone* m in gMics.allValues) {
1189
+ wantVoice = wantVoice || m.echoCancellation;
1190
+ if (!wantUID) wantUID = m.deviceUID;
1191
+ }
1192
+ if (!wantInput) gVoiceRefused = NO;
1193
+ wantVoice = wantVoice && !gVoiceRefused;
1194
+ NSString* outputUID = nil;
1195
+ NSArray<CALOutput*>* outputs = OutputsNow(&outputUID);
1196
+ bool wantOutputs = outputs.count > 0;
1197
+ if (!wantInput && !wantOutputs) {
1198
+ TearDownEngine();
1199
+ return;
1200
+ }
1201
+ bool hadInput = gSink != nil;
1202
+ bool rebuild = !gEngine || hadInput != wantInput || (wantInput && gVoice != wantVoice) ||
1203
+ (wantInput && ![wantUID ?: @"" isEqualToString:gInputUID ?: @""]);
1204
+ AUDIO_LOG("rewire: %lu microphone(s), %lu output(s), voice wanted %d (refused %d) — %s",
1205
+ (unsigned long)gMics.count, (unsigned long)outputs.count, wantVoice, (int)gVoiceRefused,
1206
+ rebuild ? (gEngine ? "rebuilding the engine" : "building the engine") : "same engine");
1207
+ if (rebuild) {
1208
+ if (gEngine) [gEngine stop];
1209
+ if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
1210
+ // a new engine each time: voice processing does not come off cleanly
1211
+ gEngine = [AVAudioEngine new];
1212
+ gSink = nil;
1213
+ gInputRing.reset();
1214
+ gVoice = NO;
1215
+ gInputUID = nil;
1216
+ if (wantInput) {
1217
+ AVAudioInputNode* input = gEngine.inputNode;
1218
+ if (wantUID) SetUnitDevice(input.audioUnit, wantUID);
1219
+ gInputUID = wantUID;
1220
+ if (wantVoice) {
1221
+ NSError* err = nil;
1222
+ gVoice = [input setVoiceProcessingEnabled:YES error:&err];
1223
+ AUDIO_LOG("voice processing %s%s", gVoice ? "on" : "refused: ",
1224
+ gVoice ? "" : (err.localizedDescription ?: @"no reason").UTF8String);
1225
+ }
1226
+ // The input's format is whatever the device and voice processing make
1227
+ // of it: the built-in microphone array is several channels under voice
1228
+ // processing, and no format at all where there is no input. Only the
1229
+ // first channel is kept under voice processing — its output, the
1230
+ // voice — and at most two otherwise: a standard format is only made
1231
+ // for one or two channels, and a converter handed the nil one gets for
1232
+ // more ends the process (a segfault, no exception to catch).
1233
+ AVAudioFormat* hw = [input outputFormatForBus:0];
1234
+ if (!hw || hw.sampleRate <= 0 || hw.channelCount == 0) {
1235
+ [NSException raise:NSInternalInconsistencyException
1236
+ format:@"the input has no audio format — is a microphone connected?"];
1237
+ }
1238
+ AVAudioChannelCount kept = gVoice ? 1 : MIN(hw.channelCount, (AVAudioChannelCount)2);
1239
+ AUDIO_LOG("input: %g Hz, %u channel(s)%s, keeping %u", hw.sampleRate, hw.channelCount,
1240
+ hw.isInterleaved ? " interleaved" : "", kept);
1241
+ gInputFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:hw.sampleRate channels:kept];
1242
+ if (!gInputFormat) {
1243
+ [NSException raise:NSInternalInconsistencyException
1244
+ format:@"no format for the input at %g Hz", hw.sampleRate];
1245
+ }
1246
+ gInputRing = std::make_unique<Ring>(kept, (size_t)(hw.sampleRate * 2));
1247
+ Ring* ring = gInputRing.get();
1248
+ // an interleaved input arrives as one buffer of every channel: its
1249
+ // first `kept` are pulled apart here, into room made now, since the
1250
+ // render thread allocates nothing
1251
+ bool interleaved = hw.isInterleaved;
1252
+ UInt32 stride = hw.channelCount;
1253
+ auto scratch = std::make_shared<std::vector<float>>(2 * 8192);
1254
+ gSink = [[AVAudioSinkNode alloc] initWithReceiverBlock:^OSStatus(const AudioTimeStamp*, AVAudioFrameCount n,
1255
+ const AudioBufferList* in) {
1256
+ const float* ch[2] = {nullptr, nullptr};
1257
+ if (interleaved && in->mNumberBuffers >= 1) {
1258
+ const float* all = (const float*)in->mBuffers[0].mData;
1259
+ AVAudioFrameCount m = n < 8192 ? n : 8192;
1260
+ for (UInt32 c = 0; c < kept; c++) {
1261
+ float* out = scratch->data() + c * 8192;
1262
+ for (AVAudioFrameCount i = 0; i < m; i++) out[i] = all[i * stride + c];
1263
+ ch[c] = out;
1264
+ }
1265
+ ring->write(ch, m);
1266
+ gSinkFrames.fetch_add(m, std::memory_order_relaxed);
1267
+ return noErr;
1268
+ }
1269
+ UInt32 count = in->mNumberBuffers < kept ? in->mNumberBuffers : kept;
1270
+ for (UInt32 i = 0; i < count; i++) ch[i] = (const float*)in->mBuffers[i].mData;
1271
+ ring->write(ch, n);
1272
+ gSinkFrames.fetch_add(n, std::memory_order_relaxed);
1273
+ return noErr;
1274
+ }];
1275
+ [gEngine attachNode:gSink];
1276
+ // at the input's own format: the sink takes what the device gives
1277
+ [gEngine connect:input to:gSink format:hw];
1278
+ }
1279
+ if (outputUID) SetUnitDevice(gEngine.outputNode.audioUnit, outputUID);
1280
+ gConfigNote = [NSNotificationCenter.defaultCenter
1281
+ addObserverForName:AVAudioEngineConfigurationChangeNotification
1282
+ object:gEngine
1283
+ queue:nil
1284
+ usingBlock:^(NSNotification*) {
1285
+ // a device came or went under the engine: wired again, at
1286
+ // the formats there are now
1287
+ dispatch_async(AudioQueue(), ^{
1288
+ // Voice processing can switch a Bluetooth headset between
1289
+ // its profiles, which is itself a configuration change:
1290
+ // rebuilt with it again, the engine changed the device
1291
+ // again, and a microphone never settled long enough to
1292
+ // give a sample while the outputs played on. Three in a
1293
+ // few seconds under voice processing, and it is given up
1294
+ // for as long as a microphone stays open.
1295
+ double now = CACurrentMediaTime();
1296
+ gChanges.push_back(now);
1297
+ while (!gChanges.empty() && now - gChanges.front() > 5) gChanges.erase(gChanges.begin());
1298
+ bool looping = gVoice && gChanges.size() >= 3;
1299
+ AUDIO_LOG("configuration changed under the engine (%zu in 5 s)%s", gChanges.size(),
1300
+ looping ? ": giving up on voice processing" : "");
1301
+ if (looping) gVoiceRefused = YES;
1302
+ TearDownEngine();
1303
+ SafeRewire();
1304
+ });
1305
+ }];
1306
+ for (CALOutput* o in outputs) o.node = nil;
1307
+ for (CALMicrophone* m in gMics.allValues) m.converter = nil;
1308
+ }
1309
+ // outputs: a source node each, into the mixer
1310
+ AVAudioMixerNode* mixer = gEngine.mainMixerNode;
1311
+ for (CALOutput* o in outputs) {
1312
+ if (o.node) continue;
1313
+ AVAudioFormat* f = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:o.sampleRate channels:o.channels];
1314
+ CALOutput* out = o;
1315
+ Ring* ring = out->ring.get();
1316
+ o.node = [[AVAudioSourceNode alloc]
1317
+ initWithFormat:f
1318
+ renderBlock:^OSStatus(BOOL* silence, const AudioTimeStamp*, AVAudioFrameCount n, AudioBufferList* buf) {
1319
+ float* ch[16] = {nullptr};
1320
+ UInt32 count = buf->mNumberBuffers < 16 ? buf->mNumberBuffers : 16;
1321
+ for (UInt32 i = 0; i < count; i++) ch[i] = (float*)buf->mBuffers[i].mData;
1322
+ size_t got = ring->channels() <= count ? ring->read(ch, n) : 0;
1323
+ for (UInt32 i = 0; i < count; i++) {
1324
+ for (size_t j = got; j < n; j++) ch[i][j] = 0;
1325
+ }
1326
+ if (out->begun.load()) out->played.fetch_add(n);
1327
+ *silence = got == 0;
1328
+ return noErr;
1329
+ }];
1330
+ [gEngine attachNode:o.node];
1331
+ [gEngine connect:o.node to:mixer format:f];
1332
+ }
1333
+ // microphones: a converter each, from the input's format to theirs
1334
+ for (CALMicrophone* m in gMics.allValues) {
1335
+ if (m.converter || !gInputFormat) continue;
1336
+ m.format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:m.sampleRate channels:m.channels];
1337
+ m.converter = m.format ? [[AVAudioConverter alloc] initFromFormat:gInputFormat toFormat:m.format] : nil;
1338
+ if (!m.converter) {
1339
+ [gMics removeObjectForKey:@(m.mid)];
1340
+ MicrophoneError(m.mid, "NotReadableError",
1341
+ [NSString stringWithFormat:@"no conversion from the input, %u channel(s) at %g Hz, "
1342
+ @"to %u at %g Hz",
1343
+ gInputFormat.channelCount, gInputFormat.sampleRate,
1344
+ m.channels, m.sampleRate]);
1345
+ continue;
1346
+ }
1347
+ if (m.channels < gInputFormat.channelCount) {
1348
+ m.converter.downmix = YES;
1349
+ } else if (m.channels > gInputFormat.channelCount) {
1350
+ // one channel in, two out: the voice on both sides
1351
+ m.converter.channelMap = @[ @0, @0 ];
1352
+ }
1353
+ }
1354
+ if (!gEngine.isRunning) {
1355
+ [gEngine prepare];
1356
+ NSError* err = nil;
1357
+ if (![gEngine startAndReturnError:&err]) {
1358
+ AUDIO_LOG("engine did not start (%ld): %s%s", (long)err.code,
1359
+ (err.localizedDescription ?: @"no reason").UTF8String,
1360
+ gVoice ? " — trying again without voice processing" : "");
1361
+ if (gVoice) {
1362
+ // voice processing would not start on this input: the microphone
1363
+ // runs without it, and microphone-started says echoCancellation false
1364
+ gVoiceRefused = YES;
1365
+ TearDownEngine();
1366
+ Rewire();
1367
+ return;
1368
+ }
1369
+ // a microphone that would not start is not open: it fails, once, and
1370
+ // goes — left in the list, it refused every microphone after it as
1371
+ // "another microphone is open"
1372
+ NSString* why = [NSString stringWithFormat:@"the audio engine did not start: %@",
1373
+ err.localizedDescription ?: @"no reason given"];
1374
+ // and one that was live has stopped: it ends, said, rather than
1375
+ // going quiet while its track still reads live
1376
+ bool dropped = false;
1377
+ for (CALMicrophone* m in gMics.allValues) {
1378
+ [gMics removeObjectForKey:@(m.mid)];
1379
+ if (m.started) {
1380
+ double mid = m.mid;
1381
+ Send(std::move(CALEvent("microphone-ended").Num("id", mid)));
1382
+ } else {
1383
+ MicrophoneError(m.mid, "NotReadableError", why);
1384
+ }
1385
+ dropped = true;
1386
+ }
1387
+ TearDownEngine();
1388
+ // what is left — the outputs, the microphones already running — once
1389
+ // more; with nothing left to drop this ends here
1390
+ if (dropped) Rewire();
1391
+ return;
1392
+ }
1393
+ }
1394
+ gOutputLatency = gEngine.outputNode.presentationLatency;
1395
+ AUDIO_LOG("engine running, voice processing %s, output latency %.1f ms", gVoice ? "on" : "off",
1396
+ gOutputLatency.load() * 1000);
1397
+ if (wantInput && !gDrain) {
1398
+ gDrain = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, AudioQueue());
1399
+ dispatch_source_set_timer(gDrain, dispatch_time(DISPATCH_TIME_NOW, 0), 10 * NSEC_PER_MSEC, 2 * NSEC_PER_MSEC);
1400
+ dispatch_source_set_event_handler(gDrain, ^{ DrainInput(); });
1401
+ dispatch_resume(gDrain);
1402
+ } else if (!wantInput && gDrain) {
1403
+ dispatch_source_cancel(gDrain);
1404
+ gDrain = nil;
1405
+ }
1406
+ AVAudioInputNode* input = wantInput ? gEngine.inputNode : nil;
1407
+ for (CALMicrophone* m in gMics.allValues) {
1408
+ if (m.started) continue;
1409
+ m.started = YES;
1410
+ bool voice = gVoice;
1411
+ bool agc = voice && input.voiceProcessingAGCEnabled;
1412
+ if (voice && !m.autoGainControl) {
1413
+ input.voiceProcessingAGCEnabled = NO;
1414
+ agc = NO;
1415
+ }
1416
+ double latency = input.presentationLatency;
1417
+ Send(std::move(CALEvent("microphone-started")
1418
+ .Num("id", m.mid)
1419
+ .Bool("echoCancellation", voice)
1420
+ .Bool("noiseSuppression", voice)
1421
+ .Bool("autoGainControl", agc)
1422
+ .Num("sampleRate", m.sampleRate)
1423
+ .Num("channels", m.channels)
1424
+ .Num("latency", latency)));
1425
+ }
1426
+ }
1427
+
1428
+ // Rewire, with what AVAudioEngine throws — a connection at a format it will
1429
+ // not take, an input on a machine with none — caught on the audio queue,
1430
+ // where nothing else would, and said to every microphone still opening.
1431
+ static void SafeRewire() {
1432
+ @try {
1433
+ Rewire();
1434
+ } @catch (NSException* e) {
1435
+ NSString* why = e.reason ?: e.name;
1436
+ for (CALMicrophone* m in gMics.allValues) {
1437
+ if (m.started) continue;
1438
+ [gMics removeObjectForKey:@(m.mid)];
1439
+ MicrophoneError(m.mid, "NotReadableError",
1440
+ [NSString stringWithFormat:@"the audio engine could not be set up: %@", why]);
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ // Every 10 ms on the audio queue: what the input gave, converted for each
1446
+ // microphone, out in 10 ms chunks.
1447
+ static void DrainInput() {
1448
+ if (gDebugAudio) {
1449
+ double now = CACurrentMediaTime();
1450
+ if (now - gLastReport >= 1) {
1451
+ gLastReport = now;
1452
+ AUDIO_LOG("last second: %llu frame(s) from the input, %llu chunk(s) to JS, engine %s",
1453
+ (unsigned long long)gSinkFrames.exchange(0), (unsigned long long)gChunksSent,
1454
+ gEngine.isRunning ? "running" : "STOPPED");
1455
+ gChunksSent = 0;
1456
+ }
1457
+ }
1458
+ Ring* ring = gInputRing.get();
1459
+ if (!ring || !gInputFormat) return;
1460
+ size_t n = ring->available();
1461
+ if (n == 0) return;
1462
+ AVAudioPCMBuffer* in = [[AVAudioPCMBuffer alloc] initWithPCMFormat:gInputFormat frameCapacity:(AVAudioFrameCount)n];
1463
+ ring->read(in.floatChannelData, n);
1464
+ in.frameLength = (AVAudioFrameCount)n;
1465
+ for (CALMicrophone* m in gMics.allValues) {
1466
+ if (!m.converter) continue;
1467
+ double ratio = m.sampleRate / gInputFormat.sampleRate;
1468
+ AVAudioFrameCount cap = (AVAudioFrameCount)ceil(n * ratio) + 64;
1469
+ AVAudioPCMBuffer* out = [[AVAudioPCMBuffer alloc] initWithPCMFormat:m.format frameCapacity:cap];
1470
+ __block bool given = false;
1471
+ NSError* err = nil;
1472
+ [m.converter convertToBuffer:out
1473
+ error:&err
1474
+ withInputFromBlock:^AVAudioBuffer*(AVAudioPacketCount, AVAudioConverterInputStatus* status) {
1475
+ if (given) {
1476
+ *status = AVAudioConverterInputStatus_NoDataNow;
1477
+ return nil;
1478
+ }
1479
+ given = true;
1480
+ *status = AVAudioConverterInputStatus_HaveData;
1481
+ return in;
1482
+ }];
1483
+ if (m->pending.size() != m.channels) m->pending.assign(m.channels, {});
1484
+ for (AVAudioChannelCount c = 0; c < m.channels; c++) {
1485
+ float* src = out.floatChannelData[c];
1486
+ m->pending[c].insert(m->pending[c].end(), src, src + out.frameLength);
1487
+ }
1488
+ size_t chunk = (size_t)llround(m.sampleRate / 100);
1489
+ while (!m->pending.empty() && m->pending[0].size() >= chunk) {
1490
+ auto planes = std::make_shared<std::vector<std::vector<float>>>();
1491
+ for (auto& p : m->pending) {
1492
+ planes->emplace_back(p.begin(), p.begin() + chunk);
1493
+ p.erase(p.begin(), p.begin() + chunk);
1494
+ }
1495
+ double time = m->sent / m.sampleRate;
1496
+ m->sent += chunk;
1497
+ // two seconds waiting is as far as it goes: past that, the oldest wait
1498
+ // and this one is counted instead
1499
+ if (m->inflight->load() > 200) {
1500
+ m->dropped++;
1501
+ continue;
1502
+ }
1503
+ int dropped = m->dropped.exchange(0);
1504
+ gChunksSent++;
1505
+ auto inflight = m->inflight;
1506
+ inflight->fetch_add(1);
1507
+ double mid = m.mid, rate = m.sampleRate;
1508
+ if (!Deliver(^{
1509
+ inflight->fetch_sub(1);
1510
+ if (!CALListening()) return;
1511
+ CALEvent ev("audio-input");
1512
+ ev.Num("id", mid).Num("sampleRate", rate).Num("frames", (double)chunk).Num("time", time);
1513
+ if (dropped) ev.Num("dropped", dropped);
1514
+ ev.Handle("channels", ^Napi::Value(Napi::Env env) {
1515
+ Napi::Array a = Napi::Array::New(env, planes->size());
1516
+ for (size_t c = 0; c < planes->size(); c++) {
1517
+ auto& p = (*planes)[c];
1518
+ Napi::ArrayBuffer ab = Napi::ArrayBuffer::New(env, p.size() * sizeof(float));
1519
+ memcpy(ab.Data(), p.data(), p.size() * sizeof(float));
1520
+ a.Set((uint32_t)c, Napi::Float32Array::New(env, p.size(), ab, 0));
1521
+ }
1522
+ return a;
1523
+ });
1524
+ CALEmit(std::move(ev));
1525
+ })) {
1526
+ inflight->fetch_sub(1);
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+
1532
+ static Napi::Value OpenMicrophone(const Napi::CallbackInfo& info) {
1533
+ Napi::Env env = info.Env();
1534
+ Napi::Value opts = info.Length() > 1 ? info[1] : env.Undefined();
1535
+ double rate = 48000, channels = 1;
1536
+ OptNum(opts, "sampleRate", &rate);
1537
+ OptNum(opts, "channels", &channels);
1538
+ rate = fmin(192000, fmax(8000, rate));
1539
+ channels = fmin(2, fmax(1, round(channels)));
1540
+ bool echo = true, noise = true, agc = true;
1541
+ OptBool(opts, "echoCancellation", &echo);
1542
+ OptBool(opts, "noiseSuppression", &noise);
1543
+ OptBool(opts, "autoGainControl", &agc);
1544
+ NSString* uid = Str(info[0]);
1545
+ double mid = (double)(++gNextCapture);
1546
+ Napi::Object out = Napi::Object::New(env);
1547
+ out.Set("id", mid);
1548
+ out.Set("sampleRate", rate);
1549
+ out.Set("channels", channels);
1550
+ out.Set("echoCancellation", echo);
1551
+ out.Set("noiseSuppression", noise);
1552
+ out.Set("autoGainControl", agc);
1553
+ CALMicrophone* m = [CALMicrophone new];
1554
+ m.mid = mid;
1555
+ m.sampleRate = rate;
1556
+ m.channels = (AVAudioChannelCount)channels;
1557
+ // the canceller brings its suppressor and its gain control: none of the
1558
+ // three without it
1559
+ m.echoCancellation = echo || noise;
1560
+ m.noiseSuppression = noise;
1561
+ m.autoGainControl = agc;
1562
+ m->inflight = std::make_shared<std::atomic<int>>(0);
1563
+ m->sent = 0;
1564
+ m->dropped = 0;
1565
+ dispatch_async(AudioQueue(), ^{
1566
+ // a device that is not there is said before anything is asked of the user
1567
+ if (uid && DeviceForUID(uid) == kAudioObjectUnknown) {
1568
+ MicrophoneError(mid, "NotFoundError", [NSString stringWithFormat:@"there is no microphone %@", uid]);
1569
+ return;
1570
+ }
1571
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
1572
+ if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
1573
+ MicrophoneError(mid, "NotAllowedError", @"the microphone is not allowed for this app (Privacy & Security › Microphone)");
1574
+ return;
1575
+ }
1576
+ void (^open)(void) = ^{
1577
+ NSString* deviceUID = uid;
1578
+ if (deviceUID && [deviceUID isEqualToString:DeviceUID(DefaultDevice(true))]) deviceUID = nil;
1579
+ if (deviceUID && DeviceForUID(deviceUID) == kAudioObjectUnknown) {
1580
+ MicrophoneError(mid, "NotFoundError", [NSString stringWithFormat:@"there is no microphone %@", deviceUID]);
1581
+ return;
1582
+ }
1583
+ for (CALMicrophone* other in gMics.allValues) {
1584
+ if (![other.deviceUID ?: @"" isEqualToString:deviceUID ?: @""]) {
1585
+ MicrophoneError(mid, "NotReadableError",
1586
+ @"another microphone is open: the engine has one input at a time");
1587
+ return;
1588
+ }
1589
+ }
1590
+ m.deviceUID = deviceUID;
1591
+ if (!gMics) gMics = [NSMutableDictionary dictionary];
1592
+ gMics[@(mid)] = m;
1593
+ SafeRewire();
1594
+ };
1595
+ if (status == AVAuthorizationStatusNotDetermined) {
1596
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
1597
+ completionHandler:^(BOOL granted) {
1598
+ dispatch_async(AudioQueue(), ^{
1599
+ if (!granted) {
1600
+ MicrophoneError(mid, "NotAllowedError",
1601
+ @"the microphone was not allowed — by the user, or by "
1602
+ @"macOS for a process it does not take for an app");
1603
+ return;
1604
+ }
1605
+ open();
1606
+ });
1607
+ }];
1608
+ return;
1609
+ }
1610
+ open();
1611
+ });
1612
+ return out;
1613
+ }
1614
+
1615
+ static Napi::Value CloseMicrophone(const Napi::CallbackInfo& info) {
1616
+ Napi::Env env = info.Env();
1617
+ if (!info[0].IsNumber()) return env.Undefined();
1618
+ double mid = info[0].As<Napi::Number>().DoubleValue();
1619
+ dispatch_async(AudioQueue(), ^{
1620
+ if (!gMics[@(mid)]) return;
1621
+ [gMics removeObjectForKey:@(mid)];
1622
+ SafeRewire();
1623
+ });
1624
+ return env.Undefined();
1625
+ }
1626
+
1627
+ static CALOutput* OutputFor(double oid) {
1628
+ @synchronized([CALOutput class]) {
1629
+ return gOutputs[@(oid)];
1630
+ }
1631
+ }
1632
+
1633
+ static Napi::Value OpenAudioOutput(const Napi::CallbackInfo& info) {
1634
+ Napi::Env env = info.Env();
1635
+ Napi::Value opts = info.Length() > 0 ? info[0] : env.Undefined();
1636
+ double rate = 48000, channels = 2;
1637
+ OptNum(opts, "sampleRate", &rate);
1638
+ OptNum(opts, "channels", &channels);
1639
+ rate = fmin(384000, fmax(1000, rate));
1640
+ channels = fmin(16, fmax(1, round(channels)));
1641
+ NSString* uid = opts.IsObject() ? Str(opts.As<Napi::Object>().Get("deviceId")) : nil;
1642
+ double oid = (double)(++gNextCapture);
1643
+ CALOutput* o = [CALOutput new];
1644
+ o.oid = oid;
1645
+ o.sampleRate = rate;
1646
+ o.channels = (AVAudioChannelCount)channels;
1647
+ o->ring = std::make_unique<Ring>((size_t)channels, (size_t)(rate * 10));
1648
+ o->played = 0;
1649
+ o->begun = false;
1650
+ @synchronized([CALOutput class]) {
1651
+ if (!gOutputs) gOutputs = [NSMutableDictionary dictionary];
1652
+ if (uid && gOutputs.count == 0) gOutputUID = uid;
1653
+ gOutputs[@(oid)] = o;
1654
+ }
1655
+ dispatch_async(AudioQueue(), ^{
1656
+ // an engine that would not wire plays nothing; its state says so
1657
+ SafeRewire();
1658
+ });
1659
+ Napi::Object out = Napi::Object::New(env);
1660
+ out.Set("id", oid);
1661
+ out.Set("sampleRate", rate);
1662
+ out.Set("channels", channels);
1663
+ out.Set("latency", 0.0);
1664
+ return out;
1665
+ }
1666
+
1667
+ static Napi::Value AudioOutputWrite(const Napi::CallbackInfo& info) {
1668
+ Napi::Env env = info.Env();
1669
+ if (!info[0].IsNumber() || !info[1].IsArray()) {
1670
+ Napi::TypeError::New(env, "audioOutputWrite(id, channels): channels is a Float32Array a channel")
1671
+ .ThrowAsJavaScriptException();
1672
+ return env.Undefined();
1673
+ }
1674
+ CALOutput* o = OutputFor(info[0].As<Napi::Number>().DoubleValue());
1675
+ if (!o) return Napi::Number::New(env, 0);
1676
+ Napi::Array arr = info[1].As<Napi::Array>();
1677
+ std::vector<const float*> ch(o.channels, nullptr);
1678
+ size_t frames = SIZE_MAX;
1679
+ for (uint32_t i = 0; i < arr.Length() && i < o.channels; i++) {
1680
+ Napi::Value v = arr.Get(i);
1681
+ if (!v.IsTypedArray() || v.As<Napi::TypedArray>().TypedArrayType() != napi_float32_array) {
1682
+ Napi::TypeError::New(env, "audioOutputWrite: every channel is a Float32Array").ThrowAsJavaScriptException();
1683
+ return env.Undefined();
1684
+ }
1685
+ Napi::Float32Array f = v.As<Napi::Float32Array>();
1686
+ ch[i] = f.Data();
1687
+ frames = f.ElementLength() < frames ? f.ElementLength() : frames;
1688
+ }
1689
+ if (frames == SIZE_MAX) frames = 0;
1690
+ // a channel not handed is the first one again
1691
+ for (size_t i = 1; i < ch.size(); i++) {
1692
+ if (!ch[i]) ch[i] = ch[0];
1693
+ }
1694
+ o->ring->write(ch.data(), frames);
1695
+ if (frames) o->begun = true;
1696
+ return Napi::Number::New(env, (double)o->ring->available());
1697
+ }
1698
+
1699
+ static Napi::Value AudioOutputState(const Napi::CallbackInfo& info) {
1700
+ Napi::Env env = info.Env();
1701
+ if (!info[0].IsNumber()) return env.Undefined();
1702
+ CALOutput* o = OutputFor(info[0].As<Napi::Number>().DoubleValue());
1703
+ Napi::Object out = Napi::Object::New(env);
1704
+ if (!o) {
1705
+ out.Set("currentTime", 0.0);
1706
+ out.Set("queued", 0.0);
1707
+ out.Set("latency", 0.0);
1708
+ return out;
1709
+ }
1710
+ out.Set("currentTime", (double)o->played.load() / o.sampleRate);
1711
+ out.Set("queued", (double)o->ring->available());
1712
+ out.Set("latency", gOutputLatency.load());
1713
+ return out;
1714
+ }
1715
+
1716
+ static Napi::Value CloseAudioOutput(const Napi::CallbackInfo& info) {
1717
+ Napi::Env env = info.Env();
1718
+ if (!info[0].IsNumber()) return env.Undefined();
1719
+ double oid = info[0].As<Napi::Number>().DoubleValue();
1720
+ CALOutput* o;
1721
+ @synchronized([CALOutput class]) {
1722
+ o = gOutputs[@(oid)];
1723
+ [gOutputs removeObjectForKey:@(oid)];
1724
+ if (gOutputs.count == 0) gOutputUID = nil;
1725
+ }
1726
+ if (!o) return env.Undefined();
1727
+ dispatch_async(AudioQueue(), ^{
1728
+ // The node is this engine's only while the engine it was attached to is
1729
+ // the one running. One rebuilt since — a device change, a headset
1730
+ // switching profiles — took it down with it, and it was off the list by
1731
+ // then so nothing let go of it; asking the new engine to disconnect it
1732
+ // throws, on this queue, and ended the process.
1733
+ @try {
1734
+ if (o.node && gEngine && [gEngine.attachedNodes containsObject:o.node]) {
1735
+ [gEngine disconnectNodeOutput:o.node];
1736
+ [gEngine detachNode:o.node];
1737
+ }
1738
+ } @catch (NSException*) {
1739
+ // gone already, which is what this was for
1740
+ }
1741
+ o.node = nil;
1742
+ SafeRewire();
1743
+ });
1744
+ return env.Undefined();
1745
+ }
1746
+
1747
+ // ---------------------------------------------------------------------------
1748
+ // the screen
1749
+ // ---------------------------------------------------------------------------
1750
+
1751
+ static Napi::Value ScreenCaptureDisplays(const Napi::CallbackInfo& info) {
1752
+ return CALAnswer(info, "screenCaptureDisplays", ^CALValueBlock {
1753
+ NSArray<NSScreen*>* screens = NSScreen.screens;
1754
+ CGFloat top = screens.count ? NSMaxY(screens[0].frame) : 0;
1755
+ struct One {
1756
+ double id, x, y, w, h, scale;
1757
+ std::string name;
1758
+ };
1759
+ auto list = std::make_shared<std::vector<One>>();
1760
+ for (NSScreen* s in screens) {
1761
+ NSNumber* n = s.deviceDescription[@"NSScreenNumber"];
1762
+ NSRect f = s.frame;
1763
+ NSString* name = @"";
1764
+ if (@available(macOS 10.15, *)) name = s.localizedName ?: @"";
1765
+ list->push_back({n.doubleValue, f.origin.x, top - NSMaxY(f), f.size.width, f.size.height,
1766
+ s.backingScaleFactor, name.UTF8String});
1767
+ }
1768
+ return ^Napi::Value(Napi::Env env) {
1769
+ Napi::Array a = Napi::Array::New(env, list->size());
1770
+ for (size_t i = 0; i < list->size(); i++) {
1771
+ const One& s = (*list)[i];
1772
+ Napi::Object o = Napi::Object::New(env);
1773
+ o.Set("id", s.id);
1774
+ o.Set("name", s.name);
1775
+ o.Set("x", s.x);
1776
+ o.Set("y", s.y);
1777
+ o.Set("width", s.w);
1778
+ o.Set("height", s.h);
1779
+ o.Set("scale", s.scale);
1780
+ a.Set((uint32_t)i, o);
1781
+ }
1782
+ return a;
1783
+ };
1784
+ });
1785
+ }
1786
+
1787
+ static CALValueBlock ScreenshotError(const char* name, NSString* message) {
1788
+ std::string n = name, m = message.UTF8String ?: "";
1789
+ return ^Napi::Value(Napi::Env env) {
1790
+ Napi::Object o = Napi::Object::New(env);
1791
+ o.Set("error", m);
1792
+ o.Set("name", n);
1793
+ return o;
1794
+ };
1795
+ }
1796
+
1797
+ // A CGImage as straight RGBA in sRGB: drawn into a premultiplied context
1798
+ // (the only kind CoreGraphics draws into) and divided back out.
1799
+ static CALValueBlock ScreenshotOf(CGImageRef img, double scale) {
1800
+ size_t w = CGImageGetWidth(img), h = CGImageGetHeight(img);
1801
+ auto px = std::make_shared<std::vector<uint8_t>>(w * h * 4);
1802
+ CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1803
+ CGContextRef ctx = CGBitmapContextCreate(px->data(), w, h, 8, w * 4, srgb,
1804
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1805
+ CGColorSpaceRelease(srgb);
1806
+ if (!ctx) return ScreenshotError("NotReadableError", @"the picture could not be converted");
1807
+ CGContextSetBlendMode(ctx, kCGBlendModeCopy);
1808
+ CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), img);
1809
+ CGContextRelease(ctx);
1810
+ uint8_t* p = px->data();
1811
+ for (size_t i = 0; i < w * h * 4; i += 4) {
1812
+ uint8_t a = p[i + 3];
1813
+ if (a == 0 || a == 255) continue;
1814
+ p[i] = (uint8_t)fmin(255, p[i] * 255.0 / a + 0.5);
1815
+ p[i + 1] = (uint8_t)fmin(255, p[i + 1] * 255.0 / a + 0.5);
1816
+ p[i + 2] = (uint8_t)fmin(255, p[i + 2] * 255.0 / a + 0.5);
1817
+ }
1818
+ return ^Napi::Value(Napi::Env env) {
1819
+ Napi::Object o = Napi::Object::New(env);
1820
+ o.Set("width", (double)w);
1821
+ o.Set("height", (double)h);
1822
+ o.Set("scale", scale);
1823
+ o.Set("data", Napi::Buffer<uint8_t>::Copy(env, px->data(), px->size()));
1824
+ return o;
1825
+ };
1826
+ }
1827
+
1828
+ static Napi::Value CaptureScreenshot(const Napi::CallbackInfo& info) {
1829
+ Napi::Env env = info.Env();
1830
+ Napi::Value last = info.Length() ? info[info.Length() - 1] : env.Undefined();
1831
+ if (!last.IsFunction()) {
1832
+ Napi::TypeError::New(env, "captureScreenshot(options, cb): it answers through cb")
1833
+ .ThrowAsJavaScriptException();
1834
+ return env.Undefined();
1835
+ }
1836
+ Napi::Value opts = info.Length() > 1 ? info[0] : env.Undefined();
1837
+ double display = 0, window = 0;
1838
+ bool hasDisplay = OptNum(opts, "display", &display);
1839
+ bool hasWindow = OptNum(opts, "window", &window);
1840
+ bool cursor = false;
1841
+ OptBool(opts, "cursor", &cursor);
1842
+ bool hasRect = false;
1843
+ CGRect rect = CGRectZero;
1844
+ if (opts.IsObject() && opts.As<Napi::Object>().Get("rect").IsObject()) {
1845
+ Napi::Value r = opts.As<Napi::Object>().Get("rect");
1846
+ double x = 0, y = 0, w = 0, h = 0;
1847
+ bool hx = OptNum(r, "x", &x), hy = OptNum(r, "y", &y);
1848
+ bool hw = OptNum(r, "width", &w), hh = OptNum(r, "height", &h);
1849
+ hasRect = hx && hy && hw && hh && w > 0 && h > 0;
1850
+ rect = CGRectMake(x, y, w, h);
1851
+ }
1852
+ CALTsfn tsfn = CALReplyTo(env, last.As<Napi::Function>(), "appkit:captureScreenshot");
1853
+ if (@available(macOS 14.0, *)) {
1854
+ [SCShareableContent
1855
+ getShareableContentExcludingDesktopWindows:NO
1856
+ onScreenWindowsOnly:YES
1857
+ completionHandler:^(SCShareableContent* content, NSError* error) {
1858
+ if (error || !content) {
1859
+ bool declined = error.code == SCStreamErrorUserDeclined;
1860
+ CALReply(tsfn, ScreenshotError(
1861
+ declined ? "NotAllowedError" : "NotReadableError",
1862
+ declined ? @"Screen Recording is not allowed for this app "
1863
+ @"(Privacy & Security › Screen Recording)"
1864
+ : (error.localizedDescription ?: @"the screen could not be listed")));
1865
+ return;
1866
+ }
1867
+ SCContentFilter* filter = nil;
1868
+ if (hasWindow) {
1869
+ for (SCWindow* w in content.windows) {
1870
+ if (w.windowID == (CGWindowID)window) {
1871
+ filter = [[SCContentFilter alloc] initWithDesktopIndependentWindow:w];
1872
+ break;
1873
+ }
1874
+ }
1875
+ } else {
1876
+ CGDirectDisplayID want = hasDisplay ? (CGDirectDisplayID)display : CGMainDisplayID();
1877
+ for (SCDisplay* d in content.displays) {
1878
+ if (d.displayID == want) {
1879
+ filter = [[SCContentFilter alloc] initWithDisplay:d excludingWindows:@[]];
1880
+ break;
1881
+ }
1882
+ }
1883
+ }
1884
+ if (!filter) {
1885
+ CALReply(tsfn, ScreenshotError("NotFoundError", hasWindow ? @"there is no such window on screen"
1886
+ : @"there is no such display"));
1887
+ return;
1888
+ }
1889
+ double scale = filter.pointPixelScale;
1890
+ CGRect area = hasRect ? rect : CGRectMake(0, 0, filter.contentRect.size.width,
1891
+ filter.contentRect.size.height);
1892
+ SCStreamConfiguration* config = [SCStreamConfiguration new];
1893
+ if (hasRect) config.sourceRect = rect;
1894
+ config.width = (size_t)llround(area.size.width * scale);
1895
+ config.height = (size_t)llround(area.size.height * scale);
1896
+ config.showsCursor = cursor;
1897
+ config.colorSpaceName = kCGColorSpaceSRGB;
1898
+ config.ignoreShadowsSingleWindow = YES;
1899
+ [SCScreenshotManager captureImageWithFilter:filter
1900
+ configuration:config
1901
+ completionHandler:^(CGImageRef img, NSError* err) {
1902
+ if (!img) {
1903
+ bool no = err.code == SCStreamErrorUserDeclined;
1904
+ CALReply(tsfn, ScreenshotError(
1905
+ no ? "NotAllowedError" : "NotReadableError",
1906
+ err.localizedDescription ?: @"no picture came back"));
1907
+ return;
1908
+ }
1909
+ CALReply(tsfn, ScreenshotOf(img, scale));
1910
+ }];
1911
+ }];
1912
+ } else {
1913
+ CALReply(tsfn, ScreenshotError("NotSupportedError", @"screenshots need macOS 14 (ScreenCaptureKit)"));
1914
+ }
1915
+ return env.Undefined();
1916
+ }
1917
+
1918
+ // systemaudio.mm's taps are captures too: their ids come from the same count,
1919
+ // so an event's id names one thing, and they cross to JS the same way.
1920
+ double CALNextCaptureId() { return (double)(++gNextCapture); }
1921
+ bool CALCaptureDeliver(dispatch_block_t block) { return Deliver(block); }
1922
+
1923
+ void InitCapture(Napi::Env env, Napi::Object exports) {
1924
+ // The delivery function is the main thread's, made the once, for the
1925
+ // reason InitNotifications gives: pump mode's listener is called there.
1926
+ if (pthread_main_np() && !gDeliver.load()) {
1927
+ DeliveryTsfn t = DeliveryTsfn::New(env, "appkit:capture", 0, 1);
1928
+ t.Unref(env);
1929
+ gDeliver.store(new CALTsfn(CALTsfn::Watch(env, t)));
1930
+ }
1931
+ exports.Set("captureDevices", Napi::Function::New(env, CaptureDevices));
1932
+ exports.Set("openCamera", Napi::Function::New(env, OpenCamera));
1933
+ exports.Set("cameraFrames", Napi::Function::New(env, CameraFrames));
1934
+ exports.Set("cameraCopyFrame", Napi::Function::New(env, CameraCopyFrame));
1935
+ exports.Set("closeCamera", Napi::Function::New(env, CloseCamera));
1936
+ exports.Set("openMicrophone", Napi::Function::New(env, OpenMicrophone));
1937
+ exports.Set("closeMicrophone", Napi::Function::New(env, CloseMicrophone));
1938
+ exports.Set("openAudioOutput", Napi::Function::New(env, OpenAudioOutput));
1939
+ exports.Set("audioOutputWrite", Napi::Function::New(env, AudioOutputWrite));
1940
+ exports.Set("audioOutputState", Napi::Function::New(env, AudioOutputState));
1941
+ exports.Set("closeAudioOutput", Napi::Function::New(env, CloseAudioOutput));
1942
+ exports.Set("screenCaptureDisplays", Napi::Function::New(env, ScreenCaptureDisplays));
1943
+ exports.Set("captureScreenshot", Napi::Function::New(env, CaptureScreenshot));
1944
+ }