@windowkit/appkit 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/capture.mm CHANGED
@@ -722,10 +722,38 @@ static AVCaptureDeviceFormat* ChooseFormat(AVCaptureDevice* d, double w, double
722
722
  return best;
723
723
  }
724
724
 
725
+ // The frame duration `f` runs `rate` at, from the range of its own that holds
726
+ // the rate — and at a range's ends, that range's own duration exactly. A
727
+ // duration worked out from the rate is rounded to its timescale: 1/30 s in
728
+ // microseconds is 33333 µs, 30.0003 frames a second, and AVFoundation throws
729
+ // for a rate a hair past the format's fastest rather than clamping it.
730
+ static CMTime FrameDuration(AVCaptureDeviceFormat* f, double rate) {
731
+ AVFrameRateRange* best = nil;
732
+ double nearest = INFINITY;
733
+ for (AVFrameRateRange* r in f.videoSupportedFrameRateRanges) {
734
+ double off = rate < r.minFrameRate ? r.minFrameRate - rate
735
+ : rate > r.maxFrameRate ? rate - r.maxFrameRate
736
+ : 0;
737
+ if (off < nearest) {
738
+ nearest = off;
739
+ best = r;
740
+ }
741
+ }
742
+ if (!best) return kCMTimeInvalid;
743
+ if (rate >= best.maxFrameRate - 1e-3) return best.minFrameDuration;
744
+ if (rate <= best.minFrameRate + 1e-3) return best.maxFrameDuration;
745
+ CMTime d = CMTimeMakeWithSeconds(1.0 / rate, 1000000);
746
+ if (CMTimeCompare(d, best.minFrameDuration) < 0) return best.minFrameDuration;
747
+ if (CMTimeCompare(d, best.maxFrameDuration) > 0) return best.maxFrameDuration;
748
+ return d;
749
+ }
750
+
725
751
  static void CameraError(double cid, const char* name, NSString* message) {
726
752
  Send(std::move(CALEvent("camera-error").Num("id", cid).Str("name", name).Str("message", message.UTF8String)));
727
753
  }
728
754
 
755
+ static void StartSession(CALCamera* c);
756
+
729
757
  // On the camera's queue: the session put together and started.
730
758
  static void StartCamera(CALCamera* c) {
731
759
  double cid = c.cid;
@@ -752,6 +780,21 @@ static void StartCamera(CALCamera* c) {
752
780
  }];
753
781
  return;
754
782
  }
783
+ // AVFoundation reports a configuration it will not take by throwing, on
784
+ // this queue, where nothing above would catch it and the process ends: it
785
+ // is the open's error instead, and the app goes on
786
+ @try {
787
+ StartSession(c);
788
+ } @catch (NSException* e) {
789
+ CameraError(cid, "NotReadableError",
790
+ [NSString stringWithFormat:@"the camera could not be configured: %@", e.reason ?: e.name]);
791
+ }
792
+ }
793
+
794
+ // On the camera's queue, allowed: the input, the output, the format and the
795
+ // rate, then the session running.
796
+ static void StartSession(CALCamera* c) {
797
+ double cid = c.cid;
755
798
  NSError* err = nil;
756
799
  AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:c.device error:&err];
757
800
  if (!input) {
@@ -778,11 +821,16 @@ static void StartCamera(CALCamera* c) {
778
821
  c.output = out;
779
822
  [s commitConfiguration];
780
823
  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];
824
+ @try {
825
+ c.device.activeFormat = c.format;
826
+ CMTime d = FrameDuration(c.format, c.frameRate);
827
+ if (CMTIME_IS_VALID(d)) {
828
+ c.device.activeVideoMinFrameDuration = d;
829
+ c.device.activeVideoMaxFrameDuration = d;
830
+ }
831
+ } @finally {
832
+ [c.device unlockForConfiguration];
833
+ }
786
834
  }
787
835
  NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
788
836
  __weak CALCamera* weak = c;
@@ -821,7 +869,9 @@ static void StartCamera(CALCamera* c) {
821
869
  CameraError(cid, "NotReadableError", @"the capture session did not start — the camera may be in use");
822
870
  return;
823
871
  }
824
- Send(std::move(CALEvent("camera-started").Num("id", cid)));
872
+ CMTime ran = c.device.activeVideoMinFrameDuration;
873
+ double rate = CMTIME_IS_VALID(ran) && ran.value > 0 ? (double)ran.timescale / ran.value : c.frameRate;
874
+ Send(std::move(CALEvent("camera-started").Num("id", cid).Num("frameRate", rate)));
825
875
  }
826
876
 
827
877
  static Napi::Value OpenCamera(const Napi::CallbackInfo& info) {
@@ -1042,7 +1092,31 @@ static AVAudioSinkNode* gSink;
1042
1092
  static std::unique_ptr<Ring> gInputRing; // the input's samples, from the render thread
1043
1093
  static AVAudioFormat* gInputFormat;
1044
1094
  static dispatch_source_t gDrain;
1095
+ // APPKIT_DEBUG_AUDIO=1: what the engine does, on stderr — its rebuilds and
1096
+ // why, voice processing engaging or not, the input's format, each start and
1097
+ // its error, configuration changes, and once a second what the input gave and
1098
+ // what reached JS. For a machine the audio cannot be watched on otherwise.
1099
+ static const bool gDebugAudio = [] {
1100
+ const char* v = getenv("APPKIT_DEBUG_AUDIO");
1101
+ return v && *v && strcmp(v, "0") != 0;
1102
+ }();
1103
+ #define AUDIO_LOG(...) \
1104
+ do { \
1105
+ if (gDebugAudio) { \
1106
+ fprintf(stderr, "@windowkit/appkit audio: " __VA_ARGS__); \
1107
+ fputc('\n', stderr); \
1108
+ } \
1109
+ } while (0)
1110
+ static std::atomic<uint64_t> gSinkFrames{0}; // frames the input gave, from the render thread
1111
+ static uint64_t gChunksSent = 0; // the audio queue's
1112
+ static double gLastReport = 0;
1113
+ // configuration changes lately, for the loop guard
1114
+ static std::vector<double> gChanges;
1045
1115
  static BOOL gVoice;
1116
+ // Voice processing would not start on this input — some Bluetooth headsets'
1117
+ // microphones, -10875 from the engine — so the microphone runs without it
1118
+ // until the input changes or every microphone closes.
1119
+ static BOOL gVoiceRefused;
1046
1120
  static NSString* gInputUID;
1047
1121
  static NSMutableDictionary<NSNumber*, CALMicrophone*>* gMics;
1048
1122
  static id gConfigNote;
@@ -1076,6 +1150,26 @@ static void SetUnitDevice(AudioUnit unit, NSString* uid) {
1076
1150
  }
1077
1151
 
1078
1152
  static void DrainInput();
1153
+ static void SafeRewire();
1154
+ static void Rewire();
1155
+
1156
+ // The engine taken down, and what was wired to it forgotten, so the next
1157
+ // Rewire builds a new one from what is open.
1158
+ static void TearDownEngine() {
1159
+ if (gEngine) [gEngine stop];
1160
+ if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
1161
+ gConfigNote = nil;
1162
+ if (gDrain) dispatch_source_cancel(gDrain);
1163
+ gDrain = nil;
1164
+ gEngine = nil;
1165
+ gSink = nil;
1166
+ gInputRing.reset();
1167
+ gVoice = NO;
1168
+ gInputUID = nil;
1169
+ gOutputLatency = 0;
1170
+ for (CALOutput* o in OutputsNow(nullptr)) o.node = nil;
1171
+ for (CALMicrophone* m in gMics.allValues) m.converter = nil;
1172
+ }
1079
1173
 
1080
1174
  static void MicrophoneError(double mid, const char* name, NSString* message) {
1081
1175
  Send(std::move(
@@ -1095,28 +1189,21 @@ static void Rewire() {
1095
1189
  wantVoice = wantVoice || m.echoCancellation;
1096
1190
  if (!wantUID) wantUID = m.deviceUID;
1097
1191
  }
1192
+ if (!wantInput) gVoiceRefused = NO;
1193
+ wantVoice = wantVoice && !gVoiceRefused;
1098
1194
  NSString* outputUID = nil;
1099
1195
  NSArray<CALOutput*>* outputs = OutputsNow(&outputUID);
1100
1196
  bool wantOutputs = outputs.count > 0;
1101
1197
  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
- }
1198
+ TearDownEngine();
1115
1199
  return;
1116
1200
  }
1117
1201
  bool hadInput = gSink != nil;
1118
1202
  bool rebuild = !gEngine || hadInput != wantInput || (wantInput && gVoice != wantVoice) ||
1119
1203
  (wantInput && ![wantUID ?: @"" isEqualToString:gInputUID ?: @""]);
1204
+ AUDIO_LOG("rewire: %lu microphone(s), %lu output(s), voice wanted %d (refused %d) — %s",
1205
+ (unsigned long)gMics.count, (unsigned long)outputs.count, wantVoice, (int)gVoiceRefused,
1206
+ rebuild ? (gEngine ? "rebuilding the engine" : "building the engine") : "same engine");
1120
1207
  if (rebuild) {
1121
1208
  if (gEngine) [gEngine stop];
1122
1209
  if (gConfigNote) [NSNotificationCenter.defaultCenter removeObserver:gConfigNote];
@@ -1133,22 +1220,61 @@ static void Rewire() {
1133
1220
  if (wantVoice) {
1134
1221
  NSError* err = nil;
1135
1222
  gVoice = [input setVoiceProcessingEnabled:YES error:&err];
1223
+ AUDIO_LOG("voice processing %s%s", gVoice ? "on" : "refused: ",
1224
+ gVoice ? "" : (err.localizedDescription ?: @"no reason").UTF8String);
1136
1225
  }
1226
+ // The input's format is whatever the device and voice processing make
1227
+ // of it: the built-in microphone array is several channels under voice
1228
+ // processing, and no format at all where there is no input. Only the
1229
+ // first channel is kept under voice processing — its output, the
1230
+ // voice — and at most two otherwise: a standard format is only made
1231
+ // for one or two channels, and a converter handed the nil one gets for
1232
+ // more ends the process (a segfault, no exception to catch).
1137
1233
  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));
1234
+ if (!hw || hw.sampleRate <= 0 || hw.channelCount == 0) {
1235
+ [NSException raise:NSInternalInconsistencyException
1236
+ format:@"the input has no audio format — is a microphone connected?"];
1237
+ }
1238
+ AVAudioChannelCount kept = gVoice ? 1 : MIN(hw.channelCount, (AVAudioChannelCount)2);
1239
+ AUDIO_LOG("input: %g Hz, %u channel(s)%s, keeping %u", hw.sampleRate, hw.channelCount,
1240
+ hw.isInterleaved ? " interleaved" : "", kept);
1241
+ gInputFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:hw.sampleRate channels:kept];
1242
+ if (!gInputFormat) {
1243
+ [NSException raise:NSInternalInconsistencyException
1244
+ format:@"no format for the input at %g Hz", hw.sampleRate];
1245
+ }
1246
+ gInputRing = std::make_unique<Ring>(kept, (size_t)(hw.sampleRate * 2));
1141
1247
  Ring* ring = gInputRing.get();
1248
+ // an interleaved input arrives as one buffer of every channel: its
1249
+ // first `kept` are pulled apart here, into room made now, since the
1250
+ // render thread allocates nothing
1251
+ bool interleaved = hw.isInterleaved;
1252
+ UInt32 stride = hw.channelCount;
1253
+ auto scratch = std::make_shared<std::vector<float>>(2 * 8192);
1142
1254
  gSink = [[AVAudioSinkNode alloc] initWithReceiverBlock:^OSStatus(const AudioTimeStamp*, AVAudioFrameCount n,
1143
1255
  const AudioBufferList* in) {
1144
- const float* ch[16] = {nullptr};
1145
- UInt32 count = in->mNumberBuffers < 16 ? in->mNumberBuffers : 16;
1256
+ const float* ch[2] = {nullptr, nullptr};
1257
+ if (interleaved && in->mNumberBuffers >= 1) {
1258
+ const float* all = (const float*)in->mBuffers[0].mData;
1259
+ AVAudioFrameCount m = n < 8192 ? n : 8192;
1260
+ for (UInt32 c = 0; c < kept; c++) {
1261
+ float* out = scratch->data() + c * 8192;
1262
+ for (AVAudioFrameCount i = 0; i < m; i++) out[i] = all[i * stride + c];
1263
+ ch[c] = out;
1264
+ }
1265
+ ring->write(ch, m);
1266
+ gSinkFrames.fetch_add(m, std::memory_order_relaxed);
1267
+ return noErr;
1268
+ }
1269
+ UInt32 count = in->mNumberBuffers < kept ? in->mNumberBuffers : kept;
1146
1270
  for (UInt32 i = 0; i < count; i++) ch[i] = (const float*)in->mBuffers[i].mData;
1147
1271
  ring->write(ch, n);
1272
+ gSinkFrames.fetch_add(n, std::memory_order_relaxed);
1148
1273
  return noErr;
1149
1274
  }];
1150
1275
  [gEngine attachNode:gSink];
1151
- [gEngine connect:input to:gSink format:gInputFormat];
1276
+ // at the input's own format: the sink takes what the device gives
1277
+ [gEngine connect:input to:gSink format:hw];
1152
1278
  }
1153
1279
  if (outputUID) SetUnitDevice(gEngine.outputNode.audioUnit, outputUID);
1154
1280
  gConfigNote = [NSNotificationCenter.defaultCenter
@@ -1159,14 +1285,22 @@ static void Rewire() {
1159
1285
  // a device came or went under the engine: wired again, at
1160
1286
  // the formats there are now
1161
1287
  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();
1288
+ // Voice processing can switch a Bluetooth headset between
1289
+ // its profiles, which is itself a configuration change:
1290
+ // rebuilt with it again, the engine changed the device
1291
+ // again, and a microphone never settled long enough to
1292
+ // give a sample while the outputs played on. Three in a
1293
+ // few seconds under voice processing, and it is given up
1294
+ // for as long as a microphone stays open.
1295
+ double now = CACurrentMediaTime();
1296
+ gChanges.push_back(now);
1297
+ while (!gChanges.empty() && now - gChanges.front() > 5) gChanges.erase(gChanges.begin());
1298
+ bool looping = gVoice && gChanges.size() >= 3;
1299
+ AUDIO_LOG("configuration changed under the engine (%zu in 5 s)%s", gChanges.size(),
1300
+ looping ? ": giving up on voice processing" : "");
1301
+ if (looping) gVoiceRefused = YES;
1302
+ TearDownEngine();
1303
+ SafeRewire();
1170
1304
  });
1171
1305
  }];
1172
1306
  for (CALOutput* o in outputs) o.node = nil;
@@ -1198,24 +1332,68 @@ static void Rewire() {
1198
1332
  }
1199
1333
  // microphones: a converter each, from the input's format to theirs
1200
1334
  for (CALMicrophone* m in gMics.allValues) {
1201
- if (m.converter) continue;
1335
+ if (m.converter || !gInputFormat) continue;
1202
1336
  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) {
1337
+ m.converter = m.format ? [[AVAudioConverter alloc] initFromFormat:gInputFormat toFormat:m.format] : nil;
1338
+ if (!m.converter) {
1339
+ [gMics removeObjectForKey:@(m.mid)];
1340
+ MicrophoneError(m.mid, "NotReadableError",
1341
+ [NSString stringWithFormat:@"no conversion from the input, %u channel(s) at %g Hz, "
1342
+ @"to %u at %g Hz",
1343
+ gInputFormat.channelCount, gInputFormat.sampleRate,
1344
+ m.channels, m.sampleRate]);
1345
+ continue;
1346
+ }
1347
+ if (m.channels < gInputFormat.channelCount) {
1205
1348
  m.converter.downmix = YES;
1349
+ } else if (m.channels > gInputFormat.channelCount) {
1350
+ // one channel in, two out: the voice on both sides
1351
+ m.converter.channelMap = @[ @0, @0 ];
1206
1352
  }
1207
1353
  }
1208
1354
  if (!gEngine.isRunning) {
1209
1355
  [gEngine prepare];
1210
1356
  NSError* err = nil;
1211
1357
  if (![gEngine startAndReturnError:&err]) {
1358
+ AUDIO_LOG("engine did not start (%ld): %s%s", (long)err.code,
1359
+ (err.localizedDescription ?: @"no reason").UTF8String,
1360
+ gVoice ? " — trying again without voice processing" : "");
1361
+ if (gVoice) {
1362
+ // voice processing would not start on this input: the microphone
1363
+ // runs without it, and microphone-started says echoCancellation false
1364
+ gVoiceRefused = YES;
1365
+ TearDownEngine();
1366
+ Rewire();
1367
+ return;
1368
+ }
1369
+ // a microphone that would not start is not open: it fails, once, and
1370
+ // goes — left in the list, it refused every microphone after it as
1371
+ // "another microphone is open"
1372
+ NSString* why = [NSString stringWithFormat:@"the audio engine did not start: %@",
1373
+ err.localizedDescription ?: @"no reason given"];
1374
+ // and one that was live has stopped: it ends, said, rather than
1375
+ // going quiet while its track still reads live
1376
+ bool dropped = false;
1212
1377
  for (CALMicrophone* m in gMics.allValues) {
1213
- if (!m.started) MicrophoneError(m.mid, "NotReadableError", err.localizedDescription ?: @"the engine did not start");
1378
+ [gMics removeObjectForKey:@(m.mid)];
1379
+ if (m.started) {
1380
+ double mid = m.mid;
1381
+ Send(std::move(CALEvent("microphone-ended").Num("id", mid)));
1382
+ } else {
1383
+ MicrophoneError(m.mid, "NotReadableError", why);
1384
+ }
1385
+ dropped = true;
1214
1386
  }
1387
+ TearDownEngine();
1388
+ // what is left — the outputs, the microphones already running — once
1389
+ // more; with nothing left to drop this ends here
1390
+ if (dropped) Rewire();
1215
1391
  return;
1216
1392
  }
1217
1393
  }
1218
1394
  gOutputLatency = gEngine.outputNode.presentationLatency;
1395
+ AUDIO_LOG("engine running, voice processing %s, output latency %.1f ms", gVoice ? "on" : "off",
1396
+ gOutputLatency.load() * 1000);
1219
1397
  if (wantInput && !gDrain) {
1220
1398
  gDrain = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, AudioQueue());
1221
1399
  dispatch_source_set_timer(gDrain, dispatch_time(DISPATCH_TIME_NOW, 0), 10 * NSEC_PER_MSEC, 2 * NSEC_PER_MSEC);
@@ -1247,9 +1425,36 @@ static void Rewire() {
1247
1425
  }
1248
1426
  }
1249
1427
 
1428
+ // Rewire, with what AVAudioEngine throws — a connection at a format it will
1429
+ // not take, an input on a machine with none — caught on the audio queue,
1430
+ // where nothing else would, and said to every microphone still opening.
1431
+ static void SafeRewire() {
1432
+ @try {
1433
+ Rewire();
1434
+ } @catch (NSException* e) {
1435
+ NSString* why = e.reason ?: e.name;
1436
+ for (CALMicrophone* m in gMics.allValues) {
1437
+ if (m.started) continue;
1438
+ [gMics removeObjectForKey:@(m.mid)];
1439
+ MicrophoneError(m.mid, "NotReadableError",
1440
+ [NSString stringWithFormat:@"the audio engine could not be set up: %@", why]);
1441
+ }
1442
+ }
1443
+ }
1444
+
1250
1445
  // Every 10 ms on the audio queue: what the input gave, converted for each
1251
1446
  // microphone, out in 10 ms chunks.
1252
1447
  static void DrainInput() {
1448
+ if (gDebugAudio) {
1449
+ double now = CACurrentMediaTime();
1450
+ if (now - gLastReport >= 1) {
1451
+ gLastReport = now;
1452
+ AUDIO_LOG("last second: %llu frame(s) from the input, %llu chunk(s) to JS, engine %s",
1453
+ (unsigned long long)gSinkFrames.exchange(0), (unsigned long long)gChunksSent,
1454
+ gEngine.isRunning ? "running" : "STOPPED");
1455
+ gChunksSent = 0;
1456
+ }
1457
+ }
1253
1458
  Ring* ring = gInputRing.get();
1254
1459
  if (!ring || !gInputFormat) return;
1255
1460
  size_t n = ring->available();
@@ -1296,6 +1501,7 @@ static void DrainInput() {
1296
1501
  continue;
1297
1502
  }
1298
1503
  int dropped = m->dropped.exchange(0);
1504
+ gChunksSent++;
1299
1505
  auto inflight = m->inflight;
1300
1506
  inflight->fetch_add(1);
1301
1507
  double mid = m.mid, rate = m.sampleRate;
@@ -1384,12 +1590,7 @@ static Napi::Value OpenMicrophone(const Napi::CallbackInfo& info) {
1384
1590
  m.deviceUID = deviceUID;
1385
1591
  if (!gMics) gMics = [NSMutableDictionary dictionary];
1386
1592
  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
- }
1593
+ SafeRewire();
1393
1594
  };
1394
1595
  if (status == AVAuthorizationStatusNotDetermined) {
1395
1596
  [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
@@ -1418,7 +1619,7 @@ static Napi::Value CloseMicrophone(const Napi::CallbackInfo& info) {
1418
1619
  dispatch_async(AudioQueue(), ^{
1419
1620
  if (!gMics[@(mid)]) return;
1420
1621
  [gMics removeObjectForKey:@(mid)];
1421
- Rewire();
1622
+ SafeRewire();
1422
1623
  });
1423
1624
  return env.Undefined();
1424
1625
  }
@@ -1452,11 +1653,8 @@ static Napi::Value OpenAudioOutput(const Napi::CallbackInfo& info) {
1452
1653
  gOutputs[@(oid)] = o;
1453
1654
  }
1454
1655
  dispatch_async(AudioQueue(), ^{
1455
- @try {
1456
- Rewire();
1457
- } @catch (NSException*) {
1458
- // an engine that would not wire plays nothing; its state says so
1459
- }
1656
+ // an engine that would not wire plays nothing; its state says so
1657
+ SafeRewire();
1460
1658
  });
1461
1659
  Napi::Object out = Napi::Object::New(env);
1462
1660
  out.Set("id", oid);
@@ -1527,12 +1725,21 @@ static Napi::Value CloseAudioOutput(const Napi::CallbackInfo& info) {
1527
1725
  }
1528
1726
  if (!o) return env.Undefined();
1529
1727
  dispatch_async(AudioQueue(), ^{
1530
- if (o.node && gEngine) {
1531
- [gEngine disconnectNodeOutput:o.node];
1532
- [gEngine detachNode:o.node];
1728
+ // The node is this engine's only while the engine it was attached to is
1729
+ // the one running. One rebuilt since — a device change, a headset
1730
+ // switching profiles — took it down with it, and it was off the list by
1731
+ // then so nothing let go of it; asking the new engine to disconnect it
1732
+ // throws, on this queue, and ended the process.
1733
+ @try {
1734
+ if (o.node && gEngine && [gEngine.attachedNodes containsObject:o.node]) {
1735
+ [gEngine disconnectNodeOutput:o.node];
1736
+ [gEngine detachNode:o.node];
1737
+ }
1738
+ } @catch (NSException*) {
1739
+ // gone already, which is what this was for
1533
1740
  }
1534
1741
  o.node = nil;
1535
- Rewire();
1742
+ SafeRewire();
1536
1743
  });
1537
1744
  return env.Undefined();
1538
1745
  }
@@ -1708,6 +1915,11 @@ static Napi::Value CaptureScreenshot(const Napi::CallbackInfo& info) {
1708
1915
  return env.Undefined();
1709
1916
  }
1710
1917
 
1918
+ // systemaudio.mm's taps are captures too: their ids come from the same count,
1919
+ // so an event's id names one thing, and they cross to JS the same way.
1920
+ double CALNextCaptureId() { return (double)(++gNextCapture); }
1921
+ bool CALCaptureDeliver(dispatch_block_t block) { return Deliver(block); }
1922
+
1711
1923
  void InitCapture(Napi::Env env, Napi::Object exports) {
1712
1924
  // The delivery function is the main thread's, made the once, for the
1713
1925
  // reason InitNotifications gives: pump mode's listener is called there.
@@ -11,6 +11,11 @@
11
11
  // thread-safe function
12
12
  // screen-recording CGPreflightScreenCaptureAccess /
13
13
  // CGRequestScreenCaptureAccess
14
+ // system-audio-recording
15
+ // TCC's own TCCAccessPreflight / TCCAccessRequest for
16
+ // kTCCServiceAudioCapture (macOS 14.2: a tap of other
17
+ // processes' sound, systemaudio.mm), which has no
18
+ // public call to read or to ask — found at run time
14
19
  // accessibility AXIsProcessTrusted / AXIsProcessTrustedWithOptions
15
20
  // with the prompt option
16
21
  // input-monitoring IOHIDCheckAccess / IOHIDRequestAccess (listen)
@@ -31,7 +36,9 @@
31
36
  // Every status that crosses to JS is one of 'authorized' | 'denied' |
32
37
  // 'restricted' | 'notDetermined' — plus 'writeOnly', which only calendars
33
38
  // and reminders can answer: macOS 14's partial grant (the app may save items
34
- // it cannot read back). It crosses as its own word rather than as either
39
+ // it cannot read back), and 'unknown', which only system-audio-recording
40
+ // answers, where there is nothing to read it with: before macOS 14.2, or a
41
+ // TCC without the calls. It crosses as its own word rather than as either
35
42
  // side, because whether it counts as granted depends on what the consumer
36
43
  // wanted to do — a writer has what it needs, a reader does not — and that is
37
44
  // the renderer's decision. Screen recording and accessibility only ever
@@ -45,6 +52,7 @@
45
52
  // inside the requesting call — and a pending request holds the event loop
46
53
  // open like pending I/O until the user has answered.
47
54
 
55
+ #include <dlfcn.h>
48
56
  #include <napi.h>
49
57
  #import <Cocoa/Cocoa.h>
50
58
  #import <AVFoundation/AVFoundation.h>
@@ -68,11 +76,13 @@ static const char* const kDenied = "denied";
68
76
  static const char* const kRestricted = "restricted";
69
77
  static const char* const kNotDetermined = "notDetermined";
70
78
  static const char* const kWriteOnly = "writeOnly";
79
+ static const char* const kUnknown = "unknown";
71
80
 
72
81
  enum class Kind {
73
82
  Camera,
74
83
  Microphone,
75
84
  ScreenRecording,
85
+ SystemAudioRecording,
76
86
  Accessibility,
77
87
  InputMonitoring,
78
88
  Automation,
@@ -82,13 +92,15 @@ enum class Kind {
82
92
  };
83
93
 
84
94
  static const char* const kKindNames =
85
- "camera, microphone, screen-recording, accessibility, input-monitoring, "
86
- "automation, location, calendars, reminders";
95
+ "camera, microphone, screen-recording, system-audio-recording, "
96
+ "accessibility, input-monitoring, automation, location, calendars, "
97
+ "reminders";
87
98
 
88
99
  static bool ParseKind(const std::string& s, Kind* out) {
89
100
  if (s == "camera") *out = Kind::Camera;
90
101
  else if (s == "microphone") *out = Kind::Microphone;
91
102
  else if (s == "screen-recording") *out = Kind::ScreenRecording;
103
+ else if (s == "system-audio-recording") *out = Kind::SystemAudioRecording;
92
104
  else if (s == "accessibility") *out = Kind::Accessibility;
93
105
  else if (s == "input-monitoring") *out = Kind::InputMonitoring;
94
106
  else if (s == "automation") *out = Kind::Automation;
@@ -254,6 +266,48 @@ EKEventStore* CALEventStore() {
254
266
  // mapping stays here, in the one place that knows it.
255
267
  const char* CALEventsAuthorizationStatus() { return EKStatus(EKEntityTypeEvent); }
256
268
 
269
+ // System Audio Recording has no public call to read it or to ask for it: the
270
+ // first read of a tap raises the prompt, and a refusal is not an error but a
271
+ // tap that delivers silence — a recording of nothing, for as long as anyone
272
+ // lets it run. So it is read and asked through TCC's own TCCAccessPreflight
273
+ // and TCCAccessRequest, private, the pair every recorder of other apps' sound
274
+ // uses, found at run time: nothing links against them, and where they are not
275
+ // there the status is 'unknown' and the tap's own prompt is the only one.
276
+ // Preflight answers 0 for a grant, 1 for a refusal and 2 for not asked yet.
277
+ // Exported for systemaudio.mm, which reads it before it makes a tap.
278
+ static void* TCCSymbol(const char* name) {
279
+ static void* handle =
280
+ dlopen("/System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC", RTLD_LAZY | RTLD_LOCAL);
281
+ return handle ? dlsym(handle, name) : nullptr;
282
+ }
283
+
284
+ static const CFStringRef kAudioCaptureService = CFSTR("kTCCServiceAudioCapture");
285
+
286
+ const char* CALAudioCaptureStatus() {
287
+ if (@available(macOS 14.2, *)) {
288
+ auto preflight = (int (*)(CFStringRef, CFDictionaryRef))TCCSymbol("TCCAccessPreflight");
289
+ if (!preflight) return kUnknown;
290
+ switch (preflight(kAudioCaptureService, nullptr)) {
291
+ case 0: return kAuthorized;
292
+ case 1: return kDenied;
293
+ case 2: return kNotDetermined;
294
+ default: return kUnknown;
295
+ }
296
+ }
297
+ return kUnknown;
298
+ }
299
+
300
+ // The prompt where nobody has been asked, then `done` on any thread; at once
301
+ // where the status is decided or cannot be read.
302
+ void CALAudioCaptureRequest(void (^done)(void)) {
303
+ auto request = (void (*)(CFStringRef, CFDictionaryRef, void (^)(Boolean)))TCCSymbol("TCCAccessRequest");
304
+ if (!request || CALAudioCaptureStatus() != kNotDetermined) {
305
+ done();
306
+ return;
307
+ }
308
+ request(kAudioCaptureService, nullptr, ^(Boolean) { done(); });
309
+ }
310
+
257
311
  // TCC's answer for sending Apple Events to `bundleId`. With `ask`, the call
258
312
  // blocks while the consent dialog is up. procNotFound means the target is
259
313
  // not running — TCC only answers for a running target, so the caller turns
@@ -379,6 +433,7 @@ static Napi::Value AuthorizationStatus(const Napi::CallbackInfo& info) {
379
433
  case Kind::ScreenRecording:
380
434
  s = CGPreflightScreenCaptureAccess() ? kAuthorized : kDenied;
381
435
  break;
436
+ case Kind::SystemAudioRecording: s = CALAudioCaptureStatus(); break;
382
437
  case Kind::Accessibility:
383
438
  s = AXIsProcessTrusted() ? kAuthorized : kDenied;
384
439
  break;
@@ -436,6 +491,11 @@ static Napi::Value RequestAuthorization(const Napi::CallbackInfo& info) {
436
491
  // returns the current grant either way
437
492
  Answer(tsfn, CGRequestScreenCaptureAccess() ? kAuthorized : kDenied);
438
493
  break;
494
+ case Kind::SystemAudioRecording: {
495
+ // the prompt where nobody was asked, the status after it either way
496
+ CALAudioCaptureRequest(^{ Answer(tsfn, CALAudioCaptureStatus()); });
497
+ break;
498
+ }
439
499
  case Kind::Accessibility: {
440
500
  NSDictionary* opts =
441
501
  @{(__bridge NSString*)kAXTrustedCheckOptionPrompt : @YES};
@@ -519,6 +579,7 @@ static Napi::Value OpenPrivacySettings(const Napi::CallbackInfo& info) {
519
579
  else if (kind == "camera") anchor = "Privacy_Camera";
520
580
  else if (kind == "microphone") anchor = "Privacy_Microphone";
521
581
  else if (kind == "screen-recording") anchor = "Privacy_ScreenCapture";
582
+ else if (kind == "system-audio-recording") anchor = "Privacy_AudioCapture";
522
583
  else if (kind == "accessibility") anchor = "Privacy_Accessibility";
523
584
  else if (kind == "input-monitoring") anchor = "Privacy_ListenEvent";
524
585
  else if (kind == "automation") anchor = "Privacy_Automation";