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.
- package/README.md +22 -0
- package/dist/assemblyai.streaming.umd.js +1291 -3
- package/dist/assemblyai.streaming.umd.min.js +1 -1
- package/dist/assemblyai.umd.js +802 -7
- package/dist/assemblyai.umd.min.js +1 -1
- package/dist/browser.mjs +775 -5
- package/dist/bun.mjs +775 -5
- package/dist/deno.mjs +775 -5
- package/dist/exports/streaming.d.ts +7 -0
- package/dist/index.cjs +802 -7
- package/dist/index.mjs +794 -8
- package/dist/node.cjs +783 -4
- package/dist/node.mjs +775 -5
- package/dist/services/index.d.ts +2 -2
- package/dist/services/streaming/browser/dual-channel-capture.d.ts +66 -0
- package/dist/services/streaming/browser/worklets/pcm16-encoder.d.ts +19 -0
- package/dist/services/streaming/energy-vad.d.ts +35 -0
- package/dist/services/streaming/index.d.ts +4 -0
- package/dist/services/streaming/label-mapper.d.ts +44 -0
- package/dist/services/streaming/resampler.d.ts +22 -0
- package/dist/services/streaming/service.d.ts +71 -2
- package/dist/streaming.browser.mjs +1247 -4
- package/dist/streaming.cjs +1287 -3
- package/dist/streaming.mjs +1276 -4
- package/dist/types/streaming/dual-channel.d.ts +48 -0
- package/dist/types/streaming/index.d.ts +140 -4
- package/dist/workerd.mjs +775 -5
- package/package.json +1 -1
- package/src/exports/streaming.ts +7 -0
- package/src/services/index.ts +20 -1
- package/src/services/streaming/browser/dual-channel-capture.ts +177 -0
- package/src/services/streaming/browser/worklets/pcm16-encoder.ts +70 -0
- package/src/services/streaming/energy-vad.ts +75 -0
- package/src/services/streaming/index.ts +4 -0
- package/src/services/streaming/label-mapper.ts +128 -0
- package/src/services/streaming/resampler.ts +69 -0
- package/src/services/streaming/service.ts +405 -3
- package/src/types/streaming/dual-channel.ts +57 -0
- package/src/types/streaming/index.ts +144 -1
package/dist/index.cjs
CHANGED
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
var ws = require('ws');
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Thrown when `DualChannelCapture` is constructed in a non-browser environment
|
|
7
|
+
* (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
|
|
8
|
+
* main entrypoint so the import path is uniform across runtimes; the runtime
|
|
9
|
+
* guard moves to construction time.
|
|
10
|
+
*/
|
|
11
|
+
class BrowserOnlyError extends Error {
|
|
12
|
+
constructor(message = "DualChannelCapture requires a browser environment (AudioContext is undefined).") {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "BrowserOnlyError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
5
18
|
/******************************************************************************
|
|
6
19
|
Copyright (c) Microsoft Corporation.
|
|
7
20
|
|
|
@@ -63,7 +76,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
|
63
76
|
defaultUserAgentString += navigator.userAgent;
|
|
64
77
|
}
|
|
65
78
|
const defaultUserAgent = {
|
|
66
|
-
sdk: { name: "JavaScript", version: "4.
|
|
79
|
+
sdk: { name: "JavaScript", version: "4.34.4" },
|
|
67
80
|
};
|
|
68
81
|
if (typeof process !== "undefined") {
|
|
69
82
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -875,11 +888,220 @@ function dataUrlToBlob(dataUrl) {
|
|
|
875
888
|
return new Blob([u8arr], { type: mime });
|
|
876
889
|
}
|
|
877
890
|
|
|
891
|
+
/**
|
|
892
|
+
* Energy-based VAD with adaptive noise-floor tracking and hangover. Pure JS,
|
|
893
|
+
* no dependencies. Suitable for the "which physical channel is speaking" task
|
|
894
|
+
* because the channels are already physically separated at capture — the harder
|
|
895
|
+
* problem (speech vs. non-speech in the wild) is one a customer can swap in a
|
|
896
|
+
* DNN VAD for via the `createVad` parameter.
|
|
897
|
+
*
|
|
898
|
+
* Tuning notes:
|
|
899
|
+
* - thresholdRatio below 2 will treat anything above noise as speech (too sensitive).
|
|
900
|
+
* - thresholdRatio above 6 will miss quiet utterance onsets/offsets.
|
|
901
|
+
* - noiseFloorAlpha above 0.1 makes the floor track quickly (good for non-stationary
|
|
902
|
+
* background) but risks slowly adapting *up* to a sustained low voice.
|
|
903
|
+
*/
|
|
904
|
+
class EnergyVad {
|
|
905
|
+
constructor(params = {}) {
|
|
906
|
+
var _a, _b, _c, _d;
|
|
907
|
+
this.hangoverRemaining = 0;
|
|
908
|
+
this.thresholdRatio = (_a = params.thresholdRatio) !== null && _a !== void 0 ? _a : 3.0;
|
|
909
|
+
this.noiseFloorAlpha = (_b = params.noiseFloorAlpha) !== null && _b !== void 0 ? _b : 0.05;
|
|
910
|
+
this.hangoverFrames = (_c = params.hangoverFrames) !== null && _c !== void 0 ? _c : 10;
|
|
911
|
+
this.initialNoiseFloor = (_d = params.initialNoiseFloor) !== null && _d !== void 0 ? _d : 1e-4;
|
|
912
|
+
this.noiseFloor = this.initialNoiseFloor;
|
|
913
|
+
}
|
|
914
|
+
process(frame) {
|
|
915
|
+
let sumSq = 0;
|
|
916
|
+
for (let i = 0; i < frame.length; i++) {
|
|
917
|
+
sumSq += frame[i] * frame[i];
|
|
918
|
+
}
|
|
919
|
+
const rms = frame.length > 0 ? Math.sqrt(sumSq / frame.length) : 0;
|
|
920
|
+
const threshold = this.noiseFloor * this.thresholdRatio;
|
|
921
|
+
let active = rms > threshold;
|
|
922
|
+
if (active) {
|
|
923
|
+
this.hangoverRemaining = this.hangoverFrames;
|
|
924
|
+
}
|
|
925
|
+
else if (this.hangoverRemaining > 0) {
|
|
926
|
+
this.hangoverRemaining--;
|
|
927
|
+
active = true;
|
|
928
|
+
// While in hangover, do not update noise floor — RMS may still reflect tail energy.
|
|
929
|
+
}
|
|
930
|
+
else {
|
|
931
|
+
this.noiseFloor =
|
|
932
|
+
this.noiseFloor * (1 - this.noiseFloorAlpha) +
|
|
933
|
+
rms * this.noiseFloorAlpha;
|
|
934
|
+
}
|
|
935
|
+
return { active, energy: rms };
|
|
936
|
+
}
|
|
937
|
+
reset() {
|
|
938
|
+
this.noiseFloor = this.initialNoiseFloor;
|
|
939
|
+
this.hangoverRemaining = 0;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* Append-only ring buffer of VAD frames in stream-relative ms order.
|
|
945
|
+
* `pushFrame` is O(1) amortized; `framesInWindow` is O(n) over kept frames,
|
|
946
|
+
* which is fine for the per-word lookups we do (a 30 s window at 50 frames/s
|
|
947
|
+
* per channel × 2 channels = 3000 entries, scanned once per word).
|
|
948
|
+
*
|
|
949
|
+
* Runtime-agnostic — no DOM or Web Audio dependencies.
|
|
950
|
+
*/
|
|
951
|
+
class VadTimeline {
|
|
952
|
+
constructor(windowMs) {
|
|
953
|
+
this.windowMs = windowMs;
|
|
954
|
+
this.frames = [];
|
|
955
|
+
this.head = 0;
|
|
956
|
+
}
|
|
957
|
+
pushFrame(frame) {
|
|
958
|
+
this.frames.push(frame);
|
|
959
|
+
const cutoff = frame.ts - this.windowMs;
|
|
960
|
+
while (this.head < this.frames.length &&
|
|
961
|
+
this.frames[this.head].ts < cutoff) {
|
|
962
|
+
this.head++;
|
|
963
|
+
}
|
|
964
|
+
if (this.head > 1024 && this.head * 2 > this.frames.length) {
|
|
965
|
+
this.frames = this.frames.slice(this.head);
|
|
966
|
+
this.head = 0;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
framesInWindow(startMs, endMs) {
|
|
970
|
+
const out = [];
|
|
971
|
+
for (let i = this.head; i < this.frames.length; i++) {
|
|
972
|
+
const f = this.frames[i];
|
|
973
|
+
if (f.ts < startMs)
|
|
974
|
+
continue;
|
|
975
|
+
if (f.ts > endMs)
|
|
976
|
+
break;
|
|
977
|
+
out.push(f);
|
|
978
|
+
}
|
|
979
|
+
return out;
|
|
980
|
+
}
|
|
981
|
+
clear() {
|
|
982
|
+
this.frames = [];
|
|
983
|
+
this.head = 0;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Sum per-channel active RMS over a window. Returns a Map from channel name
|
|
988
|
+
* to total score. Channels with zero score are omitted.
|
|
989
|
+
*/
|
|
990
|
+
function scoreChannels(frames) {
|
|
991
|
+
var _a;
|
|
992
|
+
const scores = new Map();
|
|
993
|
+
for (const f of frames) {
|
|
994
|
+
if (!f.active)
|
|
995
|
+
continue;
|
|
996
|
+
scores.set(f.channel, ((_a = scores.get(f.channel)) !== null && _a !== void 0 ? _a : 0) + f.rms);
|
|
997
|
+
}
|
|
998
|
+
return scores;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Decide which channel was dominant during a word's `[start, end]` window.
|
|
1002
|
+
*
|
|
1003
|
+
* - If no channel has any active VAD energy → `"unknown"`.
|
|
1004
|
+
* - If the top channel beats the runner-up by at least `dominanceRatio` → top channel.
|
|
1005
|
+
* - Else: top channel wins on absolute score; exact ties → `"unknown"`.
|
|
1006
|
+
*/
|
|
1007
|
+
function attributeWord(word, timeline, params) {
|
|
1008
|
+
const scores = scoreChannels(timeline.framesInWindow(word.start, word.end));
|
|
1009
|
+
if (scores.size === 0)
|
|
1010
|
+
return "unknown";
|
|
1011
|
+
const sorted = [...scores.entries()].sort((a, b) => b[1] - a[1]);
|
|
1012
|
+
if (sorted.length === 1)
|
|
1013
|
+
return sorted[0][0];
|
|
1014
|
+
const [topName, topScore] = sorted[0];
|
|
1015
|
+
const [runnerName, runnerScore] = sorted[1];
|
|
1016
|
+
if (topScore >= params.dominanceRatio * runnerScore)
|
|
1017
|
+
return topName;
|
|
1018
|
+
if (topScore > runnerScore)
|
|
1019
|
+
return topName;
|
|
1020
|
+
if (runnerScore > topScore)
|
|
1021
|
+
return runnerName;
|
|
1022
|
+
return "unknown";
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Duration-weighted majority of word channels. `"unknown"` if there are no
|
|
1026
|
+
* words, every word resolved to `"unknown"`, or two channels tie exactly.
|
|
1027
|
+
*/
|
|
1028
|
+
function rollUpTurnChannel(words) {
|
|
1029
|
+
var _a;
|
|
1030
|
+
const totals = new Map();
|
|
1031
|
+
for (const w of words) {
|
|
1032
|
+
if (!w.channel || w.channel === "unknown")
|
|
1033
|
+
continue;
|
|
1034
|
+
const dur = Math.max(0, w.end - w.start);
|
|
1035
|
+
totals.set(w.channel, ((_a = totals.get(w.channel)) !== null && _a !== void 0 ? _a : 0) + dur);
|
|
1036
|
+
}
|
|
1037
|
+
if (totals.size === 0)
|
|
1038
|
+
return "unknown";
|
|
1039
|
+
const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]);
|
|
1040
|
+
if (sorted.length === 1)
|
|
1041
|
+
return sorted[0][0];
|
|
1042
|
+
const [topName, topMs] = sorted[0];
|
|
1043
|
+
const [, runnerMs] = sorted[1];
|
|
1044
|
+
if (topMs === runnerMs)
|
|
1045
|
+
return "unknown";
|
|
1046
|
+
return topName;
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Mutate `turn` in place: write `turn.words[i].channel` for every word and set
|
|
1050
|
+
* `turn.channel` to the duration-weighted rollup.
|
|
1051
|
+
*
|
|
1052
|
+
* Returns `void` because the transcriber owns the `TurnEvent` ref and forwards
|
|
1053
|
+
* the same object to the customer listener — no need to allocate a copy.
|
|
1054
|
+
*/
|
|
1055
|
+
function attributeTurn(turn, timeline, params) {
|
|
1056
|
+
for (const w of turn.words) {
|
|
1057
|
+
w.channel = attributeWord(w, timeline, params);
|
|
1058
|
+
}
|
|
1059
|
+
turn.channel = rollUpTurnChannel(turn.words);
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* View any `AudioData` (ArrayBuffer / ArrayBufferView / typed array) as a
|
|
1064
|
+
* little-endian Int16 sample sequence without copying. Callers must guarantee
|
|
1065
|
+
* the underlying byte length is even.
|
|
1066
|
+
*/
|
|
1067
|
+
function toInt16View(audio) {
|
|
1068
|
+
// AudioData is ArrayBufferLike per the public type, but in practice callers
|
|
1069
|
+
// pass ArrayBuffer or a typed-array view. Handle both without copying.
|
|
1070
|
+
if (audio instanceof Int16Array)
|
|
1071
|
+
return audio;
|
|
1072
|
+
if (ArrayBuffer.isView(audio)) {
|
|
1073
|
+
const view = audio;
|
|
1074
|
+
return new Int16Array(view.buffer, view.byteOffset, Math.floor(view.byteLength / 2));
|
|
1075
|
+
}
|
|
1076
|
+
return new Int16Array(audio);
|
|
1077
|
+
}
|
|
878
1078
|
const defaultStreamingUrl$1 = "wss://streaming.assemblyai.com/v3/ws";
|
|
879
1079
|
const terminateSessionMessage = `{"type":"Terminate"}`;
|
|
1080
|
+
/**
|
|
1081
|
+
* Per-send chunk cap in milliseconds for the dual-channel mixer. The streaming
|
|
1082
|
+
* server rejects audio messages longer than 1000 ms (`Input Duration Error`).
|
|
1083
|
+
* If a backlog accumulates (e.g. when a browser tab is backgrounded and
|
|
1084
|
+
* `setInterval` is throttled to ~1 Hz), `flushMix` loops and emits multiple
|
|
1085
|
+
* sends each ≤ this cap until the buffers drain.
|
|
1086
|
+
*/
|
|
1087
|
+
const MAX_CHUNK_MS = 200;
|
|
1088
|
+
/**
|
|
1089
|
+
* Per-send minimum chunk size in milliseconds. The streaming server also
|
|
1090
|
+
* rejects audio messages shorter than 50 ms with the same
|
|
1091
|
+
* `Input Duration Error`, so the mixer waits until both per-channel buffers
|
|
1092
|
+
* have at least this much accumulated before emitting. Final-flush (close
|
|
1093
|
+
* path) bypasses this floor so the trailing partial buffer still gets sent.
|
|
1094
|
+
*/
|
|
1095
|
+
const MIN_CHUNK_MS = 50;
|
|
880
1096
|
class StreamingTranscriber {
|
|
881
1097
|
constructor(params) {
|
|
1098
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
882
1099
|
this.listeners = {};
|
|
1100
|
+
// Dual-channel mode state (allocated only when params.channels is set).
|
|
1101
|
+
this.isDualChannel = false;
|
|
1102
|
+
this.vadFrameSamples = 0;
|
|
1103
|
+
this.minChunkSamples = 0;
|
|
1104
|
+
this.maxChunkSamples = 0;
|
|
883
1105
|
this.params = Object.assign(Object.assign({}, params), { websocketBaseUrl: params.websocketBaseUrl || defaultStreamingUrl$1 });
|
|
884
1106
|
if ("token" in params && params.token)
|
|
885
1107
|
this.token = params.token;
|
|
@@ -888,6 +1110,42 @@ class StreamingTranscriber {
|
|
|
888
1110
|
if (!(this.token || this.apiKey)) {
|
|
889
1111
|
throw new Error("API key or temporary token is required.");
|
|
890
1112
|
}
|
|
1113
|
+
if (params.channels) {
|
|
1114
|
+
if (params.channels.length !== 2) {
|
|
1115
|
+
throw new Error("StreamingTranscriber.channels must have exactly 2 entries.");
|
|
1116
|
+
}
|
|
1117
|
+
const names = params.channels.map((c) => c.name);
|
|
1118
|
+
if (new Set(names).size !== names.length) {
|
|
1119
|
+
throw new Error("StreamingTranscriber.channels names must be unique.");
|
|
1120
|
+
}
|
|
1121
|
+
this.isDualChannel = true;
|
|
1122
|
+
this.channelNames = names;
|
|
1123
|
+
const att = (_a = params.channelAttribution) !== null && _a !== void 0 ? _a : {};
|
|
1124
|
+
this.attributionParams = {
|
|
1125
|
+
dominanceRatio: (_b = att.dominanceRatio) !== null && _b !== void 0 ? _b : 4,
|
|
1126
|
+
timelineWindowMs: (_c = att.timelineWindowMs) !== null && _c !== void 0 ? _c : 30000,
|
|
1127
|
+
createVad: (_d = att.createVad) !== null && _d !== void 0 ? _d : (() => new EnergyVad()),
|
|
1128
|
+
flushIntervalMs: (_e = att.flushIntervalMs) !== null && _e !== void 0 ? _e : 50,
|
|
1129
|
+
resolveUnknownChannelsMethod: (_f = att.resolveUnknownChannelsMethod) !== null && _f !== void 0 ? _f : "window",
|
|
1130
|
+
resolutionWindowWords: (_g = att.resolutionWindowWords) !== null && _g !== void 0 ? _g : 2,
|
|
1131
|
+
speakerHistoryMinRmsEvidence: (_h = att.speakerHistoryMinRmsEvidence) !== null && _h !== void 0 ? _h : 0.5,
|
|
1132
|
+
speakerHistoryDominanceRatio: (_j = att.speakerHistoryDominanceRatio) !== null && _j !== void 0 ? _j : 3,
|
|
1133
|
+
};
|
|
1134
|
+
if (this.attributionParams.resolveUnknownChannelsMethod ===
|
|
1135
|
+
"speaker-history") {
|
|
1136
|
+
this.speakerHistory = new Map();
|
|
1137
|
+
}
|
|
1138
|
+
// 20 ms VAD frames at the transcriber's target sample rate.
|
|
1139
|
+
this.vadFrameSamples = Math.max(1, Math.round(params.sampleRate * 0.02));
|
|
1140
|
+
this.minChunkSamples = Math.max(1, Math.round(params.sampleRate * (MIN_CHUNK_MS / 1000)));
|
|
1141
|
+
this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(params.sampleRate * (MAX_CHUNK_MS / 1000)));
|
|
1142
|
+
this.channelBuffers = new Map(names.map((n) => [n, []]));
|
|
1143
|
+
this.channelSamplesReceived = new Map(names.map((n) => [n, 0]));
|
|
1144
|
+
this.channelVadFloatBuffers = new Map(names.map((n) => [n, new Float32Array(this.vadFrameSamples)]));
|
|
1145
|
+
this.channelVadBufferIdx = new Map(names.map((n) => [n, 0]));
|
|
1146
|
+
this.channelVads = new Map(names.map((n) => [n, this.attributionParams.createVad(n)]));
|
|
1147
|
+
this.timeline = new VadTimeline(this.attributionParams.timelineWindowMs);
|
|
1148
|
+
}
|
|
891
1149
|
}
|
|
892
1150
|
connectionUrl() {
|
|
893
1151
|
var _a, _b;
|
|
@@ -937,13 +1195,18 @@ class StreamingTranscriber {
|
|
|
937
1195
|
if (this.params.prompt) {
|
|
938
1196
|
searchParams.set("prompt", this.params.prompt);
|
|
939
1197
|
}
|
|
1198
|
+
if (this.params.agentContext) {
|
|
1199
|
+
searchParams.set("agent_context", this.params.agentContext);
|
|
1200
|
+
}
|
|
940
1201
|
if (this.params.filterProfanity) {
|
|
941
1202
|
searchParams.set("filter_profanity", this.params.filterProfanity.toString());
|
|
942
1203
|
}
|
|
943
1204
|
if (this.params.speechModel === "u3-pro") {
|
|
944
1205
|
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.");
|
|
945
1206
|
}
|
|
946
|
-
|
|
1207
|
+
if (this.params.speechModel !== undefined) {
|
|
1208
|
+
searchParams.set("speech_model", this.params.speechModel.toString());
|
|
1209
|
+
}
|
|
947
1210
|
if (this.params.languageDetection !== undefined) {
|
|
948
1211
|
searchParams.set("language_detection", this.params.languageDetection.toString());
|
|
949
1212
|
}
|
|
@@ -1004,6 +1267,9 @@ class StreamingTranscriber {
|
|
|
1004
1267
|
if (this.params.redactPiiSub !== undefined) {
|
|
1005
1268
|
searchParams.set("redact_pii_sub", this.params.redactPiiSub);
|
|
1006
1269
|
}
|
|
1270
|
+
if (this.params.mode !== undefined) {
|
|
1271
|
+
searchParams.set("mode", this.params.mode);
|
|
1272
|
+
}
|
|
1007
1273
|
if (this.params.llmGateway !== undefined) {
|
|
1008
1274
|
searchParams.set("llm_gateway", JSON.stringify(this.params.llmGateway));
|
|
1009
1275
|
}
|
|
@@ -1037,6 +1303,13 @@ class StreamingTranscriber {
|
|
|
1037
1303
|
reason = StreamingErrorMessages[code];
|
|
1038
1304
|
}
|
|
1039
1305
|
}
|
|
1306
|
+
// Stop the flush timer when the socket is gone (server-initiated close,
|
|
1307
|
+
// network drop, etc.) — otherwise subsequent ticks call send() on a
|
|
1308
|
+
// closed socket and spam the error listener.
|
|
1309
|
+
if (this.flushTimer) {
|
|
1310
|
+
clearInterval(this.flushTimer);
|
|
1311
|
+
this.flushTimer = undefined;
|
|
1312
|
+
}
|
|
1040
1313
|
(_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
|
|
1041
1314
|
};
|
|
1042
1315
|
this.socket.onerror = (event) => {
|
|
@@ -1047,7 +1320,7 @@ class StreamingTranscriber {
|
|
|
1047
1320
|
(_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
|
|
1048
1321
|
};
|
|
1049
1322
|
this.socket.onmessage = ({ data }) => {
|
|
1050
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
1323
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
|
|
1051
1324
|
const message = JSON.parse(data.toString());
|
|
1052
1325
|
if ("error" in message) {
|
|
1053
1326
|
const err = new StreamingError(message.error);
|
|
@@ -1065,6 +1338,19 @@ class StreamingTranscriber {
|
|
|
1065
1338
|
break;
|
|
1066
1339
|
}
|
|
1067
1340
|
case "Turn": {
|
|
1341
|
+
if (this.isDualChannel && this.timeline && this.attributionParams) {
|
|
1342
|
+
attributeTurn(message, this.timeline, {
|
|
1343
|
+
dominanceRatio: this.attributionParams.dominanceRatio,
|
|
1344
|
+
});
|
|
1345
|
+
switch (this.attributionParams.resolveUnknownChannelsMethod) {
|
|
1346
|
+
case "window":
|
|
1347
|
+
this.resolveUnknownChannelsByWindow(message);
|
|
1348
|
+
break;
|
|
1349
|
+
case "speaker-history":
|
|
1350
|
+
this.resolveUnknownChannelsBySpeakerHistory(message);
|
|
1351
|
+
break;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1068
1354
|
(_f = (_e = this.listeners).turn) === null || _f === void 0 ? void 0 : _f.call(_e, message);
|
|
1069
1355
|
break;
|
|
1070
1356
|
}
|
|
@@ -1076,20 +1362,29 @@ class StreamingTranscriber {
|
|
|
1076
1362
|
(_k = (_j = this.listeners).llmGatewayResponse) === null || _k === void 0 ? void 0 : _k.call(_j, message);
|
|
1077
1363
|
break;
|
|
1078
1364
|
}
|
|
1365
|
+
case "SpeakerRevision": {
|
|
1366
|
+
(_m = (_l = this.listeners).speakerRevision) === null || _m === void 0 ? void 0 : _m.call(_l, message);
|
|
1367
|
+
break;
|
|
1368
|
+
}
|
|
1079
1369
|
case "Warning": {
|
|
1080
1370
|
const warning = message;
|
|
1081
1371
|
console.warn(`Streaming warning (code=${warning.warning_code}): ${warning.warning}`);
|
|
1082
|
-
(
|
|
1372
|
+
(_p = (_o = this.listeners).warning) === null || _p === void 0 ? void 0 : _p.call(_o, warning);
|
|
1083
1373
|
break;
|
|
1084
1374
|
}
|
|
1085
1375
|
case "Termination": {
|
|
1086
|
-
(
|
|
1376
|
+
(_q = this.sessionTerminatedResolve) === null || _q === void 0 ? void 0 : _q.call(this);
|
|
1087
1377
|
break;
|
|
1088
1378
|
}
|
|
1089
1379
|
}
|
|
1090
1380
|
};
|
|
1091
1381
|
});
|
|
1092
1382
|
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Returns a WritableStream that pumps PCM chunks into `sendAudio`. Single-channel
|
|
1385
|
+
* only — in dual-channel mode use `sendAudio(pcm, { channel })` directly, since
|
|
1386
|
+
* `WritableStream` has no place to carry a channel tag.
|
|
1387
|
+
*/
|
|
1093
1388
|
stream() {
|
|
1094
1389
|
return new WritableStream({
|
|
1095
1390
|
write: (chunk) => {
|
|
@@ -1097,8 +1392,239 @@ class StreamingTranscriber {
|
|
|
1097
1392
|
},
|
|
1098
1393
|
});
|
|
1099
1394
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1395
|
+
/**
|
|
1396
|
+
* Send PCM audio.
|
|
1397
|
+
*
|
|
1398
|
+
* In single-channel mode, `audio` is forwarded directly to the WebSocket and
|
|
1399
|
+
* `options` is ignored.
|
|
1400
|
+
*
|
|
1401
|
+
* In dual-channel mode (when `channels` is configured), `options.channel` is
|
|
1402
|
+
* REQUIRED and must match one of the declared channel names. Per-channel PCM is
|
|
1403
|
+
* fed into that channel's VAD, accumulated into a per-channel ring buffer, and
|
|
1404
|
+
* a scheduled flush (`channelAttribution.flushIntervalMs`, default 50ms) mixes
|
|
1405
|
+
* the buffers into mono before sending to the WebSocket.
|
|
1406
|
+
*/
|
|
1407
|
+
sendAudio(audio, options) {
|
|
1408
|
+
if (!this.isDualChannel) {
|
|
1409
|
+
this.send(audio);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (!(options === null || options === void 0 ? void 0 : options.channel)) {
|
|
1413
|
+
throw new Error("StreamingTranscriber is in dual-channel mode; sendAudio requires { channel }.");
|
|
1414
|
+
}
|
|
1415
|
+
if (!this.channelNames.includes(options.channel)) {
|
|
1416
|
+
throw new Error(`Unknown channel "${options.channel}"; declared channels: ${this.channelNames.join(", ")}.`);
|
|
1417
|
+
}
|
|
1418
|
+
this.ingestChannelAudio(options.channel, audio);
|
|
1419
|
+
}
|
|
1420
|
+
ingestChannelAudio(name, audio) {
|
|
1421
|
+
var _a, _b;
|
|
1422
|
+
const samples = toInt16View(audio);
|
|
1423
|
+
const buf = this.channelBuffers.get(name);
|
|
1424
|
+
const vadBuf = this.channelVadFloatBuffers.get(name);
|
|
1425
|
+
let vadIdx = this.channelVadBufferIdx.get(name);
|
|
1426
|
+
let received = this.channelSamplesReceived.get(name);
|
|
1427
|
+
const vad = this.channelVads.get(name);
|
|
1428
|
+
const sampleRate = this.params.sampleRate;
|
|
1429
|
+
const frameSize = this.vadFrameSamples;
|
|
1430
|
+
for (let i = 0; i < samples.length; i++) {
|
|
1431
|
+
const s = samples[i];
|
|
1432
|
+
buf.push(s);
|
|
1433
|
+
vadBuf[vadIdx++] = s / 0x8000;
|
|
1434
|
+
received++;
|
|
1435
|
+
if (vadIdx === frameSize) {
|
|
1436
|
+
const result = vad.process(vadBuf);
|
|
1437
|
+
const frame = {
|
|
1438
|
+
ts: (received / sampleRate) * 1000,
|
|
1439
|
+
channel: name,
|
|
1440
|
+
active: result.active,
|
|
1441
|
+
rms: result.energy,
|
|
1442
|
+
};
|
|
1443
|
+
this.timeline.pushFrame(frame);
|
|
1444
|
+
(_b = (_a = this.listeners).vad) === null || _b === void 0 ? void 0 : _b.call(_a, frame);
|
|
1445
|
+
vadIdx = 0;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
this.channelVadBufferIdx.set(name, vadIdx);
|
|
1449
|
+
this.channelSamplesReceived.set(name, received);
|
|
1450
|
+
if (!this.flushTimer)
|
|
1451
|
+
this.startFlushTimer();
|
|
1452
|
+
}
|
|
1453
|
+
startFlushTimer() {
|
|
1454
|
+
this.flushTimer = setInterval(() => this.flushMix(), this.attributionParams.flushIntervalMs);
|
|
1455
|
+
}
|
|
1456
|
+
flushMix(force = false) {
|
|
1457
|
+
var _a, _b;
|
|
1458
|
+
if (!this.channelNames || !this.channelBuffers)
|
|
1459
|
+
return;
|
|
1460
|
+
const bufs = this.channelNames.map((n) => this.channelBuffers.get(n));
|
|
1461
|
+
const divisor = bufs.length;
|
|
1462
|
+
// Loop so a backlog (e.g. accumulated while a browser tab was throttled in
|
|
1463
|
+
// the background) drains as multiple sends, each capped at MAX_CHUNK_MS.
|
|
1464
|
+
// Without the cap a single message could exceed the server's 1000 ms input
|
|
1465
|
+
// duration limit and be rejected with code 3007.
|
|
1466
|
+
for (;;) {
|
|
1467
|
+
let mixLen = Infinity;
|
|
1468
|
+
for (const b of bufs)
|
|
1469
|
+
if (b.length < mixLen)
|
|
1470
|
+
mixLen = b.length;
|
|
1471
|
+
if (!Number.isFinite(mixLen) || mixLen === 0)
|
|
1472
|
+
return;
|
|
1473
|
+
// The streaming server rejects audio messages shorter than 50 ms with
|
|
1474
|
+
// `Input Duration Error`. Wait until both per-channel buffers have at
|
|
1475
|
+
// least minChunkSamples worth queued before emitting. The `force` path
|
|
1476
|
+
// (final flush on close) bypasses this so the trailing partial buffer
|
|
1477
|
+
// still gets through.
|
|
1478
|
+
if (!force && mixLen < this.minChunkSamples)
|
|
1479
|
+
return;
|
|
1480
|
+
if (mixLen > this.maxChunkSamples)
|
|
1481
|
+
mixLen = this.maxChunkSamples;
|
|
1482
|
+
const out = new Int16Array(mixLen);
|
|
1483
|
+
for (let i = 0; i < mixLen; i++) {
|
|
1484
|
+
let sum = 0;
|
|
1485
|
+
for (let c = 0; c < divisor; c++)
|
|
1486
|
+
sum += bufs[c][i];
|
|
1487
|
+
const avg = Math.round(sum / divisor);
|
|
1488
|
+
out[i] = avg < -32768 ? -32768 : avg > 32767 ? 32767 : avg;
|
|
1489
|
+
}
|
|
1490
|
+
for (const b of bufs)
|
|
1491
|
+
b.splice(0, mixLen);
|
|
1492
|
+
try {
|
|
1493
|
+
this.send(out.buffer);
|
|
1494
|
+
}
|
|
1495
|
+
catch (err) {
|
|
1496
|
+
(_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
|
|
1497
|
+
return;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Fill in words whose per-word VAD attribution was `"unknown"` by looking
|
|
1503
|
+
* at the dominant non-`"unknown"` channel among ±N neighbors in the same
|
|
1504
|
+
* turn. Words with no non-`"unknown"` neighbors stay `"unknown"`. Confident
|
|
1505
|
+
* per-word VAD decisions are never modified.
|
|
1506
|
+
*
|
|
1507
|
+
* Local temporal heuristic — ignores `speaker_label`, so it works even when
|
|
1508
|
+
* AAI's diarization re-uses the same label for two physically distinct
|
|
1509
|
+
* voices. Each resolved word gets `channelResolved: true` so downstream
|
|
1510
|
+
* renderers can distinguish inferred channels from directly-measured ones.
|
|
1511
|
+
*/
|
|
1512
|
+
resolveUnknownChannelsByWindow(turn) {
|
|
1513
|
+
var _a;
|
|
1514
|
+
if (!this.attributionParams)
|
|
1515
|
+
return;
|
|
1516
|
+
const window = this.attributionParams.resolutionWindowWords;
|
|
1517
|
+
const words = turn.words;
|
|
1518
|
+
let mutated = false;
|
|
1519
|
+
for (let i = 0; i < words.length; i++) {
|
|
1520
|
+
if (words[i].channel !== "unknown")
|
|
1521
|
+
continue;
|
|
1522
|
+
const tally = new Map();
|
|
1523
|
+
const lo = Math.max(0, i - window);
|
|
1524
|
+
const hi = Math.min(words.length - 1, i + window);
|
|
1525
|
+
for (let j = lo; j <= hi; j++) {
|
|
1526
|
+
if (j === i)
|
|
1527
|
+
continue;
|
|
1528
|
+
const ch = words[j].channel;
|
|
1529
|
+
if (!ch || ch === "unknown")
|
|
1530
|
+
continue;
|
|
1531
|
+
tally.set(ch, ((_a = tally.get(ch)) !== null && _a !== void 0 ? _a : 0) + 1);
|
|
1532
|
+
}
|
|
1533
|
+
if (tally.size === 0)
|
|
1534
|
+
continue;
|
|
1535
|
+
// Pick the dominant neighbor channel. Ties → leave `"unknown"` (rare;
|
|
1536
|
+
// would require an equal count of mic and system neighbors).
|
|
1537
|
+
let top;
|
|
1538
|
+
let topCount = 0;
|
|
1539
|
+
let tied = false;
|
|
1540
|
+
for (const [name, count] of tally) {
|
|
1541
|
+
if (count > topCount) {
|
|
1542
|
+
top = name;
|
|
1543
|
+
topCount = count;
|
|
1544
|
+
tied = false;
|
|
1545
|
+
}
|
|
1546
|
+
else if (count === topCount) {
|
|
1547
|
+
tied = true;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
if (top && !tied) {
|
|
1551
|
+
words[i].channel = top;
|
|
1552
|
+
words[i].channelResolved = true;
|
|
1553
|
+
mutated = true;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
// Recompute the rollup only if any per-word channel changed.
|
|
1557
|
+
if (mutated)
|
|
1558
|
+
turn.channel = rollUpTurnChannel(words);
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* Fill `"unknown"` words by looking up the speaker's session-wide channel
|
|
1562
|
+
* evidence. For each `speaker_label`, sums active VAD frame RMS per channel
|
|
1563
|
+
* across every word the speaker has uttered to date. A speaker is
|
|
1564
|
+
* "resolvable" if their total evidence clears
|
|
1565
|
+
* `speakerHistoryMinRmsEvidence` and their top channel exceeds the
|
|
1566
|
+
* runner-up by `speakerHistoryDominanceRatio`.
|
|
1567
|
+
*
|
|
1568
|
+
* Only touches `"unknown"` words. Confident per-word VAD decisions are
|
|
1569
|
+
* never modified. `speaker_label` is never modified.
|
|
1570
|
+
*/
|
|
1571
|
+
resolveUnknownChannelsBySpeakerHistory(turn) {
|
|
1572
|
+
var _a;
|
|
1573
|
+
if (!this.timeline || !this.attributionParams || !this.speakerHistory)
|
|
1574
|
+
return;
|
|
1575
|
+
const minEvidence = this.attributionParams.speakerHistoryMinRmsEvidence;
|
|
1576
|
+
const dominanceRatio = this.attributionParams.speakerHistoryDominanceRatio;
|
|
1577
|
+
// 1. Accumulate evidence from this turn's words.
|
|
1578
|
+
for (const w of turn.words) {
|
|
1579
|
+
if (!w.speaker)
|
|
1580
|
+
continue;
|
|
1581
|
+
const frames = this.timeline.framesInWindow(w.start, w.end);
|
|
1582
|
+
let entry = this.speakerHistory.get(w.speaker);
|
|
1583
|
+
if (!entry) {
|
|
1584
|
+
entry = new Map();
|
|
1585
|
+
this.speakerHistory.set(w.speaker, entry);
|
|
1586
|
+
}
|
|
1587
|
+
for (const f of frames) {
|
|
1588
|
+
if (!f.active)
|
|
1589
|
+
continue;
|
|
1590
|
+
entry.set(f.channel, ((_a = entry.get(f.channel)) !== null && _a !== void 0 ? _a : 0) + f.rms);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
// 2. Fill unknown words whose speakers have dominant evidence.
|
|
1594
|
+
let mutated = false;
|
|
1595
|
+
for (const w of turn.words) {
|
|
1596
|
+
if (w.channel !== "unknown" || !w.speaker)
|
|
1597
|
+
continue;
|
|
1598
|
+
const entry = this.speakerHistory.get(w.speaker);
|
|
1599
|
+
if (!entry || entry.size === 0)
|
|
1600
|
+
continue;
|
|
1601
|
+
let total = 0;
|
|
1602
|
+
let topName;
|
|
1603
|
+
let topScore = 0;
|
|
1604
|
+
let runnerScore = 0;
|
|
1605
|
+
for (const [name, score] of entry) {
|
|
1606
|
+
total += score;
|
|
1607
|
+
if (score > topScore) {
|
|
1608
|
+
runnerScore = topScore;
|
|
1609
|
+
topScore = score;
|
|
1610
|
+
topName = name;
|
|
1611
|
+
}
|
|
1612
|
+
else if (score > runnerScore) {
|
|
1613
|
+
runnerScore = score;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
if (total < minEvidence)
|
|
1617
|
+
continue;
|
|
1618
|
+
if (runnerScore > 0 && topScore < dominanceRatio * runnerScore)
|
|
1619
|
+
continue;
|
|
1620
|
+
if (topName) {
|
|
1621
|
+
w.channel = topName;
|
|
1622
|
+
w.channelResolved = true;
|
|
1623
|
+
mutated = true;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (mutated)
|
|
1627
|
+
turn.channel = rollUpTurnChannel(turn.words);
|
|
1102
1628
|
}
|
|
1103
1629
|
/**
|
|
1104
1630
|
* Update the streaming configuration mid-stream.
|
|
@@ -1136,6 +1662,15 @@ class StreamingTranscriber {
|
|
|
1136
1662
|
close() {
|
|
1137
1663
|
return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
|
|
1138
1664
|
var _a;
|
|
1665
|
+
if (this.flushTimer) {
|
|
1666
|
+
clearInterval(this.flushTimer);
|
|
1667
|
+
this.flushTimer = undefined;
|
|
1668
|
+
// Best-effort: drain any final partial mix so the server gets the tail.
|
|
1669
|
+
// Bypass the 50ms floor here since this is the last flush; if the tail
|
|
1670
|
+
// is <50ms the server will reject that single message, but we'd lose
|
|
1671
|
+
// the audio either way.
|
|
1672
|
+
this.flushMix(true);
|
|
1673
|
+
}
|
|
1139
1674
|
if (this.socket) {
|
|
1140
1675
|
if (this.socket.readyState === this.socket.OPEN) {
|
|
1141
1676
|
if (waitForSessionTermination) {
|
|
@@ -1190,6 +1725,257 @@ class StreamingTranscriberFactory extends BaseService {
|
|
|
1190
1725
|
}
|
|
1191
1726
|
}
|
|
1192
1727
|
|
|
1728
|
+
/**
|
|
1729
|
+
* AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
|
|
1730
|
+
* native sample rate, resamples to `targetRate` (linear interpolation, stateful
|
|
1731
|
+
* across `process()` calls), packs to little-endian Int16 PCM, and posts
|
|
1732
|
+
* fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
|
|
1733
|
+
*
|
|
1734
|
+
* `samplesSent` is in **target-rate samples**, so the main thread can derive a
|
|
1735
|
+
* stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
|
|
1736
|
+
* frame AAI uses for `StreamingWord.start` / `.end`.
|
|
1737
|
+
*
|
|
1738
|
+
* Defined as a string so it can be registered via a Blob URL — the SDK ships as
|
|
1739
|
+
* a single ESM file, so a separate `.js` worklet asset isn't viable.
|
|
1740
|
+
*/
|
|
1741
|
+
const pcm16EncoderWorkletSource = `
|
|
1742
|
+
class Pcm16EncoderProcessor extends AudioWorkletProcessor {
|
|
1743
|
+
constructor(options) {
|
|
1744
|
+
super();
|
|
1745
|
+
const opts = (options && options.processorOptions) || {};
|
|
1746
|
+
this.targetRate = opts.targetRate || 16000;
|
|
1747
|
+
this.chunkMs = opts.chunkMs || 50;
|
|
1748
|
+
this.ratio = sampleRate / this.targetRate;
|
|
1749
|
+
this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);
|
|
1750
|
+
this.buffer = new Int16Array(this.chunkSize);
|
|
1751
|
+
this.bufferIdx = 0;
|
|
1752
|
+
this.samplesSent = 0;
|
|
1753
|
+
this.lastSample = 0;
|
|
1754
|
+
this.fractional = 0;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
process(inputs) {
|
|
1758
|
+
const input = inputs[0];
|
|
1759
|
+
if (!input || input.length === 0 || !input[0] || input[0].length === 0) {
|
|
1760
|
+
return true;
|
|
1761
|
+
}
|
|
1762
|
+
const mono = input[0];
|
|
1763
|
+
let pos = this.fractional;
|
|
1764
|
+
while (pos < mono.length) {
|
|
1765
|
+
const i = Math.floor(pos);
|
|
1766
|
+
const frac = pos - i;
|
|
1767
|
+
const a = i === 0 ? this.lastSample : mono[i - 1];
|
|
1768
|
+
const b = mono[i];
|
|
1769
|
+
const sample = a + (b - a) * frac;
|
|
1770
|
+
const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
|
|
1771
|
+
this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
|
|
1772
|
+
if (this.bufferIdx === this.chunkSize) {
|
|
1773
|
+
const out = new Int16Array(this.chunkSize);
|
|
1774
|
+
out.set(this.buffer);
|
|
1775
|
+
this.samplesSent += this.chunkSize;
|
|
1776
|
+
this.port.postMessage(
|
|
1777
|
+
{ pcm: out.buffer, samplesSent: this.samplesSent },
|
|
1778
|
+
[out.buffer],
|
|
1779
|
+
);
|
|
1780
|
+
this.bufferIdx = 0;
|
|
1781
|
+
}
|
|
1782
|
+
pos += this.ratio;
|
|
1783
|
+
}
|
|
1784
|
+
this.lastSample = mono[mono.length - 1];
|
|
1785
|
+
this.fractional = pos - mono.length;
|
|
1786
|
+
return true;
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
registerProcessor("aai-pcm16-encoder", Pcm16EncoderProcessor);
|
|
1790
|
+
`;
|
|
1791
|
+
const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
|
|
1792
|
+
|
|
1793
|
+
const DEFAULT_TARGET_RATE = 16000;
|
|
1794
|
+
const DEFAULT_CHUNK_MS = 50;
|
|
1795
|
+
const MIC_CHANNEL = "mic";
|
|
1796
|
+
const SYSTEM_CHANNEL = "system";
|
|
1797
|
+
/**
|
|
1798
|
+
* Browser-only adapter that pumps two `MediaStream`s into a `StreamingTranscriber`
|
|
1799
|
+
* configured for dual-channel mode. Each `MediaStream` runs through its own
|
|
1800
|
+
* `pcm16-encoder` AudioWorklet (resample to `targetSampleRate`, encode to Int16
|
|
1801
|
+
* PCM); each PCM chunk is forwarded via `transcriber.sendAudio(pcm, { channel })`.
|
|
1802
|
+
*
|
|
1803
|
+
* All dual-channel orchestration (mixing, VAD, per-word attribution) lives inside
|
|
1804
|
+
* `StreamingTranscriber` — this class is a pure I/O adapter. Non-browser runtimes
|
|
1805
|
+
* can replicate its job by pushing tagged PCM into `transcriber.sendAudio` directly.
|
|
1806
|
+
*
|
|
1807
|
+
* Caller responsibilities:
|
|
1808
|
+
* - **Echo cancellation** is set at `getUserMedia` time (`audio: { echoCancellation: true }`).
|
|
1809
|
+
* - **System-audio capture** is platform-dependent. Chrome's `getDisplayMedia({ audio: true })`
|
|
1810
|
+
* captures tab audio (and on Windows, full system audio when sharing the whole screen).
|
|
1811
|
+
* macOS requires a virtual loopback driver (e.g. BlackHole) to expose system audio at all.
|
|
1812
|
+
* - **Token auth.** Construct the transcriber with `token` — API-key auth is unsupported in browsers.
|
|
1813
|
+
* - **Stream ownership.** `stop()` tears down the AudioContext but does NOT stop the
|
|
1814
|
+
* `MediaStreamTrack`s passed in — callers own those.
|
|
1815
|
+
*/
|
|
1816
|
+
class DualChannelCapture {
|
|
1817
|
+
constructor(params) {
|
|
1818
|
+
var _a;
|
|
1819
|
+
this.running = false;
|
|
1820
|
+
if (typeof globalThis.AudioContext === "undefined") {
|
|
1821
|
+
throw new BrowserOnlyError();
|
|
1822
|
+
}
|
|
1823
|
+
this.params = {
|
|
1824
|
+
micStream: params.micStream,
|
|
1825
|
+
systemStream: params.systemStream,
|
|
1826
|
+
transcriber: params.transcriber,
|
|
1827
|
+
targetSampleRate: (_a = params.targetSampleRate) !== null && _a !== void 0 ? _a : DEFAULT_TARGET_RATE,
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
on(event, listener) {
|
|
1831
|
+
if (event === "error")
|
|
1832
|
+
this.errorListener = listener;
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Wire the capture pipeline and start pumping tagged PCM into the transcriber.
|
|
1836
|
+
* The transcriber must already be connected. Returns once the worklet is
|
|
1837
|
+
* registered and the audio graph is live.
|
|
1838
|
+
*/
|
|
1839
|
+
start() {
|
|
1840
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1841
|
+
if (this.running) {
|
|
1842
|
+
throw new Error("DualChannelCapture already started");
|
|
1843
|
+
}
|
|
1844
|
+
this.context = new AudioContext();
|
|
1845
|
+
const blob = new Blob([pcm16EncoderWorkletSource], {
|
|
1846
|
+
type: "application/javascript",
|
|
1847
|
+
});
|
|
1848
|
+
const url = URL.createObjectURL(blob);
|
|
1849
|
+
try {
|
|
1850
|
+
yield this.context.audioWorklet.addModule(url);
|
|
1851
|
+
}
|
|
1852
|
+
finally {
|
|
1853
|
+
URL.revokeObjectURL(url);
|
|
1854
|
+
}
|
|
1855
|
+
this.micSource = this.context.createMediaStreamSource(this.params.micStream);
|
|
1856
|
+
this.sysSource = this.context.createMediaStreamSource(this.params.systemStream);
|
|
1857
|
+
this.micEncoder = this.makeEncoder(MIC_CHANNEL);
|
|
1858
|
+
this.sysEncoder = this.makeEncoder(SYSTEM_CHANNEL);
|
|
1859
|
+
this.micSource.connect(this.micEncoder);
|
|
1860
|
+
this.sysSource.connect(this.sysEncoder);
|
|
1861
|
+
this.running = true;
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
1864
|
+
makeEncoder(channel) {
|
|
1865
|
+
const node = new AudioWorkletNode(this.context, PCM16_ENCODER_PROCESSOR_NAME, {
|
|
1866
|
+
numberOfInputs: 1,
|
|
1867
|
+
numberOfOutputs: 0,
|
|
1868
|
+
channelCount: 1,
|
|
1869
|
+
channelCountMode: "explicit",
|
|
1870
|
+
channelInterpretation: "speakers",
|
|
1871
|
+
processorOptions: {
|
|
1872
|
+
targetRate: this.params.targetSampleRate,
|
|
1873
|
+
chunkMs: DEFAULT_CHUNK_MS,
|
|
1874
|
+
},
|
|
1875
|
+
});
|
|
1876
|
+
node.port.onmessage = (e) => {
|
|
1877
|
+
var _a;
|
|
1878
|
+
try {
|
|
1879
|
+
this.params.transcriber.sendAudio(e.data.pcm, { channel });
|
|
1880
|
+
}
|
|
1881
|
+
catch (err) {
|
|
1882
|
+
(_a = this.errorListener) === null || _a === void 0 ? void 0 : _a.call(this, err);
|
|
1883
|
+
}
|
|
1884
|
+
};
|
|
1885
|
+
return node;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Tear down internal nodes and close the AudioContext. Does NOT stop the
|
|
1889
|
+
* caller-provided MediaStream tracks — they remain available for preview UI,
|
|
1890
|
+
* recording, etc. Idempotent.
|
|
1891
|
+
*/
|
|
1892
|
+
stop() {
|
|
1893
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1894
|
+
var _a, _b, _c, _d, _e, _f;
|
|
1895
|
+
if (!this.running)
|
|
1896
|
+
return;
|
|
1897
|
+
this.running = false;
|
|
1898
|
+
try {
|
|
1899
|
+
(_a = this.micEncoder) === null || _a === void 0 ? void 0 : _a.port.close();
|
|
1900
|
+
(_b = this.sysEncoder) === null || _b === void 0 ? void 0 : _b.port.close();
|
|
1901
|
+
(_c = this.micEncoder) === null || _c === void 0 ? void 0 : _c.disconnect();
|
|
1902
|
+
(_d = this.sysEncoder) === null || _d === void 0 ? void 0 : _d.disconnect();
|
|
1903
|
+
(_e = this.micSource) === null || _e === void 0 ? void 0 : _e.disconnect();
|
|
1904
|
+
(_f = this.sysSource) === null || _f === void 0 ? void 0 : _f.disconnect();
|
|
1905
|
+
}
|
|
1906
|
+
catch (_g) {
|
|
1907
|
+
// Disconnecting already-disconnected nodes throws in some browsers; ignore.
|
|
1908
|
+
}
|
|
1909
|
+
if (this.context && this.context.state !== "closed") {
|
|
1910
|
+
yield this.context.close();
|
|
1911
|
+
}
|
|
1912
|
+
this.context = undefined;
|
|
1913
|
+
this.micSource = undefined;
|
|
1914
|
+
this.sysSource = undefined;
|
|
1915
|
+
this.micEncoder = undefined;
|
|
1916
|
+
this.sysEncoder = undefined;
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/**
|
|
1922
|
+
* Linear-interpolation resampler for streaming Float32 audio. Stateful across
|
|
1923
|
+
* `process()` calls so chunk boundaries don't introduce phase discontinuities:
|
|
1924
|
+
* the last input sample and a fractional read position are carried over.
|
|
1925
|
+
*
|
|
1926
|
+
* Linear interpolation is good enough for ASR ingest — the downstream
|
|
1927
|
+
* StreamingTranscriber band-limits at the target rate anyway, and a polyphase
|
|
1928
|
+
* filter would be overkill in the AudioWorklet hot path. If a customer needs
|
|
1929
|
+
* higher quality they can supply their own VadDetector + bypass the encoder.
|
|
1930
|
+
*/
|
|
1931
|
+
class LinearResampler {
|
|
1932
|
+
constructor(sourceRate, targetRate) {
|
|
1933
|
+
this.sourceRate = sourceRate;
|
|
1934
|
+
this.targetRate = targetRate;
|
|
1935
|
+
this.lastSample = 0;
|
|
1936
|
+
this.fractional = 0;
|
|
1937
|
+
if (sourceRate <= 0 || targetRate <= 0) {
|
|
1938
|
+
throw new Error("sourceRate and targetRate must be positive");
|
|
1939
|
+
}
|
|
1940
|
+
this.ratio = sourceRate / targetRate;
|
|
1941
|
+
}
|
|
1942
|
+
process(input) {
|
|
1943
|
+
var _a;
|
|
1944
|
+
if (this.sourceRate === this.targetRate) {
|
|
1945
|
+
return input;
|
|
1946
|
+
}
|
|
1947
|
+
// Worst-case output length; we'll slice to actual.
|
|
1948
|
+
const out = new Float32Array(Math.ceil(input.length / this.ratio) + 1);
|
|
1949
|
+
let outIdx = 0;
|
|
1950
|
+
let pos = this.fractional;
|
|
1951
|
+
while (pos < input.length) {
|
|
1952
|
+
const i = Math.floor(pos);
|
|
1953
|
+
const frac = pos - i;
|
|
1954
|
+
const a = i === 0 ? this.lastSample : input[i - 1];
|
|
1955
|
+
const b = input[i];
|
|
1956
|
+
out[outIdx++] = a + (b - a) * frac;
|
|
1957
|
+
pos += this.ratio;
|
|
1958
|
+
}
|
|
1959
|
+
this.lastSample = (_a = input[input.length - 1]) !== null && _a !== void 0 ? _a : this.lastSample;
|
|
1960
|
+
this.fractional = pos - input.length;
|
|
1961
|
+
return out.subarray(0, outIdx);
|
|
1962
|
+
}
|
|
1963
|
+
reset() {
|
|
1964
|
+
this.lastSample = 0;
|
|
1965
|
+
this.fractional = 0;
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
/** Convert Float32 PCM (-1..1) to little-endian Int16 PCM. */
|
|
1969
|
+
function float32ToPcm16(input) {
|
|
1970
|
+
const out = new ArrayBuffer(input.length * 2);
|
|
1971
|
+
const view = new DataView(out);
|
|
1972
|
+
for (let i = 0; i < input.length; i++) {
|
|
1973
|
+
const clamped = Math.max(-1, Math.min(1, input[i]));
|
|
1974
|
+
view.setInt16(i * 2, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
|
|
1975
|
+
}
|
|
1976
|
+
return out;
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1193
1979
|
const defaultBaseUrl = "https://api.assemblyai.com";
|
|
1194
1980
|
const defaultStreamingUrl = "https://streaming.assemblyai.com";
|
|
1195
1981
|
class AssemblyAI {
|
|
@@ -1211,11 +1997,20 @@ class AssemblyAI {
|
|
|
1211
1997
|
}
|
|
1212
1998
|
|
|
1213
1999
|
exports.AssemblyAI = AssemblyAI;
|
|
2000
|
+
exports.BrowserOnlyError = BrowserOnlyError;
|
|
2001
|
+
exports.DualChannelCapture = DualChannelCapture;
|
|
2002
|
+
exports.EnergyVad = EnergyVad;
|
|
1214
2003
|
exports.FileService = FileService;
|
|
1215
2004
|
exports.LemurService = LemurService;
|
|
2005
|
+
exports.LinearResampler = LinearResampler;
|
|
1216
2006
|
exports.RealtimeService = RealtimeService;
|
|
1217
2007
|
exports.RealtimeServiceFactory = RealtimeServiceFactory;
|
|
1218
2008
|
exports.RealtimeTranscriber = RealtimeTranscriber;
|
|
1219
2009
|
exports.RealtimeTranscriberFactory = RealtimeTranscriberFactory;
|
|
1220
2010
|
exports.StreamingTranscriber = StreamingTranscriber;
|
|
1221
2011
|
exports.TranscriptService = TranscriptService;
|
|
2012
|
+
exports.VadTimeline = VadTimeline;
|
|
2013
|
+
exports.attributeTurn = attributeTurn;
|
|
2014
|
+
exports.attributeWord = attributeWord;
|
|
2015
|
+
exports.float32ToPcm16 = float32ToPcm16;
|
|
2016
|
+
exports.rollUpTurnChannel = rollUpTurnChannel;
|