assemblyai 4.33.3 → 4.34.4

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