@arbidocs/react 0.5.176 → 0.5.178

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkC5O4BH7B_cjs = require('../../chunk-C5O4BH7B.cjs');
3
+ var chunkVCYRQZ3R_cjs = require('../../chunk-VCYRQZ3R.cjs');
4
4
  require('../../chunk-EEIYXVM4.cjs');
5
5
  require('../../chunk-NBES77PB.cjs');
6
6
  var chunk5QOZLKAY_cjs = require('../../chunk-5QOZLKAY.cjs');
@@ -15,6 +15,7 @@ var livekitClient = require('livekit-client');
15
15
  var componentsReact = require('@livekit/components-react');
16
16
  var reactQuery = require('@tanstack/react-query');
17
17
  var browser = require('@arbidocs/sdk/browser');
18
+ var client = require('@arbidocs/client');
18
19
 
19
20
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
20
21
  function createE2EEWorker() {
@@ -123,8 +124,8 @@ function useCallTranscriber({
123
124
  const arbi = chunk5QOZLKAY_cjs.useArbi();
124
125
  const queryClient = reactQuery.useQueryClient();
125
126
  const profile = arbi.isLoggedIn ? arbi.user.profile() : null;
126
- const myProfileName = profile && chunkC5O4BH7B_cjs.toProfileView(profile).fullName || null;
127
- const deploymentAvailable = chunkC5O4BH7B_cjs.useCallTranscriptionAvailable();
127
+ const myProfileName = profile && chunkVCYRQZ3R_cjs.toProfileView(profile).fullName || null;
128
+ const deploymentAvailable = chunkVCYRQZ3R_cjs.useCallTranscriptionAvailable();
128
129
  const available = deploymentAvailable && !!callKey;
129
130
  const [state, setState] = react.useState(null);
130
131
  const [creatorExtId, setCreatorExtId] = react.useState(null);
@@ -167,7 +168,7 @@ function useCallTranscriber({
167
168
  };
168
169
  }, [available, callExtId]);
169
170
  react.useEffect(
170
- () => chunkC5O4BH7B_cjs.onCallEvent("call.transcription", (message) => {
171
+ () => chunkVCYRQZ3R_cjs.onCallEvent("call.transcription", (message) => {
171
172
  if (message.call_ext_id === callExtId) applyState(message);
172
173
  }),
173
174
  [callExtId, applyState]
@@ -183,7 +184,7 @@ function useCallTranscriber({
183
184
  const persist = react.useCallback(
184
185
  (segment, speakerNeedsProxy) => {
185
186
  if (!callKey || persisted.current.has(segment.segmentId)) return;
186
- const role = chunkC5O4BH7B_cjs.transcriptPersistRole({
187
+ const role = chunkVCYRQZ3R_cjs.transcriptPersistRole({
187
188
  myIdentity,
188
189
  canPost: canPost && (segment.speakerIdentity !== myIdentity || selfPosts.current),
189
190
  hasCallKey: true,
@@ -192,7 +193,7 @@ function useCallTranscriber({
192
193
  });
193
194
  if (!role) return;
194
195
  persisted.current.add(segment.segmentId);
195
- chunkC5O4BH7B_cjs.persistTranscriptSegment(arbi, queryClient, callExtId, callKey, segment).catch(
196
+ chunkVCYRQZ3R_cjs.persistTranscriptSegment(arbi, queryClient, callExtId, callKey, segment).catch(
196
197
  (err) => {
197
198
  persisted.current.delete(segment.segmentId);
198
199
  if (role === "own" && err?.status === 403) {
@@ -212,7 +213,7 @@ function useCallTranscriber({
212
213
  );
213
214
  react.useEffect(() => {
214
215
  const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
215
- if (topic === chunkC5O4BH7B_cjs.CALL_TRANSCRIPTION_TOPIC) {
216
+ if (topic === chunkVCYRQZ3R_cjs.CALL_TRANSCRIPTION_TOPIC) {
216
217
  if (participant || participantIdentity) return;
217
218
  try {
218
219
  const next = browser.calls.transcriptionStateFrom(JSON.parse(new TextDecoder().decode(payload)));
@@ -221,10 +222,10 @@ function useCallTranscriber({
221
222
  }
222
223
  return;
223
224
  }
224
- if (topic !== chunkC5O4BH7B_cjs.CALL_CAPTION_TOPIC || !callKey) return;
225
+ if (topic !== chunkVCYRQZ3R_cjs.CALL_CAPTION_TOPIC || !callKey) return;
225
226
  const identity = participant?.identity ?? participantIdentity;
226
227
  if (!identity || identity === myIdentity) return;
227
- void chunkC5O4BH7B_cjs.decodeCaptionPacket(payload, callKey).then((packet) => {
228
+ void chunkVCYRQZ3R_cjs.decodeCaptionPacket(payload, callKey).then((packet) => {
228
229
  if (!packet || packet.identity !== identity) return;
229
230
  const name = participant?.name || packet.name || identity;
230
231
  const t = Math.min(packet.t, Date.now());
@@ -264,7 +265,7 @@ function useCallTranscriber({
264
265
  })) {
265
266
  return;
266
267
  }
267
- const segmentId = chunkC5O4BH7B_cjs.newSegmentId();
268
+ const segmentId = chunkVCYRQZ3R_cjs.newSegmentId();
268
269
  const startedAt = new Date(segment.startedAt).toISOString();
269
270
  let text;
270
271
  try {
@@ -298,7 +299,7 @@ function useCallTranscriber({
298
299
  });
299
300
  try {
300
301
  await localParticipant.publishData(
301
- await chunkC5O4BH7B_cjs.encodeCaptionPacket(
302
+ await chunkVCYRQZ3R_cjs.encodeCaptionPacket(
302
303
  {
303
304
  v: 1,
304
305
  segment_id: segmentId,
@@ -310,7 +311,7 @@ function useCallTranscriber({
310
311
  },
311
312
  callKey
312
313
  ),
313
- { reliable: true, topic: chunkC5O4BH7B_cjs.CALL_CAPTION_TOPIC }
314
+ { reliable: true, topic: chunkVCYRQZ3R_cjs.CALL_CAPTION_TOPIC }
314
315
  );
315
316
  } catch (err) {
316
317
  console.warn("[calls] could not broadcast a caption", err);
@@ -425,14 +426,14 @@ function useCallRecorder({
425
426
  };
426
427
  }, [callExtId]);
427
428
  react.useEffect(
428
- () => chunkC5O4BH7B_cjs.onCallEvent("call.recording", (message) => {
429
+ () => chunkVCYRQZ3R_cjs.onCallEvent("call.recording", (message) => {
429
430
  if (message.call_ext_id === callExtId) applyState(message);
430
431
  }),
431
432
  [callExtId, applyState]
432
433
  );
433
434
  react.useEffect(() => {
434
435
  const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
435
- if (topic !== chunkC5O4BH7B_cjs.CALL_RECORDING_TOPIC) return;
436
+ if (topic !== chunkVCYRQZ3R_cjs.CALL_RECORDING_TOPIC) return;
436
437
  if (participant || participantIdentity) return;
437
438
  try {
438
439
  const next = browser.calls.recordingStateFrom(JSON.parse(new TextDecoder().decode(payload)));
@@ -453,7 +454,7 @@ function useCallRecorder({
453
454
  try {
454
455
  const row = call ?? await arbi.calls.get(callExtId);
455
456
  if (!row.workspace_locked && !row.chat_ext_id && callKey) {
456
- const ref = await chunkC5O4BH7B_cjs.ensureMeetingChat(arbi, queryClient, callExtId, callKey);
457
+ const ref = await chunkVCYRQZ3R_cjs.ensureMeetingChat(arbi, queryClient, callExtId, callKey);
457
458
  if (ref.kind === "chat") setCall({ ...row, chat_ext_id: ref.chatExtId });
458
459
  }
459
460
  const answer = await arbi.calls.recording.start(callExtId, mode);
@@ -555,7 +556,7 @@ function useTrackUploader(recording, callKey, kind, mimeType) {
555
556
  const queryClient = reactQuery.useQueryClient();
556
557
  return react.useMemo(() => {
557
558
  if (!shouldCapture || !recordingExtId || !call) return null;
558
- return chunkC5O4BH7B_cjs.trackUploaderFor({
559
+ return chunkVCYRQZ3R_cjs.trackUploaderFor({
559
560
  arbi,
560
561
  callExtId: call.external_id,
561
562
  recordingExtId,
@@ -563,7 +564,7 @@ function useTrackUploader(recording, callKey, kind, mimeType) {
563
564
  mimeType,
564
565
  recordingStartedAt: startedAt,
565
566
  linkVersion,
566
- conversationKey: () => chunkC5O4BH7B_cjs.conversationKeyForCall(arbi, queryClient, call, { callKey }),
567
+ conversationKey: () => chunkVCYRQZ3R_cjs.conversationKeyForCall(arbi, queryClient, call, { callKey }),
567
568
  // The server stopped the recording at the quota (its state event says so too).
568
569
  onStopped: () => markStopped()
569
570
  });
@@ -612,10 +613,10 @@ function useInCallChat({
612
613
  react.useEffect(() => {
613
614
  if (!callKey) return;
614
615
  const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
615
- if (topic !== chunkC5O4BH7B_cjs.CALL_CHAT_TOPIC) return;
616
+ if (topic !== chunkVCYRQZ3R_cjs.CALL_CHAT_TOPIC) return;
616
617
  const identity = participant?.identity ?? participantIdentity;
617
618
  if (!identity || identity === myIdentity) return;
618
- void chunkC5O4BH7B_cjs.decodeCallChatPacket(payload, callKey).then((packet) => {
619
+ void chunkVCYRQZ3R_cjs.decodeCallChatPacket(payload, callKey).then((packet) => {
619
620
  if (!packet) return;
620
621
  const key = `${identity}:${packet.id}`;
621
622
  if (seen.current.has(key)) return;
@@ -645,7 +646,7 @@ function useInCallChat({
645
646
  if (!open || !canRead || historyRequested.current) return;
646
647
  historyRequested.current = true;
647
648
  setHistoryLoading(true);
648
- chunkC5O4BH7B_cjs.loadMeetingHistory(arbi, queryClient, callExtId).then((result) => {
649
+ chunkVCYRQZ3R_cjs.loadMeetingHistory(arbi, queryClient, callExtId).then((result) => {
649
650
  if (!result) return;
650
651
  setMeetingChat(result.ref);
651
652
  setHistory(result.messages);
@@ -656,13 +657,13 @@ function useInCallChat({
656
657
  }, [open, canRead, callExtId]);
657
658
  const send = react.useCallback(
658
659
  async (raw) => {
659
- const text = raw.trim().slice(0, chunkC5O4BH7B_cjs.CALL_CHAT_MAX_CHARS);
660
+ const text = raw.trim().slice(0, chunkVCYRQZ3R_cjs.CALL_CHAT_MAX_CHARS);
660
661
  if (!text || !callKey || readOnly) return;
661
- const id = chunkC5O4BH7B_cjs.newPacketId();
662
+ const id = chunkVCYRQZ3R_cjs.newPacketId();
662
663
  const at = Date.now();
663
664
  await localParticipant.publishData(
664
- await chunkC5O4BH7B_cjs.encodeCallChatPacket({ v: 1, id, text, at }, callKey),
665
- { reliable: true, topic: chunkC5O4BH7B_cjs.CALL_CHAT_TOPIC }
665
+ await chunkVCYRQZ3R_cjs.encodeCallChatPacket({ v: 1, id, text, at }, callKey),
666
+ { reliable: true, topic: chunkVCYRQZ3R_cjs.CALL_CHAT_TOPIC }
666
667
  );
667
668
  setLive((prev) => [
668
669
  ...prev,
@@ -681,7 +682,7 @@ function useInCallChat({
681
682
  (prev) => prev.map((l) => l.id === id && l.senderIdentity === myIdentity ? { ...l, status } : l)
682
683
  );
683
684
  try {
684
- setMeetingChat(await chunkC5O4BH7B_cjs.persistMeetingMessage(arbi, queryClient, callExtId, callKey, text));
685
+ setMeetingChat(await chunkVCYRQZ3R_cjs.persistMeetingMessage(arbi, queryClient, callExtId, callKey, text));
685
686
  mark("saved");
686
687
  } catch (err) {
687
688
  console.warn("[calls] could not keep the message in the meeting chat", err);
@@ -693,7 +694,7 @@ function useInCallChat({
693
694
  const openMeeting = react.useCallback(async () => {
694
695
  if (!callKey) return;
695
696
  try {
696
- const ref = meetingChat ?? await chunkC5O4BH7B_cjs.ensureMeetingChat(arbi, queryClient, callExtId, callKey);
697
+ const ref = meetingChat ?? await chunkVCYRQZ3R_cjs.ensureMeetingChat(arbi, queryClient, callExtId, callKey);
697
698
  setMeetingChat(ref);
698
699
  openMeetingChat?.(ref);
699
700
  } catch (err) {
@@ -701,7 +702,7 @@ function useInCallChat({
701
702
  }
702
703
  }, [callExtId, callKey, meetingChat]);
703
704
  const lines = react.useMemo(
704
- () => chunkC5O4BH7B_cjs.mergeChatLines(history, live, {
705
+ () => chunkVCYRQZ3R_cjs.mergeChatLines(history, live, {
705
706
  myIdentity,
706
707
  nameOf: (identity) => identity === myIdentity ? localParticipant.name || "You" : room.remoteParticipants.get(identity)?.name || null
707
708
  }),
@@ -760,7 +761,7 @@ function useWebinar({
760
761
  const n = ++questionsRead.current;
761
762
  try {
762
763
  const rows = await webinarApi().questions.list(callExtId, linkVersion);
763
- const opened = await Promise.all(rows.map((q) => chunkC5O4BH7B_cjs.openQuestion(q, callKey)));
764
+ const opened = await Promise.all(rows.map((q) => chunkVCYRQZ3R_cjs.openQuestion(q, callKey)));
764
765
  if (n === questionsRead.current) setQuestions(opened);
765
766
  } catch (err) {
766
767
  console.warn("[calls] could not load the questions", err);
@@ -772,7 +773,7 @@ function useWebinar({
772
773
  }, [refresh, refreshQuestions]);
773
774
  react.useEffect(() => {
774
775
  if (!enabled) return;
775
- return chunkC5O4BH7B_cjs.onCallEvent("call.webinar", (m) => {
776
+ return chunkVCYRQZ3R_cjs.onCallEvent("call.webinar", (m) => {
776
777
  if (m.call_ext_id !== callExtId) return;
777
778
  setState((s) => s ? { ...s, live: m.live, chat: m.chat } : s);
778
779
  });
@@ -781,8 +782,8 @@ function useWebinar({
781
782
  react.useEffect(() => {
782
783
  if (!enabled) return;
783
784
  const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
784
- if (topic !== chunkC5O4BH7B_cjs.CALL_WEBINAR_TOPIC) return;
785
- const packet = chunkC5O4BH7B_cjs.parseWebinarPacket(payload, !!(participant || participantIdentity));
785
+ if (topic !== chunkVCYRQZ3R_cjs.CALL_WEBINAR_TOPIC) return;
786
+ const packet = chunkVCYRQZ3R_cjs.parseWebinarPacket(payload, !!(participant || participantIdentity));
786
787
  if (!packet) return;
787
788
  switch (packet.type) {
788
789
  case "state":
@@ -803,7 +804,7 @@ function useWebinar({
803
804
  return;
804
805
  case "demoted":
805
806
  setStageCheck(false);
806
- chunkC5O4BH7B_cjs.markRejoining(callExtId);
807
+ chunkVCYRQZ3R_cjs.markRejoining(callExtId);
807
808
  if (fallback.current) clearTimeout(fallback.current);
808
809
  fallback.current = setTimeout(() => void room.disconnect(), DEMOTE_REJOIN_FALLBACK_MS);
809
810
  return;
@@ -830,12 +831,12 @@ function useWebinar({
830
831
  [callExtId, linkVersion]
831
832
  );
832
833
  const stepDown = react.useCallback(async () => {
833
- chunkC5O4BH7B_cjs.markRejoining(callExtId);
834
+ chunkVCYRQZ3R_cjs.markRejoining(callExtId);
834
835
  setStageCheck(false);
835
836
  try {
836
837
  await webinarApi().demote(callExtId, myIdentity, linkVersion);
837
838
  } catch (err) {
838
- chunkC5O4BH7B_cjs.markRejoining(callExtId, false);
839
+ chunkVCYRQZ3R_cjs.markRejoining(callExtId, false);
839
840
  failed("leave the stage")(err);
840
841
  }
841
842
  }, [callExtId, myIdentity, linkVersion]);
@@ -895,7 +896,7 @@ function useWebinar({
895
896
  if (!callKey) throw new Error("This call has no key.");
896
897
  await webinarApi().questions.ask(
897
898
  callExtId,
898
- await chunkC5O4BH7B_cjs.sealQuestionText(text, callKey),
899
+ await chunkVCYRQZ3R_cjs.sealQuestionText(text, callKey),
899
900
  linkVersion
900
901
  );
901
902
  }, "ask the question"),
@@ -909,7 +910,7 @@ function useWebinar({
909
910
  await webinarApi().questions.update(
910
911
  callExtId,
911
912
  id,
912
- { answer: await chunkC5O4BH7B_cjs.sealQuestionText(text, callKey) },
913
+ { answer: await chunkVCYRQZ3R_cjs.sealQuestionText(text, callKey) },
913
914
  linkVersion
914
915
  );
915
916
  }, "answer the question"),
@@ -939,15 +940,15 @@ function useWebinar({
939
940
  function useHostMuteNotice(callExtId) {
940
941
  const room = componentsReact.useRoomContext();
941
942
  react.useEffect(() => {
942
- const notifyMuted = chunkC5O4BH7B_cjs.createMutedNotifier((text) => chunk5ECKSF6H_cjs.notify.info(text));
943
+ const notifyMuted = chunkVCYRQZ3R_cjs.createMutedNotifier((text) => chunk5ECKSF6H_cjs.notify.info(text));
943
944
  const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
944
- if (topic !== chunkC5O4BH7B_cjs.CALL_MODERATION_TOPIC) return;
945
+ if (topic !== chunkVCYRQZ3R_cjs.CALL_MODERATION_TOPIC) return;
945
946
  if (participant || participantIdentity) return;
946
- const notice = chunkC5O4BH7B_cjs.mutedNoticeFromPacket(payload);
947
+ const notice = chunkVCYRQZ3R_cjs.mutedNoticeFromPacket(payload);
947
948
  if (notice) notifyMuted(notice);
948
949
  };
949
950
  room.on(livekitClient.RoomEvent.DataReceived, onData);
950
- const offWs = chunkC5O4BH7B_cjs.onCallEvent("call.muted", (message) => {
951
+ const offWs = chunkVCYRQZ3R_cjs.onCallEvent("call.muted", (message) => {
951
952
  if (message.callExtId === callExtId) notifyMuted(message);
952
953
  });
953
954
  return () => {
@@ -956,13 +957,211 @@ function useHostMuteNotice(callExtId) {
956
957
  };
957
958
  }, [room, callExtId]);
958
959
  }
960
+ function checkedCallMedia(value, participant) {
961
+ if (!value || typeof value !== "object") throw new Error("Invalid call media");
962
+ const v = value;
963
+ if (v.protocol !== "arbi.call.media.v1" || v.participant !== participant || typeof v.utterance_id !== "string" || v.utterance_id.length > 64 || !Number.isSafeInteger(v.sequence) || Number(v.sequence) < 0 || !["start", "media", "end", "stop", "fallback"].includes(String(v.type)))
964
+ throw new Error("Invalid call media identity or sequence");
965
+ if (v.type === "start" && (v.sample_rate !== 24e3 || v.fps !== 60 || typeof v.avatar !== "string" || !Array.isArray(v.names) || v.names.length !== 52 || new Set(v.names).size !== 52 || !v.names.every((name) => typeof name === "string" && name.length < 80)))
966
+ throw new Error("Invalid call media configuration");
967
+ if (v.type === "media" && (!Number.isSafeInteger(v.start_sample) || Number(v.start_sample) < 0 || typeof v.pcm !== "string" || v.pcm.length > 6400 || !Array.isArray(v.frames) || !v.frames.length || v.frames.length > 6 || !v.frames.every(
968
+ (frame) => Array.isArray(frame) && frame.length === 52 && frame.every(
969
+ (x) => typeof x === "number" && Number.isFinite(x) && x >= -2 && x <= 2
970
+ )
971
+ )))
972
+ throw new Error("Invalid call media samples");
973
+ return v;
974
+ }
975
+ var CallMediaPlayer = class {
976
+ constructor(context, changed) {
977
+ this.context = context;
978
+ this.changed = changed;
979
+ this.recording = context.createMediaStreamDestination();
980
+ }
981
+ context;
982
+ changed;
983
+ active = false;
984
+ /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */
985
+ suppressesTrack = false;
986
+ avatar = "";
987
+ names = [];
988
+ utterance = "";
989
+ sequence = -1;
990
+ nextSample = 0;
991
+ nextTime = 0;
992
+ segments = [];
993
+ sources = /* @__PURE__ */ new Set();
994
+ seen = /* @__PURE__ */ new Set();
995
+ finishTimer;
996
+ recording;
997
+ push(message) {
998
+ if (message.type === "fallback" && message.sequence === 0 && message.utterance_id !== this.utterance) {
999
+ if (this.seen.has(message.utterance_id)) return;
1000
+ this.utterance = message.utterance_id;
1001
+ this.sequence = 0;
1002
+ this.seen.add(message.utterance_id);
1003
+ if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value);
1004
+ this.reset(true);
1005
+ return;
1006
+ }
1007
+ if (message.type === "start") {
1008
+ if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return;
1009
+ this.reset();
1010
+ this.seen.add(message.utterance_id);
1011
+ if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value);
1012
+ this.utterance = message.utterance_id;
1013
+ this.avatar = message.avatar;
1014
+ this.names = message.names;
1015
+ this.sequence = 0;
1016
+ this.nextSample = 0;
1017
+ this.nextTime = this.context.currentTime + 0.15;
1018
+ this.active = true;
1019
+ this.suppressesTrack = true;
1020
+ this.changed();
1021
+ return;
1022
+ }
1023
+ if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return;
1024
+ if (message.sequence !== this.sequence + 1) throw new Error("Call media sequence gap");
1025
+ this.sequence = message.sequence;
1026
+ if (message.type === "media") {
1027
+ if (!this.active || message.start_sample !== this.nextSample)
1028
+ throw new Error("Call media sample gap");
1029
+ const pcm = client.base64ToBytes(message.pcm);
1030
+ if (pcm.length % 2 || pcm.length > message.frames.length * 800)
1031
+ throw new Error("Invalid PCM length");
1032
+ if (this.nextTime - this.context.currentTime > 2) throw new Error("Call media queue exceeded");
1033
+ const buffer = this.context.createBuffer(1, pcm.length / 2, 24e3);
1034
+ const values = buffer.getChannelData(0);
1035
+ const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
1036
+ for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768;
1037
+ const at = Math.max(this.nextTime, this.context.currentTime + 0.02);
1038
+ const source = this.context.createBufferSource();
1039
+ source.buffer = buffer;
1040
+ source.connect(this.context.destination);
1041
+ source.connect(this.recording);
1042
+ this.sources.add(source);
1043
+ source.onended = () => {
1044
+ source.disconnect();
1045
+ this.sources.delete(source);
1046
+ };
1047
+ source.start(at);
1048
+ this.segments.push({ at, duration: buffer.duration, frames: message.frames });
1049
+ this.segments = this.segments.filter(
1050
+ (s) => s.at + s.duration > this.context.currentTime - 0.1
1051
+ );
1052
+ this.nextTime = at + buffer.duration;
1053
+ this.nextSample += values.length;
1054
+ } else if (message.type === "end") {
1055
+ this.finishTimer = setTimeout(
1056
+ () => this.reset(),
1057
+ Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
1058
+ );
1059
+ } else if (message.type === "fallback" || message.type === "stop") {
1060
+ this.reset(message.type === "fallback");
1061
+ }
1062
+ }
1063
+ sample() {
1064
+ const now = this.context.currentTime;
1065
+ const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
1066
+ if (!segment) return null;
1067
+ const frame = (now - segment.at) * 60;
1068
+ const i = Math.min(Math.floor(frame), segment.frames.length - 1);
1069
+ const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
1070
+ return a.map((value, j) => value + (b[j] - value) * (frame - i));
1071
+ }
1072
+ reset(releaseTrack = false) {
1073
+ clearTimeout(this.finishTimer);
1074
+ for (const source of this.sources) {
1075
+ source.stop();
1076
+ source.disconnect();
1077
+ }
1078
+ this.sources.clear();
1079
+ this.segments = [];
1080
+ this.active = false;
1081
+ if (releaseTrack) this.suppressesTrack = false;
1082
+ this.changed();
1083
+ }
1084
+ };
1085
+
1086
+ // src/calls/livekit/useCallMedia.ts
1087
+ function useCallMedia(enabled, key) {
1088
+ const room = componentsReact.useRoomContext();
1089
+ const [players, setPlayers] = react.useState(/* @__PURE__ */ new Map());
1090
+ react.useEffect(() => {
1091
+ if (!enabled || !key || typeof AudioContext === "undefined") return;
1092
+ const context = new AudioContext();
1093
+ const live = /* @__PURE__ */ new Map();
1094
+ const chains = /* @__PURE__ */ new Map();
1095
+ let disposed = false;
1096
+ const advertise = () => {
1097
+ if (!disposed && context.state === "running" && room.state === livekitClient.ConnectionState.Connected) {
1098
+ void room.localParticipant.setAttributes({ "arbi.call_media": client.CALL_MEDIA_PROTOCOL }).catch(() => void 0);
1099
+ }
1100
+ };
1101
+ const changed = () => {
1102
+ if (!disposed) setPlayers(new Map(live));
1103
+ };
1104
+ const received = (bytes, from, _kind, topic) => {
1105
+ if (topic !== client.CALL_MEDIA_PROTOCOL || !from || from.attributes["arbi.call_assistant"] !== "true")
1106
+ return;
1107
+ const identity = from.identity;
1108
+ const chain = chains.get(identity) ?? Promise.resolve();
1109
+ chains.set(
1110
+ identity,
1111
+ chain.then(async () => {
1112
+ if (disposed) return;
1113
+ const message = checkedCallMedia(await client.decryptCallMedia(bytes, key), identity);
1114
+ let player = live.get(identity);
1115
+ if (!player) {
1116
+ player = new CallMediaPlayer(context, changed);
1117
+ live.set(identity, player);
1118
+ }
1119
+ if (context.state !== "running") await context.resume();
1120
+ if (context.state !== "running") throw new Error("Call audio is unavailable");
1121
+ player.push(message);
1122
+ }).catch(() => {
1123
+ live.get(identity)?.reset(true);
1124
+ void room.localParticipant.setAttributes({ "arbi.call_media": "" }).catch(() => void 0);
1125
+ })
1126
+ );
1127
+ };
1128
+ const removed = (participant) => {
1129
+ live.get(participant.identity)?.reset();
1130
+ live.delete(participant.identity);
1131
+ changed();
1132
+ };
1133
+ room.on(livekitClient.RoomEvent.DataReceived, received);
1134
+ room.on(livekitClient.RoomEvent.ParticipantDisconnected, removed);
1135
+ room.on(livekitClient.RoomEvent.Connected, advertise);
1136
+ room.on(livekitClient.RoomEvent.Reconnected, advertise);
1137
+ void context.resume().then(() => {
1138
+ advertise();
1139
+ }).catch(() => void 0);
1140
+ return () => {
1141
+ disposed = true;
1142
+ room.off(livekitClient.RoomEvent.DataReceived, received);
1143
+ room.off(livekitClient.RoomEvent.ParticipantDisconnected, removed);
1144
+ room.off(livekitClient.RoomEvent.Connected, advertise);
1145
+ room.off(livekitClient.RoomEvent.Reconnected, advertise);
1146
+ if (room.state === livekitClient.ConnectionState.Connected) {
1147
+ void room.localParticipant.setAttributes({ "arbi.call_media": "" }).catch(() => void 0);
1148
+ }
1149
+ for (const player of live.values()) player.reset();
1150
+ void context.close();
1151
+ setPlayers(/* @__PURE__ */ new Map());
1152
+ };
1153
+ }, [enabled, key, room]);
1154
+ return players;
1155
+ }
959
1156
 
1157
+ exports.CallMediaPlayer = CallMediaPlayer;
960
1158
  exports.DEMOTE_REJOIN_FALLBACK_MS = DEMOTE_REJOIN_FALLBACK_MS;
961
1159
  exports.FINAL_SEGMENT_GRACE_MS = FINAL_SEGMENT_GRACE_MS;
962
1160
  exports.captureAllowed = captureAllowed;
963
1161
  exports.createE2EEWorker = createE2EEWorker;
964
1162
  exports.mayStillSend = mayStillSend;
965
1163
  exports.storedSpeakerName = storedSpeakerName;
1164
+ exports.useCallMedia = useCallMedia;
966
1165
  exports.useCallRecorder = useCallRecorder;
967
1166
  exports.useCallRoom = useCallRoom;
968
1167
  exports.useCallTranscriber = useCallTranscriber;