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