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