@arbidocs/react 0.5.178 → 0.5.180

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.
@@ -15,14 +15,20 @@ function checkedCallMedia(value, participant) {
15
15
  return v;
16
16
  }
17
17
  class CallMediaPlayer {
18
- constructor(context, changed) {
18
+ constructor(context, changed, measured = () => void 0) {
19
19
  this.context = context;
20
20
  this.changed = changed;
21
+ this.measured = measured;
21
22
  this.recording = context.createMediaStreamDestination();
22
23
  }
23
24
  context;
24
25
  changed;
25
- active = false;
26
+ measured;
27
+ streaming = false;
28
+ audible = false;
29
+ get active() {
30
+ return this.audible;
31
+ }
26
32
  /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */
27
33
  suppressesTrack = false;
28
34
  avatar = "";
@@ -35,8 +41,13 @@ class CallMediaPlayer {
35
41
  sources = /* @__PURE__ */ new Set();
36
42
  seen = /* @__PURE__ */ new Set();
37
43
  finishTimer;
44
+ measurements = [];
45
+ renderedMouth = false;
46
+ mouthRest;
47
+ scheduledNonzeroPcm = false;
48
+ scheduledPcm = false;
38
49
  recording;
39
- push(message) {
50
+ push(message, receivedAt = performance.now()) {
40
51
  if (message.type === "fallback" && message.sequence === 0 && message.utterance_id !== this.utterance) {
41
52
  if (this.seen.has(message.utterance_id)) return;
42
53
  this.utterance = message.utterance_id;
@@ -57,8 +68,13 @@ class CallMediaPlayer {
57
68
  this.sequence = 0;
58
69
  this.nextSample = 0;
59
70
  this.nextTime = this.context.currentTime + 0.15;
60
- this.active = true;
71
+ this.streaming = true;
72
+ this.renderedMouth = false;
73
+ this.mouthRest = void 0;
74
+ this.scheduledNonzeroPcm = false;
75
+ this.scheduledPcm = false;
61
76
  this.suppressesTrack = true;
77
+ this.measure({ event: "utterance_start_received", client_performance_ms: receivedAt });
62
78
  this.changed();
63
79
  return;
64
80
  }
@@ -66,7 +82,7 @@ class CallMediaPlayer {
66
82
  if (message.sequence !== this.sequence + 1) throw new Error("Call media sequence gap");
67
83
  this.sequence = message.sequence;
68
84
  if (message.type === "media") {
69
- if (!this.active || message.start_sample !== this.nextSample)
85
+ if (!this.streaming || message.start_sample !== this.nextSample)
70
86
  throw new Error("Call media sample gap");
71
87
  const pcm = base64ToBytes(message.pcm);
72
88
  if (pcm.length % 2 || pcm.length > message.frames.length * 800)
@@ -85,15 +101,53 @@ class CallMediaPlayer {
85
101
  source.onended = () => {
86
102
  source.disconnect();
87
103
  this.sources.delete(source);
104
+ if (!this.sources.size) this.setAudible(false);
88
105
  };
89
106
  source.start(at);
90
- this.segments.push({ at, duration: buffer.duration, frames: message.frames });
107
+ this.setAudible(true);
108
+ if (!this.scheduledPcm) {
109
+ this.scheduledPcm = true;
110
+ this.measure({
111
+ event: "first_media_received",
112
+ client_performance_ms: receivedAt,
113
+ source_sample: message.start_sample
114
+ });
115
+ this.measure({
116
+ event: "first_pcm_scheduled",
117
+ audio_context_seconds: at,
118
+ source_sample: message.start_sample
119
+ });
120
+ }
121
+ if (!this.scheduledNonzeroPcm) {
122
+ const first = values.findIndex((value) => Math.abs(value) > 1 / 32768);
123
+ if (first >= 0) {
124
+ this.scheduledNonzeroPcm = true;
125
+ this.measure({
126
+ event: "first_nonzero_pcm_scheduled",
127
+ audio_context_seconds: at + first / 24e3,
128
+ estimated_output_performance_ms: this.outputTime(at + first / 24e3),
129
+ source_sample: message.start_sample + first
130
+ });
131
+ }
132
+ }
133
+ this.segments.push({
134
+ at,
135
+ startSample: message.start_sample,
136
+ duration: buffer.duration,
137
+ frames: message.frames
138
+ });
91
139
  this.segments = this.segments.filter(
92
140
  (s) => s.at + s.duration > this.context.currentTime - 0.1
93
141
  );
94
142
  this.nextTime = at + buffer.duration;
95
143
  this.nextSample += values.length;
96
144
  } else if (message.type === "end") {
145
+ this.measure({
146
+ event: "utterance_end_received",
147
+ client_performance_ms: receivedAt,
148
+ source_sample: this.nextSample
149
+ });
150
+ this.streaming = false;
97
151
  this.finishTimer = setTimeout(
98
152
  () => this.reset(),
99
153
  Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
@@ -111,6 +165,61 @@ class CallMediaPlayer {
111
165
  const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
112
166
  return a.map((value, j) => value + (b[j] - value) * (frame - i));
113
167
  }
168
+ /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */
169
+ reportMouthRenderSubmitted(controls) {
170
+ if (this.renderedMouth) return;
171
+ const now = this.context.currentTime;
172
+ const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
173
+ if (!segment) return;
174
+ const mouth = Object.fromEntries(
175
+ Object.entries(controls).filter(
176
+ ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)
177
+ )
178
+ );
179
+ if (!this.mouthRest) {
180
+ this.mouthRest = mouth;
181
+ return;
182
+ }
183
+ const delta = Math.max(
184
+ 0,
185
+ ...Object.entries(mouth).map(
186
+ ([name, value]) => Math.abs(value - (this.mouthRest[name] ?? value))
187
+ )
188
+ );
189
+ if (delta < 0.02) return;
190
+ this.renderedMouth = true;
191
+ this.measure({
192
+ event: "first_mouth_render_submitted",
193
+ audio_context_seconds: now,
194
+ source_sample: segment.startSample + Math.floor((now - segment.at) * 24e3),
195
+ mouth_delta: delta,
196
+ mouth_delta_threshold: 0.02
197
+ });
198
+ }
199
+ timing(event, receivedAt = performance.now(), batchSize = 1) {
200
+ this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize });
201
+ }
202
+ measure(value) {
203
+ const entry = {
204
+ utterance_id: this.utterance,
205
+ client_performance_ms: performance.now(),
206
+ ...value
207
+ };
208
+ this.measurements.push(entry);
209
+ if (this.measurements.length > 256) this.measurements.shift();
210
+ this.measured(entry);
211
+ }
212
+ outputTime(at) {
213
+ const stamp = this.context.getOutputTimestamp?.();
214
+ if (stamp?.contextTime !== void 0 && stamp.performanceTime !== void 0 && stamp.performanceTime > 0)
215
+ return stamp.performanceTime + (at - stamp.contextTime) * 1e3;
216
+ return performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1e3;
217
+ }
218
+ setAudible(value) {
219
+ if (this.audible === value) return;
220
+ this.audible = value;
221
+ this.changed();
222
+ }
114
223
  reset(releaseTrack = false) {
115
224
  clearTimeout(this.finishTimer);
116
225
  for (const source of this.sources) {
@@ -119,7 +228,8 @@ class CallMediaPlayer {
119
228
  }
120
229
  this.sources.clear();
121
230
  this.segments = [];
122
- this.active = false;
231
+ this.streaming = false;
232
+ this.setAudible(false);
123
233
  if (releaseTrack) this.suppressesTrack = false;
124
234
  this.changed();
125
235
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/calls/livekit/call-media-player.ts"],
4
- "sourcesContent": ["/** A single PCM clock drives both audible speech and timestamped animation controls. */\nimport { base64ToBytes } from '@arbidocs/client'\n\nexport interface CallMediaEnvelope {\n protocol: 'arbi.call.media.v1'\n participant: string\n utterance_id: string\n sequence: number\n type: 'start' | 'media' | 'end' | 'stop' | 'fallback'\n avatar?: string\n sample_rate?: number\n fps?: number\n names?: string[]\n start_sample?: number\n pcm?: string\n frames?: number[][]\n}\n\nexport function checkedCallMedia(value: unknown, participant: string): CallMediaEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call media')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== 'arbi.call.media.v1' ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.sequence) ||\n Number(v.sequence) < 0 ||\n !['start', 'media', 'end', 'stop', 'fallback'].includes(String(v.type))\n )\n throw new Error('Invalid call media identity or sequence')\n if (\n v.type === 'start' &&\n (v.sample_rate !== 24000 ||\n v.fps !== 60 ||\n typeof v.avatar !== 'string' ||\n !Array.isArray(v.names) ||\n v.names.length !== 52 ||\n new Set(v.names).size !== 52 ||\n !v.names.every((name) => typeof name === 'string' && name.length < 80))\n )\n throw new Error('Invalid call media configuration')\n if (\n v.type === 'media' &&\n (!Number.isSafeInteger(v.start_sample) ||\n Number(v.start_sample) < 0 ||\n typeof v.pcm !== 'string' ||\n v.pcm.length > 6400 ||\n !Array.isArray(v.frames) ||\n !v.frames.length ||\n v.frames.length > 6 ||\n !v.frames.every(\n (frame: unknown) =>\n Array.isArray(frame) &&\n frame.length === 52 &&\n frame.every(\n (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= -2 && x <= 2\n )\n ))\n )\n throw new Error('Invalid call media samples')\n return v as unknown as CallMediaEnvelope\n}\n\ninterface Segment {\n at: number\n duration: number\n frames: number[][]\n}\n\nexport class CallMediaPlayer {\n active = false\n /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */\n suppressesTrack = false\n avatar = ''\n names: string[] = []\n private utterance = ''\n private sequence = -1\n private nextSample = 0\n private nextTime = 0\n private segments: Segment[] = []\n private sources = new Set<AudioBufferSourceNode>()\n private seen = new Set<string>()\n private finishTimer: ReturnType<typeof setTimeout> | undefined\n readonly recording: MediaStreamAudioDestinationNode\n\n constructor(\n readonly context: AudioContext,\n private changed: () => void\n ) {\n this.recording = context.createMediaStreamDestination()\n }\n\n push(message: CallMediaEnvelope): void {\n if (\n message.type === 'fallback' &&\n message.sequence === 0 &&\n message.utterance_id !== this.utterance\n ) {\n if (this.seen.has(message.utterance_id)) return\n this.utterance = message.utterance_id\n this.sequence = 0\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.reset(true)\n return\n }\n if (message.type === 'start') {\n if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return\n this.reset()\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.utterance = message.utterance_id\n this.avatar = message.avatar!\n this.names = message.names!\n this.sequence = 0\n this.nextSample = 0\n this.nextTime = this.context.currentTime + 0.15\n this.active = true\n this.suppressesTrack = true\n this.changed()\n return\n }\n if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return\n if (message.sequence !== this.sequence + 1) throw new Error('Call media sequence gap')\n this.sequence = message.sequence\n if (message.type === 'media') {\n if (!this.active || message.start_sample !== this.nextSample)\n throw new Error('Call media sample gap')\n const pcm = base64ToBytes(message.pcm!)\n if (pcm.length % 2 || pcm.length > message.frames!.length * 800)\n throw new Error('Invalid PCM length')\n if (this.nextTime - this.context.currentTime > 2) throw new Error('Call media queue exceeded')\n const buffer = this.context.createBuffer(1, pcm.length / 2, 24000)\n const values = buffer.getChannelData(0)\n const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768\n const at = Math.max(this.nextTime, this.context.currentTime + 0.02)\n const source = this.context.createBufferSource()\n source.buffer = buffer\n source.connect(this.context.destination)\n source.connect(this.recording)\n this.sources.add(source)\n source.onended = () => {\n source.disconnect()\n this.sources.delete(source)\n }\n source.start(at)\n this.segments.push({ at, duration: buffer.duration, frames: message.frames! })\n this.segments = this.segments.filter(\n (s) => s.at + s.duration > this.context.currentTime - 0.1\n )\n this.nextTime = at + buffer.duration\n this.nextSample += values.length\n } else if (message.type === 'end') {\n this.finishTimer = setTimeout(\n () => this.reset(),\n Math.max(0, this.nextTime - this.context.currentTime) * 1000 + 30\n )\n } else if (message.type === 'fallback' || message.type === 'stop') {\n this.reset(message.type === 'fallback')\n }\n }\n\n sample(): number[] | null {\n const now = this.context.currentTime\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return null\n const frame = (now - segment.at) * 60\n const i = Math.min(Math.floor(frame), segment.frames.length - 1)\n const a = segment.frames[i],\n b = segment.frames[Math.min(i + 1, segment.frames.length - 1)]\n return a.map((value, j) => value + (b[j] - value) * (frame - i))\n }\n\n reset(releaseTrack = false): void {\n clearTimeout(this.finishTimer)\n for (const source of this.sources) {\n source.stop()\n source.disconnect()\n }\n this.sources.clear()\n this.segments = []\n this.active = false\n if (releaseTrack) this.suppressesTrack = false\n this.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ls. */\nimport { base64ToBytes } from '@arbidocs/client'\nimport type { CallTimingEnvelope, CallTimingMeasurement } from './call-timing'\n\nexport interface CallMediaEnvelope {\n protocol: 'arbi.call.media.v1'\n participant: string\n utterance_id: string\n sequence: number\n type: 'start' | 'media' | 'end' | 'stop' | 'fallback'\n avatar?: string\n sample_rate?: number\n fps?: number\n names?: string[]\n start_sample?: number\n pcm?: string\n frames?: number[][]\n}\n\nexport function checkedCallMedia(value: unknown, participant: string): CallMediaEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call media')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== 'arbi.call.media.v1' ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.sequence) ||\n Number(v.sequence) < 0 ||\n !['start', 'media', 'end', 'stop', 'fallback'].includes(String(v.type))\n )\n throw new Error('Invalid call media identity or sequence')\n if (\n v.type === 'start' &&\n (v.sample_rate !== 24000 ||\n v.fps !== 60 ||\n typeof v.avatar !== 'string' ||\n !Array.isArray(v.names) ||\n v.names.length !== 52 ||\n new Set(v.names).size !== 52 ||\n !v.names.every((name) => typeof name === 'string' && name.length < 80))\n )\n throw new Error('Invalid call media configuration')\n if (\n v.type === 'media' &&\n (!Number.isSafeInteger(v.start_sample) ||\n Number(v.start_sample) < 0 ||\n typeof v.pcm !== 'string' ||\n v.pcm.length > 6400 ||\n !Array.isArray(v.frames) ||\n !v.frames.length ||\n v.frames.length > 6 ||\n !v.frames.every(\n (frame: unknown) =>\n Array.isArray(frame) &&\n frame.length === 52 &&\n frame.every(\n (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= -2 && x <= 2\n )\n ))\n )\n throw new Error('Invalid call media samples')\n return v as unknown as CallMediaEnvelope\n}\n\ninterface Segment {\n at: number\n startSample: number\n duration: number\n frames: number[][]\n}\n\nexport class CallMediaPlayer {\n private streaming = false\n private audible = false\n get active(): boolean {\n return this.audible\n }\n /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */\n suppressesTrack = false\n avatar = ''\n names: string[] = []\n private utterance = ''\n private sequence = -1\n private nextSample = 0\n private nextTime = 0\n private segments: Segment[] = []\n private sources = new Set<AudioBufferSourceNode>()\n private seen = new Set<string>()\n private finishTimer: ReturnType<typeof setTimeout> | undefined\n readonly measurements: CallTimingMeasurement[] = []\n private renderedMouth = false\n private mouthRest: Record<string, number> | undefined\n private scheduledNonzeroPcm = false\n private scheduledPcm = false\n readonly recording: MediaStreamAudioDestinationNode\n\n constructor(\n readonly context: AudioContext,\n private changed: () => void,\n private measured: (measurement: CallTimingMeasurement) => void = () => undefined\n ) {\n this.recording = context.createMediaStreamDestination()\n }\n\n push(message: CallMediaEnvelope, receivedAt = performance.now()): void {\n if (\n message.type === 'fallback' &&\n message.sequence === 0 &&\n message.utterance_id !== this.utterance\n ) {\n if (this.seen.has(message.utterance_id)) return\n this.utterance = message.utterance_id\n this.sequence = 0\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.reset(true)\n return\n }\n if (message.type === 'start') {\n if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return\n this.reset()\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.utterance = message.utterance_id\n this.avatar = message.avatar!\n this.names = message.names!\n this.sequence = 0\n this.nextSample = 0\n this.nextTime = this.context.currentTime + 0.15\n this.streaming = true\n this.renderedMouth = false\n this.mouthRest = undefined\n this.scheduledNonzeroPcm = false\n this.scheduledPcm = false\n this.suppressesTrack = true\n this.measure({ event: 'utterance_start_received', client_performance_ms: receivedAt })\n this.changed()\n return\n }\n if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return\n if (message.sequence !== this.sequence + 1) throw new Error('Call media sequence gap')\n this.sequence = message.sequence\n if (message.type === 'media') {\n if (!this.streaming || message.start_sample !== this.nextSample)\n throw new Error('Call media sample gap')\n const pcm = base64ToBytes(message.pcm!)\n if (pcm.length % 2 || pcm.length > message.frames!.length * 800)\n throw new Error('Invalid PCM length')\n if (this.nextTime - this.context.currentTime > 2) throw new Error('Call media queue exceeded')\n const buffer = this.context.createBuffer(1, pcm.length / 2, 24000)\n const values = buffer.getChannelData(0)\n const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768\n const at = Math.max(this.nextTime, this.context.currentTime + 0.02)\n const source = this.context.createBufferSource()\n source.buffer = buffer\n source.connect(this.context.destination)\n source.connect(this.recording)\n this.sources.add(source)\n source.onended = () => {\n source.disconnect()\n this.sources.delete(source)\n if (!this.sources.size) this.setAudible(false)\n }\n source.start(at)\n this.setAudible(true)\n if (!this.scheduledPcm) {\n this.scheduledPcm = true\n this.measure({\n event: 'first_media_received',\n client_performance_ms: receivedAt,\n source_sample: message.start_sample,\n })\n this.measure({\n event: 'first_pcm_scheduled',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n })\n }\n if (!this.scheduledNonzeroPcm) {\n const first = values.findIndex((value) => Math.abs(value) > 1 / 32768)\n if (first >= 0) {\n this.scheduledNonzeroPcm = true\n this.measure({\n event: 'first_nonzero_pcm_scheduled',\n audio_context_seconds: at + first / 24000,\n estimated_output_performance_ms: this.outputTime(at + first / 24000),\n source_sample: message.start_sample! + first,\n })\n }\n }\n this.segments.push({\n at,\n startSample: message.start_sample!,\n duration: buffer.duration,\n frames: message.frames!,\n })\n this.segments = this.segments.filter(\n (s) => s.at + s.duration > this.context.currentTime - 0.1\n )\n this.nextTime = at + buffer.duration\n this.nextSample += values.length\n } else if (message.type === 'end') {\n this.measure({\n event: 'utterance_end_received',\n client_performance_ms: receivedAt,\n source_sample: this.nextSample,\n })\n this.streaming = false\n this.finishTimer = setTimeout(\n () => this.reset(),\n Math.max(0, this.nextTime - this.context.currentTime) * 1000 + 30\n )\n } else if (message.type === 'fallback' || message.type === 'stop') {\n this.reset(message.type === 'fallback')\n }\n }\n\n sample(): number[] | null {\n const now = this.context.currentTime\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return null\n const frame = (now - segment.at) * 60\n const i = Math.min(Math.floor(frame), segment.frames.length - 1)\n const a = segment.frames[i],\n b = segment.frames[Math.min(i + 1, segment.frames.length - 1)]\n return a.map((value, j) => value + (b[j] - value) * (frame - i))\n }\n\n /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */\n reportMouthRenderSubmitted(controls: Readonly<Record<string, number>>): void {\n if (this.renderedMouth) return\n const now = this.context.currentTime\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return\n const mouth = Object.fromEntries(\n Object.entries(controls).filter(\n ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)\n )\n )\n // The first displayed source pose is a baseline, never an onset. Constant NN idle\n // offsets and blink/gaze cannot satisfy this documented 0.02 control-change proxy.\n if (!this.mouthRest) {\n this.mouthRest = mouth\n return\n }\n const delta = Math.max(\n 0,\n ...Object.entries(mouth).map(([name, value]) =>\n Math.abs(value - (this.mouthRest![name] ?? value))\n )\n )\n if (delta < 0.02) return\n this.renderedMouth = true\n this.measure({\n event: 'first_mouth_render_submitted',\n audio_context_seconds: now,\n source_sample: segment.startSample + Math.floor((now - segment.at) * 24000),\n mouth_delta: delta,\n mouth_delta_threshold: 0.02,\n })\n }\n\n timing(event: CallTimingEnvelope, receivedAt = performance.now(), batchSize = 1): void {\n this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize })\n }\n\n private measure(value: Partial<CallTimingMeasurement> & { event: string }): void {\n const entry: CallTimingMeasurement = {\n utterance_id: this.utterance,\n client_performance_ms: performance.now(),\n ...value,\n }\n this.measurements.push(entry)\n if (this.measurements.length > 256) this.measurements.shift()\n this.measured(entry)\n }\n\n private outputTime(at: number): number {\n const stamp = this.context.getOutputTimestamp?.()\n if (\n stamp?.contextTime !== undefined &&\n stamp.performanceTime !== undefined &&\n stamp.performanceTime > 0\n )\n return stamp.performanceTime + (at - stamp.contextTime) * 1000\n return (\n performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1000\n )\n }\n\n private setAudible(value: boolean): void {\n if (this.audible === value) return\n this.audible = value\n this.changed()\n }\n\n reset(releaseTrack = false): void {\n clearTimeout(this.finishTimer)\n for (const source of this.sources) {\n source.stop()\n source.disconnect()\n }\n this.sources.clear()\n this.segments = []\n this.streaming = false\n this.setAudible(false)\n if (releaseTrack) this.suppressesTrack = false\n this.changed()\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,qBAAqB;AAkBvB,SAAS,iBAAiB,OAAgB,aAAwC;AACvF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,oBAAoB;AAC7E,QAAM,IAAI;AACV,MACE,EAAE,aAAa,wBACf,EAAE,gBAAgB,eAClB,OAAO,EAAE,iBAAiB,YAC1B,EAAE,aAAa,SAAS,MACxB,CAAC,OAAO,cAAc,EAAE,QAAQ,KAChC,OAAO,EAAE,QAAQ,IAAI,KACrB,CAAC,CAAC,SAAS,SAAS,OAAO,QAAQ,UAAU,EAAE,SAAS,OAAO,EAAE,IAAI,CAAC;AAEtE,UAAM,IAAI,MAAM,yCAAyC;AAC3D,MACE,EAAE,SAAS,YACV,EAAE,gBAAgB,QACjB,EAAE,QAAQ,MACV,OAAO,EAAE,WAAW,YACpB,CAAC,MAAM,QAAQ,EAAE,KAAK,KACtB,EAAE,MAAM,WAAW,MACnB,IAAI,IAAI,EAAE,KAAK,EAAE,SAAS,MAC1B,CAAC,EAAE,MAAM,MAAM,CAAC,SAAS,OAAO,SAAS,YAAY,KAAK,SAAS,EAAE;AAEvE,UAAM,IAAI,MAAM,kCAAkC;AACpD,MACE,EAAE,SAAS,YACV,CAAC,OAAO,cAAc,EAAE,YAAY,KACnC,OAAO,EAAE,YAAY,IAAI,KACzB,OAAO,EAAE,QAAQ,YACjB,EAAE,IAAI,SAAS,QACf,CAAC,MAAM,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AAK,SAAS,KAAK;AAAA,EACrB;AAAA,EAEQ,WAAW,IAAoB;AACrC,UAAM,QAAQ,KAAK,QAAQ,qBAAqB;AAChD,QACE,OAAO,gBAAgB,UACvB,MAAM,oBAAoB,UAC1B,MAAM,kBAAkB;AAExB,aAAO,MAAM,mBAAmB,KAAK,MAAM,eAAe;AAC5D,WACE,YAAY,IAAI,KAAK,KAAK,KAAK,QAAQ,eAAe,KAAK,QAAQ,eAAe,MAAM;AAAA,EAE5F;AAAA,EAEQ,WAAW,OAAsB;AACvC,QAAI,KAAK,YAAY,MAAO;AAC5B,SAAK,UAAU;AACf,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,eAAe,OAAa;AAChC,iBAAa,KAAK,WAAW;AAC7B,eAAW,UAAU,KAAK,SAAS;AACjC,aAAO,KAAK;AACZ,aAAO,WAAW;AAAA,IACpB;AACA,SAAK,QAAQ,MAAM;AACnB,SAAK,WAAW,CAAC;AACjB,SAAK,YAAY;AACjB,SAAK,WAAW,KAAK;AACrB,QAAI,aAAc,MAAK,kBAAkB;AACzC,SAAK,QAAQ;AAAA,EACf;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,49 @@
1
+ const CALL_TIMING_PROTOCOL = "arbi.call.timing.v1";
2
+ const EVENTS = /* @__PURE__ */ new Set([
3
+ "speech_end",
4
+ "transcription_started",
5
+ "transcription_completed",
6
+ "agent_started",
7
+ "first_answer_text",
8
+ "first_tts_request",
9
+ "first_pcm",
10
+ "first_pose",
11
+ "animation_connect_started",
12
+ "animation_ready"
13
+ ]);
14
+ function checkedCallTiming(value, participant) {
15
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
16
+ const v = value;
17
+ if (v.protocol !== CALL_TIMING_PROTOCOL || v.participant !== participant || typeof v.utterance_id !== "string" || !v.utterance_id.length || v.utterance_id.length > 64 || !Number.isSafeInteger(v.generation) || Number(v.generation) < 0 || typeof v.event !== "string" || !EVENTS.has(v.event) || typeof v.server_epoch_ms !== "number" || !Number.isFinite(v.server_epoch_ms) || typeof v.server_monotonic_ms !== "number" || !Number.isFinite(v.server_monotonic_ms))
18
+ throw new Error("Invalid call timing");
19
+ return v;
20
+ }
21
+ function checkedCallTimings(value, participant) {
22
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
23
+ const v = value;
24
+ if (!("events" in v)) return [checkedCallTiming(v, participant)];
25
+ if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)
26
+ throw new Error("Invalid call timing batch");
27
+ return v.events.map((event) => {
28
+ if (!event || typeof event !== "object") throw new Error("Invalid call timing event");
29
+ const e = event;
30
+ return checkedCallTiming(
31
+ {
32
+ protocol: v.protocol,
33
+ participant: v.participant,
34
+ utterance_id: v.utterance_id,
35
+ generation: v.generation,
36
+ event: e.event,
37
+ server_epoch_ms: e.server_epoch_ms,
38
+ server_monotonic_ms: e.server_monotonic_ms
39
+ },
40
+ participant
41
+ );
42
+ });
43
+ }
44
+ export {
45
+ CALL_TIMING_PROTOCOL,
46
+ checkedCallTiming,
47
+ checkedCallTimings
48
+ };
49
+ //# sourceMappingURL=call-timing.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/calls/livekit/call-timing.ts"],
4
+ "sourcesContent": ["/** Content-free call measurements. Server and browser clocks remain explicitly separate. */\nexport const CALL_TIMING_PROTOCOL = 'arbi.call.timing.v1'\nconst EVENTS = new Set([\n 'speech_end',\n 'transcription_started',\n 'transcription_completed',\n 'agent_started',\n 'first_answer_text',\n 'first_tts_request',\n 'first_pcm',\n 'first_pose',\n 'animation_connect_started',\n 'animation_ready',\n])\nexport interface CallTimingEnvelope {\n protocol: typeof CALL_TIMING_PROTOCOL\n participant: string\n utterance_id: string\n generation: number\n event: string\n server_epoch_ms: number\n server_monotonic_ms: number\n}\nexport interface CallTimingMeasurement {\n utterance_id: string\n event: string\n client_performance_ms: number\n audio_context_seconds?: number\n estimated_output_performance_ms?: number\n source_sample?: number\n server_epoch_ms?: number\n server_monotonic_ms?: number\n generation?: number\n timing_batch_size?: number\n mouth_delta?: number\n mouth_delta_threshold?: number\n}\nexport function checkedCallTiming(value: unknown, participant: string): CallTimingEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== CALL_TIMING_PROTOCOL ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n !v.utterance_id.length ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.generation) ||\n Number(v.generation) < 0 ||\n typeof v.event !== 'string' ||\n !EVENTS.has(v.event) ||\n typeof v.server_epoch_ms !== 'number' ||\n !Number.isFinite(v.server_epoch_ms) ||\n typeof v.server_monotonic_ms !== 'number' ||\n !Number.isFinite(v.server_monotonic_ms)\n )\n throw new Error('Invalid call timing')\n return v as unknown as CallTimingEnvelope\n}\n\n/** Publication can be deferred/coalesced; server timestamps must survive that transport delay. */\nexport function checkedCallTimings(value: unknown, participant: string): CallTimingEnvelope[] {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (!('events' in v)) return [checkedCallTiming(v, participant)]\n if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)\n throw new Error('Invalid call timing batch')\n return v.events.map((event: unknown) => {\n if (!event || typeof event !== 'object') throw new Error('Invalid call timing event')\n const e = event as Record<string, unknown>\n return checkedCallTiming(\n {\n protocol: v.protocol,\n participant: v.participant,\n utterance_id: v.utterance_id,\n generation: v.generation,\n event: e.event,\n server_epoch_ms: e.server_epoch_ms,\n server_monotonic_ms: e.server_monotonic_ms,\n },\n participant\n )\n })\n}\n"],
5
+ "mappings": "AACO,MAAM,uBAAuB;AACpC,MAAM,SAAS,oBAAI,IAAI;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAwBM,SAAS,kBAAkB,OAAgB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
@@ -973,14 +973,20 @@ function checkedCallMedia(value, participant) {
973
973
  return v;
974
974
  }
975
975
  var CallMediaPlayer = class {
976
- constructor(context, changed) {
976
+ constructor(context, changed, measured = () => void 0) {
977
977
  this.context = context;
978
978
  this.changed = changed;
979
+ this.measured = measured;
979
980
  this.recording = context.createMediaStreamDestination();
980
981
  }
981
982
  context;
982
983
  changed;
983
- active = false;
984
+ measured;
985
+ streaming = false;
986
+ audible = false;
987
+ get active() {
988
+ return this.audible;
989
+ }
984
990
  /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */
985
991
  suppressesTrack = false;
986
992
  avatar = "";
@@ -993,8 +999,13 @@ var CallMediaPlayer = class {
993
999
  sources = /* @__PURE__ */ new Set();
994
1000
  seen = /* @__PURE__ */ new Set();
995
1001
  finishTimer;
1002
+ measurements = [];
1003
+ renderedMouth = false;
1004
+ mouthRest;
1005
+ scheduledNonzeroPcm = false;
1006
+ scheduledPcm = false;
996
1007
  recording;
997
- push(message) {
1008
+ push(message, receivedAt = performance.now()) {
998
1009
  if (message.type === "fallback" && message.sequence === 0 && message.utterance_id !== this.utterance) {
999
1010
  if (this.seen.has(message.utterance_id)) return;
1000
1011
  this.utterance = message.utterance_id;
@@ -1015,8 +1026,13 @@ var CallMediaPlayer = class {
1015
1026
  this.sequence = 0;
1016
1027
  this.nextSample = 0;
1017
1028
  this.nextTime = this.context.currentTime + 0.15;
1018
- this.active = true;
1029
+ this.streaming = true;
1030
+ this.renderedMouth = false;
1031
+ this.mouthRest = void 0;
1032
+ this.scheduledNonzeroPcm = false;
1033
+ this.scheduledPcm = false;
1019
1034
  this.suppressesTrack = true;
1035
+ this.measure({ event: "utterance_start_received", client_performance_ms: receivedAt });
1020
1036
  this.changed();
1021
1037
  return;
1022
1038
  }
@@ -1024,7 +1040,7 @@ var CallMediaPlayer = class {
1024
1040
  if (message.sequence !== this.sequence + 1) throw new Error("Call media sequence gap");
1025
1041
  this.sequence = message.sequence;
1026
1042
  if (message.type === "media") {
1027
- if (!this.active || message.start_sample !== this.nextSample)
1043
+ if (!this.streaming || message.start_sample !== this.nextSample)
1028
1044
  throw new Error("Call media sample gap");
1029
1045
  const pcm = client.base64ToBytes(message.pcm);
1030
1046
  if (pcm.length % 2 || pcm.length > message.frames.length * 800)
@@ -1043,15 +1059,53 @@ var CallMediaPlayer = class {
1043
1059
  source.onended = () => {
1044
1060
  source.disconnect();
1045
1061
  this.sources.delete(source);
1062
+ if (!this.sources.size) this.setAudible(false);
1046
1063
  };
1047
1064
  source.start(at);
1048
- this.segments.push({ at, duration: buffer.duration, frames: message.frames });
1065
+ this.setAudible(true);
1066
+ if (!this.scheduledPcm) {
1067
+ this.scheduledPcm = true;
1068
+ this.measure({
1069
+ event: "first_media_received",
1070
+ client_performance_ms: receivedAt,
1071
+ source_sample: message.start_sample
1072
+ });
1073
+ this.measure({
1074
+ event: "first_pcm_scheduled",
1075
+ audio_context_seconds: at,
1076
+ source_sample: message.start_sample
1077
+ });
1078
+ }
1079
+ if (!this.scheduledNonzeroPcm) {
1080
+ const first = values.findIndex((value) => Math.abs(value) > 1 / 32768);
1081
+ if (first >= 0) {
1082
+ this.scheduledNonzeroPcm = true;
1083
+ this.measure({
1084
+ event: "first_nonzero_pcm_scheduled",
1085
+ audio_context_seconds: at + first / 24e3,
1086
+ estimated_output_performance_ms: this.outputTime(at + first / 24e3),
1087
+ source_sample: message.start_sample + first
1088
+ });
1089
+ }
1090
+ }
1091
+ this.segments.push({
1092
+ at,
1093
+ startSample: message.start_sample,
1094
+ duration: buffer.duration,
1095
+ frames: message.frames
1096
+ });
1049
1097
  this.segments = this.segments.filter(
1050
1098
  (s) => s.at + s.duration > this.context.currentTime - 0.1
1051
1099
  );
1052
1100
  this.nextTime = at + buffer.duration;
1053
1101
  this.nextSample += values.length;
1054
1102
  } else if (message.type === "end") {
1103
+ this.measure({
1104
+ event: "utterance_end_received",
1105
+ client_performance_ms: receivedAt,
1106
+ source_sample: this.nextSample
1107
+ });
1108
+ this.streaming = false;
1055
1109
  this.finishTimer = setTimeout(
1056
1110
  () => this.reset(),
1057
1111
  Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
@@ -1069,6 +1123,61 @@ var CallMediaPlayer = class {
1069
1123
  const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
1070
1124
  return a.map((value, j) => value + (b[j] - value) * (frame - i));
1071
1125
  }
1126
+ /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */
1127
+ reportMouthRenderSubmitted(controls) {
1128
+ if (this.renderedMouth) return;
1129
+ const now = this.context.currentTime;
1130
+ const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
1131
+ if (!segment) return;
1132
+ const mouth = Object.fromEntries(
1133
+ Object.entries(controls).filter(
1134
+ ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)
1135
+ )
1136
+ );
1137
+ if (!this.mouthRest) {
1138
+ this.mouthRest = mouth;
1139
+ return;
1140
+ }
1141
+ const delta = Math.max(
1142
+ 0,
1143
+ ...Object.entries(mouth).map(
1144
+ ([name, value]) => Math.abs(value - (this.mouthRest[name] ?? value))
1145
+ )
1146
+ );
1147
+ if (delta < 0.02) return;
1148
+ this.renderedMouth = true;
1149
+ this.measure({
1150
+ event: "first_mouth_render_submitted",
1151
+ audio_context_seconds: now,
1152
+ source_sample: segment.startSample + Math.floor((now - segment.at) * 24e3),
1153
+ mouth_delta: delta,
1154
+ mouth_delta_threshold: 0.02
1155
+ });
1156
+ }
1157
+ timing(event, receivedAt = performance.now(), batchSize = 1) {
1158
+ this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize });
1159
+ }
1160
+ measure(value) {
1161
+ const entry = {
1162
+ utterance_id: this.utterance,
1163
+ client_performance_ms: performance.now(),
1164
+ ...value
1165
+ };
1166
+ this.measurements.push(entry);
1167
+ if (this.measurements.length > 256) this.measurements.shift();
1168
+ this.measured(entry);
1169
+ }
1170
+ outputTime(at) {
1171
+ const stamp = this.context.getOutputTimestamp?.();
1172
+ if (stamp?.contextTime !== void 0 && stamp.performanceTime !== void 0 && stamp.performanceTime > 0)
1173
+ return stamp.performanceTime + (at - stamp.contextTime) * 1e3;
1174
+ return performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1e3;
1175
+ }
1176
+ setAudible(value) {
1177
+ if (this.audible === value) return;
1178
+ this.audible = value;
1179
+ this.changed();
1180
+ }
1072
1181
  reset(releaseTrack = false) {
1073
1182
  clearTimeout(this.finishTimer);
1074
1183
  for (const source of this.sources) {
@@ -1077,12 +1186,58 @@ var CallMediaPlayer = class {
1077
1186
  }
1078
1187
  this.sources.clear();
1079
1188
  this.segments = [];
1080
- this.active = false;
1189
+ this.streaming = false;
1190
+ this.setAudible(false);
1081
1191
  if (releaseTrack) this.suppressesTrack = false;
1082
1192
  this.changed();
1083
1193
  }
1084
1194
  };
1085
1195
 
1196
+ // src/calls/livekit/call-timing.ts
1197
+ var CALL_TIMING_PROTOCOL = "arbi.call.timing.v1";
1198
+ var EVENTS = /* @__PURE__ */ new Set([
1199
+ "speech_end",
1200
+ "transcription_started",
1201
+ "transcription_completed",
1202
+ "agent_started",
1203
+ "first_answer_text",
1204
+ "first_tts_request",
1205
+ "first_pcm",
1206
+ "first_pose",
1207
+ "animation_connect_started",
1208
+ "animation_ready"
1209
+ ]);
1210
+ function checkedCallTiming(value, participant) {
1211
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
1212
+ const v = value;
1213
+ if (v.protocol !== CALL_TIMING_PROTOCOL || v.participant !== participant || typeof v.utterance_id !== "string" || !v.utterance_id.length || v.utterance_id.length > 64 || !Number.isSafeInteger(v.generation) || Number(v.generation) < 0 || typeof v.event !== "string" || !EVENTS.has(v.event) || typeof v.server_epoch_ms !== "number" || !Number.isFinite(v.server_epoch_ms) || typeof v.server_monotonic_ms !== "number" || !Number.isFinite(v.server_monotonic_ms))
1214
+ throw new Error("Invalid call timing");
1215
+ return v;
1216
+ }
1217
+ function checkedCallTimings(value, participant) {
1218
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
1219
+ const v = value;
1220
+ if (!("events" in v)) return [checkedCallTiming(v, participant)];
1221
+ if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)
1222
+ throw new Error("Invalid call timing batch");
1223
+ return v.events.map((event) => {
1224
+ if (!event || typeof event !== "object") throw new Error("Invalid call timing event");
1225
+ const e = event;
1226
+ return checkedCallTiming(
1227
+ {
1228
+ protocol: v.protocol,
1229
+ participant: v.participant,
1230
+ utterance_id: v.utterance_id,
1231
+ generation: v.generation,
1232
+ event: e.event,
1233
+ server_epoch_ms: e.server_epoch_ms,
1234
+ server_monotonic_ms: e.server_monotonic_ms
1235
+ },
1236
+ participant
1237
+ );
1238
+ });
1239
+ }
1240
+
1086
1241
  // src/calls/livekit/useCallMedia.ts
1087
1242
  function useCallMedia(enabled, key) {
1088
1243
  const room = componentsReact.useRoomContext();
@@ -1102,24 +1257,38 @@ function useCallMedia(enabled, key) {
1102
1257
  if (!disposed) setPlayers(new Map(live));
1103
1258
  };
1104
1259
  const received = (bytes, from, _kind, topic) => {
1105
- if (topic !== client.CALL_MEDIA_PROTOCOL || !from || from.attributes["arbi.call_assistant"] !== "true")
1260
+ if (topic !== client.CALL_MEDIA_PROTOCOL && topic !== CALL_TIMING_PROTOCOL || !from || from.attributes["arbi.call_assistant"] !== "true")
1106
1261
  return;
1262
+ const receivedAt = performance.now();
1107
1263
  const identity = from.identity;
1108
1264
  const chain = chains.get(identity) ?? Promise.resolve();
1109
1265
  chains.set(
1110
1266
  identity,
1111
1267
  chain.then(async () => {
1112
1268
  if (disposed) return;
1113
- const message = checkedCallMedia(await client.decryptCallMedia(bytes, key), identity);
1269
+ const plaintext = await client.decryptCallMedia(bytes, key);
1114
1270
  let player = live.get(identity);
1115
1271
  if (!player) {
1116
- player = new CallMediaPlayer(context, changed);
1272
+ player = new CallMediaPlayer(context, changed, (measurement) => {
1273
+ window.dispatchEvent(
1274
+ new CustomEvent("arbi:call-timing", {
1275
+ detail: { participant: identity, ...measurement }
1276
+ })
1277
+ );
1278
+ });
1117
1279
  live.set(identity, player);
1118
1280
  }
1281
+ if (topic === CALL_TIMING_PROTOCOL) {
1282
+ const events = checkedCallTimings(plaintext, identity);
1283
+ for (const event of events) player.timing(event, receivedAt, events.length);
1284
+ return;
1285
+ }
1286
+ const message = checkedCallMedia(plaintext, identity);
1119
1287
  if (context.state !== "running") await context.resume();
1120
1288
  if (context.state !== "running") throw new Error("Call audio is unavailable");
1121
- player.push(message);
1289
+ player.push(message, receivedAt);
1122
1290
  }).catch(() => {
1291
+ if (topic === CALL_TIMING_PROTOCOL) return;
1123
1292
  live.get(identity)?.reset(true);
1124
1293
  void room.localParticipant.setAttributes({ "arbi.call_media": "" }).catch(() => void 0);
1125
1294
  })
@@ -1154,6 +1323,7 @@ function useCallMedia(enabled, key) {
1154
1323
  return players;
1155
1324
  }
1156
1325
 
1326
+ exports.CALL_TIMING_PROTOCOL = CALL_TIMING_PROTOCOL;
1157
1327
  exports.CallMediaPlayer = CallMediaPlayer;
1158
1328
  exports.DEMOTE_REJOIN_FALLBACK_MS = DEMOTE_REJOIN_FALLBACK_MS;
1159
1329
  exports.FINAL_SEGMENT_GRACE_MS = FINAL_SEGMENT_GRACE_MS;