@arbidocs/react 0.5.179 → 0.5.181

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.
@@ -8,8 +8,8 @@ var chunk5QOZLKAY_cjs = require('../chunk-5QOZLKAY.cjs');
8
8
  require('../chunk-N73IMVFF.cjs');
9
9
  var chunkDQODLWFX_cjs = require('../chunk-DQODLWFX.cjs');
10
10
  require('../chunk-5NOZDH3F.cjs');
11
- var chunkVOFNX4P6_cjs = require('../chunk-VOFNX4P6.cjs');
12
11
  require('../chunk-S6A6FSG7.cjs');
12
+ var chunkVOFNX4P6_cjs = require('../chunk-VOFNX4P6.cjs');
13
13
  var react = require('react');
14
14
  var reactQuery = require('@tanstack/react-query');
15
15
  var jsxRuntime = require('react/jsx-runtime');
@@ -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)
@@ -77,6 +93,13 @@ class CallMediaPlayer {
77
93
  const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
78
94
  for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768;
79
95
  const at = Math.max(this.nextTime, this.context.currentTime + 0.02);
96
+ if (this.scheduledPcm && at > this.nextTime + 1 / 24e3)
97
+ this.measure({
98
+ event: "playback_underrun",
99
+ audio_context_seconds: at,
100
+ source_sample: message.start_sample,
101
+ playback_gap_ms: (at - this.nextTime) * 1e3
102
+ });
80
103
  const source = this.context.createBufferSource();
81
104
  source.buffer = buffer;
82
105
  source.connect(this.context.destination);
@@ -85,15 +108,53 @@ class CallMediaPlayer {
85
108
  source.onended = () => {
86
109
  source.disconnect();
87
110
  this.sources.delete(source);
111
+ if (!this.sources.size) this.setAudible(false);
88
112
  };
89
113
  source.start(at);
90
- this.segments.push({ at, duration: buffer.duration, frames: message.frames });
114
+ this.setAudible(true);
115
+ if (!this.scheduledPcm) {
116
+ this.scheduledPcm = true;
117
+ this.measure({
118
+ event: "first_media_received",
119
+ client_performance_ms: receivedAt,
120
+ source_sample: message.start_sample
121
+ });
122
+ this.measure({
123
+ event: "first_pcm_scheduled",
124
+ audio_context_seconds: at,
125
+ source_sample: message.start_sample
126
+ });
127
+ }
128
+ if (!this.scheduledNonzeroPcm) {
129
+ const first = values.findIndex((value) => Math.abs(value) > 1 / 32768);
130
+ if (first >= 0) {
131
+ this.scheduledNonzeroPcm = true;
132
+ this.measure({
133
+ event: "first_nonzero_pcm_scheduled",
134
+ audio_context_seconds: at + first / 24e3,
135
+ estimated_output_performance_ms: this.outputTime(at + first / 24e3),
136
+ source_sample: message.start_sample + first
137
+ });
138
+ }
139
+ }
140
+ this.segments.push({
141
+ at,
142
+ startSample: message.start_sample,
143
+ duration: buffer.duration,
144
+ frames: message.frames
145
+ });
91
146
  this.segments = this.segments.filter(
92
147
  (s) => s.at + s.duration > this.context.currentTime - 0.1
93
148
  );
94
149
  this.nextTime = at + buffer.duration;
95
150
  this.nextSample += values.length;
96
151
  } else if (message.type === "end") {
152
+ this.measure({
153
+ event: "utterance_end_received",
154
+ client_performance_ms: receivedAt,
155
+ source_sample: this.nextSample
156
+ });
157
+ this.streaming = false;
97
158
  this.finishTimer = setTimeout(
98
159
  () => this.reset(),
99
160
  Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
@@ -111,6 +172,61 @@ class CallMediaPlayer {
111
172
  const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
112
173
  return a.map((value, j) => value + (b[j] - value) * (frame - i));
113
174
  }
175
+ /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */
176
+ reportMouthRenderSubmitted(controls) {
177
+ if (this.renderedMouth) return;
178
+ const now = this.context.currentTime;
179
+ const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
180
+ if (!segment) return;
181
+ const mouth = Object.fromEntries(
182
+ Object.entries(controls).filter(
183
+ ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)
184
+ )
185
+ );
186
+ if (!this.mouthRest) {
187
+ this.mouthRest = mouth;
188
+ return;
189
+ }
190
+ const delta = Math.max(
191
+ 0,
192
+ ...Object.entries(mouth).map(
193
+ ([name, value]) => Math.abs(value - (this.mouthRest[name] ?? value))
194
+ )
195
+ );
196
+ if (delta < 0.02) return;
197
+ this.renderedMouth = true;
198
+ this.measure({
199
+ event: "first_mouth_render_submitted",
200
+ audio_context_seconds: now,
201
+ source_sample: segment.startSample + Math.floor((now - segment.at) * 24e3),
202
+ mouth_delta: delta,
203
+ mouth_delta_threshold: 0.02
204
+ });
205
+ }
206
+ timing(event, receivedAt = performance.now(), batchSize = 1) {
207
+ this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize });
208
+ }
209
+ measure(value) {
210
+ const entry = {
211
+ utterance_id: this.utterance,
212
+ client_performance_ms: performance.now(),
213
+ ...value
214
+ };
215
+ this.measurements.push(entry);
216
+ if (this.measurements.length > 256) this.measurements.shift();
217
+ this.measured(entry);
218
+ }
219
+ outputTime(at) {
220
+ const stamp = this.context.getOutputTimestamp?.();
221
+ if (stamp?.contextTime !== void 0 && stamp.performanceTime !== void 0 && stamp.performanceTime > 0)
222
+ return stamp.performanceTime + (at - stamp.contextTime) * 1e3;
223
+ return performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1e3;
224
+ }
225
+ setAudible(value) {
226
+ if (this.audible === value) return;
227
+ this.audible = value;
228
+ this.changed();
229
+ }
114
230
  reset(releaseTrack = false) {
115
231
  clearTimeout(this.finishTimer);
116
232
  for (const source of this.sources) {
@@ -119,7 +235,8 @@ class CallMediaPlayer {
119
235
  }
120
236
  this.sources.clear();
121
237
  this.segments = [];
122
- this.active = false;
238
+ this.streaming = false;
239
+ this.setAudible(false);
123
240
  if (releaseTrack) this.suppressesTrack = false;
124
241
  this.changed();
125
242
  }
@@ -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.changed()\n }\n}\n"],
5
- "mappings": "AACA,SAAS,qBAAqB;AAiBvB,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,y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,QAAQ;AACzB,UAAM,UAAU,KAAK,SAAS,KAAK,CAAC,MAAM,OAAO,EAAE,MAAM,MAAM,EAAE,KAAK,EAAE,QAAQ;AAChF,QAAI,CAAC,QAAS,QAAO;AACrB,UAAM,SAAS,MAAM,QAAQ,MAAM;AACnC,UAAM,IAAI,KAAK,IAAI,KAAK,MAAM,KAAK,GAAG,QAAQ,OAAO,SAAS,CAAC;AAC/D,UAAM,IAAI,QAAQ,OAAO,CAAC,GACxB,IAAI,QAAQ,OAAO,KAAK,IAAI,IAAI,GAAG,QAAQ,OAAO,SAAS,CAAC,CAAC;AAC/D,WAAO,EAAE,IAAI,CAAC,OAAO,MAAM,SAAS,EAAE,CAAC,IAAI,UAAU,QAAQ,EAAE;AAAA,EACjE;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,SAAS;AACd,QAAI,aAAc,MAAK,kBAAkB;AACzC,SAAK,QAAQ;AAAA,EACf;AACF;",
4
+ "sourcesContent": ["/** A single PCM clock drives both audible speech and timestamped animation controls. */\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 if (this.scheduledPcm && at > this.nextTime + 1 / 24000)\n this.measure({\n event: 'playback_underrun',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n playback_gap_ms: (at - this.nextTime) * 1000,\n })\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\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AM,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 playback_gap_ms?: 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;AAyBM,SAAS,kBAAkB,OAAgB,aAAyC;AACzF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,qBAAqB;AAC9E,QAAM,IAAI;AACV,MACE,EAAE,aA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DQODLWFX.cjs');
10
10
  require('../../chunk-5NOZDH3F.cjs');
11
- require('../../chunk-VOFNX4P6.cjs');
12
11
  require('../../chunk-S6A6FSG7.cjs');
12
+ require('../../chunk-VOFNX4P6.cjs');
13
13
  var react = require('react');
14
14
  var livekitClient = require('livekit-client');
15
15
  var componentsReact = require('@livekit/components-react');
@@ -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)
@@ -1035,6 +1051,13 @@ var CallMediaPlayer = class {
1035
1051
  const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
1036
1052
  for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768;
1037
1053
  const at = Math.max(this.nextTime, this.context.currentTime + 0.02);
1054
+ if (this.scheduledPcm && at > this.nextTime + 1 / 24e3)
1055
+ this.measure({
1056
+ event: "playback_underrun",
1057
+ audio_context_seconds: at,
1058
+ source_sample: message.start_sample,
1059
+ playback_gap_ms: (at - this.nextTime) * 1e3
1060
+ });
1038
1061
  const source = this.context.createBufferSource();
1039
1062
  source.buffer = buffer;
1040
1063
  source.connect(this.context.destination);
@@ -1043,15 +1066,53 @@ var CallMediaPlayer = class {
1043
1066
  source.onended = () => {
1044
1067
  source.disconnect();
1045
1068
  this.sources.delete(source);
1069
+ if (!this.sources.size) this.setAudible(false);
1046
1070
  };
1047
1071
  source.start(at);
1048
- this.segments.push({ at, duration: buffer.duration, frames: message.frames });
1072
+ this.setAudible(true);
1073
+ if (!this.scheduledPcm) {
1074
+ this.scheduledPcm = true;
1075
+ this.measure({
1076
+ event: "first_media_received",
1077
+ client_performance_ms: receivedAt,
1078
+ source_sample: message.start_sample
1079
+ });
1080
+ this.measure({
1081
+ event: "first_pcm_scheduled",
1082
+ audio_context_seconds: at,
1083
+ source_sample: message.start_sample
1084
+ });
1085
+ }
1086
+ if (!this.scheduledNonzeroPcm) {
1087
+ const first = values.findIndex((value) => Math.abs(value) > 1 / 32768);
1088
+ if (first >= 0) {
1089
+ this.scheduledNonzeroPcm = true;
1090
+ this.measure({
1091
+ event: "first_nonzero_pcm_scheduled",
1092
+ audio_context_seconds: at + first / 24e3,
1093
+ estimated_output_performance_ms: this.outputTime(at + first / 24e3),
1094
+ source_sample: message.start_sample + first
1095
+ });
1096
+ }
1097
+ }
1098
+ this.segments.push({
1099
+ at,
1100
+ startSample: message.start_sample,
1101
+ duration: buffer.duration,
1102
+ frames: message.frames
1103
+ });
1049
1104
  this.segments = this.segments.filter(
1050
1105
  (s) => s.at + s.duration > this.context.currentTime - 0.1
1051
1106
  );
1052
1107
  this.nextTime = at + buffer.duration;
1053
1108
  this.nextSample += values.length;
1054
1109
  } else if (message.type === "end") {
1110
+ this.measure({
1111
+ event: "utterance_end_received",
1112
+ client_performance_ms: receivedAt,
1113
+ source_sample: this.nextSample
1114
+ });
1115
+ this.streaming = false;
1055
1116
  this.finishTimer = setTimeout(
1056
1117
  () => this.reset(),
1057
1118
  Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
@@ -1069,6 +1130,61 @@ var CallMediaPlayer = class {
1069
1130
  const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
1070
1131
  return a.map((value, j) => value + (b[j] - value) * (frame - i));
1071
1132
  }
1133
+ /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */
1134
+ reportMouthRenderSubmitted(controls) {
1135
+ if (this.renderedMouth) return;
1136
+ const now = this.context.currentTime;
1137
+ const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
1138
+ if (!segment) return;
1139
+ const mouth = Object.fromEntries(
1140
+ Object.entries(controls).filter(
1141
+ ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)
1142
+ )
1143
+ );
1144
+ if (!this.mouthRest) {
1145
+ this.mouthRest = mouth;
1146
+ return;
1147
+ }
1148
+ const delta = Math.max(
1149
+ 0,
1150
+ ...Object.entries(mouth).map(
1151
+ ([name, value]) => Math.abs(value - (this.mouthRest[name] ?? value))
1152
+ )
1153
+ );
1154
+ if (delta < 0.02) return;
1155
+ this.renderedMouth = true;
1156
+ this.measure({
1157
+ event: "first_mouth_render_submitted",
1158
+ audio_context_seconds: now,
1159
+ source_sample: segment.startSample + Math.floor((now - segment.at) * 24e3),
1160
+ mouth_delta: delta,
1161
+ mouth_delta_threshold: 0.02
1162
+ });
1163
+ }
1164
+ timing(event, receivedAt = performance.now(), batchSize = 1) {
1165
+ this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize });
1166
+ }
1167
+ measure(value) {
1168
+ const entry = {
1169
+ utterance_id: this.utterance,
1170
+ client_performance_ms: performance.now(),
1171
+ ...value
1172
+ };
1173
+ this.measurements.push(entry);
1174
+ if (this.measurements.length > 256) this.measurements.shift();
1175
+ this.measured(entry);
1176
+ }
1177
+ outputTime(at) {
1178
+ const stamp = this.context.getOutputTimestamp?.();
1179
+ if (stamp?.contextTime !== void 0 && stamp.performanceTime !== void 0 && stamp.performanceTime > 0)
1180
+ return stamp.performanceTime + (at - stamp.contextTime) * 1e3;
1181
+ return performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1e3;
1182
+ }
1183
+ setAudible(value) {
1184
+ if (this.audible === value) return;
1185
+ this.audible = value;
1186
+ this.changed();
1187
+ }
1072
1188
  reset(releaseTrack = false) {
1073
1189
  clearTimeout(this.finishTimer);
1074
1190
  for (const source of this.sources) {
@@ -1077,12 +1193,58 @@ var CallMediaPlayer = class {
1077
1193
  }
1078
1194
  this.sources.clear();
1079
1195
  this.segments = [];
1080
- this.active = false;
1196
+ this.streaming = false;
1197
+ this.setAudible(false);
1081
1198
  if (releaseTrack) this.suppressesTrack = false;
1082
1199
  this.changed();
1083
1200
  }
1084
1201
  };
1085
1202
 
1203
+ // src/calls/livekit/call-timing.ts
1204
+ var CALL_TIMING_PROTOCOL = "arbi.call.timing.v1";
1205
+ var EVENTS = /* @__PURE__ */ new Set([
1206
+ "speech_end",
1207
+ "transcription_started",
1208
+ "transcription_completed",
1209
+ "agent_started",
1210
+ "first_answer_text",
1211
+ "first_tts_request",
1212
+ "first_pcm",
1213
+ "first_pose",
1214
+ "animation_connect_started",
1215
+ "animation_ready"
1216
+ ]);
1217
+ function checkedCallTiming(value, participant) {
1218
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
1219
+ const v = value;
1220
+ 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))
1221
+ throw new Error("Invalid call timing");
1222
+ return v;
1223
+ }
1224
+ function checkedCallTimings(value, participant) {
1225
+ if (!value || typeof value !== "object") throw new Error("Invalid call timing");
1226
+ const v = value;
1227
+ if (!("events" in v)) return [checkedCallTiming(v, participant)];
1228
+ if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)
1229
+ throw new Error("Invalid call timing batch");
1230
+ return v.events.map((event) => {
1231
+ if (!event || typeof event !== "object") throw new Error("Invalid call timing event");
1232
+ const e = event;
1233
+ return checkedCallTiming(
1234
+ {
1235
+ protocol: v.protocol,
1236
+ participant: v.participant,
1237
+ utterance_id: v.utterance_id,
1238
+ generation: v.generation,
1239
+ event: e.event,
1240
+ server_epoch_ms: e.server_epoch_ms,
1241
+ server_monotonic_ms: e.server_monotonic_ms
1242
+ },
1243
+ participant
1244
+ );
1245
+ });
1246
+ }
1247
+
1086
1248
  // src/calls/livekit/useCallMedia.ts
1087
1249
  function useCallMedia(enabled, key) {
1088
1250
  const room = componentsReact.useRoomContext();
@@ -1102,24 +1264,38 @@ function useCallMedia(enabled, key) {
1102
1264
  if (!disposed) setPlayers(new Map(live));
1103
1265
  };
1104
1266
  const received = (bytes, from, _kind, topic) => {
1105
- if (topic !== client.CALL_MEDIA_PROTOCOL || !from || from.attributes["arbi.call_assistant"] !== "true")
1267
+ if (topic !== client.CALL_MEDIA_PROTOCOL && topic !== CALL_TIMING_PROTOCOL || !from || from.attributes["arbi.call_assistant"] !== "true")
1106
1268
  return;
1269
+ const receivedAt = performance.now();
1107
1270
  const identity = from.identity;
1108
1271
  const chain = chains.get(identity) ?? Promise.resolve();
1109
1272
  chains.set(
1110
1273
  identity,
1111
1274
  chain.then(async () => {
1112
1275
  if (disposed) return;
1113
- const message = checkedCallMedia(await client.decryptCallMedia(bytes, key), identity);
1276
+ const plaintext = await client.decryptCallMedia(bytes, key);
1114
1277
  let player = live.get(identity);
1115
1278
  if (!player) {
1116
- player = new CallMediaPlayer(context, changed);
1279
+ player = new CallMediaPlayer(context, changed, (measurement) => {
1280
+ window.dispatchEvent(
1281
+ new CustomEvent("arbi:call-timing", {
1282
+ detail: { participant: identity, ...measurement }
1283
+ })
1284
+ );
1285
+ });
1117
1286
  live.set(identity, player);
1118
1287
  }
1288
+ if (topic === CALL_TIMING_PROTOCOL) {
1289
+ const events = checkedCallTimings(plaintext, identity);
1290
+ for (const event of events) player.timing(event, receivedAt, events.length);
1291
+ return;
1292
+ }
1293
+ const message = checkedCallMedia(plaintext, identity);
1119
1294
  if (context.state !== "running") await context.resume();
1120
1295
  if (context.state !== "running") throw new Error("Call audio is unavailable");
1121
- player.push(message);
1296
+ player.push(message, receivedAt);
1122
1297
  }).catch(() => {
1298
+ if (topic === CALL_TIMING_PROTOCOL) return;
1123
1299
  live.get(identity)?.reset(true);
1124
1300
  void room.localParticipant.setAttributes({ "arbi.call_media": "" }).catch(() => void 0);
1125
1301
  })
@@ -1154,6 +1330,7 @@ function useCallMedia(enabled, key) {
1154
1330
  return players;
1155
1331
  }
1156
1332
 
1333
+ exports.CALL_TIMING_PROTOCOL = CALL_TIMING_PROTOCOL;
1157
1334
  exports.CallMediaPlayer = CallMediaPlayer;
1158
1335
  exports.DEMOTE_REJOIN_FALLBACK_MS = DEMOTE_REJOIN_FALLBACK_MS;
1159
1336
  exports.FINAL_SEGMENT_GRACE_MS = FINAL_SEGMENT_GRACE_MS;