@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.
@@ -0,0 +1,876 @@
1
+ // @windowkit/appkit systemaudio.mm — the sound other applications play, for a
2
+ // renderer's media capture (react-x11's design/architecture/media-capture.md):
3
+ // CoreAudio's process taps (macOS 14.2), of every process but this one or of
4
+ // one application, delivered the way a microphone's sound is.
5
+ //
6
+ // The processes — nothing asked of the user, nothing prompts:
7
+ //
8
+ // - audioProcesses() -> [{ pid, bundleId, name, playing, app? }], or the same
9
+ // through audioProcesses(cb) from a queue of its own: CoreAudio's process
10
+ // objects, every process connected to the audio server and not only those
11
+ // playing. `playing` is whether it has output running now; `app` is the
12
+ // outermost application bundle its executable sits in, `{ bundleId, name,
13
+ // regular }`, `regular` for an app with a Dock icon. A browser's renderers
14
+ // and an Electron app's helpers play under helper bundle ids of their own
15
+ // (com.google.Chrome.helper), and `app` is what a person would call them.
16
+ // - event `audio-processes` whenever a process connects or goes, or starts or
17
+ // stops playing. Watched from the first audioProcesses() on.
18
+ //
19
+ // A tap:
20
+ //
21
+ // - openSystemAudio({ pid?, bundleId?, exclude?, sampleRate, channels }) ->
22
+ // { id, sampleRate, channels }: a private tap of every process but this one
23
+ // and the pids in `exclude`; with `pid`, of that process; with `bundleId`,
24
+ // of every process whose own bundle id or `app` is that one. A bundle id's
25
+ // tap follows the application: a helper that starts later joins it, and an
26
+ // application that is not running is silence until it is. The audio is
27
+ // resampled and mixed to the rate and count asked, as a microphone's is.
28
+ // `system-audio-started { id, sampleRate, channels, latency }` or
29
+ // `system-audio-error { id, name, message }` answers the open, `name` Media
30
+ // Capture's (NotFoundError for a pid with no audio, NotAllowedError, and
31
+ // NotReadableError for CoreAudio saying no); then `audio-input { id,
32
+ // sampleRate, channels: [Float32Array], frames, time, dropped? }` every
33
+ // 10 ms — a microphone's event — silence included while nothing plays, and
34
+ // nothing dropped short of two seconds waiting. `system-audio-ended { id }`
35
+ // when the one process tapped has gone. closeSystemAudio(id).
36
+ //
37
+ // These verbs are exported on macOS 14.2 and later only, which is how a
38
+ // renderer tells whether there is a tap to open.
39
+ //
40
+ // The permission is TCC's System Audio Recording (kTCCServiceAudioCapture;
41
+ // NSAudioCaptureUsageDescription is the bundle's key), which permissions.mm
42
+ // reads and asks for as `system-audio-recording`. A tap without it is not an
43
+ // error — it delivers silence, for as long as anybody reads it — so an open
44
+ // reads the status first: a refusal is a NotAllowedError, and an undecided one
45
+ // is asked before the tap is made.
46
+ //
47
+ // Each tap is an aggregate device of its own holding the tap and nothing else:
48
+ // no output device beside it, whose input streams would be opened with it (a
49
+ // headset's microphone, and a Bluetooth headset switched into its call
50
+ // profile by that) and come first in the buffers. The IO block runs on a
51
+ // queue of the tap's own; everything else — making, following, closing — on
52
+ // one queue for all of them, where CoreAudio's listeners call too.
53
+ //
54
+ // APPKIT_DEBUG_AUDIO=1 — capture.mm's switch — says on stderr what each tap
55
+ // did: the grant read, each CoreAudio call's status, the first buffers'
56
+ // layout, and once a second the frames in, the chunks out and the loudest
57
+ // sample. A peak of 0 with something playing is a refused grant: macOS feeds
58
+ // such a tap silence.
59
+
60
+ #include <napi.h>
61
+ #import <AVFoundation/AVFoundation.h>
62
+ #import <Cocoa/Cocoa.h>
63
+ #import <CoreAudio/AudioHardwareTapping.h>
64
+ #import <CoreAudio/CATapDescription.h>
65
+ #import <CoreAudio/CoreAudio.h>
66
+ #include <libproc.h>
67
+ #include <mach/mach_time.h>
68
+ #include <unistd.h>
69
+
70
+ #include <atomic>
71
+ #include <cmath>
72
+ #include <memory>
73
+ #include <string>
74
+ #include <vector>
75
+
76
+ #include "channel.h"
77
+
78
+ // capture.mm: the count every capture's id comes from, so an event's id names
79
+ // one thing, and the one way a queue of CoreAudio's reaches JS
80
+ double CALNextCaptureId();
81
+ bool CALCaptureDeliver(dispatch_block_t block);
82
+
83
+ // permissions.mm: TCC's System Audio Recording, read and asked
84
+ const char* CALAudioCaptureStatus();
85
+ void CALAudioCaptureRequest(void (^done)(void));
86
+
87
+ static const bool gDebugAudio = [] {
88
+ const char* v = getenv("APPKIT_DEBUG_AUDIO");
89
+ return v && *v && strcmp(v, "0") != 0;
90
+ }();
91
+ #define TAP_LOG(...) \
92
+ do { \
93
+ if (gDebugAudio) { \
94
+ fprintf(stderr, "@windowkit/appkit system audio: " __VA_ARGS__); \
95
+ fputc('\n', stderr); \
96
+ } \
97
+ } while (0)
98
+
99
+ static double Seconds() {
100
+ static mach_timebase_info_data_t base = [] {
101
+ mach_timebase_info_data_t b;
102
+ mach_timebase_info(&b);
103
+ return b;
104
+ }();
105
+ return (double)mach_absolute_time() * base.numer / base.denom / 1e9;
106
+ }
107
+
108
+ static void Send(CALEvent ev) {
109
+ auto held = std::make_shared<CALEvent>(std::move(ev));
110
+ CALCaptureDeliver(^{
111
+ if (CALListening()) CALEmit(std::move(*held));
112
+ });
113
+ }
114
+
115
+ static NSString* Str(Napi::Value v) {
116
+ if (!v.IsString()) return nil;
117
+ return [NSString stringWithUTF8String:v.As<Napi::String>().Utf8Value().c_str()];
118
+ }
119
+
120
+ static bool OptNum(Napi::Value obj, const char* k, double* out) {
121
+ if (!obj.IsObject()) return false;
122
+ Napi::Value v = obj.As<Napi::Object>().Get(k);
123
+ if (!v.IsNumber()) return false;
124
+ double d = v.As<Napi::Number>().DoubleValue();
125
+ if (!std::isfinite(d)) return false;
126
+ *out = d;
127
+ return true;
128
+ }
129
+
130
+ static AudioObjectPropertyAddress Global(AudioObjectPropertySelector sel) {
131
+ return {sel, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain};
132
+ }
133
+
134
+ // One queue for making, following and closing taps, and for CoreAudio's
135
+ // listeners: everything below that is not the IO itself.
136
+ static dispatch_queue_t Control() {
137
+ static dispatch_queue_t q;
138
+ static dispatch_once_t once;
139
+ dispatch_once(&once, ^{ q = dispatch_queue_create("appkit.systemaudio", DISPATCH_QUEUE_SERIAL); });
140
+ return q;
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // processes
145
+ // ---------------------------------------------------------------------------
146
+
147
+ static std::vector<AudioObjectID> ProcessObjects() {
148
+ AudioObjectPropertyAddress a = Global(kAudioHardwarePropertyProcessObjectList);
149
+ UInt32 size = 0;
150
+ if (AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &a, 0, nullptr, &size) != noErr) return {};
151
+ std::vector<AudioObjectID> ids(size / sizeof(AudioObjectID));
152
+ if (ids.empty() || AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, nullptr, &size, ids.data()) != noErr) {
153
+ return {};
154
+ }
155
+ ids.resize(size / sizeof(AudioObjectID));
156
+ return ids;
157
+ }
158
+
159
+ static pid_t PidOf(AudioObjectID p) {
160
+ pid_t pid = -1;
161
+ UInt32 size = sizeof(pid);
162
+ AudioObjectPropertyAddress a = Global(kAudioProcessPropertyPID);
163
+ if (AudioObjectGetPropertyData(p, &a, 0, nullptr, &size, &pid) != noErr) return -1;
164
+ return pid;
165
+ }
166
+
167
+ static NSString* BundleIdOf(AudioObjectID p) {
168
+ CFStringRef s = nullptr;
169
+ UInt32 size = sizeof(s);
170
+ AudioObjectPropertyAddress a = Global(kAudioProcessPropertyBundleID);
171
+ if (AudioObjectGetPropertyData(p, &a, 0, nullptr, &size, &s) != noErr || !s) return @"";
172
+ return (__bridge_transfer NSString*)s;
173
+ }
174
+
175
+ static bool PlayingOf(AudioObjectID p) {
176
+ UInt32 on = 0, size = sizeof(on);
177
+ AudioObjectPropertyAddress a = Global(kAudioProcessPropertyIsRunningOutput);
178
+ return AudioObjectGetPropertyData(p, &a, 0, nullptr, &size, &on) == noErr && on;
179
+ }
180
+
181
+ static NSString* ExecutableOf(pid_t pid) {
182
+ char path[PROC_PIDPATHINFO_MAXSIZE];
183
+ if (pid <= 0 || proc_pidpath(pid, path, sizeof(path)) <= 0) return nil;
184
+ return [NSString stringWithUTF8String:path];
185
+ }
186
+
187
+ // The outermost application bundle `path` is inside: the browser a renderer
188
+ // belongs to, the app an Electron helper is a part of. Nil for a tool that is
189
+ // in no bundle.
190
+ static NSBundle* OutermostApp(NSString* path) {
191
+ NSString* found = nil;
192
+ for (NSString* p = path; p.length > 1; p = p.stringByDeletingLastPathComponent) {
193
+ if ([p.pathExtension caseInsensitiveCompare:@"app"] == NSOrderedSame) found = p;
194
+ }
195
+ return found ? [NSBundle bundleWithPath:found] : nil;
196
+ }
197
+
198
+ static NSString* BundleName(NSBundle* b) {
199
+ NSString* name = [b objectForInfoDictionaryKey:@"CFBundleDisplayName"];
200
+ if (!name.length) name = [b objectForInfoDictionaryKey:@"CFBundleName"];
201
+ return name.length ? name : b.bundlePath.lastPathComponent.stringByDeletingPathExtension;
202
+ }
203
+
204
+ // The bundle id a tap of one application matches a process by: the
205
+ // application it runs from, or its own where it runs from none.
206
+ static NSString* AppIdOf(AudioObjectID p, pid_t pid) {
207
+ NSString* app = OutermostApp(ExecutableOf(pid)).bundleIdentifier;
208
+ return app.length ? app : BundleIdOf(p);
209
+ }
210
+
211
+ struct Proc {
212
+ pid_t pid = -1;
213
+ std::string bundleId, name;
214
+ bool playing = false;
215
+ bool hasApp = false;
216
+ std::string appBundleId, appName;
217
+ bool regular = false;
218
+ };
219
+
220
+ // The processes there are, as plain data: on any thread.
221
+ static std::vector<Proc> ListProcesses() {
222
+ std::vector<Proc> list;
223
+ for (AudioObjectID object : ProcessObjects()) {
224
+ @autoreleasepool {
225
+ Proc p;
226
+ p.pid = PidOf(object);
227
+ if (p.pid <= 0) continue;
228
+ p.bundleId = BundleIdOf(object).UTF8String ?: "";
229
+ p.playing = PlayingOf(object);
230
+ NSString* exe = ExecutableOf(p.pid);
231
+ NSString* name = [NSRunningApplication runningApplicationWithProcessIdentifier:p.pid].localizedName;
232
+ if (!name.length) name = exe.lastPathComponent;
233
+ if (!name.length) {
234
+ char n[2 * MAXCOMLEN + 1] = {0};
235
+ if (proc_name(p.pid, n, sizeof(n)) > 0) name = [NSString stringWithUTF8String:n];
236
+ }
237
+ p.name = name.UTF8String ?: "";
238
+ NSBundle* app = exe ? OutermostApp(exe) : nil;
239
+ if (app.bundleIdentifier.length) {
240
+ p.hasApp = true;
241
+ p.appBundleId = app.bundleIdentifier.UTF8String;
242
+ // the running application's name is in the user's language; the
243
+ // bundle's own, read from here, is in this process's
244
+ NSString* appName = nil;
245
+ for (NSRunningApplication* r in [NSRunningApplication runningApplicationsWithBundleIdentifier:app.bundleIdentifier]) {
246
+ if (r.activationPolicy == NSApplicationActivationPolicyRegular) p.regular = true;
247
+ if (!appName.length) appName = r.localizedName;
248
+ }
249
+ p.appName = (appName.length ? appName : BundleName(app)).UTF8String ?: "";
250
+ }
251
+ list.push_back(std::move(p));
252
+ }
253
+ }
254
+ return list;
255
+ }
256
+
257
+ static Napi::Value ProcessesValue(Napi::Env env, const std::vector<Proc>& list) {
258
+ Napi::Array out = Napi::Array::New(env, list.size());
259
+ for (size_t i = 0; i < list.size(); i++) {
260
+ const Proc& p = list[i];
261
+ Napi::Object o = Napi::Object::New(env);
262
+ o.Set("pid", (double)p.pid);
263
+ o.Set("bundleId", p.bundleId);
264
+ o.Set("name", p.name);
265
+ o.Set("playing", p.playing);
266
+ if (p.hasApp) {
267
+ Napi::Object app = Napi::Object::New(env);
268
+ app.Set("bundleId", p.appBundleId);
269
+ app.Set("name", p.appName);
270
+ app.Set("regular", p.regular);
271
+ o.Set("app", app);
272
+ }
273
+ out.Set((uint32_t)i, o);
274
+ }
275
+ return out;
276
+ }
277
+
278
+ // What a listing shows that changes: who is connected and who is playing.
279
+ // CoreAudio reuses a process object's id for a later process, so the pid is
280
+ // part of it.
281
+ static NSString* Signature() {
282
+ NSMutableArray<NSString*>* parts = [NSMutableArray array];
283
+ for (AudioObjectID o : ProcessObjects()) {
284
+ [parts addObject:[NSString stringWithFormat:@"%d|%@|%d", PidOf(o), BundleIdOf(o), PlayingOf(o)]];
285
+ }
286
+ [parts sortUsingSelector:@selector(compare:)];
287
+ return [parts componentsJoinedByString:@"\n"];
288
+ }
289
+
290
+ // ---------------------------------------------------------------------------
291
+ // taps
292
+ // ---------------------------------------------------------------------------
293
+
294
+ API_AVAILABLE(macos(14.2))
295
+ @interface CALTap : NSObject
296
+ @property(nonatomic) double tid;
297
+ @property(nonatomic) pid_t pid; // one process, or 0
298
+ @property(nonatomic, copy) NSString* bundleId; // one application, or nil
299
+ @property(nonatomic, copy) NSArray<NSNumber*>* excludePids;
300
+ @property(nonatomic) double sampleRate;
301
+ @property(nonatomic) AVAudioChannelCount channels;
302
+ @property(nonatomic, strong) CATapDescription* desc;
303
+ @property(nonatomic, copy) NSSet<NSNumber*>* objects; // the process objects in it (out of it, for everything)
304
+ @property(nonatomic, strong) dispatch_queue_t io;
305
+ @property(nonatomic, copy) AudioObjectPropertyListenerBlock formatListener;
306
+ @property(nonatomic) BOOL started, ended;
307
+ // the IO queue's
308
+ @property(nonatomic, strong) AVAudioFormat* format; // what was asked
309
+ @property(nonatomic, strong) AVAudioFormat* source; // what the tap's buffers hold
310
+ @property(nonatomic, strong) AVAudioConverter* converter;
311
+ @end
312
+
313
+ @implementation CALTap {
314
+ @public
315
+ AudioObjectID tap, aggregate;
316
+ AudioDeviceIOProcID proc;
317
+ double tapRate; // the IO queue's once the IO runs
318
+ std::atomic<bool> closed;
319
+ std::vector<std::vector<float>> pending; // converted, not yet a 10 ms chunk
320
+ double sent; // frames sent, for `time`
321
+ std::shared_ptr<std::atomic<int>> inflight;
322
+ std::atomic<int> dropped;
323
+ // APPKIT_DEBUG_AUDIO's, the IO queue's
324
+ bool described;
325
+ uint64_t framesIn, chunksOut;
326
+ float peak;
327
+ double lastReport;
328
+ }
329
+
330
+ // The process objects the tap is of now — or for everything, the ones it
331
+ // leaves out: this process and what the caller excluded.
332
+ - (NSSet<NSNumber*>*)wanted {
333
+ NSMutableSet<NSNumber*>* out = [NSMutableSet set];
334
+ pid_t me = getpid();
335
+ for (AudioObjectID o : ProcessObjects()) {
336
+ pid_t pid = PidOf(o);
337
+ if (self.pid > 0) {
338
+ if (pid == self.pid) [out addObject:@(o)];
339
+ } else if (self.bundleId) {
340
+ if ([self.bundleId isEqualToString:AppIdOf(o, pid)] || [self.bundleId isEqualToString:BundleIdOf(o)]) {
341
+ [out addObject:@(o)];
342
+ }
343
+ } else if (pid == me || [self.excludePids containsObject:@(pid)]) {
344
+ [out addObject:@(o)];
345
+ }
346
+ }
347
+ return out;
348
+ }
349
+
350
+ // On the IO queue: what the tap gave, converted, out in 10 ms chunks.
351
+ - (void)took:(const AudioBufferList*)in {
352
+ if (closed.load() || !in || in->mNumberBuffers == 0 || !(tapRate > 0)) return;
353
+ const AudioBuffer& first = in->mBuffers[0];
354
+ UInt32 perFrame = first.mNumberChannels ?: 1;
355
+ bool interleaved = in->mNumberBuffers == 1 && perFrame > 1;
356
+ AVAudioChannelCount count = interleaved ? perFrame : in->mNumberBuffers;
357
+ AVAudioFrameCount frames = (AVAudioFrameCount)(first.mDataByteSize / (sizeof(float) * perFrame));
358
+ if (gDebugAudio) {
359
+ if (!described) {
360
+ described = true;
361
+ TAP_LOG("tap %g: first buffers — %u buffer(s), %u channel(s) in the first, %u bytes, %u frames at %g Hz",
362
+ self.tid, (unsigned)in->mNumberBuffers, (unsigned)first.mNumberChannels,
363
+ (unsigned)first.mDataByteSize, (unsigned)frames, tapRate);
364
+ }
365
+ framesIn += frames;
366
+ for (UInt32 b = 0; b < in->mNumberBuffers; b++) {
367
+ const float* p = (const float*)in->mBuffers[b].mData;
368
+ size_t n = p ? in->mBuffers[b].mDataByteSize / sizeof(float) : 0;
369
+ for (size_t i = 0; i < n; i++) peak = fmaxf(peak, fabsf(p[i]));
370
+ }
371
+ double now = Seconds();
372
+ if (now - lastReport >= 1) {
373
+ TAP_LOG("tap %g: last second %llu frame(s) in, %llu chunk(s) out, peak %.4f%s", self.tid,
374
+ (unsigned long long)framesIn, (unsigned long long)chunksOut, peak,
375
+ peak == 0 ? " — silence: nothing playing, or the grant refused" : "");
376
+ framesIn = chunksOut = 0;
377
+ peak = 0;
378
+ lastReport = now;
379
+ }
380
+ }
381
+ if (frames == 0) return;
382
+ if (!self.source || self.source.channelCount != count || self.source.isInterleaved != interleaved ||
383
+ self.source.sampleRate != tapRate) {
384
+ self.source = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32
385
+ sampleRate:tapRate
386
+ channels:count
387
+ interleaved:interleaved];
388
+ self.converter = nil;
389
+ }
390
+ if (!self.converter) {
391
+ self.converter = [[AVAudioConverter alloc] initFromFormat:self.source toFormat:self.format];
392
+ if (self.format.channelCount < count) self.converter.downmix = YES;
393
+ }
394
+ AVAudioPCMBuffer* buf = [[AVAudioPCMBuffer alloc] initWithPCMFormat:self.source bufferListNoCopy:in deallocator:nil];
395
+ if (!buf || !self.converter) return;
396
+ buf.frameLength = frames;
397
+ AVAudioFrameCount cap = (AVAudioFrameCount)ceil(frames * self.format.sampleRate / tapRate) + 64;
398
+ AVAudioPCMBuffer* out = [[AVAudioPCMBuffer alloc] initWithPCMFormat:self.format frameCapacity:cap];
399
+ __block bool given = false;
400
+ NSError* err = nil;
401
+ [self.converter convertToBuffer:out
402
+ error:&err
403
+ withInputFromBlock:^AVAudioBuffer*(AVAudioPacketCount, AVAudioConverterInputStatus* status) {
404
+ if (given) {
405
+ *status = AVAudioConverterInputStatus_NoDataNow;
406
+ return nil;
407
+ }
408
+ given = true;
409
+ *status = AVAudioConverterInputStatus_HaveData;
410
+ return buf;
411
+ }];
412
+ AVAudioChannelCount n = self.format.channelCount;
413
+ if (pending.size() != n) pending.assign(n, {});
414
+ for (AVAudioChannelCount c = 0; c < n; c++) {
415
+ float* src = out.floatChannelData[c];
416
+ pending[c].insert(pending[c].end(), src, src + out.frameLength);
417
+ }
418
+ size_t chunk = (size_t)llround(self.format.sampleRate / 100);
419
+ while (pending[0].size() >= chunk) {
420
+ auto planes = std::make_shared<std::vector<std::vector<float>>>();
421
+ for (auto& p : pending) {
422
+ planes->emplace_back(p.begin(), p.begin() + chunk);
423
+ p.erase(p.begin(), p.begin() + chunk);
424
+ }
425
+ double time = sent / self.format.sampleRate;
426
+ sent += chunk;
427
+ // two seconds waiting is as far as it goes: past that, the oldest wait
428
+ // and this one is counted instead
429
+ if (inflight->load() > 200) {
430
+ dropped++;
431
+ continue;
432
+ }
433
+ int lost = dropped.exchange(0);
434
+ chunksOut++;
435
+ auto waiting = inflight;
436
+ waiting->fetch_add(1);
437
+ double tid = self.tid, rate = self.format.sampleRate;
438
+ if (!CALCaptureDeliver(^{
439
+ waiting->fetch_sub(1);
440
+ if (!CALListening()) return;
441
+ CALEvent ev("audio-input");
442
+ ev.Num("id", tid).Num("sampleRate", rate).Num("frames", (double)chunk).Num("time", time);
443
+ if (lost) ev.Num("dropped", lost);
444
+ ev.Handle("channels", ^Napi::Value(Napi::Env env) {
445
+ Napi::Array a = Napi::Array::New(env, planes->size());
446
+ for (size_t c = 0; c < planes->size(); c++) {
447
+ auto& p = (*planes)[c];
448
+ Napi::ArrayBuffer ab = Napi::ArrayBuffer::New(env, p.size() * sizeof(float));
449
+ memcpy(ab.Data(), p.data(), p.size() * sizeof(float));
450
+ a.Set((uint32_t)c, Napi::Float32Array::New(env, p.size(), ab, 0));
451
+ }
452
+ return a;
453
+ });
454
+ CALEmit(std::move(ev));
455
+ })) {
456
+ waiting->fetch_sub(1);
457
+ }
458
+ }
459
+ }
460
+
461
+ @end
462
+
463
+ // JS's and the control queue's alike, only under @synchronized(gTapsLock).
464
+ static NSMutableDictionary<NSNumber*, id>* gTaps;
465
+ static NSObject* gTapsLock;
466
+
467
+ static NSArray* TapsNow() {
468
+ @synchronized(gTapsLock) {
469
+ return gTaps.allValues ?: @[];
470
+ }
471
+ }
472
+
473
+ static void TapError(double tid, const char* name, NSString* message) {
474
+ Send(std::move(
475
+ CALEvent("system-audio-error").Num("id", tid).Str("name", name).Str("message", message.UTF8String)));
476
+ }
477
+
478
+ // The aggregate device's input latency in seconds: what its streams and its
479
+ // buffer add, as CoreAudio reports them.
480
+ static double LatencyOf(AudioObjectID device, double rate) {
481
+ if (!(rate > 0)) return 0;
482
+ UInt32 frames = 0, safety = 0, buffer = 0, size = sizeof(UInt32);
483
+ AudioObjectPropertyAddress a = {kAudioDevicePropertyLatency, kAudioObjectPropertyScopeInput,
484
+ kAudioObjectPropertyElementMain};
485
+ AudioObjectGetPropertyData(device, &a, 0, nullptr, &size, &frames);
486
+ a.mSelector = kAudioDevicePropertySafetyOffset;
487
+ size = sizeof(UInt32);
488
+ AudioObjectGetPropertyData(device, &a, 0, nullptr, &size, &safety);
489
+ a = Global(kAudioDevicePropertyBufferFrameSize);
490
+ size = sizeof(UInt32);
491
+ AudioObjectGetPropertyData(device, &a, 0, nullptr, &size, &buffer);
492
+ return (double)(frames + safety + buffer) / rate;
493
+ }
494
+
495
+ // The rate the IO block's buffers are at: the aggregate device's, which runs
496
+ // them, and the tap's own format where the device does not say.
497
+ static double TapRate(AudioObjectID tap, AudioObjectID aggregate) {
498
+ Float64 rate = 0;
499
+ UInt32 size = sizeof(rate);
500
+ AudioObjectPropertyAddress a = Global(kAudioDevicePropertyNominalSampleRate);
501
+ if (AudioObjectGetPropertyData(aggregate, &a, 0, nullptr, &size, &rate) == noErr && rate > 0) return rate;
502
+ AudioStreamBasicDescription asbd = {};
503
+ size = sizeof(asbd);
504
+ a = Global(kAudioTapPropertyFormat);
505
+ if (AudioObjectGetPropertyData(tap, &a, 0, nullptr, &size, &asbd) == noErr) return asbd.mSampleRate;
506
+ return 0;
507
+ }
508
+
509
+ // On the control queue: everything the tap holds let go, in the reverse of
510
+ // the order it was made.
511
+ API_AVAILABLE(macos(14.2))
512
+ static void StopTap(CALTap* t) {
513
+ TAP_LOG("tap %g: closed", t.tid);
514
+ if (t->proc) {
515
+ AudioDeviceStop(t->aggregate, t->proc);
516
+ AudioDeviceDestroyIOProcID(t->aggregate, t->proc);
517
+ t->proc = nullptr;
518
+ }
519
+ if (t->aggregate != kAudioObjectUnknown) {
520
+ AudioHardwareDestroyAggregateDevice(t->aggregate);
521
+ t->aggregate = kAudioObjectUnknown;
522
+ }
523
+ if (t->tap != kAudioObjectUnknown) {
524
+ if (t.formatListener) {
525
+ AudioObjectPropertyAddress a = Global(kAudioTapPropertyFormat);
526
+ AudioObjectRemovePropertyListenerBlock(t->tap, &a, Control(), t.formatListener);
527
+ t.formatListener = nil;
528
+ }
529
+ AudioHardwareDestroyProcessTap(t->tap);
530
+ t->tap = kAudioObjectUnknown;
531
+ }
532
+ }
533
+
534
+ API_AVAILABLE(macos(14.2))
535
+ static CATapDescription* DescriptionFor(CALTap* t, NSSet<NSNumber*>* objects) {
536
+ NSArray<NSNumber*>* list = objects.allObjects;
537
+ bool everything = t.pid <= 0 && !t.bundleId;
538
+ bool mono = t.channels == 1;
539
+ CATapDescription* d;
540
+ if (everything) {
541
+ d = mono ? [[CATapDescription alloc] initMonoGlobalTapButExcludeProcesses:list]
542
+ : [[CATapDescription alloc] initStereoGlobalTapButExcludeProcesses:list];
543
+ } else {
544
+ d = mono ? [[CATapDescription alloc] initMonoMixdownOfProcesses:list]
545
+ : [[CATapDescription alloc] initStereoMixdownOfProcesses:list];
546
+ }
547
+ d.name = @"appkit system audio";
548
+ d.UUID = [NSUUID UUID];
549
+ d.privateTap = YES;
550
+ d.muteBehavior = CATapUnmuted;
551
+ return d;
552
+ }
553
+
554
+ // On the control queue, with the permission settled: the tap, the aggregate
555
+ // device holding it, the IO on it, started.
556
+ API_AVAILABLE(macos(14.2))
557
+ static void StartTap(CALTap* t) {
558
+ double tid = t.tid;
559
+ if (t->closed.load()) return;
560
+ t.objects = [t wanted];
561
+ if (t.pid > 0 && t.objects.count == 0) {
562
+ TapError(tid, "NotFoundError", [NSString stringWithFormat:@"process %d has no audio to tap", t.pid]);
563
+ return;
564
+ }
565
+ t.desc = DescriptionFor(t, t.objects);
566
+ OSStatus st = AudioHardwareCreateProcessTap(t.desc, &t->tap);
567
+ TAP_LOG("tap %g: %s%s, %lu process(es) %s, %u channel(s): AudioHardwareCreateProcessTap %d", tid,
568
+ t.pid > 0 ? "one process" : t.bundleId ? "one application" : "everything",
569
+ t.bundleId ? [@" " stringByAppendingString:t.bundleId].UTF8String : "",
570
+ (unsigned long)t.objects.count, t.pid > 0 || t.bundleId ? "in it" : "left out", (unsigned)t.channels,
571
+ (int)st);
572
+ if (st != noErr) {
573
+ t->tap = kAudioObjectUnknown;
574
+ TapError(tid, "NotReadableError", [NSString stringWithFormat:@"CoreAudio made no tap (%d)", (int)st]);
575
+ return;
576
+ }
577
+ NSDictionary* composition = @{
578
+ @kAudioAggregateDeviceNameKey : @"appkit system audio",
579
+ @kAudioAggregateDeviceUIDKey : [NSUUID UUID].UUIDString,
580
+ @kAudioAggregateDeviceIsPrivateKey : @YES,
581
+ @kAudioAggregateDeviceIsStackedKey : @NO,
582
+ // the IO runs from the start, silence included, so `time` is the
583
+ // recording's and not the first sound's
584
+ @kAudioAggregateDeviceTapAutoStartKey : @NO,
585
+ @kAudioAggregateDeviceTapListKey : @[
586
+ @{@kAudioSubTapUIDKey : t.desc.UUID.UUIDString, @kAudioSubTapDriftCompensationKey : @YES},
587
+ ],
588
+ };
589
+ st = AudioHardwareCreateAggregateDevice((__bridge CFDictionaryRef)composition, &t->aggregate);
590
+ TAP_LOG("tap %g: AudioHardwareCreateAggregateDevice %d", tid, (int)st);
591
+ if (st != noErr) {
592
+ t->aggregate = kAudioObjectUnknown;
593
+ StopTap(t);
594
+ TapError(tid, "NotReadableError", [NSString stringWithFormat:@"CoreAudio made no device for the tap (%d)", (int)st]);
595
+ return;
596
+ }
597
+ double rate = TapRate(t->tap, t->aggregate);
598
+ if (gDebugAudio) {
599
+ AudioStreamBasicDescription asbd = {};
600
+ UInt32 size = sizeof(asbd);
601
+ AudioObjectPropertyAddress a = Global(kAudioTapPropertyFormat);
602
+ OSStatus fs = AudioObjectGetPropertyData(t->tap, &a, 0, nullptr, &size, &asbd);
603
+ TAP_LOG("tap %g: the device runs at %g Hz; the tap's format (%d) %g Hz, %u channel(s), %u bits, flags %#x", tid,
604
+ rate, (int)fs, asbd.mSampleRate, (unsigned)asbd.mChannelsPerFrame, (unsigned)asbd.mBitsPerChannel,
605
+ (unsigned)asbd.mFormatFlags);
606
+ }
607
+ dispatch_sync(t.io, ^{ t->tapRate = rate; });
608
+ // the output device under the tapped processes changed rate: so does the tap
609
+ __weak CALTap* weak = t;
610
+ t.formatListener = ^(UInt32, const AudioObjectPropertyAddress*) {
611
+ CALTap* tap = weak;
612
+ if (!tap || tap->closed.load()) return;
613
+ double now = TapRate(tap->tap, tap->aggregate);
614
+ TAP_LOG("tap %g: the format changed, now %g Hz", tap.tid, now);
615
+ dispatch_async(tap.io, ^{
616
+ tap->tapRate = now;
617
+ tap.source = nil;
618
+ tap.converter = nil;
619
+ });
620
+ };
621
+ AudioObjectPropertyAddress fa = Global(kAudioTapPropertyFormat);
622
+ AudioObjectAddPropertyListenerBlock(t->tap, &fa, Control(), t.formatListener);
623
+ st = AudioDeviceCreateIOProcIDWithBlock(&t->proc, t->aggregate, t.io,
624
+ ^(const AudioTimeStamp*, const AudioBufferList* in, const AudioTimeStamp*,
625
+ AudioBufferList*, const AudioTimeStamp*) {
626
+ CALTap* tap = weak;
627
+ if (tap) [tap took:in];
628
+ });
629
+ TAP_LOG("tap %g: AudioDeviceCreateIOProcIDWithBlock %d", tid, (int)st);
630
+ if (st != noErr) {
631
+ t->proc = nullptr;
632
+ StopTap(t);
633
+ TapError(tid, "NotReadableError", [NSString stringWithFormat:@"the tap's device would not run (%d)", (int)st]);
634
+ return;
635
+ }
636
+ st = AudioDeviceStart(t->aggregate, t->proc);
637
+ TAP_LOG("tap %g: AudioDeviceStart %d, latency %.1f ms", tid, (int)st, LatencyOf(t->aggregate, rate) * 1000);
638
+ if (st != noErr) {
639
+ StopTap(t);
640
+ TapError(tid, "NotReadableError", [NSString stringWithFormat:@"the tap's device did not start (%d)", (int)st]);
641
+ return;
642
+ }
643
+ t.started = YES;
644
+ Send(std::move(CALEvent("system-audio-started")
645
+ .Num("id", tid)
646
+ .Num("sampleRate", t.sampleRate)
647
+ .Num("channels", t.channels)
648
+ .Num("latency", LatencyOf(t->aggregate, rate))));
649
+ }
650
+
651
+ // On the control queue, when the processes changed: an application's tap
652
+ // takes in the helpers that started and lets go of the ones that ended, the
653
+ // tap of everything leaves this process out once it has connected, and a tap
654
+ // of one process says when that process has gone.
655
+ API_AVAILABLE(macos(14.2))
656
+ static void Follow(CALTap* t) {
657
+ if (!t.started || t.ended || t->closed.load()) return;
658
+ NSSet<NSNumber*>* now = [t wanted];
659
+ if (t.pid > 0 && now.count == 0) {
660
+ t.ended = YES;
661
+ Send(std::move(CALEvent("system-audio-ended").Num("id", t.tid)));
662
+ return;
663
+ }
664
+ if ([now isEqualToSet:t.objects]) return;
665
+ NSUInteger before = t.objects.count;
666
+ t.objects = now;
667
+ t.desc.processes = now.allObjects;
668
+ CATapDescription* __unsafe_unretained desc = t.desc;
669
+ AudioObjectPropertyAddress a = Global(kAudioTapPropertyDescription);
670
+ OSStatus st = AudioObjectSetPropertyData(t->tap, &a, 0, nullptr, sizeof(desc), &desc);
671
+ TAP_LOG("tap %g: followed the processes, %lu → %lu: %d", t.tid, (unsigned long)before,
672
+ (unsigned long)now.count, (int)st);
673
+ }
674
+
675
+ // ---------------------------------------------------------------------------
676
+ // watching
677
+ // ---------------------------------------------------------------------------
678
+
679
+ static std::atomic<bool> gAnnounce{false};
680
+
681
+ // The control queue's: process objects with a listener on their output, as
682
+ // `object:pid` since CoreAudio reuses an object's id; and the last signature.
683
+ static NSMutableSet<NSString*>* gWatched;
684
+ static NSString* gSignature;
685
+
686
+ static void Changed();
687
+
688
+ static void WatchEach() {
689
+ NSMutableSet<NSString*>* seen = [NSMutableSet set];
690
+ for (AudioObjectID o : ProcessObjects()) {
691
+ NSString* key = [NSString stringWithFormat:@"%u:%d", o, PidOf(o)];
692
+ [seen addObject:key];
693
+ if ([gWatched containsObject:key]) continue;
694
+ AudioObjectPropertyAddress a = Global(kAudioProcessPropertyIsRunningOutput);
695
+ AudioObjectAddPropertyListenerBlock(o, &a, Control(), ^(UInt32, const AudioObjectPropertyAddress*) {
696
+ Changed();
697
+ });
698
+ [gWatched addObject:key];
699
+ }
700
+ [gWatched intersectSet:seen];
701
+ }
702
+
703
+ static void Changed() {
704
+ WatchEach();
705
+ if (@available(macOS 14.2, *)) {
706
+ for (CALTap* t in TapsNow()) Follow(t);
707
+ }
708
+ NSString* now = Signature();
709
+ if ([now isEqualToString:gSignature]) return;
710
+ gSignature = now;
711
+ if (gAnnounce.load()) Send(CALEvent("audio-processes"));
712
+ }
713
+
714
+ // From the first listing or the first tap on: processes connecting, going,
715
+ // starting and stopping, followed by every tap and said as `audio-processes`.
716
+ static void WatchProcesses() {
717
+ static dispatch_once_t once;
718
+ dispatch_once(&once, ^{
719
+ dispatch_async(Control(), ^{
720
+ gWatched = [NSMutableSet set];
721
+ gSignature = Signature();
722
+ AudioObjectPropertyAddress a = Global(kAudioHardwarePropertyProcessObjectList);
723
+ AudioObjectAddPropertyListenerBlock(kAudioObjectSystemObject, &a, Control(),
724
+ ^(UInt32, const AudioObjectPropertyAddress*) { Changed(); });
725
+ WatchEach();
726
+ });
727
+ });
728
+ }
729
+
730
+ // ---------------------------------------------------------------------------
731
+ // the verbs
732
+ // ---------------------------------------------------------------------------
733
+
734
+ // audioProcesses() answers at once; audioProcesses(cb) lists on a queue of its
735
+ // own and answers through cb, which is the form a worker uses.
736
+ static Napi::Value AudioProcesses(const Napi::CallbackInfo& info) {
737
+ Napi::Env env = info.Env();
738
+ gAnnounce = true;
739
+ WatchProcesses();
740
+ if (info.Length() && info[info.Length() - 1].IsFunction()) {
741
+ CALTsfn tsfn = CALReplyTo(env, info[info.Length() - 1].As<Napi::Function>(), "appkit:audioProcesses");
742
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
743
+ auto list = std::make_shared<std::vector<Proc>>(ListProcesses());
744
+ CALReply(tsfn, ^Napi::Value(Napi::Env e) { return ProcessesValue(e, *list); });
745
+ });
746
+ return env.Undefined();
747
+ }
748
+ return ProcessesValue(env, ListProcesses());
749
+ }
750
+
751
+ API_AVAILABLE(macos(14.2))
752
+ static Napi::Value OpenSystemAudio(const Napi::CallbackInfo& info) {
753
+ Napi::Env env = info.Env();
754
+ Napi::Value opts = info.Length() ? info[0] : env.Undefined();
755
+ if (!opts.IsUndefined() && !opts.IsNull() && !opts.IsObject()) {
756
+ Napi::TypeError::New(env, "openSystemAudio(options): options is an object").ThrowAsJavaScriptException();
757
+ return env.Undefined();
758
+ }
759
+ double pid = 0;
760
+ bool hasPid = OptNum(opts, "pid", &pid);
761
+ NSString* bundleId = opts.IsObject() ? Str(opts.As<Napi::Object>().Get("bundleId")) : nil;
762
+ if (opts.IsObject() && opts.As<Napi::Object>().Has("pid") && (!hasPid || pid < 1 || pid != floor(pid))) {
763
+ Napi::TypeError::New(env, "openSystemAudio: pid is a process id").ThrowAsJavaScriptException();
764
+ return env.Undefined();
765
+ }
766
+ if (hasPid && bundleId) {
767
+ Napi::TypeError::New(env, "openSystemAudio: a pid or a bundleId, not both").ThrowAsJavaScriptException();
768
+ return env.Undefined();
769
+ }
770
+ NSMutableArray<NSNumber*>* exclude = [NSMutableArray array];
771
+ if (opts.IsObject() && opts.As<Napi::Object>().Get("exclude").IsArray()) {
772
+ Napi::Array list = opts.As<Napi::Object>().Get("exclude").As<Napi::Array>();
773
+ for (uint32_t i = 0; i < list.Length(); i++) {
774
+ Napi::Value v = list.Get(i);
775
+ if (v.IsNumber()) [exclude addObject:@((pid_t)v.As<Napi::Number>().Int32Value())];
776
+ }
777
+ }
778
+ double rate = 48000, channels = 2;
779
+ OptNum(opts, "sampleRate", &rate);
780
+ OptNum(opts, "channels", &channels);
781
+ rate = fmin(192000, fmax(8000, rate));
782
+ channels = fmin(2, fmax(1, round(channels)));
783
+
784
+ CALTap* t = [CALTap new];
785
+ t.tid = CALNextCaptureId();
786
+ t.pid = hasPid ? (pid_t)pid : 0;
787
+ t.bundleId = bundleId;
788
+ t.excludePids = exclude;
789
+ t.sampleRate = rate;
790
+ t.channels = (AVAudioChannelCount)channels;
791
+ t.io = dispatch_queue_create("appkit.systemaudio.io", DISPATCH_QUEUE_SERIAL);
792
+ t.format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:rate channels:t.channels];
793
+ t->tap = kAudioObjectUnknown;
794
+ t->aggregate = kAudioObjectUnknown;
795
+ t->proc = nullptr;
796
+ t->tapRate = 0;
797
+ t->closed = false;
798
+ t->sent = 0;
799
+ t->inflight = std::make_shared<std::atomic<int>>(0);
800
+ t->dropped = 0;
801
+ t->described = false;
802
+ t->framesIn = t->chunksOut = 0;
803
+ t->peak = 0;
804
+ t->lastReport = Seconds();
805
+ @synchronized(gTapsLock) {
806
+ gTaps[@(t.tid)] = t;
807
+ }
808
+ WatchProcesses();
809
+ double tid = t.tid;
810
+ dispatch_async(Control(), ^{
811
+ if (t->closed.load()) return;
812
+ // a process that is not there is said before anything is asked of the user
813
+ if (t.pid > 0 && [t wanted].count == 0) {
814
+ TapError(tid, "NotFoundError", [NSString stringWithFormat:@"process %d has no audio to tap", t.pid]);
815
+ return;
816
+ }
817
+ const char* status = CALAudioCaptureStatus();
818
+ TAP_LOG("tap %g: System Audio Recording is %s", tid, status);
819
+ if (!strcmp(status, "denied") || !strcmp(status, "restricted")) {
820
+ TapError(tid, "NotAllowedError",
821
+ @"System Audio Recording is not allowed for this app (Privacy & Security › Screen & System "
822
+ @"Audio Recording)");
823
+ return;
824
+ }
825
+ if (!strcmp(status, "notDetermined")) {
826
+ CALAudioCaptureRequest(^{
827
+ dispatch_async(Control(), ^{
828
+ if (t->closed.load()) return;
829
+ TAP_LOG("tap %g: asked; System Audio Recording is %s", tid, CALAudioCaptureStatus());
830
+ if (strcmp(CALAudioCaptureStatus(), "authorized") != 0) {
831
+ TapError(tid, "NotAllowedError",
832
+ @"System Audio Recording was not allowed — by the user, or by macOS for a process it "
833
+ @"does not take for an app, or one without NSAudioCaptureUsageDescription");
834
+ return;
835
+ }
836
+ StartTap(t);
837
+ });
838
+ });
839
+ return;
840
+ }
841
+ StartTap(t);
842
+ });
843
+ Napi::Object out = Napi::Object::New(env);
844
+ out.Set("id", tid);
845
+ out.Set("sampleRate", rate);
846
+ out.Set("channels", channels);
847
+ return out;
848
+ }
849
+
850
+ API_AVAILABLE(macos(14.2))
851
+ static Napi::Value CloseSystemAudio(const Napi::CallbackInfo& info) {
852
+ Napi::Env env = info.Env();
853
+ if (!info.Length() || !info[0].IsNumber()) return env.Undefined();
854
+ double tid = info[0].As<Napi::Number>().DoubleValue();
855
+ CALTap* t;
856
+ @synchronized(gTapsLock) {
857
+ t = gTaps[@(tid)];
858
+ [gTaps removeObjectForKey:@(tid)];
859
+ }
860
+ if (!t) return env.Undefined();
861
+ t->closed = true;
862
+ dispatch_async(Control(), ^{ StopTap(t); });
863
+ return env.Undefined();
864
+ }
865
+
866
+ void InitSystemAudio(Napi::Env env, Napi::Object exports) {
867
+ if (@available(macOS 14.2, *)) {
868
+ if (!gTapsLock) {
869
+ gTapsLock = [NSObject new];
870
+ gTaps = [NSMutableDictionary dictionary];
871
+ }
872
+ exports.Set("audioProcesses", Napi::Function::New(env, AudioProcesses));
873
+ exports.Set("openSystemAudio", Napi::Function::New(env, OpenSystemAudio));
874
+ exports.Set("closeSystemAudio", Napi::Function::New(env, CloseSystemAudio));
875
+ }
876
+ }