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