@mentra/cloud-client 3.2.1-dev.314 → 3.3.0-beta.1000

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.
@@ -24,7 +24,11 @@
24
24
  */
25
25
  import nacl from "tweetnacl";
26
26
  import type { UdpSocketLike } from "../../transports";
27
- import { UDP_LIVENESS_PROBE_PREFIX, type ConnectionAck } from "@mentra/cloud-protocol";
27
+ import {
28
+ UDP_LIVENESS_PROBE_PREFIX,
29
+ type AudioPosition,
30
+ type ConnectionAck,
31
+ } from "@mentra/cloud-protocol";
28
32
 
29
33
  /** The audio block of `connection.ack`, present only when UDP audio is offered. */
30
34
  type AudioConfig = NonNullable<ConnectionAck["audio"]>;
@@ -40,6 +44,7 @@ const SEQ_MODULO = 0x10000;
40
44
 
41
45
  export interface UdpAudioDeps {
42
46
  udp: () => UdpSocketLike;
47
+ audio?: { codec: "pcm" | "lc3"; sampleRate: number; frameSizeBytes?: number };
43
48
  }
44
49
 
45
50
  export type RuntimeAudioTransport = "udp" | "ws" | "none";
@@ -59,6 +64,8 @@ interface UdpSession {
59
64
  key: Uint8Array;
60
65
  /** Per-session packet counter; wraps at the u16 boundary. */
61
66
  seq: number;
67
+ offsetMs: number;
68
+ frameTimelineVersion?: 1;
62
69
  }
63
70
 
64
71
  export class UdpAudio {
@@ -67,6 +74,17 @@ export class UdpAudio {
67
74
 
68
75
  constructor(deps: UdpAudioDeps) {
69
76
  this.udpFactory = deps.udp;
77
+ this.format = deps.audio ?? { codec: "pcm", sampleRate: 16000 };
78
+ }
79
+
80
+ private readonly format: NonNullable<UdpAudioDeps["audio"]>;
81
+
82
+ /** @internal Next submitted frame, used by the phone runtime's subscription cutoff. */
83
+ get audioPosition(): AudioPosition | null {
84
+ const s = this.session;
85
+ return s?.frameTimelineVersion === 1
86
+ ? { sessionTag: s.sessionTag, offsetMs: s.offsetMs }
87
+ : null;
70
88
  }
71
89
 
72
90
  /** The audio transport currently configured for outbound frames. */
@@ -78,6 +96,13 @@ export class UdpAudio {
78
96
  return this.session?.sessionTag ?? null;
79
97
  }
80
98
 
99
+ /** Refresh a dead UDP route without changing the session key, tag or sequence. */
100
+ resetSocket(): void {
101
+ if (!this.session) return;
102
+ this.session.socket.close();
103
+ this.session.socket = this.udpFactory();
104
+ }
105
+
81
106
  /**
82
107
  * Open the UDP socket and load the session's routing + encryption material
83
108
  * from `connection.ack.audio`.
@@ -98,6 +123,8 @@ export class UdpAudio {
98
123
  port: audio.udp.port,
99
124
  key: decodeBase64(audio.encryption.key),
100
125
  seq: 0,
126
+ offsetMs: 0,
127
+ frameTimelineVersion: audio.frameTimelineVersion,
101
128
  };
102
129
  }
103
130
 
@@ -115,18 +142,50 @@ export class UdpAudio {
115
142
  const session = this.session;
116
143
  if (!session) return false;
117
144
 
118
- session.socket.send(this.buildEncryptedPacket(session, payload), session.host, session.port);
145
+ session.socket.send(
146
+ this.buildEncryptedPacket(
147
+ session,
148
+ this.positionedPayload(session, payload),
149
+ ),
150
+ session.host,
151
+ session.port,
152
+ );
119
153
  return true;
120
154
  }
121
155
 
122
156
  sendProbe(probeId: string): boolean {
123
- return this.sendFrame(asciiBytes(`${UDP_LIVENESS_PROBE_PREFIX}${probeId}`));
157
+ const session = this.session;
158
+ if (!session) return false;
159
+ session.socket.send(
160
+ this.buildEncryptedPacket(
161
+ session,
162
+ asciiBytes(`${UDP_LIVENESS_PROBE_PREFIX}${probeId}`),
163
+ ),
164
+ session.host,
165
+ session.port,
166
+ );
167
+ return true;
124
168
  }
125
169
 
126
170
  buildPlainFrame(payload: Uint8Array): Uint8Array | null {
127
171
  const session = this.session;
128
172
  if (!session) return null;
129
- return this.buildPacket(session, payload);
173
+ return this.buildPacket(session, this.positionedPayload(session, payload));
174
+ }
175
+
176
+ private positionedPayload(
177
+ session: UdpSession,
178
+ payload: Uint8Array,
179
+ ): Uint8Array {
180
+ if (session.frameTimelineVersion !== 1) return payload;
181
+ const result = new Uint8Array(8 + payload.length);
182
+ new DataView(result.buffer).setFloat64(0, session.offsetMs, false);
183
+ result.set(payload, 8);
184
+ session.offsetMs +=
185
+ this.format.codec === "lc3"
186
+ ? (payload.length / (this.format.frameSizeBytes ?? 20)) * 10
187
+ : (Math.floor(payload.length / 2) / this.format.sampleRate) * 1000;
188
+ return result;
130
189
  }
131
190
 
132
191
  private buildEncryptedPacket(session: UdpSession, payload: Uint8Array): Uint8Array {
@@ -9,9 +9,51 @@ export interface AcsMeetingCredential {
9
9
  guestReason?: "teams-license-unavailable"
10
10
  }
11
11
 
12
+ export interface CreatedTeamsMeeting {
13
+ provider: "acs-teams"
14
+ joinUrl: string
15
+ meetingRef: string
16
+ identityMode: "guest" | "teams-user"
17
+ guestReason?: "no-entra-identity" | "teams-license-unavailable"
18
+ }
19
+
12
20
  export class Meetings {
13
21
  constructor(private readonly http: HttpClient) {}
14
22
 
23
+ async createTeamsMeeting(
24
+ options: {subject?: string; durationMinutes?: number},
25
+ teamsUserAadToken?: string,
26
+ ): Promise<CreatedTeamsMeeting> {
27
+ const value = await this.http.post<CreatedTeamsMeeting>("/api/meetings/teams/create", {
28
+ ...options,
29
+ ...(teamsUserAadToken ? {teamsUserAadToken} : {}),
30
+ })
31
+ if (
32
+ !value ||
33
+ value.provider !== "acs-teams" ||
34
+ typeof value.joinUrl !== "string" ||
35
+ !/^https:\/\/(teams\.microsoft\.com|teams\.cloud\.microsoft)\//.test(value.joinUrl) ||
36
+ typeof value.meetingRef !== "string" ||
37
+ !value.meetingRef ||
38
+ !["guest", "teams-user"].includes(value.identityMode) ||
39
+ (teamsUserAadToken && value.identityMode === "guest" && value.guestReason !== "teams-license-unavailable") ||
40
+ (!teamsUserAadToken && (value.identityMode !== "guest" || value.guestReason !== "no-entra-identity"))
41
+ ) {
42
+ throw new Error("Runtime returned an invalid created meeting")
43
+ }
44
+ return {
45
+ provider: value.provider,
46
+ joinUrl: value.joinUrl,
47
+ meetingRef: value.meetingRef,
48
+ identityMode: value.identityMode,
49
+ ...(value.identityMode === "guest" ? {guestReason: value.guestReason} : {}),
50
+ }
51
+ }
52
+
53
+ async retireTeamsMeeting(meetingRef: string): Promise<void> {
54
+ await this.http.post("/api/meetings/teams/retire", {meetingRef})
55
+ }
56
+
15
57
  async getAcsCredential(teamsUserAadToken?: string): Promise<AcsMeetingCredential> {
16
58
  const value = await this.http.post<AcsMeetingCredential>(
17
59
  "/api/meetings/acs/token",
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import type {
20
20
  AudioSubscription,
21
+ AudioPosition,
21
22
  TranscriptionData,
22
23
  TranslationData,
23
24
  ProtocolError,
@@ -29,10 +30,25 @@ import type { Connection } from "./connection";
29
30
  import { HandshakeRejectedError } from "./connection";
30
31
  import type { RuntimeEmitter, RuntimeEvents } from "./emitter";
31
32
  import type { Subscriptions } from "./subscriptions";
32
- import type { Camera, StreamOptions, ManagedStream, StreamStatusResult } from "./camera";
33
+ import type {
34
+ Camera,
35
+ StreamOptions,
36
+ ManagedStream,
37
+ StreamStatusResult,
38
+ } from "./camera";
33
39
  import type { Meetings } from "./meetings";
34
- import type { Maps, DirectionsRequest, DirectionsResult, LatLng, ReverseGeocodeResult } from "./maps";
35
- import type { Tts, RuntimeTtsSpeakOptions, RuntimeTtsSpeechSource } from "./tts";
40
+ import type {
41
+ Maps,
42
+ DirectionsRequest,
43
+ DirectionsResult,
44
+ LatLng,
45
+ ReverseGeocodeResult,
46
+ } from "./maps";
47
+ import type {
48
+ Tts,
49
+ RuntimeTtsSpeakOptions,
50
+ RuntimeTtsSpeechSource,
51
+ } from "./tts";
36
52
  import type { UdpAudio } from "./audio-udp";
37
53
  import type { RuntimeSnapshot } from "./status";
38
54
  import { systemTimers, type CloudClientTimers } from "../../timers";
@@ -82,6 +98,8 @@ export interface RuntimeModule {
82
98
  * sent before the session is configured is dropped, not thrown on.
83
99
  */
84
100
  sendAudioFrame(frame: Uint8Array): void;
101
+ /** @internal Audio cursor for the phone runtime; not a miniapp API. */
102
+ getAudioPosition(): AudioPosition | null;
85
103
 
86
104
  getStatus(): RuntimeSnapshot;
87
105
 
@@ -162,6 +180,7 @@ export class Runtime implements RuntimeModule {
162
180
  private udpProbeTimer: unknown | null = null;
163
181
  private udpProbeStartedAt = 0;
164
182
  private lastUdpAckAt = 0;
183
+ private readonly pendingUdpProbes = new Map<string, number>();
165
184
 
166
185
  /**
167
186
  * Whether the inbound-message routing has been wired to the connection yet.
@@ -393,7 +412,9 @@ export class Runtime implements RuntimeModule {
393
412
  private configureAudio(ack: ConnectionAck): void {
394
413
  if (ack.audio) {
395
414
  this.audio.configure(ack.audio);
396
- this.updateStatus({ audioTransport: "udp" });
415
+ // Configured credentials do not prove DNS/connect or UDP delivery works.
416
+ // Use the already-open WS while probes establish the new UDP route.
417
+ this.updateStatus({ audioTransport: this.connection.isOpen ? "ws" : "none" });
397
418
  this.startUdpLiveness();
398
419
  return;
399
420
  }
@@ -451,6 +472,10 @@ export class Runtime implements RuntimeModule {
451
472
  return { ...this.status };
452
473
  }
453
474
 
475
+ getAudioPosition(): AudioPosition | null {
476
+ return this.audio.audioPosition;
477
+ }
478
+
454
479
  // --- Camera: managed photo/stream (delegated) -----------------------------
455
480
 
456
481
  requestManagedPhoto(): Promise<{ requestId: string; readUrl: string }> {
@@ -536,8 +561,8 @@ export class Runtime implements RuntimeModule {
536
561
  this.lastUdpAckAt = 0;
537
562
  this.sendUdpProbe();
538
563
  this.udpProbeTimer = this.timers.setInterval(() => {
539
- this.sendUdpProbe();
540
564
  this.checkUdpLiveness();
565
+ this.sendUdpProbe();
541
566
  }, UDP_PROBE_INTERVAL_MS);
542
567
  }
543
568
 
@@ -548,12 +573,18 @@ export class Runtime implements RuntimeModule {
548
573
  }
549
574
  this.udpProbeStartedAt = 0;
550
575
  this.lastUdpAckAt = 0;
576
+ this.pendingUdpProbes.clear();
551
577
  }
552
578
 
553
579
  private sendUdpProbe(): void {
554
580
  const tag = this.audio.sessionTag;
555
581
  if (tag === null) return;
556
- const probeId = `${tag}-${Date.now()}-${Math.floor(Math.random() * 1_000_000)}`;
582
+ const now = Date.now();
583
+ for (const [id, sentAt] of this.pendingUdpProbes) {
584
+ if (now - sentAt >= UDP_LIVENESS_TIMEOUT_MS) this.pendingUdpProbes.delete(id);
585
+ }
586
+ const probeId = `${tag}-${now}-${Math.floor(Math.random() * 1_000_000)}`;
587
+ this.pendingUdpProbes.set(probeId, now);
557
588
  this.audio.sendProbe(probeId);
558
589
  }
559
590
 
@@ -562,6 +593,14 @@ export class Runtime implements RuntimeModule {
562
593
  const since = this.lastUdpAckAt || this.udpProbeStartedAt;
563
594
  if (since === 0 || Date.now() - since < UDP_LIVENESS_TIMEOUT_MS) return;
564
595
  this.updateStatus({ audioTransport: this.connection.isOpen ? "ws" : "none" });
596
+ // Connected UDP sockets retain their resolved peer and route. Recreate one
597
+ // after a missed liveness window so DNS/network changes can recover even
598
+ // when the WebSocket stayed open. Only this replacement's probes may restore
599
+ // UDP: an old socket's delayed ack does not establish the new route works.
600
+ this.pendingUdpProbes.clear();
601
+ this.audio.resetSocket();
602
+ this.lastUdpAckAt = 0;
603
+ this.udpProbeStartedAt = Date.now();
565
604
  }
566
605
 
567
606
  private handleUdpLivenessAck(payload: {
@@ -571,6 +610,9 @@ export class Runtime implements RuntimeModule {
571
610
  receivedAt: number;
572
611
  }): void {
573
612
  if (payload.sessionTag !== this.audio.sessionTag) return;
613
+ const sentAt = this.pendingUdpProbes.get(payload.probeId);
614
+ this.pendingUdpProbes.delete(payload.probeId);
615
+ if (sentAt === undefined || Date.now() - sentAt >= UDP_LIVENESS_TIMEOUT_MS) return;
574
616
  this.lastUdpAckAt = Date.now();
575
617
  if (this.status.status === "connected") {
576
618
  this.updateStatus({ audioTransport: "udp" });