@absolutejs/voice 0.0.22-beta.319 → 0.0.22-beta.320

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.
@@ -5023,6 +5023,412 @@ var serverMessageToAction = (message) => {
5023
5023
  }
5024
5024
  };
5025
5025
 
5026
+ // node_modules/@absolutejs/media/dist/index.js
5027
+ var formatLabel = (format) => `${format.container}/${format.encoding}/${String(format.sampleRateHz)}hz/${String(format.channels)}ch`;
5028
+ var formatMatches = (actual, expected) => actual.container === expected.container && actual.encoding === expected.encoding && actual.sampleRateHz === expected.sampleRateHz && actual.channels === expected.channels;
5029
+ var pushIssue = (issues, severity, code, message) => {
5030
+ issues.push({ code, message, severity });
5031
+ };
5032
+ var numericMetadata = (frame, key) => {
5033
+ const value = frame.metadata?.[key];
5034
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
5035
+ };
5036
+ var average = (values) => values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length;
5037
+ var max = (values) => values.length === 0 ? undefined : Math.max(...values);
5038
+ var min = (values) => values.length === 0 ? undefined : Math.min(...values);
5039
+ var numericStat = (stat, key) => {
5040
+ const value = stat[key];
5041
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
5042
+ };
5043
+ var booleanStat = (stat, key) => {
5044
+ const value = stat[key];
5045
+ return typeof value === "boolean" ? value : undefined;
5046
+ };
5047
+ var stringStat = (stat, key) => {
5048
+ const value = stat[key];
5049
+ return typeof value === "string" ? value : undefined;
5050
+ };
5051
+ var secondsToMs = (value) => value === undefined ? undefined : value * 1000;
5052
+ var normalizeWebRTCStat = (stat) => {
5053
+ const sample = {};
5054
+ for (const [key, value] of Object.entries(stat)) {
5055
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
5056
+ sample[key] = value;
5057
+ }
5058
+ }
5059
+ return sample;
5060
+ };
5061
+ var buildMediaResamplingPlan = (input) => {
5062
+ const required = !formatMatches(input.inputFormat, input.outputFormat);
5063
+ return {
5064
+ inputFormat: input.inputFormat,
5065
+ outputFormat: input.outputFormat,
5066
+ ratio: input.outputFormat.sampleRateHz / input.inputFormat.sampleRateHz,
5067
+ required,
5068
+ status: input.inputFormat.container === input.outputFormat.container && input.inputFormat.encoding === input.outputFormat.encoding && input.inputFormat.channels === input.outputFormat.channels ? "pass" : "warn"
5069
+ };
5070
+ };
5071
+ var speechProbability = (frame) => {
5072
+ if (frame.metadata?.isSpeech === true) {
5073
+ return 1;
5074
+ }
5075
+ if (frame.metadata?.isSpeech === false) {
5076
+ return 0;
5077
+ }
5078
+ for (const key of ["speechProbability", "voiceProbability", "rms", "energy"]) {
5079
+ const value = numericMetadata(frame, key);
5080
+ if (value !== undefined) {
5081
+ return value;
5082
+ }
5083
+ }
5084
+ return 0;
5085
+ };
5086
+ var buildMediaVadReport = (input = {}) => {
5087
+ const frames = (input.frames ?? []).filter((frame) => frame.kind === "input-audio");
5088
+ const speechStartThreshold = input.speechStartThreshold ?? 0.6;
5089
+ const speechEndThreshold = input.speechEndThreshold ?? 0.35;
5090
+ const minSpeechFrames = input.minSpeechFrames ?? 1;
5091
+ const maxSilenceFrames = input.maxSilenceFrames ?? 1;
5092
+ const segments = [];
5093
+ let activeFrames = [];
5094
+ let silenceFrames = 0;
5095
+ const closeSegment = () => {
5096
+ if (activeFrames.length < minSpeechFrames) {
5097
+ activeFrames = [];
5098
+ silenceFrames = 0;
5099
+ return;
5100
+ }
5101
+ const first = activeFrames[0];
5102
+ const last = activeFrames.at(-1);
5103
+ if (!first) {
5104
+ return;
5105
+ }
5106
+ segments.push({
5107
+ durationMs: first.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined,
5108
+ endAt: last?.at !== undefined ? last.at + (last.durationMs ?? 0) : undefined,
5109
+ frameCount: activeFrames.length,
5110
+ segmentId: `vad:${String(segments.length + 1)}`,
5111
+ sessionId: first.sessionId,
5112
+ startAt: first.at,
5113
+ turnId: first.turnId
5114
+ });
5115
+ activeFrames = [];
5116
+ silenceFrames = 0;
5117
+ };
5118
+ for (const frame of frames) {
5119
+ const probability = speechProbability(frame);
5120
+ if (activeFrames.length === 0) {
5121
+ if (probability >= speechStartThreshold) {
5122
+ activeFrames.push(frame);
5123
+ }
5124
+ continue;
5125
+ }
5126
+ activeFrames.push(frame);
5127
+ if (probability <= speechEndThreshold) {
5128
+ silenceFrames += 1;
5129
+ } else {
5130
+ silenceFrames = 0;
5131
+ }
5132
+ if (silenceFrames > maxSilenceFrames) {
5133
+ closeSegment();
5134
+ }
5135
+ }
5136
+ closeSegment();
5137
+ return {
5138
+ checkedAt: Date.now(),
5139
+ inputAudioFrames: frames.length,
5140
+ segments,
5141
+ status: frames.length === 0 ? "warn" : "pass"
5142
+ };
5143
+ };
5144
+ var buildMediaInterruptionReport = (input = {}) => {
5145
+ const issues = [];
5146
+ const interruptionFrames = (input.frames ?? []).filter((frame) => frame.kind === "interruption");
5147
+ const latenciesMs = interruptionFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
5148
+ const maxInterruptionLatencyMs = input.maxInterruptionLatencyMs;
5149
+ if (interruptionFrames.length === 0) {
5150
+ pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
5151
+ }
5152
+ if (maxInterruptionLatencyMs !== undefined && latenciesMs.some((latency) => latency > maxInterruptionLatencyMs)) {
5153
+ pushIssue(issues, "error", "media.interruption_latency", `Interruption latency exceeded ${String(maxInterruptionLatencyMs)}ms.`);
5154
+ }
5155
+ return {
5156
+ checkedAt: Date.now(),
5157
+ interruptionFrames: interruptionFrames.length,
5158
+ issues,
5159
+ latenciesMs,
5160
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass"
5161
+ };
5162
+ };
5163
+ var buildMediaQualityReport = (input = {}) => {
5164
+ const frames = [...input.frames ?? []].sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
5165
+ const audioFrames = frames.filter((frame) => frame.kind === "input-audio" || frame.kind === "assistant-audio");
5166
+ const inputAudioFrames = frames.filter((frame) => frame.kind === "input-audio");
5167
+ const assistantAudioFrames = frames.filter((frame) => frame.kind === "assistant-audio");
5168
+ const issues = [];
5169
+ const gapsMs = [];
5170
+ for (const [index, frame] of audioFrames.entries()) {
5171
+ const previous = audioFrames[index - 1];
5172
+ if (previous?.at === undefined || frame.at === undefined || previous.durationMs === undefined) {
5173
+ continue;
5174
+ }
5175
+ const gap = frame.at - (previous.at + previous.durationMs);
5176
+ if (gap > 0) {
5177
+ gapsMs.push(gap);
5178
+ }
5179
+ }
5180
+ const jitterMs = audioFrames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined).at(-1) ?? max(gapsMs);
5181
+ const first = audioFrames.find((frame) => frame.at !== undefined);
5182
+ const last = audioFrames.toReversed().find((frame) => frame.at !== undefined);
5183
+ const durationMs = first?.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined;
5184
+ const expectedDurationMs = audioFrames.length > 0 ? audioFrames.reduce((total, frame) => total + (frame.durationMs ?? 0), 0) : undefined;
5185
+ const timestampDriftMs = durationMs !== undefined && expectedDurationMs !== undefined ? Math.max(0, durationMs - expectedDurationMs) : undefined;
5186
+ const speechScores = inputAudioFrames.map(speechProbability);
5187
+ const speechFrames = speechScores.filter((score) => score >= 0.6).length;
5188
+ const silenceFrames = speechScores.filter((score) => score <= 0.35).length;
5189
+ const unknownSpeechFrames = Math.max(0, inputAudioFrames.length - speechFrames - silenceFrames);
5190
+ const speechRatio = inputAudioFrames.length === 0 ? 0 : speechFrames / inputAudioFrames.length;
5191
+ const silenceRatio = inputAudioFrames.length === 0 ? 0 : silenceFrames / inputAudioFrames.length;
5192
+ const levels = audioFrames.map((frame) => numericMetadata(frame, "level") ?? numericMetadata(frame, "rms") ?? numericMetadata(frame, "energy")).filter((value) => value !== undefined);
5193
+ const backpressureEvents = input.transport?.backpressureEvents ?? 0;
5194
+ const maxGapMs = input.maxGapMs;
5195
+ if (maxGapMs !== undefined && gapsMs.some((gap) => gap > maxGapMs)) {
5196
+ pushIssue(issues, "warning", "media.quality_gap", `Observed media gap above ${String(maxGapMs)}ms.`);
5197
+ }
5198
+ if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
5199
+ pushIssue(issues, "warning", "media.quality_jitter", `Observed jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
5200
+ }
5201
+ if (input.maxTimestampDriftMs !== undefined && timestampDriftMs !== undefined && timestampDriftMs > input.maxTimestampDriftMs) {
5202
+ pushIssue(issues, "warning", "media.quality_timestamp_drift", `Observed timestamp drift ${String(timestampDriftMs)}ms above ${String(input.maxTimestampDriftMs)}ms.`);
5203
+ }
5204
+ if (input.minSpeechRatio !== undefined && inputAudioFrames.length > 0 && speechRatio < input.minSpeechRatio) {
5205
+ pushIssue(issues, "warning", "media.quality_speech_ratio", `Observed speech ratio ${String(speechRatio)} below ${String(input.minSpeechRatio)}.`);
5206
+ }
5207
+ if (input.maxBackpressureEvents !== undefined && backpressureEvents > input.maxBackpressureEvents) {
5208
+ pushIssue(issues, "warning", "media.quality_backpressure", `Observed ${String(backpressureEvents)} backpressure event(s), above ${String(input.maxBackpressureEvents)}.`);
5209
+ }
5210
+ return {
5211
+ assistantAudioFrames: assistantAudioFrames.length,
5212
+ backpressureEvents,
5213
+ checkedAt: Date.now(),
5214
+ durationMs,
5215
+ gapCount: gapsMs.length,
5216
+ gapsMs,
5217
+ inputAudioFrames: inputAudioFrames.length,
5218
+ issues,
5219
+ jitterMs,
5220
+ levelAverage: average(levels),
5221
+ levelMax: max(levels),
5222
+ levelMin: min(levels),
5223
+ silenceFrames,
5224
+ silenceRatio,
5225
+ speechFrames,
5226
+ speechRatio,
5227
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
5228
+ timestampDriftMs,
5229
+ totalFrames: frames.length,
5230
+ unknownSpeechFrames
5231
+ };
5232
+ };
5233
+ var buildMediaWebRTCStatsReport = (input = {}) => {
5234
+ const stats = input.stats ?? [];
5235
+ const issues = [];
5236
+ const inbound = stats.filter((stat) => stat.type === "inbound-rtp" && stringStat(stat, "kind") !== "video");
5237
+ const outbound = stats.filter((stat) => stat.type === "outbound-rtp" && stringStat(stat, "kind") !== "video");
5238
+ const candidatePairs = stats.filter((stat) => stat.type === "candidate-pair");
5239
+ const audioTracks = stats.filter((stat) => (stat.type === "track" || stat.type === "media-source") && stringStat(stat, "kind") === "audio");
5240
+ const activeCandidatePairs = candidatePairs.filter((stat) => booleanStat(stat, "selected") === true || booleanStat(stat, "nominated") === true || stringStat(stat, "state") === "succeeded").length;
5241
+ const liveAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") !== "ended" && stringStat(stat, "trackState") !== "ended" && booleanStat(stat, "ended") !== true).length;
5242
+ const endedAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") === "ended" || stringStat(stat, "trackState") === "ended" || booleanStat(stat, "ended") === true).length;
5243
+ const inboundPackets = inbound.reduce((total, stat) => total + (numericStat(stat, "packetsReceived") ?? 0), 0);
5244
+ const outboundPackets = outbound.reduce((total, stat) => total + (numericStat(stat, "packetsSent") ?? 0), 0);
5245
+ const packetsLost = [...inbound, ...outbound].reduce((total, stat) => total + Math.max(0, numericStat(stat, "packetsLost") ?? 0), 0);
5246
+ const packetLossDenominator = inboundPackets + packetsLost;
5247
+ const packetLossRatio = packetLossDenominator === 0 ? 0 : packetsLost / packetLossDenominator;
5248
+ const bytesReceived = inbound.reduce((total, stat) => total + (numericStat(stat, "bytesReceived") ?? 0), 0);
5249
+ const bytesSent = outbound.reduce((total, stat) => total + (numericStat(stat, "bytesSent") ?? 0), 0);
5250
+ const roundTripTimeMs = max(candidatePairs.map((stat) => secondsToMs(numericStat(stat, "currentRoundTripTime") ?? numericStat(stat, "roundTripTime"))).filter((value) => value !== undefined));
5251
+ const jitterMs = max([...inbound, ...outbound].map((stat) => secondsToMs(numericStat(stat, "jitter"))).filter((value) => value !== undefined));
5252
+ const jitterBufferDelayMs = max(inbound.map((stat) => {
5253
+ const delay = numericStat(stat, "jitterBufferDelay");
5254
+ const emitted = numericStat(stat, "jitterBufferEmittedCount");
5255
+ return delay !== undefined && emitted !== undefined && emitted > 0 ? delay / emitted * 1000 : undefined;
5256
+ }).filter((value) => value !== undefined));
5257
+ const audioLevels = audioTracks.map((stat) => numericStat(stat, "audioLevel")).filter((value) => value !== undefined);
5258
+ if (input.requireConnectedCandidatePair && candidatePairs.length > 0 && activeCandidatePairs === 0) {
5259
+ pushIssue(issues, "error", "media.webrtc_candidate_pair_missing", "No active WebRTC candidate pair was observed.");
5260
+ }
5261
+ if (input.requireLiveAudioTrack && liveAudioTracks === 0) {
5262
+ pushIssue(issues, "error", "media.webrtc_audio_track_missing", "No live WebRTC audio track was observed.");
5263
+ }
5264
+ if (input.maxPacketLossRatio !== undefined && packetLossRatio > input.maxPacketLossRatio) {
5265
+ pushIssue(issues, "warning", "media.webrtc_packet_loss", `Observed WebRTC packet loss ratio ${String(packetLossRatio)} above ${String(input.maxPacketLossRatio)}.`);
5266
+ }
5267
+ if (input.maxRoundTripTimeMs !== undefined && roundTripTimeMs !== undefined && roundTripTimeMs > input.maxRoundTripTimeMs) {
5268
+ pushIssue(issues, "warning", "media.webrtc_round_trip_time", `Observed WebRTC RTT ${String(roundTripTimeMs)}ms above ${String(input.maxRoundTripTimeMs)}ms.`);
5269
+ }
5270
+ if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
5271
+ pushIssue(issues, "warning", "media.webrtc_jitter", `Observed WebRTC jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
5272
+ }
5273
+ return {
5274
+ activeCandidatePairs,
5275
+ audioLevelAverage: average(audioLevels),
5276
+ bytesReceived,
5277
+ bytesSent,
5278
+ checkedAt: Date.now(),
5279
+ endedAudioTracks,
5280
+ inboundPackets,
5281
+ issues,
5282
+ jitterBufferDelayMs,
5283
+ jitterMs,
5284
+ liveAudioTracks,
5285
+ outboundPackets,
5286
+ packetLossRatio,
5287
+ packetsLost,
5288
+ roundTripTimeMs,
5289
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
5290
+ totalStats: stats.length
5291
+ };
5292
+ };
5293
+ var collectMediaWebRTCStats = async (input) => {
5294
+ const report = await input.peerConnection.getStats(input.selector ?? null);
5295
+ return [...report.values()].map(normalizeWebRTCStat);
5296
+ };
5297
+ var collectMediaWebRTCStatsReport = async (input) => {
5298
+ const stats = await collectMediaWebRTCStats(input);
5299
+ return buildMediaWebRTCStatsReport({
5300
+ ...input,
5301
+ stats
5302
+ });
5303
+ };
5304
+ var buildMediaPipelineCalibrationReport = (input = {}) => {
5305
+ const frames = input.frames ?? [];
5306
+ const issues = [];
5307
+ const inputFrames = frames.filter((frame) => frame.kind === "input-audio");
5308
+ const assistantFrames = frames.filter((frame) => frame.kind === "assistant-audio");
5309
+ const turnCommitFrames = frames.filter((frame) => frame.kind === "turn-commit");
5310
+ const interruptionFrameRecords = frames.filter((frame) => frame.kind === "interruption");
5311
+ const traceLinkedFrames = frames.filter((frame) => frame.traceEventId).length;
5312
+ const backpressureFrames = frames.filter((frame) => Boolean(frame.metadata?.backpressure)).length;
5313
+ const audioLatencies = assistantFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
5314
+ const firstAudioLatencyMs = audioLatencies.length > 0 ? Math.min(...audioLatencies) : undefined;
5315
+ const jitterValues = frames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined);
5316
+ const jitterMs = jitterValues.length > 0 ? Math.max(...jitterValues) : undefined;
5317
+ const inputFormat = input.inputFormat ?? inputFrames.find((frame) => frame.format)?.format;
5318
+ const outputFormat = input.outputFormat ?? assistantFrames.find((frame) => frame.format)?.format;
5319
+ const resamplingRequired = Boolean(input.expectedInputFormat && inputFormat && inputFormat.sampleRateHz !== input.expectedInputFormat.sampleRateHz) || Boolean(input.expectedOutputFormat && outputFormat && outputFormat.sampleRateHz !== input.expectedOutputFormat.sampleRateHz);
5320
+ const resamplingTargetHz = resamplingRequired && input.expectedInputFormat ? input.expectedInputFormat.sampleRateHz : resamplingRequired ? input.expectedOutputFormat?.sampleRateHz : undefined;
5321
+ if (inputFrames.length === 0) {
5322
+ pushIssue(issues, "warning", "media.input_audio_missing", "No input audio frames were observed.");
5323
+ }
5324
+ if (assistantFrames.length === 0) {
5325
+ pushIssue(issues, "warning", "media.assistant_audio_missing", "No assistant audio frames were observed.");
5326
+ }
5327
+ if (input.expectedInputFormat && inputFormat && !formatMatches(inputFormat, input.expectedInputFormat)) {
5328
+ pushIssue(issues, inputFormat.sampleRateHz === input.expectedInputFormat.sampleRateHz ? "warning" : "error", "media.input_format_mismatch", `Input format ${formatLabel(inputFormat)} does not match expected ${formatLabel(input.expectedInputFormat)}.`);
5329
+ }
5330
+ if (input.expectedOutputFormat && outputFormat && !formatMatches(outputFormat, input.expectedOutputFormat)) {
5331
+ pushIssue(issues, outputFormat.sampleRateHz === input.expectedOutputFormat.sampleRateHz ? "warning" : "error", "media.output_format_mismatch", `Output format ${formatLabel(outputFormat)} does not match expected ${formatLabel(input.expectedOutputFormat)}.`);
5332
+ }
5333
+ if (firstAudioLatencyMs !== undefined && input.maxFirstAudioLatencyMs !== undefined && firstAudioLatencyMs > input.maxFirstAudioLatencyMs) {
5334
+ pushIssue(issues, "error", "media.first_audio_latency", `First audio latency ${String(firstAudioLatencyMs)}ms exceeds budget ${String(input.maxFirstAudioLatencyMs)}ms.`);
5335
+ }
5336
+ if (jitterMs !== undefined && input.maxJitterMs !== undefined && jitterMs > input.maxJitterMs) {
5337
+ pushIssue(issues, "warning", "media.jitter", `Media jitter ${String(jitterMs)}ms exceeds budget ${String(input.maxJitterMs)}ms.`);
5338
+ }
5339
+ if (input.maxBackpressureFrames !== undefined && backpressureFrames > input.maxBackpressureFrames) {
5340
+ pushIssue(issues, "warning", "media.backpressure", `Backpressure frame count ${String(backpressureFrames)} exceeds budget ${String(input.maxBackpressureFrames)}.`);
5341
+ }
5342
+ if (input.requireInterruptionFrame && interruptionFrameRecords.length === 0) {
5343
+ pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
5344
+ }
5345
+ if (input.requireTraceEvidence && traceLinkedFrames === 0) {
5346
+ pushIssue(issues, "warning", "media.trace_evidence_missing", "No media frames were linked to trace evidence.");
5347
+ }
5348
+ return {
5349
+ assistantAudioFrames: assistantFrames.length,
5350
+ backpressureFrames,
5351
+ checkedAt: Date.now(),
5352
+ firstAudioLatencyMs,
5353
+ inputAudioFrames: inputFrames.length,
5354
+ inputFormat,
5355
+ interruptionFrames: interruptionFrameRecords.length,
5356
+ issues,
5357
+ jitterMs,
5358
+ outputFormat,
5359
+ resamplingRequired,
5360
+ resamplingTargetHz,
5361
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
5362
+ surface: input.surface ?? "media-pipeline",
5363
+ traceLinkedFrames,
5364
+ turnCommitFrames: turnCommitFrames.length
5365
+ };
5366
+ };
5367
+
5368
+ // src/client/browserMedia.ts
5369
+ var DEFAULT_BROWSER_MEDIA_PATH = "/api/voice/browser-media";
5370
+ var DEFAULT_BROWSER_MEDIA_INTERVAL_MS = 5000;
5371
+ var resolvePeerConnection = async (options) => options.peerConnection ?? await options.getPeerConnection?.() ?? null;
5372
+ var postBrowserMediaReport = async (payload, options) => {
5373
+ const requestFetch = options.fetch ?? globalThis.fetch;
5374
+ if (!requestFetch) {
5375
+ return;
5376
+ }
5377
+ await requestFetch(options.path ?? DEFAULT_BROWSER_MEDIA_PATH, {
5378
+ body: JSON.stringify(payload),
5379
+ headers: {
5380
+ "Content-Type": "application/json"
5381
+ },
5382
+ keepalive: true,
5383
+ method: "POST"
5384
+ });
5385
+ };
5386
+ var createVoiceBrowserMediaReporter = (options) => {
5387
+ let interval = null;
5388
+ const reportOnce = async () => {
5389
+ const peerConnection = await resolvePeerConnection(options);
5390
+ if (!peerConnection) {
5391
+ return;
5392
+ }
5393
+ const report = await collectMediaWebRTCStatsReport({
5394
+ ...options,
5395
+ peerConnection
5396
+ });
5397
+ const payload = {
5398
+ at: Date.now(),
5399
+ report,
5400
+ scenarioId: options.getScenarioId?.() ?? null,
5401
+ sessionId: options.getSessionId?.() ?? null
5402
+ };
5403
+ options.onReport?.(payload);
5404
+ await postBrowserMediaReport(payload, options);
5405
+ return payload;
5406
+ };
5407
+ const run = () => {
5408
+ reportOnce().catch((error) => {
5409
+ options.onError?.(error);
5410
+ });
5411
+ };
5412
+ const stop = () => {
5413
+ if (interval) {
5414
+ clearInterval(interval);
5415
+ interval = null;
5416
+ }
5417
+ };
5418
+ return {
5419
+ close: stop,
5420
+ reportOnce,
5421
+ start: () => {
5422
+ if (interval) {
5423
+ return;
5424
+ }
5425
+ run();
5426
+ interval = setInterval(run, options.intervalMs ?? DEFAULT_BROWSER_MEDIA_INTERVAL_MS);
5427
+ },
5428
+ stop
5429
+ };
5430
+ };
5431
+
5026
5432
  // src/client/connection.ts
5027
5433
  var WS_OPEN = 1;
5028
5434
  var WS_CLOSED = 3;
@@ -5455,12 +5861,18 @@ var createVoiceStreamStore = () => {
5455
5861
  var createVoiceStream = (path, options = {}) => {
5456
5862
  const connection = createVoiceConnection(path, options);
5457
5863
  const store = createVoiceStreamStore();
5864
+ const browserMediaReporter = options.browserMedia && typeof window !== "undefined" ? createVoiceBrowserMediaReporter({
5865
+ ...options.browserMedia,
5866
+ getScenarioId: () => options.browserMedia ? options.browserMedia.getScenarioId?.() ?? connection.getScenarioId() : connection.getScenarioId(),
5867
+ getSessionId: () => options.browserMedia ? options.browserMedia.getSessionId?.() ?? connection.getSessionId() : connection.getSessionId()
5868
+ }) : null;
5458
5869
  const subscribers = new Set;
5459
5870
  const start = (input) => Promise.resolve().then(() => {
5460
5871
  if (!input?.sessionId && !input?.scenarioId) {
5461
5872
  return;
5462
5873
  }
5463
5874
  connection.start(input);
5875
+ browserMediaReporter?.start();
5464
5876
  });
5465
5877
  const notify = () => {
5466
5878
  subscribers.forEach((subscriber) => subscriber());
@@ -5502,6 +5914,7 @@ var createVoiceStream = (path, options = {}) => {
5502
5914
  },
5503
5915
  close() {
5504
5916
  unsubscribeConnection();
5917
+ browserMediaReporter?.close();
5505
5918
  connection.close();
5506
5919
  store.dispatch({ type: "disconnected" });
5507
5920
  notify();