@windowkit/appkit 0.30.2 → 0.31.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,1732 @@
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
+ static void CameraError(double cid, const char* name, NSString* message) {
726
+ Send(std::move(CALEvent("camera-error").Num("id", cid).Str("name", name).Str("message", message.UTF8String)));
727
+ }
728
+
729
+ // On the camera's queue: the session put together and started.
730
+ static void StartCamera(CALCamera* c) {
731
+ double cid = c.cid;
732
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
733
+ if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
734
+ CameraError(cid, "NotAllowedError", @"the camera is not allowed for this app (Privacy & Security › Camera)");
735
+ return;
736
+ }
737
+ if (status == AVAuthorizationStatusNotDetermined) {
738
+ // asked here so a request that comes back no is a NotAllowedError and not
739
+ // a session that delivers nothing; the session starts once it says yes
740
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
741
+ completionHandler:^(BOOL granted) {
742
+ dispatch_async(c.queue, ^{
743
+ if (c.closed) return;
744
+ if (!granted) {
745
+ CameraError(cid, "NotAllowedError",
746
+ @"the camera was not allowed — by the user, or by "
747
+ @"macOS for a process it does not take for an app");
748
+ return;
749
+ }
750
+ StartCamera(c);
751
+ });
752
+ }];
753
+ return;
754
+ }
755
+ NSError* err = nil;
756
+ AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:c.device error:&err];
757
+ if (!input) {
758
+ CameraError(cid, "NotReadableError", err.localizedDescription ?: @"the camera could not be opened");
759
+ return;
760
+ }
761
+ AVCaptureSession* s = c.session;
762
+ [s beginConfiguration];
763
+ if (![s canAddInput:input]) {
764
+ [s commitConfiguration];
765
+ CameraError(cid, "NotReadableError", @"the camera could not be added to a capture session");
766
+ return;
767
+ }
768
+ [s addInput:input];
769
+ AVCaptureVideoDataOutput* out = [AVCaptureVideoDataOutput new];
770
+ out.alwaysDiscardsLateVideoFrames = YES;
771
+ // the format's own layout, so nothing is converted on the way
772
+ FourCharCode sub = CMFormatDescriptionGetMediaSubType(c.format.formatDescription);
773
+ out.videoSettings = @{
774
+ (id)kCVPixelBufferPixelFormatTypeKey : @(IsYCbCr420(c.format) ? sub : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
775
+ };
776
+ [out setSampleBufferDelegate:c queue:c.queue];
777
+ if ([s canAddOutput:out]) [s addOutput:out];
778
+ c.output = out;
779
+ [s commitConfiguration];
780
+ if ([c.device lockForConfiguration:&err]) {
781
+ c.device.activeFormat = c.format;
782
+ CMTime d = CMTimeMakeWithSeconds(1.0 / c.frameRate, 1000000);
783
+ c.device.activeVideoMinFrameDuration = d;
784
+ c.device.activeVideoMaxFrameDuration = d;
785
+ [c.device unlockForConfiguration];
786
+ }
787
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
788
+ __weak CALCamera* weak = c;
789
+ c.notes = [NSMutableArray array];
790
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionWasInterruptedNotification
791
+ object:s
792
+ queue:nil
793
+ usingBlock:^(NSNotification*) {
794
+ Send(std::move(CALEvent("camera-muted").Num("id", cid).Bool("muted", true)));
795
+ }]];
796
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionInterruptionEndedNotification
797
+ object:s
798
+ queue:nil
799
+ usingBlock:^(NSNotification*) {
800
+ Send(std::move(CALEvent("camera-muted").Num("id", cid).Bool("muted", false)));
801
+ }]];
802
+ [c.notes addObject:[nc addObserverForName:AVCaptureSessionRuntimeErrorNotification
803
+ object:s
804
+ queue:nil
805
+ usingBlock:^(NSNotification*) {
806
+ CALCamera* cam = weak;
807
+ if (!cam || cam.closed) return;
808
+ Send(std::move(CALEvent("camera-ended").Num("id", cid)));
809
+ }]];
810
+ [c.notes addObject:[nc addObserverForName:AVCaptureDeviceWasDisconnectedNotification
811
+ object:c.device
812
+ queue:nil
813
+ usingBlock:^(NSNotification*) {
814
+ CALCamera* cam = weak;
815
+ if (!cam || cam.closed) return;
816
+ Send(std::move(CALEvent("camera-ended").Num("id", cid)));
817
+ }]];
818
+ [s startRunning];
819
+ if (c.closed) return;
820
+ if (!s.isRunning) {
821
+ CameraError(cid, "NotReadableError", @"the capture session did not start — the camera may be in use");
822
+ return;
823
+ }
824
+ Send(std::move(CALEvent("camera-started").Num("id", cid)));
825
+ }
826
+
827
+ static Napi::Value OpenCamera(const Napi::CallbackInfo& info) {
828
+ Napi::Env env = info.Env();
829
+ Napi::Value opts = info.Length() > 1 ? info[1] : env.Undefined();
830
+ double w = 0, h = 0, rate = 0;
831
+ OptNum(opts, "width", &w);
832
+ OptNum(opts, "height", &h);
833
+ OptNum(opts, "frameRate", &rate);
834
+ NSString* uid = Str(info[0]);
835
+ AVCaptureDevice* device =
836
+ uid ? [AVCaptureDevice deviceWithUniqueID:uid] : [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
837
+ double cid = (double)(++gNextCapture);
838
+ Napi::Object out = Napi::Object::New(env);
839
+ out.Set("id", cid);
840
+ if (!device || ![device hasMediaType:AVMediaTypeVideo]) {
841
+ CameraError(cid, "NotFoundError", uid ? [NSString stringWithFormat:@"there is no camera %@", uid]
842
+ : @"there is no camera");
843
+ return out;
844
+ }
845
+ double chosenRate = 30;
846
+ AVCaptureDeviceFormat* format = ChooseFormat(device, w, h, rate, &chosenRate);
847
+ if (!format) {
848
+ CameraError(cid, "NotReadableError", @"the camera lists no format to capture in");
849
+ return out;
850
+ }
851
+ CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
852
+ FourCharCode sub = CMFormatDescriptionGetMediaSubType(format.formatDescription);
853
+ CFTypeRef matrix = CMFormatDescriptionGetExtension(format.formatDescription,
854
+ kCMFormatDescriptionExtension_YCbCrMatrix);
855
+ out.Set("width", (double)dim.width);
856
+ out.Set("height", (double)dim.height);
857
+ out.Set("frameRate", chosenRate);
858
+ out.Set("format", "NV12");
859
+ out.Set("range", sub == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange ? "full" : "video");
860
+ out.Set("colorSpace",
861
+ matrix && CFEqual(matrix, kCMFormatDescriptionYCbCrMatrix_ITU_R_601_4) ? "bt601" : "bt709");
862
+
863
+ CALCamera* c = [CALCamera new];
864
+ c.cid = cid;
865
+ c.device = device;
866
+ c.format = format;
867
+ c.frameRate = chosenRate;
868
+ c.session = [AVCaptureSession new];
869
+ c.queue = dispatch_queue_create("appkit.camera", DISPATCH_QUEUE_SERIAL);
870
+ @synchronized([CALCamera class]) {
871
+ if (!gCameras) gCameras = [NSMutableDictionary dictionary];
872
+ gCameras[@(cid)] = c;
873
+ }
874
+ AVCaptureVideoPreviewLayer* (^make)(void) = ^AVCaptureVideoPreviewLayer* {
875
+ AVCaptureVideoPreviewLayer* layer = [AVCaptureVideoPreviewLayer layerWithSession:c.session];
876
+ layer.videoGravity = AVLayerVideoGravityResize;
877
+ AVCaptureConnection* conn = layer.connection;
878
+ if (conn.isVideoMirroringSupported) {
879
+ conn.automaticallyAdjustsVideoMirroring = NO;
880
+ conn.videoMirrored = NO;
881
+ }
882
+ c.layer = layer;
883
+ return layer;
884
+ };
885
+ if (pthread_main_np()) {
886
+ void* retained = (void*)CFBridgingRetain(make());
887
+ out.Set("layer", Napi::External<void>::New(env, retained, [](Napi::Env, void* d) { CFRelease(d); }));
888
+ } else {
889
+ CALHandle* handle = CALNewHandle();
890
+ out.Set("layer", CALWrapHandle(env, handle, false));
891
+ CALOnUI(^{ handle->object_ = make(); });
892
+ }
893
+ dispatch_async(c.queue, ^{
894
+ if (!c.closed) StartCamera(c);
895
+ });
896
+ return out;
897
+ }
898
+
899
+ static Napi::Value CameraFrames(const Napi::CallbackInfo& info) {
900
+ Napi::Env env = info.Env();
901
+ if (!info[0].IsNumber()) {
902
+ Napi::TypeError::New(env, "cameraFrames(id, on): id is the number openCamera answered")
903
+ .ThrowAsJavaScriptException();
904
+ return env.Undefined();
905
+ }
906
+ CALCamera* c = CameraFor(info[0].As<Napi::Number>().DoubleValue());
907
+ [c setFramesOn:info.Length() > 1 && info[1].ToBoolean().Value()];
908
+ return env.Undefined();
909
+ }
910
+
911
+ static Napi::Value CameraCopyFrame(const Napi::CallbackInfo& info) {
912
+ Napi::Env env = info.Env();
913
+ if (!info[0].IsNumber()) {
914
+ Napi::TypeError::New(env, "cameraCopyFrame(id, surface): id is the number openCamera answered")
915
+ .ThrowAsJavaScriptException();
916
+ return env.Undefined();
917
+ }
918
+ uint8_t* data;
919
+ size_t sw, sh, bpr;
920
+ if (!CALVideoTargetBitmap(info[1], &data, &sw, &sh, &bpr)) return env.Undefined();
921
+ CALCamera* c = CameraFor(info[0].As<Napi::Number>().DoubleValue());
922
+ double time = 0;
923
+ CVPixelBufferRef pb = [c takeNewest:&time];
924
+ if (!pb) return env.Null();
925
+ size_t w = CVPixelBufferGetWidth(pb), h = CVPixelBufferGetHeight(pb);
926
+ Napi::Object out = Napi::Object::New(env);
927
+ out.Set("width", (double)w);
928
+ out.Set("height", (double)h);
929
+ out.Set("time", time);
930
+ bool fits = w == sw && h == sh;
931
+ bool ok = !fits || CALPixelBufferToBGRA(env, "cameraCopyFrame", pb, data, bpr);
932
+ CVPixelBufferRelease(pb);
933
+ if (!ok) return env.Undefined();
934
+ out.Set("written", fits);
935
+ return out;
936
+ }
937
+
938
+ static Napi::Value CloseCamera(const Napi::CallbackInfo& info) {
939
+ Napi::Env env = info.Env();
940
+ if (!info[0].IsNumber()) return env.Undefined();
941
+ double cid = info[0].As<Napi::Number>().DoubleValue();
942
+ CALCamera* c;
943
+ @synchronized([CALCamera class]) {
944
+ c = gCameras[@(cid)];
945
+ [gCameras removeObjectForKey:@(cid)];
946
+ }
947
+ if (!c) return env.Undefined();
948
+ c.closed = YES;
949
+ dispatch_async(c.queue, ^{ [c stop]; });
950
+ CALOnUI(^{ c.layer.session = nil; });
951
+ return env.Undefined();
952
+ }
953
+
954
+ // ---------------------------------------------------------------------------
955
+ // audio: one engine, its input and its outputs
956
+ // ---------------------------------------------------------------------------
957
+
958
+ // A ring of planar float samples, one writer and one reader — the render
959
+ // thread at one end, so neither end takes a lock.
960
+ class Ring {
961
+ public:
962
+ Ring(size_t channels, size_t capacity) : channels_(channels), cap_(capacity) {
963
+ data_.resize(channels * capacity);
964
+ }
965
+ size_t channels() const { return channels_; }
966
+ size_t available() const { return w_.load(std::memory_order_acquire) - r_.load(std::memory_order_acquire); }
967
+ // what fitted
968
+ size_t write(const float* const* src, size_t frames) {
969
+ size_t w = w_.load(std::memory_order_relaxed), r = r_.load(std::memory_order_acquire);
970
+ size_t room = cap_ - (w - r);
971
+ size_t n = frames < room ? frames : room;
972
+ for (size_t c = 0; c < channels_; c++) {
973
+ float* dst = &data_[c * cap_];
974
+ const float* s = src[c < channels_ ? c : 0];
975
+ for (size_t i = 0; i < n; i++) dst[(w + i) % cap_] = s ? s[i] : 0;
976
+ }
977
+ w_.store(w + n, std::memory_order_release);
978
+ return n;
979
+ }
980
+ size_t read(float* const* dst, size_t frames) {
981
+ size_t r = r_.load(std::memory_order_relaxed), w = w_.load(std::memory_order_acquire);
982
+ size_t n = frames < w - r ? frames : w - r;
983
+ for (size_t c = 0; c < channels_; c++) {
984
+ const float* src = &data_[c * cap_];
985
+ for (size_t i = 0; i < n; i++) dst[c][i] = src[(r + i) % cap_];
986
+ }
987
+ r_.store(r + n, std::memory_order_release);
988
+ return n;
989
+ }
990
+ void clear() { r_.store(w_.load()); }
991
+
992
+ private:
993
+ size_t channels_, cap_;
994
+ std::vector<float> data_;
995
+ std::atomic<size_t> w_{0}, r_{0};
996
+ };
997
+
998
+ @interface CALMicrophone : NSObject
999
+ @property(nonatomic) double mid;
1000
+ @property(nonatomic) double sampleRate;
1001
+ @property(nonatomic) AVAudioChannelCount channels;
1002
+ @property(nonatomic) BOOL echoCancellation, noiseSuppression, autoGainControl;
1003
+ @property(nonatomic, strong) NSString* deviceUID;
1004
+ @property(nonatomic, strong) AVAudioConverter* converter;
1005
+ @property(nonatomic, strong) AVAudioFormat* format;
1006
+ @property(nonatomic) BOOL started;
1007
+ @end
1008
+
1009
+ @implementation CALMicrophone {
1010
+ @public
1011
+ std::vector<std::vector<float>> pending; // converted, not yet a 10 ms chunk
1012
+ double sent; // frames sent, for `time`
1013
+ std::shared_ptr<std::atomic<int>> inflight;
1014
+ std::atomic<int> dropped;
1015
+ }
1016
+ @end
1017
+
1018
+ @interface CALOutput : NSObject
1019
+ @property(nonatomic) double oid;
1020
+ @property(nonatomic) double sampleRate;
1021
+ @property(nonatomic) AVAudioChannelCount channels;
1022
+ @property(nonatomic, strong) AVAudioSourceNode* node;
1023
+ @end
1024
+
1025
+ @implementation CALOutput {
1026
+ @public
1027
+ std::unique_ptr<Ring> ring;
1028
+ std::atomic<uint64_t> played; // frames the render thread pulled since the first write
1029
+ std::atomic<bool> begun;
1030
+ }
1031
+ @end
1032
+
1033
+ // The audio queue's, and touched nowhere else: the engine and everything
1034
+ // wired to it. The two things other threads need from it are kept apart —
1035
+ // the outputs, which JS opens and closes, under their own lock
1036
+ // (`OutputsNow`), and the latency `audioOutputState` reports, published as
1037
+ // a number — since a strong pointer the queue reassigns while JS reads it is
1038
+ // a use after free, and a dictionary JS mutates while the queue enumerates it
1039
+ // is a corrupted heap: both were seen, as a crash in an unrelated allocation.
1040
+ static AVAudioEngine* gEngine;
1041
+ static AVAudioSinkNode* gSink;
1042
+ static std::unique_ptr<Ring> gInputRing; // the input's samples, from the render thread
1043
+ static AVAudioFormat* gInputFormat;
1044
+ static dispatch_source_t gDrain;
1045
+ static BOOL gVoice;
1046
+ static NSString* gInputUID;
1047
+ static NSMutableDictionary<NSNumber*, CALMicrophone*>* gMics;
1048
+ static id gConfigNote;
1049
+ static std::atomic<double> gOutputLatency{0};
1050
+
1051
+ // JS's and the queue's alike, only ever under @synchronized([CALOutput class]).
1052
+ static NSMutableDictionary<NSNumber*, CALOutput*>* gOutputs;
1053
+ static NSString* gOutputUID;
1054
+
1055
+ // The outputs open now and the device the first of them named: a copy, taken
1056
+ // under the lock, which the queue works from.
1057
+ static NSArray<CALOutput*>* OutputsNow(NSString** uid) {
1058
+ @synchronized([CALOutput class]) {
1059
+ if (uid) *uid = gOutputUID;
1060
+ return gOutputs.allValues ?: @[];
1061
+ }
1062
+ }
1063
+
1064
+ static dispatch_queue_t AudioQueue() {
1065
+ static dispatch_queue_t q;
1066
+ static dispatch_once_t once;
1067
+ dispatch_once(&once, ^{ q = dispatch_queue_create("appkit.audio", DISPATCH_QUEUE_SERIAL); });
1068
+ return q;
1069
+ }
1070
+
1071
+ static void SetUnitDevice(AudioUnit unit, NSString* uid) {
1072
+ AudioDeviceID dev = DeviceForUID(uid);
1073
+ if (!unit || dev == kAudioObjectUnknown) return;
1074
+ AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &dev,
1075
+ sizeof(dev));
1076
+ }
1077
+
1078
+ static void DrainInput();
1079
+
1080
+ static void MicrophoneError(double mid, const char* name, NSString* message) {
1081
+ Send(std::move(
1082
+ CALEvent("microphone-error").Num("id", mid).Str("name", name).Str("message", message.UTF8String)));
1083
+ }
1084
+
1085
+ // On the audio queue: the engine wired for what is open now — its input
1086
+ // while a microphone is, voice processing while an echo-cancelled one is,
1087
+ // every output a source node into the mixer — and running while anything is.
1088
+ // Changing whether there is an input or voice processing stops the engine
1089
+ // first: neither can change on a running one.
1090
+ static void Rewire() {
1091
+ bool wantInput = gMics.count > 0;
1092
+ bool wantVoice = false;
1093
+ NSString* wantUID = nil;
1094
+ for (CALMicrophone* m in gMics.allValues) {
1095
+ wantVoice = wantVoice || m.echoCancellation;
1096
+ if (!wantUID) wantUID = m.deviceUID;
1097
+ }
1098
+ NSString* outputUID = nil;
1099
+ NSArray<CALOutput*>* outputs = OutputsNow(&outputUID);
1100
+ bool wantOutputs = outputs.count > 0;
1101
+ if (!wantInput && !wantOutputs) {
1102
+ if (gEngine) {
1103
+ [gEngine stop];
1104
+ if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
1105
+ gConfigNote = nil;
1106
+ if (gDrain) dispatch_source_cancel(gDrain);
1107
+ gDrain = nil;
1108
+ gEngine = nil;
1109
+ gSink = nil;
1110
+ gInputRing.reset();
1111
+ gVoice = NO;
1112
+ gInputUID = nil;
1113
+ gOutputLatency = 0;
1114
+ }
1115
+ return;
1116
+ }
1117
+ bool hadInput = gSink != nil;
1118
+ bool rebuild = !gEngine || hadInput != wantInput || (wantInput && gVoice != wantVoice) ||
1119
+ (wantInput && ![wantUID ?: @"" isEqualToString:gInputUID ?: @""]);
1120
+ if (rebuild) {
1121
+ if (gEngine) [gEngine stop];
1122
+ if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
1123
+ // a new engine each time: voice processing does not come off cleanly
1124
+ gEngine = [AVAudioEngine new];
1125
+ gSink = nil;
1126
+ gInputRing.reset();
1127
+ gVoice = NO;
1128
+ gInputUID = nil;
1129
+ if (wantInput) {
1130
+ AVAudioInputNode* input = gEngine.inputNode;
1131
+ if (wantUID) SetUnitDevice(input.audioUnit, wantUID);
1132
+ gInputUID = wantUID;
1133
+ if (wantVoice) {
1134
+ NSError* err = nil;
1135
+ gVoice = [input setVoiceProcessingEnabled:YES error:&err];
1136
+ }
1137
+ AVAudioFormat* hw = [input outputFormatForBus:0];
1138
+ gInputFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:hw.sampleRate
1139
+ channels:hw.channelCount];
1140
+ gInputRing = std::make_unique<Ring>(hw.channelCount, (size_t)(hw.sampleRate * 2));
1141
+ Ring* ring = gInputRing.get();
1142
+ gSink = [[AVAudioSinkNode alloc] initWithReceiverBlock:^OSStatus(const AudioTimeStamp*, AVAudioFrameCount n,
1143
+ const AudioBufferList* in) {
1144
+ const float* ch[16] = {nullptr};
1145
+ UInt32 count = in->mNumberBuffers < 16 ? in->mNumberBuffers : 16;
1146
+ for (UInt32 i = 0; i < count; i++) ch[i] = (const float*)in->mBuffers[i].mData;
1147
+ ring->write(ch, n);
1148
+ return noErr;
1149
+ }];
1150
+ [gEngine attachNode:gSink];
1151
+ [gEngine connect:input to:gSink format:gInputFormat];
1152
+ }
1153
+ if (outputUID) SetUnitDevice(gEngine.outputNode.audioUnit, outputUID);
1154
+ gConfigNote = [NSNotificationCenter.defaultCenter
1155
+ addObserverForName:AVAudioEngineConfigurationChangeNotification
1156
+ object:gEngine
1157
+ queue:nil
1158
+ usingBlock:^(NSNotification*) {
1159
+ // a device came or went under the engine: wired again, at
1160
+ // the formats there are now
1161
+ dispatch_async(AudioQueue(), ^{
1162
+ if (gEngine) {
1163
+ [gEngine stop];
1164
+ gEngine = nil;
1165
+ gSink = nil;
1166
+ for (CALOutput* o in OutputsNow(nullptr)) o.node = nil;
1167
+ for (CALMicrophone* m in gMics.allValues) m.converter = nil;
1168
+ }
1169
+ Rewire();
1170
+ });
1171
+ }];
1172
+ for (CALOutput* o in outputs) o.node = nil;
1173
+ for (CALMicrophone* m in gMics.allValues) m.converter = nil;
1174
+ }
1175
+ // outputs: a source node each, into the mixer
1176
+ AVAudioMixerNode* mixer = gEngine.mainMixerNode;
1177
+ for (CALOutput* o in outputs) {
1178
+ if (o.node) continue;
1179
+ AVAudioFormat* f = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:o.sampleRate channels:o.channels];
1180
+ CALOutput* out = o;
1181
+ Ring* ring = out->ring.get();
1182
+ o.node = [[AVAudioSourceNode alloc]
1183
+ initWithFormat:f
1184
+ renderBlock:^OSStatus(BOOL* silence, const AudioTimeStamp*, AVAudioFrameCount n, AudioBufferList* buf) {
1185
+ float* ch[16] = {nullptr};
1186
+ UInt32 count = buf->mNumberBuffers < 16 ? buf->mNumberBuffers : 16;
1187
+ for (UInt32 i = 0; i < count; i++) ch[i] = (float*)buf->mBuffers[i].mData;
1188
+ size_t got = ring->channels() <= count ? ring->read(ch, n) : 0;
1189
+ for (UInt32 i = 0; i < count; i++) {
1190
+ for (size_t j = got; j < n; j++) ch[i][j] = 0;
1191
+ }
1192
+ if (out->begun.load()) out->played.fetch_add(n);
1193
+ *silence = got == 0;
1194
+ return noErr;
1195
+ }];
1196
+ [gEngine attachNode:o.node];
1197
+ [gEngine connect:o.node to:mixer format:f];
1198
+ }
1199
+ // microphones: a converter each, from the input's format to theirs
1200
+ for (CALMicrophone* m in gMics.allValues) {
1201
+ if (m.converter) continue;
1202
+ m.format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:m.sampleRate channels:m.channels];
1203
+ m.converter = [[AVAudioConverter alloc] initFromFormat:gInputFormat toFormat:m.format];
1204
+ if (m.channels < gInputFormat.channelCount && m.channels == 1) {
1205
+ m.converter.downmix = YES;
1206
+ }
1207
+ }
1208
+ if (!gEngine.isRunning) {
1209
+ [gEngine prepare];
1210
+ NSError* err = nil;
1211
+ if (![gEngine startAndReturnError:&err]) {
1212
+ for (CALMicrophone* m in gMics.allValues) {
1213
+ if (!m.started) MicrophoneError(m.mid, "NotReadableError", err.localizedDescription ?: @"the engine did not start");
1214
+ }
1215
+ return;
1216
+ }
1217
+ }
1218
+ gOutputLatency = gEngine.outputNode.presentationLatency;
1219
+ if (wantInput && !gDrain) {
1220
+ gDrain = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, AudioQueue());
1221
+ dispatch_source_set_timer(gDrain, dispatch_time(DISPATCH_TIME_NOW, 0), 10 * NSEC_PER_MSEC, 2 * NSEC_PER_MSEC);
1222
+ dispatch_source_set_event_handler(gDrain, ^{ DrainInput(); });
1223
+ dispatch_resume(gDrain);
1224
+ } else if (!wantInput && gDrain) {
1225
+ dispatch_source_cancel(gDrain);
1226
+ gDrain = nil;
1227
+ }
1228
+ AVAudioInputNode* input = wantInput ? gEngine.inputNode : nil;
1229
+ for (CALMicrophone* m in gMics.allValues) {
1230
+ if (m.started) continue;
1231
+ m.started = YES;
1232
+ bool voice = gVoice;
1233
+ bool agc = voice && input.voiceProcessingAGCEnabled;
1234
+ if (voice && !m.autoGainControl) {
1235
+ input.voiceProcessingAGCEnabled = NO;
1236
+ agc = NO;
1237
+ }
1238
+ double latency = input.presentationLatency;
1239
+ Send(std::move(CALEvent("microphone-started")
1240
+ .Num("id", m.mid)
1241
+ .Bool("echoCancellation", voice)
1242
+ .Bool("noiseSuppression", voice)
1243
+ .Bool("autoGainControl", agc)
1244
+ .Num("sampleRate", m.sampleRate)
1245
+ .Num("channels", m.channels)
1246
+ .Num("latency", latency)));
1247
+ }
1248
+ }
1249
+
1250
+ // Every 10 ms on the audio queue: what the input gave, converted for each
1251
+ // microphone, out in 10 ms chunks.
1252
+ static void DrainInput() {
1253
+ Ring* ring = gInputRing.get();
1254
+ if (!ring || !gInputFormat) return;
1255
+ size_t n = ring->available();
1256
+ if (n == 0) return;
1257
+ AVAudioPCMBuffer* in = [[AVAudioPCMBuffer alloc] initWithPCMFormat:gInputFormat frameCapacity:(AVAudioFrameCount)n];
1258
+ ring->read(in.floatChannelData, n);
1259
+ in.frameLength = (AVAudioFrameCount)n;
1260
+ for (CALMicrophone* m in gMics.allValues) {
1261
+ if (!m.converter) continue;
1262
+ double ratio = m.sampleRate / gInputFormat.sampleRate;
1263
+ AVAudioFrameCount cap = (AVAudioFrameCount)ceil(n * ratio) + 64;
1264
+ AVAudioPCMBuffer* out = [[AVAudioPCMBuffer alloc] initWithPCMFormat:m.format frameCapacity:cap];
1265
+ __block bool given = false;
1266
+ NSError* err = nil;
1267
+ [m.converter convertToBuffer:out
1268
+ error:&err
1269
+ withInputFromBlock:^AVAudioBuffer*(AVAudioPacketCount, AVAudioConverterInputStatus* status) {
1270
+ if (given) {
1271
+ *status = AVAudioConverterInputStatus_NoDataNow;
1272
+ return nil;
1273
+ }
1274
+ given = true;
1275
+ *status = AVAudioConverterInputStatus_HaveData;
1276
+ return in;
1277
+ }];
1278
+ if (m->pending.size() != m.channels) m->pending.assign(m.channels, {});
1279
+ for (AVAudioChannelCount c = 0; c < m.channels; c++) {
1280
+ float* src = out.floatChannelData[c];
1281
+ m->pending[c].insert(m->pending[c].end(), src, src + out.frameLength);
1282
+ }
1283
+ size_t chunk = (size_t)llround(m.sampleRate / 100);
1284
+ while (!m->pending.empty() && m->pending[0].size() >= chunk) {
1285
+ auto planes = std::make_shared<std::vector<std::vector<float>>>();
1286
+ for (auto& p : m->pending) {
1287
+ planes->emplace_back(p.begin(), p.begin() + chunk);
1288
+ p.erase(p.begin(), p.begin() + chunk);
1289
+ }
1290
+ double time = m->sent / m.sampleRate;
1291
+ m->sent += chunk;
1292
+ // two seconds waiting is as far as it goes: past that, the oldest wait
1293
+ // and this one is counted instead
1294
+ if (m->inflight->load() > 200) {
1295
+ m->dropped++;
1296
+ continue;
1297
+ }
1298
+ int dropped = m->dropped.exchange(0);
1299
+ auto inflight = m->inflight;
1300
+ inflight->fetch_add(1);
1301
+ double mid = m.mid, rate = m.sampleRate;
1302
+ if (!Deliver(^{
1303
+ inflight->fetch_sub(1);
1304
+ if (!CALListening()) return;
1305
+ CALEvent ev("audio-input");
1306
+ ev.Num("id", mid).Num("sampleRate", rate).Num("frames", (double)chunk).Num("time", time);
1307
+ if (dropped) ev.Num("dropped", dropped);
1308
+ ev.Handle("channels", ^Napi::Value(Napi::Env env) {
1309
+ Napi::Array a = Napi::Array::New(env, planes->size());
1310
+ for (size_t c = 0; c < planes->size(); c++) {
1311
+ auto& p = (*planes)[c];
1312
+ Napi::ArrayBuffer ab = Napi::ArrayBuffer::New(env, p.size() * sizeof(float));
1313
+ memcpy(ab.Data(), p.data(), p.size() * sizeof(float));
1314
+ a.Set((uint32_t)c, Napi::Float32Array::New(env, p.size(), ab, 0));
1315
+ }
1316
+ return a;
1317
+ });
1318
+ CALEmit(std::move(ev));
1319
+ })) {
1320
+ inflight->fetch_sub(1);
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ static Napi::Value OpenMicrophone(const Napi::CallbackInfo& info) {
1327
+ Napi::Env env = info.Env();
1328
+ Napi::Value opts = info.Length() > 1 ? info[1] : env.Undefined();
1329
+ double rate = 48000, channels = 1;
1330
+ OptNum(opts, "sampleRate", &rate);
1331
+ OptNum(opts, "channels", &channels);
1332
+ rate = fmin(192000, fmax(8000, rate));
1333
+ channels = fmin(2, fmax(1, round(channels)));
1334
+ bool echo = true, noise = true, agc = true;
1335
+ OptBool(opts, "echoCancellation", &echo);
1336
+ OptBool(opts, "noiseSuppression", &noise);
1337
+ OptBool(opts, "autoGainControl", &agc);
1338
+ NSString* uid = Str(info[0]);
1339
+ double mid = (double)(++gNextCapture);
1340
+ Napi::Object out = Napi::Object::New(env);
1341
+ out.Set("id", mid);
1342
+ out.Set("sampleRate", rate);
1343
+ out.Set("channels", channels);
1344
+ out.Set("echoCancellation", echo);
1345
+ out.Set("noiseSuppression", noise);
1346
+ out.Set("autoGainControl", agc);
1347
+ CALMicrophone* m = [CALMicrophone new];
1348
+ m.mid = mid;
1349
+ m.sampleRate = rate;
1350
+ m.channels = (AVAudioChannelCount)channels;
1351
+ // the canceller brings its suppressor and its gain control: none of the
1352
+ // three without it
1353
+ m.echoCancellation = echo || noise;
1354
+ m.noiseSuppression = noise;
1355
+ m.autoGainControl = agc;
1356
+ m->inflight = std::make_shared<std::atomic<int>>(0);
1357
+ m->sent = 0;
1358
+ m->dropped = 0;
1359
+ dispatch_async(AudioQueue(), ^{
1360
+ // a device that is not there is said before anything is asked of the user
1361
+ if (uid && DeviceForUID(uid) == kAudioObjectUnknown) {
1362
+ MicrophoneError(mid, "NotFoundError", [NSString stringWithFormat:@"there is no microphone %@", uid]);
1363
+ return;
1364
+ }
1365
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
1366
+ if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
1367
+ MicrophoneError(mid, "NotAllowedError", @"the microphone is not allowed for this app (Privacy & Security › Microphone)");
1368
+ return;
1369
+ }
1370
+ void (^open)(void) = ^{
1371
+ NSString* deviceUID = uid;
1372
+ if (deviceUID && [deviceUID isEqualToString:DeviceUID(DefaultDevice(true))]) deviceUID = nil;
1373
+ if (deviceUID && DeviceForUID(deviceUID) == kAudioObjectUnknown) {
1374
+ MicrophoneError(mid, "NotFoundError", [NSString stringWithFormat:@"there is no microphone %@", deviceUID]);
1375
+ return;
1376
+ }
1377
+ for (CALMicrophone* other in gMics.allValues) {
1378
+ if (![other.deviceUID ?: @"" isEqualToString:deviceUID ?: @""]) {
1379
+ MicrophoneError(mid, "NotReadableError",
1380
+ @"another microphone is open: the engine has one input at a time");
1381
+ return;
1382
+ }
1383
+ }
1384
+ m.deviceUID = deviceUID;
1385
+ if (!gMics) gMics = [NSMutableDictionary dictionary];
1386
+ gMics[@(mid)] = m;
1387
+ @try {
1388
+ Rewire();
1389
+ } @catch (NSException* e) {
1390
+ [gMics removeObjectForKey:@(mid)];
1391
+ MicrophoneError(mid, "NotReadableError", e.reason ?: @"the microphone could not be opened");
1392
+ }
1393
+ };
1394
+ if (status == AVAuthorizationStatusNotDetermined) {
1395
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
1396
+ completionHandler:^(BOOL granted) {
1397
+ dispatch_async(AudioQueue(), ^{
1398
+ if (!granted) {
1399
+ MicrophoneError(mid, "NotAllowedError",
1400
+ @"the microphone was not allowed — by the user, or by "
1401
+ @"macOS for a process it does not take for an app");
1402
+ return;
1403
+ }
1404
+ open();
1405
+ });
1406
+ }];
1407
+ return;
1408
+ }
1409
+ open();
1410
+ });
1411
+ return out;
1412
+ }
1413
+
1414
+ static Napi::Value CloseMicrophone(const Napi::CallbackInfo& info) {
1415
+ Napi::Env env = info.Env();
1416
+ if (!info[0].IsNumber()) return env.Undefined();
1417
+ double mid = info[0].As<Napi::Number>().DoubleValue();
1418
+ dispatch_async(AudioQueue(), ^{
1419
+ if (!gMics[@(mid)]) return;
1420
+ [gMics removeObjectForKey:@(mid)];
1421
+ Rewire();
1422
+ });
1423
+ return env.Undefined();
1424
+ }
1425
+
1426
+ static CALOutput* OutputFor(double oid) {
1427
+ @synchronized([CALOutput class]) {
1428
+ return gOutputs[@(oid)];
1429
+ }
1430
+ }
1431
+
1432
+ static Napi::Value OpenAudioOutput(const Napi::CallbackInfo& info) {
1433
+ Napi::Env env = info.Env();
1434
+ Napi::Value opts = info.Length() > 0 ? info[0] : env.Undefined();
1435
+ double rate = 48000, channels = 2;
1436
+ OptNum(opts, "sampleRate", &rate);
1437
+ OptNum(opts, "channels", &channels);
1438
+ rate = fmin(384000, fmax(1000, rate));
1439
+ channels = fmin(16, fmax(1, round(channels)));
1440
+ NSString* uid = opts.IsObject() ? Str(opts.As<Napi::Object>().Get("deviceId")) : nil;
1441
+ double oid = (double)(++gNextCapture);
1442
+ CALOutput* o = [CALOutput new];
1443
+ o.oid = oid;
1444
+ o.sampleRate = rate;
1445
+ o.channels = (AVAudioChannelCount)channels;
1446
+ o->ring = std::make_unique<Ring>((size_t)channels, (size_t)(rate * 10));
1447
+ o->played = 0;
1448
+ o->begun = false;
1449
+ @synchronized([CALOutput class]) {
1450
+ if (!gOutputs) gOutputs = [NSMutableDictionary dictionary];
1451
+ if (uid && gOutputs.count == 0) gOutputUID = uid;
1452
+ gOutputs[@(oid)] = o;
1453
+ }
1454
+ dispatch_async(AudioQueue(), ^{
1455
+ @try {
1456
+ Rewire();
1457
+ } @catch (NSException*) {
1458
+ // an engine that would not wire plays nothing; its state says so
1459
+ }
1460
+ });
1461
+ Napi::Object out = Napi::Object::New(env);
1462
+ out.Set("id", oid);
1463
+ out.Set("sampleRate", rate);
1464
+ out.Set("channels", channels);
1465
+ out.Set("latency", 0.0);
1466
+ return out;
1467
+ }
1468
+
1469
+ static Napi::Value AudioOutputWrite(const Napi::CallbackInfo& info) {
1470
+ Napi::Env env = info.Env();
1471
+ if (!info[0].IsNumber() || !info[1].IsArray()) {
1472
+ Napi::TypeError::New(env, "audioOutputWrite(id, channels): channels is a Float32Array a channel")
1473
+ .ThrowAsJavaScriptException();
1474
+ return env.Undefined();
1475
+ }
1476
+ CALOutput* o = OutputFor(info[0].As<Napi::Number>().DoubleValue());
1477
+ if (!o) return Napi::Number::New(env, 0);
1478
+ Napi::Array arr = info[1].As<Napi::Array>();
1479
+ std::vector<const float*> ch(o.channels, nullptr);
1480
+ size_t frames = SIZE_MAX;
1481
+ for (uint32_t i = 0; i < arr.Length() && i < o.channels; i++) {
1482
+ Napi::Value v = arr.Get(i);
1483
+ if (!v.IsTypedArray() || v.As<Napi::TypedArray>().TypedArrayType() != napi_float32_array) {
1484
+ Napi::TypeError::New(env, "audioOutputWrite: every channel is a Float32Array").ThrowAsJavaScriptException();
1485
+ return env.Undefined();
1486
+ }
1487
+ Napi::Float32Array f = v.As<Napi::Float32Array>();
1488
+ ch[i] = f.Data();
1489
+ frames = f.ElementLength() < frames ? f.ElementLength() : frames;
1490
+ }
1491
+ if (frames == SIZE_MAX) frames = 0;
1492
+ // a channel not handed is the first one again
1493
+ for (size_t i = 1; i < ch.size(); i++) {
1494
+ if (!ch[i]) ch[i] = ch[0];
1495
+ }
1496
+ o->ring->write(ch.data(), frames);
1497
+ if (frames) o->begun = true;
1498
+ return Napi::Number::New(env, (double)o->ring->available());
1499
+ }
1500
+
1501
+ static Napi::Value AudioOutputState(const Napi::CallbackInfo& info) {
1502
+ Napi::Env env = info.Env();
1503
+ if (!info[0].IsNumber()) return env.Undefined();
1504
+ CALOutput* o = OutputFor(info[0].As<Napi::Number>().DoubleValue());
1505
+ Napi::Object out = Napi::Object::New(env);
1506
+ if (!o) {
1507
+ out.Set("currentTime", 0.0);
1508
+ out.Set("queued", 0.0);
1509
+ out.Set("latency", 0.0);
1510
+ return out;
1511
+ }
1512
+ out.Set("currentTime", (double)o->played.load() / o.sampleRate);
1513
+ out.Set("queued", (double)o->ring->available());
1514
+ out.Set("latency", gOutputLatency.load());
1515
+ return out;
1516
+ }
1517
+
1518
+ static Napi::Value CloseAudioOutput(const Napi::CallbackInfo& info) {
1519
+ Napi::Env env = info.Env();
1520
+ if (!info[0].IsNumber()) return env.Undefined();
1521
+ double oid = info[0].As<Napi::Number>().DoubleValue();
1522
+ CALOutput* o;
1523
+ @synchronized([CALOutput class]) {
1524
+ o = gOutputs[@(oid)];
1525
+ [gOutputs removeObjectForKey:@(oid)];
1526
+ if (gOutputs.count == 0) gOutputUID = nil;
1527
+ }
1528
+ if (!o) return env.Undefined();
1529
+ dispatch_async(AudioQueue(), ^{
1530
+ if (o.node && gEngine) {
1531
+ [gEngine disconnectNodeOutput:o.node];
1532
+ [gEngine detachNode:o.node];
1533
+ }
1534
+ o.node = nil;
1535
+ Rewire();
1536
+ });
1537
+ return env.Undefined();
1538
+ }
1539
+
1540
+ // ---------------------------------------------------------------------------
1541
+ // the screen
1542
+ // ---------------------------------------------------------------------------
1543
+
1544
+ static Napi::Value ScreenCaptureDisplays(const Napi::CallbackInfo& info) {
1545
+ return CALAnswer(info, "screenCaptureDisplays", ^CALValueBlock {
1546
+ NSArray<NSScreen*>* screens = NSScreen.screens;
1547
+ CGFloat top = screens.count ? NSMaxY(screens[0].frame) : 0;
1548
+ struct One {
1549
+ double id, x, y, w, h, scale;
1550
+ std::string name;
1551
+ };
1552
+ auto list = std::make_shared<std::vector<One>>();
1553
+ for (NSScreen* s in screens) {
1554
+ NSNumber* n = s.deviceDescription[@"NSScreenNumber"];
1555
+ NSRect f = s.frame;
1556
+ NSString* name = @"";
1557
+ if (@available(macOS 10.15, *)) name = s.localizedName ?: @"";
1558
+ list->push_back({n.doubleValue, f.origin.x, top - NSMaxY(f), f.size.width, f.size.height,
1559
+ s.backingScaleFactor, name.UTF8String});
1560
+ }
1561
+ return ^Napi::Value(Napi::Env env) {
1562
+ Napi::Array a = Napi::Array::New(env, list->size());
1563
+ for (size_t i = 0; i < list->size(); i++) {
1564
+ const One& s = (*list)[i];
1565
+ Napi::Object o = Napi::Object::New(env);
1566
+ o.Set("id", s.id);
1567
+ o.Set("name", s.name);
1568
+ o.Set("x", s.x);
1569
+ o.Set("y", s.y);
1570
+ o.Set("width", s.w);
1571
+ o.Set("height", s.h);
1572
+ o.Set("scale", s.scale);
1573
+ a.Set((uint32_t)i, o);
1574
+ }
1575
+ return a;
1576
+ };
1577
+ });
1578
+ }
1579
+
1580
+ static CALValueBlock ScreenshotError(const char* name, NSString* message) {
1581
+ std::string n = name, m = message.UTF8String ?: "";
1582
+ return ^Napi::Value(Napi::Env env) {
1583
+ Napi::Object o = Napi::Object::New(env);
1584
+ o.Set("error", m);
1585
+ o.Set("name", n);
1586
+ return o;
1587
+ };
1588
+ }
1589
+
1590
+ // A CGImage as straight RGBA in sRGB: drawn into a premultiplied context
1591
+ // (the only kind CoreGraphics draws into) and divided back out.
1592
+ static CALValueBlock ScreenshotOf(CGImageRef img, double scale) {
1593
+ size_t w = CGImageGetWidth(img), h = CGImageGetHeight(img);
1594
+ auto px = std::make_shared<std::vector<uint8_t>>(w * h * 4);
1595
+ CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1596
+ CGContextRef ctx = CGBitmapContextCreate(px->data(), w, h, 8, w * 4, srgb,
1597
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1598
+ CGColorSpaceRelease(srgb);
1599
+ if (!ctx) return ScreenshotError("NotReadableError", @"the picture could not be converted");
1600
+ CGContextSetBlendMode(ctx, kCGBlendModeCopy);
1601
+ CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), img);
1602
+ CGContextRelease(ctx);
1603
+ uint8_t* p = px->data();
1604
+ for (size_t i = 0; i < w * h * 4; i += 4) {
1605
+ uint8_t a = p[i + 3];
1606
+ if (a == 0 || a == 255) continue;
1607
+ p[i] = (uint8_t)fmin(255, p[i] * 255.0 / a + 0.5);
1608
+ p[i + 1] = (uint8_t)fmin(255, p[i + 1] * 255.0 / a + 0.5);
1609
+ p[i + 2] = (uint8_t)fmin(255, p[i + 2] * 255.0 / a + 0.5);
1610
+ }
1611
+ return ^Napi::Value(Napi::Env env) {
1612
+ Napi::Object o = Napi::Object::New(env);
1613
+ o.Set("width", (double)w);
1614
+ o.Set("height", (double)h);
1615
+ o.Set("scale", scale);
1616
+ o.Set("data", Napi::Buffer<uint8_t>::Copy(env, px->data(), px->size()));
1617
+ return o;
1618
+ };
1619
+ }
1620
+
1621
+ static Napi::Value CaptureScreenshot(const Napi::CallbackInfo& info) {
1622
+ Napi::Env env = info.Env();
1623
+ Napi::Value last = info.Length() ? info[info.Length() - 1] : env.Undefined();
1624
+ if (!last.IsFunction()) {
1625
+ Napi::TypeError::New(env, "captureScreenshot(options, cb): it answers through cb")
1626
+ .ThrowAsJavaScriptException();
1627
+ return env.Undefined();
1628
+ }
1629
+ Napi::Value opts = info.Length() > 1 ? info[0] : env.Undefined();
1630
+ double display = 0, window = 0;
1631
+ bool hasDisplay = OptNum(opts, "display", &display);
1632
+ bool hasWindow = OptNum(opts, "window", &window);
1633
+ bool cursor = false;
1634
+ OptBool(opts, "cursor", &cursor);
1635
+ bool hasRect = false;
1636
+ CGRect rect = CGRectZero;
1637
+ if (opts.IsObject() && opts.As<Napi::Object>().Get("rect").IsObject()) {
1638
+ Napi::Value r = opts.As<Napi::Object>().Get("rect");
1639
+ double x = 0, y = 0, w = 0, h = 0;
1640
+ bool hx = OptNum(r, "x", &x), hy = OptNum(r, "y", &y);
1641
+ bool hw = OptNum(r, "width", &w), hh = OptNum(r, "height", &h);
1642
+ hasRect = hx && hy && hw && hh && w > 0 && h > 0;
1643
+ rect = CGRectMake(x, y, w, h);
1644
+ }
1645
+ CALTsfn tsfn = CALReplyTo(env, last.As<Napi::Function>(), "appkit:captureScreenshot");
1646
+ if (@available(macOS 14.0, *)) {
1647
+ [SCShareableContent
1648
+ getShareableContentExcludingDesktopWindows:NO
1649
+ onScreenWindowsOnly:YES
1650
+ completionHandler:^(SCShareableContent* content, NSError* error) {
1651
+ if (error || !content) {
1652
+ bool declined = error.code == SCStreamErrorUserDeclined;
1653
+ CALReply(tsfn, ScreenshotError(
1654
+ declined ? "NotAllowedError" : "NotReadableError",
1655
+ declined ? @"Screen Recording is not allowed for this app "
1656
+ @"(Privacy & Security › Screen Recording)"
1657
+ : (error.localizedDescription ?: @"the screen could not be listed")));
1658
+ return;
1659
+ }
1660
+ SCContentFilter* filter = nil;
1661
+ if (hasWindow) {
1662
+ for (SCWindow* w in content.windows) {
1663
+ if (w.windowID == (CGWindowID)window) {
1664
+ filter = [[SCContentFilter alloc] initWithDesktopIndependentWindow:w];
1665
+ break;
1666
+ }
1667
+ }
1668
+ } else {
1669
+ CGDirectDisplayID want = hasDisplay ? (CGDirectDisplayID)display : CGMainDisplayID();
1670
+ for (SCDisplay* d in content.displays) {
1671
+ if (d.displayID == want) {
1672
+ filter = [[SCContentFilter alloc] initWithDisplay:d excludingWindows:@[]];
1673
+ break;
1674
+ }
1675
+ }
1676
+ }
1677
+ if (!filter) {
1678
+ CALReply(tsfn, ScreenshotError("NotFoundError", hasWindow ? @"there is no such window on screen"
1679
+ : @"there is no such display"));
1680
+ return;
1681
+ }
1682
+ double scale = filter.pointPixelScale;
1683
+ CGRect area = hasRect ? rect : CGRectMake(0, 0, filter.contentRect.size.width,
1684
+ filter.contentRect.size.height);
1685
+ SCStreamConfiguration* config = [SCStreamConfiguration new];
1686
+ if (hasRect) config.sourceRect = rect;
1687
+ config.width = (size_t)llround(area.size.width * scale);
1688
+ config.height = (size_t)llround(area.size.height * scale);
1689
+ config.showsCursor = cursor;
1690
+ config.colorSpaceName = kCGColorSpaceSRGB;
1691
+ config.ignoreShadowsSingleWindow = YES;
1692
+ [SCScreenshotManager captureImageWithFilter:filter
1693
+ configuration:config
1694
+ completionHandler:^(CGImageRef img, NSError* err) {
1695
+ if (!img) {
1696
+ bool no = err.code == SCStreamErrorUserDeclined;
1697
+ CALReply(tsfn, ScreenshotError(
1698
+ no ? "NotAllowedError" : "NotReadableError",
1699
+ err.localizedDescription ?: @"no picture came back"));
1700
+ return;
1701
+ }
1702
+ CALReply(tsfn, ScreenshotOf(img, scale));
1703
+ }];
1704
+ }];
1705
+ } else {
1706
+ CALReply(tsfn, ScreenshotError("NotSupportedError", @"screenshots need macOS 14 (ScreenCaptureKit)"));
1707
+ }
1708
+ return env.Undefined();
1709
+ }
1710
+
1711
+ void InitCapture(Napi::Env env, Napi::Object exports) {
1712
+ // The delivery function is the main thread's, made the once, for the
1713
+ // reason InitNotifications gives: pump mode's listener is called there.
1714
+ if (pthread_main_np() && !gDeliver.load()) {
1715
+ DeliveryTsfn t = DeliveryTsfn::New(env, "appkit:capture", 0, 1);
1716
+ t.Unref(env);
1717
+ gDeliver.store(new CALTsfn(CALTsfn::Watch(env, t)));
1718
+ }
1719
+ exports.Set("captureDevices", Napi::Function::New(env, CaptureDevices));
1720
+ exports.Set("openCamera", Napi::Function::New(env, OpenCamera));
1721
+ exports.Set("cameraFrames", Napi::Function::New(env, CameraFrames));
1722
+ exports.Set("cameraCopyFrame", Napi::Function::New(env, CameraCopyFrame));
1723
+ exports.Set("closeCamera", Napi::Function::New(env, CloseCamera));
1724
+ exports.Set("openMicrophone", Napi::Function::New(env, OpenMicrophone));
1725
+ exports.Set("closeMicrophone", Napi::Function::New(env, CloseMicrophone));
1726
+ exports.Set("openAudioOutput", Napi::Function::New(env, OpenAudioOutput));
1727
+ exports.Set("audioOutputWrite", Napi::Function::New(env, AudioOutputWrite));
1728
+ exports.Set("audioOutputState", Napi::Function::New(env, AudioOutputState));
1729
+ exports.Set("closeAudioOutput", Napi::Function::New(env, CloseAudioOutput));
1730
+ exports.Set("screenCaptureDisplays", Napi::Function::New(env, ScreenCaptureDisplays));
1731
+ exports.Set("captureScreenshot", Napi::Function::New(env, CaptureScreenshot));
1732
+ }