assemblyai 4.33.3 → 4.34.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.
Files changed (38) hide show
  1. package/dist/assemblyai.streaming.umd.js +1279 -3
  2. package/dist/assemblyai.streaming.umd.min.js +1 -1
  3. package/dist/assemblyai.umd.js +786 -3
  4. package/dist/assemblyai.umd.min.js +1 -1
  5. package/dist/browser.mjs +762 -4
  6. package/dist/bun.mjs +762 -4
  7. package/dist/deno.mjs +762 -4
  8. package/dist/exports/streaming.d.ts +7 -0
  9. package/dist/index.cjs +786 -3
  10. package/dist/index.mjs +778 -4
  11. package/dist/node.cjs +770 -3
  12. package/dist/node.mjs +762 -4
  13. package/dist/services/index.d.ts +2 -2
  14. package/dist/services/streaming/browser/dual-channel-capture.d.ts +66 -0
  15. package/dist/services/streaming/browser/worklets/pcm16-encoder.d.ts +19 -0
  16. package/dist/services/streaming/energy-vad.d.ts +35 -0
  17. package/dist/services/streaming/index.d.ts +4 -0
  18. package/dist/services/streaming/label-mapper.d.ts +44 -0
  19. package/dist/services/streaming/resampler.d.ts +22 -0
  20. package/dist/services/streaming/service.d.ts +69 -1
  21. package/dist/streaming.browser.mjs +1235 -4
  22. package/dist/streaming.cjs +1275 -3
  23. package/dist/streaming.mjs +1264 -4
  24. package/dist/types/streaming/dual-channel.d.ts +48 -0
  25. package/dist/types/streaming/index.d.ts +110 -1
  26. package/dist/workerd.mjs +762 -4
  27. package/package.json +1 -1
  28. package/src/exports/streaming.ts +7 -0
  29. package/src/services/index.ts +20 -1
  30. package/src/services/streaming/browser/dual-channel-capture.ts +177 -0
  31. package/src/services/streaming/browser/worklets/pcm16-encoder.ts +70 -0
  32. package/src/services/streaming/energy-vad.ts +75 -0
  33. package/src/services/streaming/index.ts +4 -0
  34. package/src/services/streaming/label-mapper.ts +128 -0
  35. package/src/services/streaming/resampler.ts +69 -0
  36. package/src/services/streaming/service.ts +385 -2
  37. package/src/types/streaming/dual-channel.ts +57 -0
  38. package/src/types/streaming/index.ts +110 -0
package/dist/deno.mjs CHANGED
@@ -1,5 +1,18 @@
1
1
  import ws from 'ws';
2
2
 
3
+ /**
4
+ * Thrown when `DualChannelCapture` is constructed in a non-browser environment
5
+ * (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
6
+ * main entrypoint so the import path is uniform across runtimes; the runtime
7
+ * guard moves to construction time.
8
+ */
9
+ class BrowserOnlyError extends Error {
10
+ constructor(message = "DualChannelCapture requires a browser environment (AudioContext is undefined).") {
11
+ super(message);
12
+ this.name = "BrowserOnlyError";
13
+ }
14
+ }
15
+
3
16
  const DEFAULT_FETCH_INIT = {
4
17
  cache: "no-store",
5
18
  };
@@ -17,7 +30,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
17
30
  defaultUserAgentString += navigator.userAgent;
18
31
  }
19
32
  const defaultUserAgent = {
20
- sdk: { name: "JavaScript", version: "4.33.3" },
33
+ sdk: { name: "JavaScript", version: "4.34.0" },
21
34
  };
22
35
  if (typeof process !== "undefined") {
23
36
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -782,11 +795,216 @@ function dataUrlToBlob(dataUrl) {
782
795
  return new Blob([u8arr], { type: mime });
783
796
  }
784
797
 
798
+ /**
799
+ * Energy-based VAD with adaptive noise-floor tracking and hangover. Pure JS,
800
+ * no dependencies. Suitable for the "which physical channel is speaking" task
801
+ * because the channels are already physically separated at capture — the harder
802
+ * problem (speech vs. non-speech in the wild) is one a customer can swap in a
803
+ * DNN VAD for via the `createVad` parameter.
804
+ *
805
+ * Tuning notes:
806
+ * - thresholdRatio below 2 will treat anything above noise as speech (too sensitive).
807
+ * - thresholdRatio above 6 will miss quiet utterance onsets/offsets.
808
+ * - noiseFloorAlpha above 0.1 makes the floor track quickly (good for non-stationary
809
+ * background) but risks slowly adapting *up* to a sustained low voice.
810
+ */
811
+ class EnergyVad {
812
+ constructor(params = {}) {
813
+ this.hangoverRemaining = 0;
814
+ this.thresholdRatio = params.thresholdRatio ?? 3.0;
815
+ this.noiseFloorAlpha = params.noiseFloorAlpha ?? 0.05;
816
+ this.hangoverFrames = params.hangoverFrames ?? 10;
817
+ this.initialNoiseFloor = params.initialNoiseFloor ?? 1e-4;
818
+ this.noiseFloor = this.initialNoiseFloor;
819
+ }
820
+ process(frame) {
821
+ let sumSq = 0;
822
+ for (let i = 0; i < frame.length; i++) {
823
+ sumSq += frame[i] * frame[i];
824
+ }
825
+ const rms = frame.length > 0 ? Math.sqrt(sumSq / frame.length) : 0;
826
+ const threshold = this.noiseFloor * this.thresholdRatio;
827
+ let active = rms > threshold;
828
+ if (active) {
829
+ this.hangoverRemaining = this.hangoverFrames;
830
+ }
831
+ else if (this.hangoverRemaining > 0) {
832
+ this.hangoverRemaining--;
833
+ active = true;
834
+ // While in hangover, do not update noise floor — RMS may still reflect tail energy.
835
+ }
836
+ else {
837
+ this.noiseFloor =
838
+ this.noiseFloor * (1 - this.noiseFloorAlpha) +
839
+ rms * this.noiseFloorAlpha;
840
+ }
841
+ return { active, energy: rms };
842
+ }
843
+ reset() {
844
+ this.noiseFloor = this.initialNoiseFloor;
845
+ this.hangoverRemaining = 0;
846
+ }
847
+ }
848
+
849
+ /**
850
+ * Append-only ring buffer of VAD frames in stream-relative ms order.
851
+ * `pushFrame` is O(1) amortized; `framesInWindow` is O(n) over kept frames,
852
+ * which is fine for the per-word lookups we do (a 30 s window at 50 frames/s
853
+ * per channel × 2 channels = 3000 entries, scanned once per word).
854
+ *
855
+ * Runtime-agnostic — no DOM or Web Audio dependencies.
856
+ */
857
+ class VadTimeline {
858
+ constructor(windowMs) {
859
+ this.windowMs = windowMs;
860
+ this.frames = [];
861
+ this.head = 0;
862
+ }
863
+ pushFrame(frame) {
864
+ this.frames.push(frame);
865
+ const cutoff = frame.ts - this.windowMs;
866
+ while (this.head < this.frames.length &&
867
+ this.frames[this.head].ts < cutoff) {
868
+ this.head++;
869
+ }
870
+ if (this.head > 1024 && this.head * 2 > this.frames.length) {
871
+ this.frames = this.frames.slice(this.head);
872
+ this.head = 0;
873
+ }
874
+ }
875
+ framesInWindow(startMs, endMs) {
876
+ const out = [];
877
+ for (let i = this.head; i < this.frames.length; i++) {
878
+ const f = this.frames[i];
879
+ if (f.ts < startMs)
880
+ continue;
881
+ if (f.ts > endMs)
882
+ break;
883
+ out.push(f);
884
+ }
885
+ return out;
886
+ }
887
+ clear() {
888
+ this.frames = [];
889
+ this.head = 0;
890
+ }
891
+ }
892
+ /**
893
+ * Sum per-channel active RMS over a window. Returns a Map from channel name
894
+ * to total score. Channels with zero score are omitted.
895
+ */
896
+ function scoreChannels(frames) {
897
+ const scores = new Map();
898
+ for (const f of frames) {
899
+ if (!f.active)
900
+ continue;
901
+ scores.set(f.channel, (scores.get(f.channel) ?? 0) + f.rms);
902
+ }
903
+ return scores;
904
+ }
905
+ /**
906
+ * Decide which channel was dominant during a word's `[start, end]` window.
907
+ *
908
+ * - If no channel has any active VAD energy → `"unknown"`.
909
+ * - If the top channel beats the runner-up by at least `dominanceRatio` → top channel.
910
+ * - Else: top channel wins on absolute score; exact ties → `"unknown"`.
911
+ */
912
+ function attributeWord(word, timeline, params) {
913
+ const scores = scoreChannels(timeline.framesInWindow(word.start, word.end));
914
+ if (scores.size === 0)
915
+ return "unknown";
916
+ const sorted = [...scores.entries()].sort((a, b) => b[1] - a[1]);
917
+ if (sorted.length === 1)
918
+ return sorted[0][0];
919
+ const [topName, topScore] = sorted[0];
920
+ const [runnerName, runnerScore] = sorted[1];
921
+ if (topScore >= params.dominanceRatio * runnerScore)
922
+ return topName;
923
+ if (topScore > runnerScore)
924
+ return topName;
925
+ if (runnerScore > topScore)
926
+ return runnerName;
927
+ return "unknown";
928
+ }
929
+ /**
930
+ * Duration-weighted majority of word channels. `"unknown"` if there are no
931
+ * words, every word resolved to `"unknown"`, or two channels tie exactly.
932
+ */
933
+ function rollUpTurnChannel(words) {
934
+ const totals = new Map();
935
+ for (const w of words) {
936
+ if (!w.channel || w.channel === "unknown")
937
+ continue;
938
+ const dur = Math.max(0, w.end - w.start);
939
+ totals.set(w.channel, (totals.get(w.channel) ?? 0) + dur);
940
+ }
941
+ if (totals.size === 0)
942
+ return "unknown";
943
+ const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]);
944
+ if (sorted.length === 1)
945
+ return sorted[0][0];
946
+ const [topName, topMs] = sorted[0];
947
+ const [, runnerMs] = sorted[1];
948
+ if (topMs === runnerMs)
949
+ return "unknown";
950
+ return topName;
951
+ }
952
+ /**
953
+ * Mutate `turn` in place: write `turn.words[i].channel` for every word and set
954
+ * `turn.channel` to the duration-weighted rollup.
955
+ *
956
+ * Returns `void` because the transcriber owns the `TurnEvent` ref and forwards
957
+ * the same object to the customer listener — no need to allocate a copy.
958
+ */
959
+ function attributeTurn(turn, timeline, params) {
960
+ for (const w of turn.words) {
961
+ w.channel = attributeWord(w, timeline, params);
962
+ }
963
+ turn.channel = rollUpTurnChannel(turn.words);
964
+ }
965
+
966
+ /**
967
+ * View any `AudioData` (ArrayBuffer / ArrayBufferView / typed array) as a
968
+ * little-endian Int16 sample sequence without copying. Callers must guarantee
969
+ * the underlying byte length is even.
970
+ */
971
+ function toInt16View(audio) {
972
+ // AudioData is ArrayBufferLike per the public type, but in practice callers
973
+ // pass ArrayBuffer or a typed-array view. Handle both without copying.
974
+ if (audio instanceof Int16Array)
975
+ return audio;
976
+ if (ArrayBuffer.isView(audio)) {
977
+ const view = audio;
978
+ return new Int16Array(view.buffer, view.byteOffset, Math.floor(view.byteLength / 2));
979
+ }
980
+ return new Int16Array(audio);
981
+ }
785
982
  const defaultStreamingUrl$1 = "wss://streaming.assemblyai.com/v3/ws";
786
983
  const terminateSessionMessage = `{"type":"Terminate"}`;
984
+ /**
985
+ * Per-send chunk cap in milliseconds for the dual-channel mixer. The streaming
986
+ * server rejects audio messages longer than 1000 ms (`Input Duration Error`).
987
+ * If a backlog accumulates (e.g. when a browser tab is backgrounded and
988
+ * `setInterval` is throttled to ~1 Hz), `flushMix` loops and emits multiple
989
+ * sends each ≤ this cap until the buffers drain.
990
+ */
991
+ const MAX_CHUNK_MS = 200;
992
+ /**
993
+ * Per-send minimum chunk size in milliseconds. The streaming server also
994
+ * rejects audio messages shorter than 50 ms with the same
995
+ * `Input Duration Error`, so the mixer waits until both per-channel buffers
996
+ * have at least this much accumulated before emitting. Final-flush (close
997
+ * path) bypasses this floor so the trailing partial buffer still gets sent.
998
+ */
999
+ const MIN_CHUNK_MS = 50;
787
1000
  class StreamingTranscriber {
788
1001
  constructor(params) {
789
1002
  this.listeners = {};
1003
+ // Dual-channel mode state (allocated only when params.channels is set).
1004
+ this.isDualChannel = false;
1005
+ this.vadFrameSamples = 0;
1006
+ this.minChunkSamples = 0;
1007
+ this.maxChunkSamples = 0;
790
1008
  this.params = {
791
1009
  ...params,
792
1010
  websocketBaseUrl: params.websocketBaseUrl || defaultStreamingUrl$1,
@@ -798,6 +1016,42 @@ class StreamingTranscriber {
798
1016
  if (!(this.token || this.apiKey)) {
799
1017
  throw new Error("API key or temporary token is required.");
800
1018
  }
1019
+ if (params.channels) {
1020
+ if (params.channels.length !== 2) {
1021
+ throw new Error("StreamingTranscriber.channels must have exactly 2 entries.");
1022
+ }
1023
+ const names = params.channels.map((c) => c.name);
1024
+ if (new Set(names).size !== names.length) {
1025
+ throw new Error("StreamingTranscriber.channels names must be unique.");
1026
+ }
1027
+ this.isDualChannel = true;
1028
+ this.channelNames = names;
1029
+ const att = params.channelAttribution ?? {};
1030
+ this.attributionParams = {
1031
+ dominanceRatio: att.dominanceRatio ?? 4,
1032
+ timelineWindowMs: att.timelineWindowMs ?? 30_000,
1033
+ createVad: att.createVad ?? (() => new EnergyVad()),
1034
+ flushIntervalMs: att.flushIntervalMs ?? 50,
1035
+ resolveUnknownChannelsMethod: att.resolveUnknownChannelsMethod ?? "window",
1036
+ resolutionWindowWords: att.resolutionWindowWords ?? 2,
1037
+ speakerHistoryMinRmsEvidence: att.speakerHistoryMinRmsEvidence ?? 0.5,
1038
+ speakerHistoryDominanceRatio: att.speakerHistoryDominanceRatio ?? 3,
1039
+ };
1040
+ if (this.attributionParams.resolveUnknownChannelsMethod ===
1041
+ "speaker-history") {
1042
+ this.speakerHistory = new Map();
1043
+ }
1044
+ // 20 ms VAD frames at the transcriber's target sample rate.
1045
+ this.vadFrameSamples = Math.max(1, Math.round(params.sampleRate * 0.02));
1046
+ this.minChunkSamples = Math.max(1, Math.round(params.sampleRate * (MIN_CHUNK_MS / 1000)));
1047
+ this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(params.sampleRate * (MAX_CHUNK_MS / 1000)));
1048
+ this.channelBuffers = new Map(names.map((n) => [n, []]));
1049
+ this.channelSamplesReceived = new Map(names.map((n) => [n, 0]));
1050
+ this.channelVadFloatBuffers = new Map(names.map((n) => [n, new Float32Array(this.vadFrameSamples)]));
1051
+ this.channelVadBufferIdx = new Map(names.map((n) => [n, 0]));
1052
+ this.channelVads = new Map(names.map((n) => [n, this.attributionParams.createVad(n)]));
1053
+ this.timeline = new VadTimeline(this.attributionParams.timelineWindowMs);
1054
+ }
801
1055
  }
802
1056
  connectionUrl() {
803
1057
  const url = new URL(this.params.websocketBaseUrl ?? "");
@@ -946,6 +1200,13 @@ class StreamingTranscriber {
946
1200
  reason = StreamingErrorMessages[code];
947
1201
  }
948
1202
  }
1203
+ // Stop the flush timer when the socket is gone (server-initiated close,
1204
+ // network drop, etc.) — otherwise subsequent ticks call send() on a
1205
+ // closed socket and spam the error listener.
1206
+ if (this.flushTimer) {
1207
+ clearInterval(this.flushTimer);
1208
+ this.flushTimer = undefined;
1209
+ }
949
1210
  this.listeners.close?.(code, reason);
950
1211
  };
951
1212
  this.socket.onerror = (event) => {
@@ -972,6 +1233,19 @@ class StreamingTranscriber {
972
1233
  break;
973
1234
  }
974
1235
  case "Turn": {
1236
+ if (this.isDualChannel && this.timeline && this.attributionParams) {
1237
+ attributeTurn(message, this.timeline, {
1238
+ dominanceRatio: this.attributionParams.dominanceRatio,
1239
+ });
1240
+ switch (this.attributionParams.resolveUnknownChannelsMethod) {
1241
+ case "window":
1242
+ this.resolveUnknownChannelsByWindow(message);
1243
+ break;
1244
+ case "speaker-history":
1245
+ this.resolveUnknownChannelsBySpeakerHistory(message);
1246
+ break;
1247
+ }
1248
+ }
975
1249
  this.listeners.turn?.(message);
976
1250
  break;
977
1251
  }
@@ -997,6 +1271,11 @@ class StreamingTranscriber {
997
1271
  };
998
1272
  });
999
1273
  }
1274
+ /**
1275
+ * Returns a WritableStream that pumps PCM chunks into `sendAudio`. Single-channel
1276
+ * only — in dual-channel mode use `sendAudio(pcm, { channel })` directly, since
1277
+ * `WritableStream` has no place to carry a channel tag.
1278
+ */
1000
1279
  stream() {
1001
1280
  return new WritableStream({
1002
1281
  write: (chunk) => {
@@ -1004,8 +1283,235 @@ class StreamingTranscriber {
1004
1283
  },
1005
1284
  });
1006
1285
  }
1007
- sendAudio(audio) {
1008
- this.send(audio);
1286
+ /**
1287
+ * Send PCM audio.
1288
+ *
1289
+ * In single-channel mode, `audio` is forwarded directly to the WebSocket and
1290
+ * `options` is ignored.
1291
+ *
1292
+ * In dual-channel mode (when `channels` is configured), `options.channel` is
1293
+ * REQUIRED and must match one of the declared channel names. Per-channel PCM is
1294
+ * fed into that channel's VAD, accumulated into a per-channel ring buffer, and
1295
+ * a scheduled flush (`channelAttribution.flushIntervalMs`, default 50ms) mixes
1296
+ * the buffers into mono before sending to the WebSocket.
1297
+ */
1298
+ sendAudio(audio, options) {
1299
+ if (!this.isDualChannel) {
1300
+ this.send(audio);
1301
+ return;
1302
+ }
1303
+ if (!options?.channel) {
1304
+ throw new Error("StreamingTranscriber is in dual-channel mode; sendAudio requires { channel }.");
1305
+ }
1306
+ if (!this.channelNames.includes(options.channel)) {
1307
+ throw new Error(`Unknown channel "${options.channel}"; declared channels: ${this.channelNames.join(", ")}.`);
1308
+ }
1309
+ this.ingestChannelAudio(options.channel, audio);
1310
+ }
1311
+ ingestChannelAudio(name, audio) {
1312
+ const samples = toInt16View(audio);
1313
+ const buf = this.channelBuffers.get(name);
1314
+ const vadBuf = this.channelVadFloatBuffers.get(name);
1315
+ let vadIdx = this.channelVadBufferIdx.get(name);
1316
+ let received = this.channelSamplesReceived.get(name);
1317
+ const vad = this.channelVads.get(name);
1318
+ const sampleRate = this.params.sampleRate;
1319
+ const frameSize = this.vadFrameSamples;
1320
+ for (let i = 0; i < samples.length; i++) {
1321
+ const s = samples[i];
1322
+ buf.push(s);
1323
+ vadBuf[vadIdx++] = s / 0x8000;
1324
+ received++;
1325
+ if (vadIdx === frameSize) {
1326
+ const result = vad.process(vadBuf);
1327
+ const frame = {
1328
+ ts: (received / sampleRate) * 1000,
1329
+ channel: name,
1330
+ active: result.active,
1331
+ rms: result.energy,
1332
+ };
1333
+ this.timeline.pushFrame(frame);
1334
+ this.listeners.vad?.(frame);
1335
+ vadIdx = 0;
1336
+ }
1337
+ }
1338
+ this.channelVadBufferIdx.set(name, vadIdx);
1339
+ this.channelSamplesReceived.set(name, received);
1340
+ if (!this.flushTimer)
1341
+ this.startFlushTimer();
1342
+ }
1343
+ startFlushTimer() {
1344
+ this.flushTimer = setInterval(() => this.flushMix(), this.attributionParams.flushIntervalMs);
1345
+ }
1346
+ flushMix(force = false) {
1347
+ if (!this.channelNames || !this.channelBuffers)
1348
+ return;
1349
+ const bufs = this.channelNames.map((n) => this.channelBuffers.get(n));
1350
+ const divisor = bufs.length;
1351
+ // Loop so a backlog (e.g. accumulated while a browser tab was throttled in
1352
+ // the background) drains as multiple sends, each capped at MAX_CHUNK_MS.
1353
+ // Without the cap a single message could exceed the server's 1000 ms input
1354
+ // duration limit and be rejected with code 3007.
1355
+ for (;;) {
1356
+ let mixLen = Infinity;
1357
+ for (const b of bufs)
1358
+ if (b.length < mixLen)
1359
+ mixLen = b.length;
1360
+ if (!Number.isFinite(mixLen) || mixLen === 0)
1361
+ return;
1362
+ // The streaming server rejects audio messages shorter than 50 ms with
1363
+ // `Input Duration Error`. Wait until both per-channel buffers have at
1364
+ // least minChunkSamples worth queued before emitting. The `force` path
1365
+ // (final flush on close) bypasses this so the trailing partial buffer
1366
+ // still gets through.
1367
+ if (!force && mixLen < this.minChunkSamples)
1368
+ return;
1369
+ if (mixLen > this.maxChunkSamples)
1370
+ mixLen = this.maxChunkSamples;
1371
+ const out = new Int16Array(mixLen);
1372
+ for (let i = 0; i < mixLen; i++) {
1373
+ let sum = 0;
1374
+ for (let c = 0; c < divisor; c++)
1375
+ sum += bufs[c][i];
1376
+ const avg = Math.round(sum / divisor);
1377
+ out[i] = avg < -32768 ? -32768 : avg > 32767 ? 32767 : avg;
1378
+ }
1379
+ for (const b of bufs)
1380
+ b.splice(0, mixLen);
1381
+ try {
1382
+ this.send(out.buffer);
1383
+ }
1384
+ catch (err) {
1385
+ this.listeners.error?.(err);
1386
+ return;
1387
+ }
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Fill in words whose per-word VAD attribution was `"unknown"` by looking
1392
+ * at the dominant non-`"unknown"` channel among ±N neighbors in the same
1393
+ * turn. Words with no non-`"unknown"` neighbors stay `"unknown"`. Confident
1394
+ * per-word VAD decisions are never modified.
1395
+ *
1396
+ * Local temporal heuristic — ignores `speaker_label`, so it works even when
1397
+ * AAI's diarization re-uses the same label for two physically distinct
1398
+ * voices. Each resolved word gets `channelResolved: true` so downstream
1399
+ * renderers can distinguish inferred channels from directly-measured ones.
1400
+ */
1401
+ resolveUnknownChannelsByWindow(turn) {
1402
+ if (!this.attributionParams)
1403
+ return;
1404
+ const window = this.attributionParams.resolutionWindowWords;
1405
+ const words = turn.words;
1406
+ let mutated = false;
1407
+ for (let i = 0; i < words.length; i++) {
1408
+ if (words[i].channel !== "unknown")
1409
+ continue;
1410
+ const tally = new Map();
1411
+ const lo = Math.max(0, i - window);
1412
+ const hi = Math.min(words.length - 1, i + window);
1413
+ for (let j = lo; j <= hi; j++) {
1414
+ if (j === i)
1415
+ continue;
1416
+ const ch = words[j].channel;
1417
+ if (!ch || ch === "unknown")
1418
+ continue;
1419
+ tally.set(ch, (tally.get(ch) ?? 0) + 1);
1420
+ }
1421
+ if (tally.size === 0)
1422
+ continue;
1423
+ // Pick the dominant neighbor channel. Ties → leave `"unknown"` (rare;
1424
+ // would require an equal count of mic and system neighbors).
1425
+ let top;
1426
+ let topCount = 0;
1427
+ let tied = false;
1428
+ for (const [name, count] of tally) {
1429
+ if (count > topCount) {
1430
+ top = name;
1431
+ topCount = count;
1432
+ tied = false;
1433
+ }
1434
+ else if (count === topCount) {
1435
+ tied = true;
1436
+ }
1437
+ }
1438
+ if (top && !tied) {
1439
+ words[i].channel = top;
1440
+ words[i].channelResolved = true;
1441
+ mutated = true;
1442
+ }
1443
+ }
1444
+ // Recompute the rollup only if any per-word channel changed.
1445
+ if (mutated)
1446
+ turn.channel = rollUpTurnChannel(words);
1447
+ }
1448
+ /**
1449
+ * Fill `"unknown"` words by looking up the speaker's session-wide channel
1450
+ * evidence. For each `speaker_label`, sums active VAD frame RMS per channel
1451
+ * across every word the speaker has uttered to date. A speaker is
1452
+ * "resolvable" if their total evidence clears
1453
+ * `speakerHistoryMinRmsEvidence` and their top channel exceeds the
1454
+ * runner-up by `speakerHistoryDominanceRatio`.
1455
+ *
1456
+ * Only touches `"unknown"` words. Confident per-word VAD decisions are
1457
+ * never modified. `speaker_label` is never modified.
1458
+ */
1459
+ resolveUnknownChannelsBySpeakerHistory(turn) {
1460
+ if (!this.timeline || !this.attributionParams || !this.speakerHistory)
1461
+ return;
1462
+ const minEvidence = this.attributionParams.speakerHistoryMinRmsEvidence;
1463
+ const dominanceRatio = this.attributionParams.speakerHistoryDominanceRatio;
1464
+ // 1. Accumulate evidence from this turn's words.
1465
+ for (const w of turn.words) {
1466
+ if (!w.speaker)
1467
+ continue;
1468
+ const frames = this.timeline.framesInWindow(w.start, w.end);
1469
+ let entry = this.speakerHistory.get(w.speaker);
1470
+ if (!entry) {
1471
+ entry = new Map();
1472
+ this.speakerHistory.set(w.speaker, entry);
1473
+ }
1474
+ for (const f of frames) {
1475
+ if (!f.active)
1476
+ continue;
1477
+ entry.set(f.channel, (entry.get(f.channel) ?? 0) + f.rms);
1478
+ }
1479
+ }
1480
+ // 2. Fill unknown words whose speakers have dominant evidence.
1481
+ let mutated = false;
1482
+ for (const w of turn.words) {
1483
+ if (w.channel !== "unknown" || !w.speaker)
1484
+ continue;
1485
+ const entry = this.speakerHistory.get(w.speaker);
1486
+ if (!entry || entry.size === 0)
1487
+ continue;
1488
+ let total = 0;
1489
+ let topName;
1490
+ let topScore = 0;
1491
+ let runnerScore = 0;
1492
+ for (const [name, score] of entry) {
1493
+ total += score;
1494
+ if (score > topScore) {
1495
+ runnerScore = topScore;
1496
+ topScore = score;
1497
+ topName = name;
1498
+ }
1499
+ else if (score > runnerScore) {
1500
+ runnerScore = score;
1501
+ }
1502
+ }
1503
+ if (total < minEvidence)
1504
+ continue;
1505
+ if (runnerScore > 0 && topScore < dominanceRatio * runnerScore)
1506
+ continue;
1507
+ if (topName) {
1508
+ w.channel = topName;
1509
+ w.channelResolved = true;
1510
+ mutated = true;
1511
+ }
1512
+ }
1513
+ if (mutated)
1514
+ turn.channel = rollUpTurnChannel(turn.words);
1009
1515
  }
1010
1516
  /**
1011
1517
  * Update the streaming configuration mid-stream.
@@ -1045,6 +1551,15 @@ class StreamingTranscriber {
1045
1551
  this.socket.send(data);
1046
1552
  }
1047
1553
  async close(waitForSessionTermination = true) {
1554
+ if (this.flushTimer) {
1555
+ clearInterval(this.flushTimer);
1556
+ this.flushTimer = undefined;
1557
+ // Best-effort: drain any final partial mix so the server gets the tail.
1558
+ // Bypass the 50ms floor here since this is the last flush; if the tail
1559
+ // is <50ms the server will reject that single message, but we'd lose
1560
+ // the audio either way.
1561
+ this.flushMix(true);
1562
+ }
1048
1563
  if (this.socket) {
1049
1564
  if (this.socket.readyState === this.socket.OPEN) {
1050
1565
  if (waitForSessionTermination) {
@@ -1096,6 +1611,249 @@ class StreamingTranscriberFactory extends BaseService {
1096
1611
  }
1097
1612
  }
1098
1613
 
1614
+ /**
1615
+ * AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
1616
+ * native sample rate, resamples to `targetRate` (linear interpolation, stateful
1617
+ * across `process()` calls), packs to little-endian Int16 PCM, and posts
1618
+ * fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
1619
+ *
1620
+ * `samplesSent` is in **target-rate samples**, so the main thread can derive a
1621
+ * stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
1622
+ * frame AAI uses for `StreamingWord.start` / `.end`.
1623
+ *
1624
+ * Defined as a string so it can be registered via a Blob URL — the SDK ships as
1625
+ * a single ESM file, so a separate `.js` worklet asset isn't viable.
1626
+ */
1627
+ const pcm16EncoderWorkletSource = `
1628
+ class Pcm16EncoderProcessor extends AudioWorkletProcessor {
1629
+ constructor(options) {
1630
+ super();
1631
+ const opts = (options && options.processorOptions) || {};
1632
+ this.targetRate = opts.targetRate || 16000;
1633
+ this.chunkMs = opts.chunkMs || 50;
1634
+ this.ratio = sampleRate / this.targetRate;
1635
+ this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);
1636
+ this.buffer = new Int16Array(this.chunkSize);
1637
+ this.bufferIdx = 0;
1638
+ this.samplesSent = 0;
1639
+ this.lastSample = 0;
1640
+ this.fractional = 0;
1641
+ }
1642
+
1643
+ process(inputs) {
1644
+ const input = inputs[0];
1645
+ if (!input || input.length === 0 || !input[0] || input[0].length === 0) {
1646
+ return true;
1647
+ }
1648
+ const mono = input[0];
1649
+ let pos = this.fractional;
1650
+ while (pos < mono.length) {
1651
+ const i = Math.floor(pos);
1652
+ const frac = pos - i;
1653
+ const a = i === 0 ? this.lastSample : mono[i - 1];
1654
+ const b = mono[i];
1655
+ const sample = a + (b - a) * frac;
1656
+ const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
1657
+ this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
1658
+ if (this.bufferIdx === this.chunkSize) {
1659
+ const out = new Int16Array(this.chunkSize);
1660
+ out.set(this.buffer);
1661
+ this.samplesSent += this.chunkSize;
1662
+ this.port.postMessage(
1663
+ { pcm: out.buffer, samplesSent: this.samplesSent },
1664
+ [out.buffer],
1665
+ );
1666
+ this.bufferIdx = 0;
1667
+ }
1668
+ pos += this.ratio;
1669
+ }
1670
+ this.lastSample = mono[mono.length - 1];
1671
+ this.fractional = pos - mono.length;
1672
+ return true;
1673
+ }
1674
+ }
1675
+ registerProcessor("aai-pcm16-encoder", Pcm16EncoderProcessor);
1676
+ `;
1677
+ const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
1678
+
1679
+ const DEFAULT_TARGET_RATE = 16_000;
1680
+ const DEFAULT_CHUNK_MS = 50;
1681
+ const MIC_CHANNEL = "mic";
1682
+ const SYSTEM_CHANNEL = "system";
1683
+ /**
1684
+ * Browser-only adapter that pumps two `MediaStream`s into a `StreamingTranscriber`
1685
+ * configured for dual-channel mode. Each `MediaStream` runs through its own
1686
+ * `pcm16-encoder` AudioWorklet (resample to `targetSampleRate`, encode to Int16
1687
+ * PCM); each PCM chunk is forwarded via `transcriber.sendAudio(pcm, { channel })`.
1688
+ *
1689
+ * All dual-channel orchestration (mixing, VAD, per-word attribution) lives inside
1690
+ * `StreamingTranscriber` — this class is a pure I/O adapter. Non-browser runtimes
1691
+ * can replicate its job by pushing tagged PCM into `transcriber.sendAudio` directly.
1692
+ *
1693
+ * Caller responsibilities:
1694
+ * - **Echo cancellation** is set at `getUserMedia` time (`audio: { echoCancellation: true }`).
1695
+ * - **System-audio capture** is platform-dependent. Chrome's `getDisplayMedia({ audio: true })`
1696
+ * captures tab audio (and on Windows, full system audio when sharing the whole screen).
1697
+ * macOS requires a virtual loopback driver (e.g. BlackHole) to expose system audio at all.
1698
+ * - **Token auth.** Construct the transcriber with `token` — API-key auth is unsupported in browsers.
1699
+ * - **Stream ownership.** `stop()` tears down the AudioContext but does NOT stop the
1700
+ * `MediaStreamTrack`s passed in — callers own those.
1701
+ */
1702
+ class DualChannelCapture {
1703
+ constructor(params) {
1704
+ this.running = false;
1705
+ if (typeof globalThis.AudioContext === "undefined") {
1706
+ throw new BrowserOnlyError();
1707
+ }
1708
+ this.params = {
1709
+ micStream: params.micStream,
1710
+ systemStream: params.systemStream,
1711
+ transcriber: params.transcriber,
1712
+ targetSampleRate: params.targetSampleRate ?? DEFAULT_TARGET_RATE,
1713
+ };
1714
+ }
1715
+ on(event, listener) {
1716
+ if (event === "error")
1717
+ this.errorListener = listener;
1718
+ }
1719
+ /**
1720
+ * Wire the capture pipeline and start pumping tagged PCM into the transcriber.
1721
+ * The transcriber must already be connected. Returns once the worklet is
1722
+ * registered and the audio graph is live.
1723
+ */
1724
+ async start() {
1725
+ if (this.running) {
1726
+ throw new Error("DualChannelCapture already started");
1727
+ }
1728
+ this.context = new AudioContext();
1729
+ const blob = new Blob([pcm16EncoderWorkletSource], {
1730
+ type: "application/javascript",
1731
+ });
1732
+ const url = URL.createObjectURL(blob);
1733
+ try {
1734
+ await this.context.audioWorklet.addModule(url);
1735
+ }
1736
+ finally {
1737
+ URL.revokeObjectURL(url);
1738
+ }
1739
+ this.micSource = this.context.createMediaStreamSource(this.params.micStream);
1740
+ this.sysSource = this.context.createMediaStreamSource(this.params.systemStream);
1741
+ this.micEncoder = this.makeEncoder(MIC_CHANNEL);
1742
+ this.sysEncoder = this.makeEncoder(SYSTEM_CHANNEL);
1743
+ this.micSource.connect(this.micEncoder);
1744
+ this.sysSource.connect(this.sysEncoder);
1745
+ this.running = true;
1746
+ }
1747
+ makeEncoder(channel) {
1748
+ const node = new AudioWorkletNode(this.context, PCM16_ENCODER_PROCESSOR_NAME, {
1749
+ numberOfInputs: 1,
1750
+ numberOfOutputs: 0,
1751
+ channelCount: 1,
1752
+ channelCountMode: "explicit",
1753
+ channelInterpretation: "speakers",
1754
+ processorOptions: {
1755
+ targetRate: this.params.targetSampleRate,
1756
+ chunkMs: DEFAULT_CHUNK_MS,
1757
+ },
1758
+ });
1759
+ node.port.onmessage = (e) => {
1760
+ try {
1761
+ this.params.transcriber.sendAudio(e.data.pcm, { channel });
1762
+ }
1763
+ catch (err) {
1764
+ this.errorListener?.(err);
1765
+ }
1766
+ };
1767
+ return node;
1768
+ }
1769
+ /**
1770
+ * Tear down internal nodes and close the AudioContext. Does NOT stop the
1771
+ * caller-provided MediaStream tracks — they remain available for preview UI,
1772
+ * recording, etc. Idempotent.
1773
+ */
1774
+ async stop() {
1775
+ if (!this.running)
1776
+ return;
1777
+ this.running = false;
1778
+ try {
1779
+ this.micEncoder?.port.close();
1780
+ this.sysEncoder?.port.close();
1781
+ this.micEncoder?.disconnect();
1782
+ this.sysEncoder?.disconnect();
1783
+ this.micSource?.disconnect();
1784
+ this.sysSource?.disconnect();
1785
+ }
1786
+ catch {
1787
+ // Disconnecting already-disconnected nodes throws in some browsers; ignore.
1788
+ }
1789
+ if (this.context && this.context.state !== "closed") {
1790
+ await this.context.close();
1791
+ }
1792
+ this.context = undefined;
1793
+ this.micSource = undefined;
1794
+ this.sysSource = undefined;
1795
+ this.micEncoder = undefined;
1796
+ this.sysEncoder = undefined;
1797
+ }
1798
+ }
1799
+
1800
+ /**
1801
+ * Linear-interpolation resampler for streaming Float32 audio. Stateful across
1802
+ * `process()` calls so chunk boundaries don't introduce phase discontinuities:
1803
+ * the last input sample and a fractional read position are carried over.
1804
+ *
1805
+ * Linear interpolation is good enough for ASR ingest — the downstream
1806
+ * StreamingTranscriber band-limits at the target rate anyway, and a polyphase
1807
+ * filter would be overkill in the AudioWorklet hot path. If a customer needs
1808
+ * higher quality they can supply their own VadDetector + bypass the encoder.
1809
+ */
1810
+ class LinearResampler {
1811
+ constructor(sourceRate, targetRate) {
1812
+ this.sourceRate = sourceRate;
1813
+ this.targetRate = targetRate;
1814
+ this.lastSample = 0;
1815
+ this.fractional = 0;
1816
+ if (sourceRate <= 0 || targetRate <= 0) {
1817
+ throw new Error("sourceRate and targetRate must be positive");
1818
+ }
1819
+ this.ratio = sourceRate / targetRate;
1820
+ }
1821
+ process(input) {
1822
+ if (this.sourceRate === this.targetRate) {
1823
+ return input;
1824
+ }
1825
+ // Worst-case output length; we'll slice to actual.
1826
+ const out = new Float32Array(Math.ceil(input.length / this.ratio) + 1);
1827
+ let outIdx = 0;
1828
+ let pos = this.fractional;
1829
+ while (pos < input.length) {
1830
+ const i = Math.floor(pos);
1831
+ const frac = pos - i;
1832
+ const a = i === 0 ? this.lastSample : input[i - 1];
1833
+ const b = input[i];
1834
+ out[outIdx++] = a + (b - a) * frac;
1835
+ pos += this.ratio;
1836
+ }
1837
+ this.lastSample = input[input.length - 1] ?? this.lastSample;
1838
+ this.fractional = pos - input.length;
1839
+ return out.subarray(0, outIdx);
1840
+ }
1841
+ reset() {
1842
+ this.lastSample = 0;
1843
+ this.fractional = 0;
1844
+ }
1845
+ }
1846
+ /** Convert Float32 PCM (-1..1) to little-endian Int16 PCM. */
1847
+ function float32ToPcm16(input) {
1848
+ const out = new ArrayBuffer(input.length * 2);
1849
+ const view = new DataView(out);
1850
+ for (let i = 0; i < input.length; i++) {
1851
+ const clamped = Math.max(-1, Math.min(1, input[i]));
1852
+ view.setInt16(i * 2, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
1853
+ }
1854
+ return out;
1855
+ }
1856
+
1099
1857
  const defaultBaseUrl = "https://api.assemblyai.com";
1100
1858
  const defaultStreamingUrl = "https://streaming.assemblyai.com";
1101
1859
  class AssemblyAI {
@@ -1119,4 +1877,4 @@ class AssemblyAI {
1119
1877
  }
1120
1878
  }
1121
1879
 
1122
- export { AssemblyAI, FileService, LemurService, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService };
1880
+ export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService, VadTimeline, attributeTurn, attributeWord, float32ToPcm16, rollUpTurnChannel };