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