File size: 8,670 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**

 * MicSessionManager

 *

 * The engine's microphone ownership layer. Applications acquire a lease that

 * says what they are doing; this class tracks the live leases, resolves them

 * through `micPolicy`, and pushes the result to MicStateCoordinator.

 *

 * Everything above it is semantic ("I need a glasses microphone for a voice

 * call"). Everything below it is hardware. Audio *sinks* β€” AcsMeetingService

 * today, another transport later β€” are downstream of the PCM this produces and

 * must not reach past it to the coordinator or the Bluetooth SDK.

 */

import {Platform} from "react-native"
import BluetoothSdk from "@mentra/bluetooth-sdk/internal"

import {getCallGainSweep} from "./CallGainSweep"
import micStateCoordinator from "./MicStateCoordinator"
import {
  resolveMicPolicy,
  type MicPlatformCaps,
  type MicSessionSpec,
  type MicSource,
  type MicUseCase,
} from "./micPolicy"

const LOG_TAG = "MIC_SESSION"

/** Raised when a second source is requested while another is already live. */
export const MIC_SOURCE_CONFLICT = "MIC_SOURCE_CONFLICT"

export interface MicSessionOptions {
  /** Package name for a miniapp, or `engine:<name>` for an engine feature. */
  owner: string
  source: MicSource
  useCase: MicUseCase
}

export interface MicSession {
  readonly id: number
  readonly owner: string
  readonly source: MicSource
  readonly useCase: MicUseCase
  /** Idempotent. Releasing a session that is already gone is a no-op. */
  release(): void
}

interface LiveSession extends MicSessionSpec {
  id: number
  owner: string
}

function defaultCaps(): MicPlatformCaps {
  return {
    // iOS has no `setMicSourcePin`, so it cannot promise the phone microphone
    // stays shut, and `glassesLc3UplinkSupported` never selects the BLE LC3
    // uplink there.
    glassesPcmUplink: Platform.OS === "android" && typeof BluetoothSdk.setMicSourcePin === "function",
  }
}

class MicSessionManager {
  private static instance: MicSessionManager | null = null

  private readonly sessions = new Map<number, LiveSession>()
  private nextId = 1
  private caps: MicPlatformCaps = defaultCaps()
  /** Last pin we asked for, so a no-op change does not re-enter native. */
  private pinned = false
  /**

   * One 15β†’14β†’15β†’13 walk per voice-call generation. Cleared when the last

   * glasses voice_call session drops so the next join can measure again.

   */
  private sweepFinished = false
  /** One-shot A/B walk. Off now that 15/14/13 is measured; Super Mode can still start it. */
  private sweepEnabled = false

  private constructor() {}

  public static getInstance(): MicSessionManager {
    if (!MicSessionManager.instance) {
      MicSessionManager.instance = new MicSessionManager()
    }
    return MicSessionManager.instance
  }

  /** Test seam. Production reads the platform once at construction. */
  public setPlatformCaps(caps: MicPlatformCaps): void {
    this.caps = caps
  }

  /**

   * Take a microphone lease.

   *

   * Throws [MIC_SOURCE_CONFLICT] when a different source is already live: only

   * the glasses can be pinned, so silently mixing sources would leave one

   * consumer reading a microphone it did not ask for. That is the failure ACS

   * already guards against frame by frame.

   */
  public acquire(options: MicSessionOptions): MicSession {
    const conflicting = [...this.sessions.values()].find((s) => s.source !== options.source)
    if (conflicting) {
      throw new Error(
        `${MIC_SOURCE_CONFLICT}: ${options.owner} asked for "${options.source}" while ` +
          `${conflicting.owner} holds "${conflicting.source}"`,
      )
    }

    const id = this.nextId++
    this.sessions.set(id, {id, owner: options.owner, source: options.source, useCase: options.useCase})
    console.log(`${LOG_TAG}: acquire #${id} ${options.owner} ${options.useCase}/${options.source}`)
    this.recompute()

    return {
      id,
      owner: options.owner,
      source: options.source,
      useCase: options.useCase,
      release: () => this.releaseId(id),
    }
  }

  /** Drop every lease an owner holds. The backstop for unregister / disconnect. */
  public releaseOwner(owner: string): boolean {
    let removed = false
    for (const [id, session] of this.sessions) {
      if (session.owner !== owner) continue
      this.sessions.delete(id)
      removed = true
    }
    if (removed) {
      console.log(`${LOG_TAG}: released all sessions for ${owner}`)
      this.recompute()
    }
    return removed
  }

  /**

   * Whether an owner holds a glasses lease.

   *

   * Ownership only. Whether that lease has any hardware effect is

   * [resolveMicPolicy]'s business, so on a platform without a glasses PCM

   * uplink this still answers true while nothing is claimed.

   */
  public hasGlassesSession(owner: string): boolean {
    for (const session of this.sessions.values()) {
      if (session.owner === owner && session.source === "glasses") return true
    }
    return false
  }

  public releaseAll(): void {
    if (this.sessions.size === 0) {
      this.stopSweep("released_all")
      return
    }
    this.sessions.clear()
    console.log(`${LOG_TAG}: released all sessions`)
    this.recompute()
  }

  public cleanup(): void {
    this.stopSweep("cleanup")
    this.sessions.clear()
    this.pinned = false
    this.sweepFinished = false
    MicSessionManager.instance = null
  }

  /** Tests disable the auto-walk so acquire still means "policy 14". */
  public setCallGainSweepEnabled(enabled: boolean): void {
    this.sweepEnabled = enabled
    if (!enabled) this.stopSweep("disabled")
  }

  /**

   * Start or restart the 15β†’14β†’15β†’13 comparison on a live voice_call session.

   * Super Mode uses this so a call already in progress can be measured.

   */
  public startCallGainSweep(): boolean {
    if (!this.hasVoiceCallGlasses()) {
      console.warn(`${LOG_TAG}: CALL_GAIN_SWEEP ignored β€” no live voice_call glasses session`)
      return false
    }
    if (micStateCoordinator.hasConfiguredMicTuning()) {
      console.warn(
        `${LOG_TAG}: CALL_GAIN_SWEEP Super Mode mic-tuning is set; reset it or the glasses will ignore the sweep`,
      )
    }
    this.sweepFinished = false
    return getCallGainSweep().restart(
      (gain) => micStateCoordinator.setSessionMicTuning({gain}),
      () => {
        this.sweepFinished = true
        this.recompute()
      },
    )
  }

  private releaseId(id: number): void {
    if (!this.sessions.delete(id)) return
    console.log(`${LOG_TAG}: release #${id}`)
    this.recompute()
  }

  private hasVoiceCallGlasses(): boolean {
    if (!this.caps.glassesPcmUplink) return false
    for (const session of this.sessions.values()) {
      if (session.useCase === "voice_call" && session.source === "glasses") return true
    }
    return false
  }

  private stopSweep(reason: string): void {
    if (getCallGainSweep().isActive()) getCallGainSweep().stop(reason)
  }

  private recompute(): void {
    const policy = resolveMicPolicy([...this.sessions.values()], this.caps)
    const voiceCall = this.hasVoiceCallGlasses()
    if (!voiceCall) {
      this.stopSweep("session_ended")
      this.sweepFinished = false
    }

    // Pin before claiming PCM, so the first frame the claim produces is
    // already from the right microphone and the phone mic is never opened.
    if (policy.pinGlasses !== this.pinned) {
      this.pinned = policy.pinGlasses
      void Promise.resolve(BluetoothSdk.setMicSourcePin?.(policy.pinGlasses ? "glasses" : null)).catch(
        (error) => {
          console.warn(`${LOG_TAG}: setMicSourcePin failed`, error)
        },
      )
    }

    micStateCoordinator.setSessionRequirement(policy.rawPcm)
    // Barrier is the only echo control left once the PCM claim turns hardware VAD off, so it
    // rides with the claim rather than with the tuning a sweep may be rewriting.
    micStateCoordinator.setSessionLoudnessGate(policy.loudnessGate)

    if (getCallGainSweep().isActive()) {
      const gain = getCallGainSweep().currentGain()
      micStateCoordinator.setSessionMicTuning(gain == null ? policy.micTuning : {gain})
      return
    }

    if (this.sweepEnabled && voiceCall && !this.sweepFinished) {
      this.startCallGainSweep()
      return
    }

    micStateCoordinator.setSessionMicTuning(policy.micTuning)
  }
}

const micSessionManager = MicSessionManager.getInstance()
export default micSessionManager