File size: 42,802 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 | import {createAudioPlayer, AudioPlayer, AudioStatus, setAudioModeAsync} from "expo-audio"
import BluetoothSdk from "@mentra/bluetooth-sdk/internal"
import {BgTimer} from "../utils/timers"
import {setAudioCloudUplinkSuppressed} from "./AudioCloudUplink"
import {SILENT_AUDIO_SOURCE} from "./audioPlaybackAssets"
const RESTORE_GLASSES_VOLUME_AFTER_PLAYBACK = false
interface AudioPlayRequest {
startPositionMs?: number
startupTimeoutMs?: number
requestId: string
audioUrl: string
appId?: string
volume?: number
stopOtherAudio?: boolean
/**
* Suppress microphone audio sent to cloud STT while this audio is audible.
* Opt-in and off by default: the suppression is global to the uplink, so a
* caller that sets this silences STT for every running app, not just itself.
* No platform path sets it today (see AudioCloudUplink and OS-1741).
*/
suppressCloudUplink?: boolean
}
export type AudioPlaybackCompletionReason = "completed" | "interrupted" | "error"
type AudioPlaybackCompletion = (
requestId: string,
success: boolean,
error: string | null,
duration: number | null,
reason: AudioPlaybackCompletionReason,
) => void
interface PlaybackState {
startPositionMs: number
startupTimer: number | null
hasStarted: boolean
requestId: string
audioUrl: string
uplinkSuppressionId: string
appId?: string
startTime: number
completed: boolean // Guard against double callbacks
suppressCloudUplink: boolean
onComplete: AudioPlaybackCompletion
}
interface PendingPlaybackState {
startPositionMs: number
cancelled: boolean
audioUrl: string
appId?: string
createdAt: number
}
/** Open request for a live PCM output stream (miniapp speaker.createStream). */
export interface AudioStreamOpenRequest {
streamId: string
appId: string
/** PCM sample rate in Hz (16000 / 24000 / 48000). */
sampleRate: number
/** Channel count. v1 is mono. */
channels: number
volume?: number
/**
* Interrupt other audio when this stream starts: at open, or at the first
* write for a prewarmed stream. Default true.
*/
stopOtherAudio?: boolean
/**
* Open the native stream now but treat it as silent until its first write:
* it doesn't interrupt other audio, doesn't count as playing, and other
* audio leaves it alone.
*/
prewarm?: boolean
/**
* Audio queued before playback starts, and the playout cushion after that.
* Both platforms honor it; native defaults to 500 ms.
*/
jitterMs?: number
/**
* Called when the stream ends for any reason (drained after close, aborted,
* interrupted by other audio, or native error). `started` is false when it
* ended before any audio was written.
*/
onEnded: (
streamId: string,
success: boolean,
error: string | null,
durationMs: number | null,
started: boolean,
) => void
}
/** Cloud speech streamed from a URL straight into the native PCM player. */
export interface AudioPcmUrlRequest {
requestId: string
appId: string
/** Raw signed 16-bit little-endian mono PCM. */
url: string
sampleRate: number
volume?: number
jitterMs?: number
stopOtherAudio?: boolean
/** Same opt-in, uplink-wide mute as {@link AudioPlayRequest.suppressCloudUplink}. */
suppressCloudUplink?: boolean
}
/** One live PCM stream session, backed by native streaming audio. */
interface StreamState {
/** False until the first write (prewarmed streams only). Unstarted streams are inert. */
started: boolean
streamId: string
appId: string
startTime: number
ended: boolean // Guard against double onEnded
stopOtherAudio: boolean
/** Cloud-uplink suppression source held while this stream is audible, if any. */
uplinkSuppressionId?: string
onEnded: AudioStreamOpenRequest["onEnded"]
}
class AudioPlaybackService {
private static instance: AudioPlaybackService | null = null
// Reuse a single AudioPlayer to avoid AudioTrack exhaustion
// Creating new ExoPlayer instances per request leads to -12 ENOMEM errors
private player: AudioPlayer | null = null
// The source currently loaded into the reusable player. Keep object identity
// so a delayed tail cleanup from an older request cannot unload a newer one.
private loadedPlayback: PlaybackState | null = null
private currentPlayback: PlaybackState | null = null
// Requests that entered play() but have not yet reached the native player.
// Keeping these addressable prevents a cancelled request from starting after
// an async audio-mode or stream-cleanup step finishes.
private pendingPlaybacks = new Map<string, PendingPlaybackState>()
// Live PCM streams (speaker.createStream), keyed by streamId. The runtime
// enforces one per app; stopOtherAudio interrupts across apps.
private streams = new Map<string, StreamState>()
private audioModeConfigured: boolean = false
private preparing?: Promise<void>
// Debounce timer for notifying native that audio stopped
// Prevents mic toggle flicker when playing back-to-back audio
// Uses BgTimer to work reliably when app is backgrounded on Android
private audioStopDebounceTimer: number | null = null
// Playback that opted into suppression stays suppressed briefly while its
// A2DP tail drains. Track those completed sources so a later unsuppressed
// sound can resume listening immediately instead of inheriting that gate.
private tailUplinkSuppressions = new Set<string>()
// Original glasses media volume captured before we bump it for A2DP playback.
private glassesVolumeRestoreLevel: number | null = null
private static readonly AUDIO_STOP_DEBOUNCE_MS = 1500
private static readonly A2DP_TAIL_DRAIN_MS = 700
/** Break accidental same-app replay storms without affecting deliberate later replays. */
private static readonly DUPLICATE_PLAY_WINDOW_MS = 750
/** If glasses report step volume at or below this, bump to FLOOR before A2DP playback. */
private static readonly GLASSES_VOLUME_LOW_THRESHOLD = 2
private static readonly GLASSES_VOLUME_FLOOR = 9
private constructor() {}
/**
* Configure audio mode for playback, re-asserting it on EVERY play.
*
* This must run before each play β not just once β because other parts of the
* app put the shared iOS AVAudioSession into a record-oriented category and
* never restore it. In particular the phone mic (PhoneMic.swift) switches the
* session to `.playAndRecord` (sometimes `.voiceChat`/earpiece routing) while
* capturing and only deactivates it on stop, leaving the category sticky. A
* miniapp like the Recorder records and then immediately plays back through
* this service; if we kept the old "configure once" guard, playback would land
* in the leftover `.playAndRecord` session and be inaudible on the phone
* speaker (the symptom: the progress bar runs but no sound comes out). Calling
* setAudioModeAsync with no `allowsRecording` maps to category `.playback`,
* reclaiming the speaker route. `audioModeConfigured` is kept only to gate the
* one-time log.
*/
private async ensureAudioModeConfigured(): Promise<void> {
try {
await setAudioModeAsync({
shouldPlayInBackground: true,
playsInSilentMode: true,
interruptionMode: "duckOthers",
})
if (!this.audioModeConfigured) {
this.audioModeConfigured = true
console.log("AUDIO: Audio mode configured for playback")
}
} catch (error) {
console.error("AUDIO: Failed to configure audio mode:", error)
// Don't block playback if audio mode config fails
}
}
public static getInstance(): AudioPlaybackService {
if (!AudioPlaybackService.instance) {
AudioPlaybackService.instance = new AudioPlaybackService()
}
return AudioPlaybackService.instance
}
/**
* Configure the audio session and create the shared player ahead of the
* next sound (e.g. on a wake-word detection), without playing anything or
* acquiring the microphone.
*/
public prepareForPlayback(): Promise<void> {
if (!this.preparing)
this.preparing = this.ensureAudioModeConfigured()
.then(() => {
this.ensurePlayer()
})
.finally(() => {
this.preparing = undefined
})
return this.preparing
}
/**
* Ensure we have a reusable player instance. The default 500 ms status
* interval only paces position updates: expo-audio reports play/pause and
* completion from player events on both platforms.
*/
private ensurePlayer(): AudioPlayer {
if (!this.player) {
console.log("AUDIO: Creating reusable AudioPlayer instance")
this.player = createAudioPlayer(null)
// Add status listener once - it will handle all playback completions
this.player.addListener("playbackStatusUpdate", (status: AudioStatus) => {
this.onPlaybackStatusUpdate(status)
})
}
return this.player
}
private async getGlassesMediaVolumeWithTiming() {
const startedAt = Date.now()
try {
const result = await BluetoothSdk.getGlassesMediaVolume()
console.log(`AUDIO: Glasses media volume read completed in ${Date.now() - startedAt}ms`)
return result
} catch (error) {
console.warn(
`AUDIO: Glasses media volume read failed after ${Date.now() - startedAt}ms:`,
error instanceof Error ? error.message : String(error),
)
throw error
}
}
private async setGlassesMediaVolumeWithTiming(level: number) {
const startedAt = Date.now()
try {
const result = await BluetoothSdk.setGlassesMediaVolume(level)
console.log(`AUDIO: Glasses media volume set(${level}) completed in ${Date.now() - startedAt}ms`)
return result
} catch (error) {
console.warn(
`AUDIO: Glasses media volume set(${level}) failed after ${Date.now() - startedAt}ms:`,
error instanceof Error ? error.message : String(error),
)
throw error
}
}
/**
* Mentra Live: raise glasses media volume over BLE when it is very low so A2DP prompts are audible.
* Fail-open on unsupported devices, timeouts, or errors.
*/
private async ensureGlassesMediaVolumeForA2dp(playback: PlaybackState): Promise<void> {
if (this.glassesVolumeRestoreLevel !== null) {
console.log(
`AUDIO: Keeping bumped glasses media volume at ${AudioPlaybackService.GLASSES_VOLUME_FLOOR} during ongoing playback`,
)
return
}
try {
const raw = await this.getGlassesMediaVolumeWithTiming()
const level = Number(raw.level)
const statusCode = Number(raw.statusCode)
if (!Number.isFinite(level)) {
console.log("AUDIO: Received glasses media volume response without numeric level:", JSON.stringify(raw))
return
}
const k900S = Number.isFinite(statusCode) && statusCode >= 0 ? ` K900_S=${statusCode}` : ""
console.log(`AUDIO: Glasses media step volume (wearable knob, 0-15 scale): ${level}/15.${k900S}`)
if (level > AudioPlaybackService.GLASSES_VOLUME_LOW_THRESHOLD) {
return
}
if (this.currentPlayback !== playback || playback.completed) {
console.log("AUDIO: Skipping glasses volume bump; playback already ended")
return
}
console.log(`AUDIO: Raising glasses media volume (was ${level})`)
await this.setGlassesMediaVolumeWithTiming(AudioPlaybackService.GLASSES_VOLUME_FLOOR)
if (this.currentPlayback === playback && !playback.completed) {
this.glassesVolumeRestoreLevel = level
} else if (RESTORE_GLASSES_VOLUME_AFTER_PLAYBACK) {
console.log("AUDIO: Restoring glasses volume immediately; playback ended during volume bump")
await this.setGlassesMediaVolumeWithTiming(level)
} else {
console.log("AUDIO: Leaving bumped glasses media volume unchanged after playback")
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
console.warn("AUDIO: Skipping glasses volume bump:", msg)
}
}
/**
* Restore the user's original glasses media step volume after A2DP playback finishes.
*/
private async restoreGlassesMediaVolume(): Promise<void> {
const restoreLevel = this.glassesVolumeRestoreLevel
if (restoreLevel === null) {
return
}
if (!RESTORE_GLASSES_VOLUME_AFTER_PLAYBACK) {
this.glassesVolumeRestoreLevel = null
console.log("AUDIO: Leaving bumped glasses media volume unchanged after playback")
return
}
try {
console.log(`AUDIO: Restoring glasses media volume to ${restoreLevel}`)
await this.setGlassesMediaVolumeWithTiming(restoreLevel)
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
console.warn(`AUDIO: Failed to restore glasses volume to ${restoreLevel}:`, msg)
} finally {
this.glassesVolumeRestoreLevel = null
}
}
private clearStartupTimer(playback: PlaybackState): void {
if (playback.startupTimer === null) return
BgTimer.clearTimeout(playback.startupTimer)
playback.startupTimer = null
}
private unloadPlaybackSource(playback: PlaybackState, reason: string): void {
this.clearStartupTimer(playback)
if (this.loadedPlayback !== playback) return
const player = this.player
if (!player) {
this.loadedPlayback = null
return
}
try {
player.pause()
} catch (e) {
console.warn(`AUDIO: Error pausing ${playback.requestId} during ${reason}:`, e)
}
try {
// replace(null) fails native argument casting on iOS, while remove()
// destroys the ExoPlayer that Android must reuse to avoid AudioTrack
// exhaustion. Replacing with bundled silence detaches the previous media
// item on both platforms and leaves the native player alive.
player.replace(SILENT_AUDIO_SOURCE)
console.log(`AUDIO: Cleared source for ${playback.requestId} during ${reason}`)
} catch (e) {
console.warn(`AUDIO: Error clearing ${playback.requestId} during ${reason}:`, e)
} finally {
if (this.loadedPlayback === playback) this.loadedPlayback = null
}
}
private clearFinishedPlayerAfterTail(playback: PlaybackState): void {
if (playback.suppressCloudUplink) {
this.tailUplinkSuppressions.add(playback.uplinkSuppressionId)
}
BgTimer.setTimeout(() => {
// ExoPlayer's completion event precedes the final A2DP audio reaching the
// glasses. Keep cloud STT gated until that audible tail has drained, then
// accept fresh microphone audio immediately without restarting LC3.
if (playback.suppressCloudUplink && this.tailUplinkSuppressions.delete(playback.uplinkSuppressionId)) {
setAudioCloudUplinkSuppressed(playback.uplinkSuppressionId, false)
}
this.unloadPlaybackSource(playback, `${AudioPlaybackService.A2DP_TAIL_DRAIN_MS}ms A2DP tail drain`)
}, AudioPlaybackService.A2DP_TAIL_DRAIN_MS)
}
private releaseTailUplinkSuppressions(): void {
for (const sourceId of this.tailUplinkSuppressions) {
setAudioCloudUplinkSuppressed(sourceId, false)
}
this.tailUplinkSuppressions.clear()
}
private failPlayback(playback: PlaybackState, message: string): void {
if (this.currentPlayback !== playback || playback.completed) return
console.error(`AUDIO: Playback failed for ${playback.requestId}: ${message}`)
playback.completed = true
this.currentPlayback = null
if (playback.suppressCloudUplink) {
setAudioCloudUplinkSuppressed(playback.uplinkSuppressionId, false)
}
this.unloadPlaybackSource(playback, "playback failure")
this.notifyAudioStopDebounced()
void this.restoreGlassesMediaVolume()
// Unload and finish bookkeeping before the caller can start offline TTS.
playback.onComplete(playback.requestId, false, message, null, "error")
}
/**
* Play audio from a URL.
* Returns a promise that resolves with playback result when audio finishes or errors.
*/
public async play(request: AudioPlayRequest, onComplete: AudioPlaybackCompletion): Promise<void> {
const {requestId, audioUrl, appId, volume = 1.0, stopOtherAudio = true, suppressCloudUplink = false} = request
const startPositionMs = Number.isFinite(request.startPositionMs) ? Math.max(0, request.startPositionMs!) : 0
const now = Date.now()
const activeDuplicate =
this.currentPlayback &&
!this.currentPlayback.completed &&
this.currentPlayback.appId === appId &&
this.currentPlayback.audioUrl === audioUrl &&
this.currentPlayback.startPositionMs === startPositionMs &&
now - this.currentPlayback.startTime < AudioPlaybackService.DUPLICATE_PLAY_WINDOW_MS
const pendingDuplicate = [...this.pendingPlaybacks.values()].some(
(candidate) =>
!candidate.cancelled &&
candidate.appId === appId &&
candidate.audioUrl === audioUrl &&
candidate.startPositionMs === startPositionMs &&
now - candidate.createdAt < AudioPlaybackService.DUPLICATE_PLAY_WINDOW_MS,
)
if (activeDuplicate || pendingDuplicate) {
console.warn(`AUDIO: Suppressed duplicate play request ${requestId}${appId ? ` from ${appId}` : ""}`)
onComplete(requestId, false, "Duplicate audio request suppressed", 0, "error")
return
}
const pending: PendingPlaybackState = {cancelled: false, audioUrl, appId, createdAt: now, startPositionMs}
this.pendingPlaybacks.set(requestId, pending)
const loggedUrl = audioUrl.startsWith("data:")
? `${audioUrl.split(",")[0]},[bundled audio]`
: /^https?:/i.test(audioUrl)
? audioUrl.split("?")[0]
: audioUrl
console.log(`AUDIO: Play request ${requestId}${appId ? ` from ${appId}` : ""}: ${loggedUrl}`)
try {
// Ensure audio mode is configured for background playback
await this.ensureAudioModeConfigured()
if (pending.cancelled) {
onComplete(requestId, true, null, 0, "interrupted")
return
}
// URL playback reuses one native player, so replacing its source always
// interrupts the previous URL even when stopOtherAudio is false. Notify
// that request before replacing it so its promise cannot hang. The option
// still controls whether separate PCM streams are interrupted below.
if (this.currentPlayback && !this.currentPlayback.completed) {
console.log(`AUDIO: Interrupting current URL playback for new request`)
this.interruptCurrentPlayback(true)
}
// Live PCM streams count as "other audio" too.
if (stopOtherAudio) {
await this.abortAllStreams()
}
if (pending.cancelled) {
onComplete(requestId, true, null, 0, "interrupted")
return
}
if (!suppressCloudUplink) {
this.releaseTailUplinkSuppressions()
}
// Get or create the reusable player
const player = this.ensurePlayer()
// Set volume
player.volume = Math.max(0, Math.min(1, volume))
// Store the new playback state
const playback: PlaybackState = {
startPositionMs,
startupTimer: null,
hasStarted: false,
requestId,
audioUrl,
uplinkSuppressionId: `url:${requestId}`,
appId,
startTime: Date.now(),
completed: false,
suppressCloudUplink,
onComplete,
}
this.currentPlayback = playback
this.pendingPlaybacks.delete(requestId)
if (playback.suppressCloudUplink) {
setAudioCloudUplinkSuppressed(playback.uplinkSuppressionId, true)
}
// Replace the source and play
// Using replace() reuses the existing ExoPlayer/AudioTrack instead of creating new ones
if (startPositionMs > 0) player.pause()
player.replace({uri: audioUrl})
this.loadedPlayback = playback
if (startPositionMs > 0) await player.seekTo(startPositionMs / 1000)
// A newer play/stop may have replaced this request while seeking.
if (this.currentPlayback !== playback || playback.completed) return
player.play()
// Mentra Live volume reads can block up to 5s when the glasses don't
// answer. Do not put that in front of playback; guard it against late
// completion so a stale volume response cannot bump after this request is
// already over.
void this.ensureGlassesMediaVolumeForA2dp(playback)
// Notify native that our app is playing audio
// Used to suspend LC3 mic during audio playback to avoid MCU overload
// Cancel any pending "stop" notification first (handles back-to-back audio)
if (this.audioStopDebounceTimer !== null) {
BgTimer.clearTimeout(this.audioStopDebounceTimer)
this.audioStopDebounceTimer = null
}
BluetoothSdk.setOwnAppAudioPlaying(true).catch((e) => {
console.warn("AUDIO: Failed to notify native of audio start:", e)
})
console.log(`AUDIO: Requested native playback for ${requestId}`)
const startupTimeoutMs = request.startupTimeoutMs
if (
this.currentPlayback === playback &&
!playback.completed &&
!playback.hasStarted &&
startupTimeoutMs !== undefined &&
Number.isFinite(startupTimeoutMs) &&
startupTimeoutMs > 0
) {
playback.startupTimer = BgTimer.setTimeout(() => {
playback.startupTimer = null
if (playback.hasStarted) return
this.failPlayback(playback, `Playback did not start within ${startupTimeoutMs}ms`)
}, startupTimeoutMs)
}
} catch (error) {
if (suppressCloudUplink) {
setAudioCloudUplinkSuppressed(`url:${requestId}`, false)
}
const failedPlayback = this.currentPlayback?.requestId === requestId ? this.currentPlayback : null
if (failedPlayback) {
failedPlayback.completed = true
this.currentPlayback = null
this.unloadPlaybackSource(failedPlayback, "playback start failure")
}
if (pending.cancelled) {
onComplete(requestId, true, null, 0, "interrupted")
return
}
const errorMessage = error instanceof Error ? error.message : "Unknown error loading audio"
console.error(`AUDIO: Failed to play ${requestId}:`, errorMessage)
void this.restoreGlassesMediaVolume()
onComplete(requestId, false, errorMessage, null, "error")
} finally {
if (this.pendingPlaybacks.get(requestId) === pending) {
this.pendingPlaybacks.delete(requestId)
}
}
}
/**
* Cancel one URL playback without touching audio owned by another request.
* Pending requests are prevented from reaching the native player; active
* requests are paused synchronously before their completion callback fires.
*/
public cancelPlayback(requestId: string): void {
const pending = this.pendingPlaybacks.get(requestId)
if (pending) pending.cancelled = true
// Cloud speech plays as a PCM stream keyed by its request id.
if (this.streams.has(requestId)) void this.abortStream(requestId)
if (this.currentPlayback?.requestId === requestId && !this.currentPlayback.completed) {
this.interruptCurrentPlayback()
}
}
/**
* Interrupt current playback and notify its callback
*/
private interruptCurrentPlayback(preserveGlassesMediaVolume: boolean = false): void {
if (!this.currentPlayback || this.currentPlayback.completed) return
const playback = this.currentPlayback
playback.completed = true
this.currentPlayback = null
if (playback.suppressCloudUplink) {
setAudioCloudUplinkSuppressed(playback.uplinkSuppressionId, false)
}
// Pausing alone leaves the URI available to OS/Bluetooth media Play.
// Unload it unless a newer request has already replaced this source.
this.unloadPlaybackSource(playback, "interruption")
// Notify native that our app stopped playing audio (debounced)
this.notifyAudioStopDebounced()
if (!preserveGlassesMediaVolume) {
void this.restoreGlassesMediaVolume()
}
// Notify that playback was interrupted
const elapsedMs = Date.now() - playback.startTime
playback.onComplete(playback.requestId, true, null, elapsedMs, "interrupted")
console.log(`AUDIO: Interrupted ${playback.requestId} after ${elapsedMs}ms`)
}
/**
* Handle playback status updates from expo-audio
*/
private onPlaybackStatusUpdate(status: AudioStatus): void {
const playback = this.currentPlayback
// Guard against callbacks for unknown or completed playbacks
if (!playback || playback.completed) {
return
}
if (status.playing && !status.isBuffering && status.currentTime * 1000 > playback.startPositionMs) {
playback.hasStarted = true
this.clearStartupTimer(playback)
}
// Check if playback finished
if (status.didJustFinish) {
const durationMs = (status.duration || 0) * 1000 // expo-audio uses seconds
console.log(`AUDIO: Playback finished for ${playback.requestId}, duration: ${durationMs}ms`)
playback.completed = true
this.clearStartupTimer(playback)
// ExoPlayer can report finished before an A2DP sink has audibly drained
// the last buffered audio. Pausing immediately can clip the tail on
// Mentra Live; defer cleanup and guard it against a newer loaded source.
this.clearFinishedPlayerAfterTail(playback)
this.currentPlayback = null
playback.onComplete(playback.requestId, true, null, durationMs, "completed")
// Notify native that our app stopped playing audio (debounced)
this.notifyAudioStopDebounced()
void this.restoreGlassesMediaVolume()
return
}
// iOS "failed" is terminal even during startup. Android's unloaded idle
// status can also occur during source replacement, so retain its grace period.
const wentIdle = status.playbackState === "idle" && !status.isBuffering && !status.isLoaded
const elapsedMs = Date.now() - playback.startTime
if (status.playbackState === "failed" || (wentIdle && elapsedMs > 1500)) {
this.failPlayback(
playback,
wentIdle ? "Playback failed (player went idle)" : "Playback failed (native player failed)",
)
}
}
/**
* Notify native that audio stopped, with debouncing to prevent mic toggle flicker
* when playing back-to-back audio files
*/
private notifyAudioStopDebounced(): void {
// Clear any existing timer
if (this.audioStopDebounceTimer !== null) {
BgTimer.clearTimeout(this.audioStopDebounceTimer)
}
// Set a new timer - if new audio starts within this window, the timer gets cancelled
// Uses BgTimer to work reliably when app is backgrounded on Android
this.audioStopDebounceTimer = BgTimer.setTimeout(() => {
this.audioStopDebounceTimer = null
// URL playback and live PCM streams may overlap when stopOtherAudio is false.
// A URL that ends must not clear the native playback signal while another
// source is still active, or the mic watchdog can interrupt that source.
if (this.isPlaying()) return
BluetoothSdk.setOwnAppAudioPlaying(false).catch((e) => {
console.warn("AUDIO: Failed to notify native of audio stop:", e)
})
}, AudioPlaybackService.AUDIO_STOP_DEBOUNCE_MS)
}
// ββ live PCM output streams (miniapp speaker.createStream) ββββββββββββββββ
/**
* Open a live PCM stream session. Chunks are pushed with writeStreamChunk
* into native streaming audio (AudioTrack on Android, AVAudioEngine on iOS),
* following the media route such as A2DP to connected glasses.
*/
public async openStream(request: AudioStreamOpenRequest): Promise<void> {
const {streamId, appId, sampleRate, channels, volume = 1.0, stopOtherAudio = true, jitterMs} = request
const prewarm = request.prewarm === true
console.log(
`AUDIO: Stream open ${streamId} from ${appId}: rate=${sampleRate} ch=${channels}` +
(jitterMs === undefined ? "" : ` jitterMs=${jitterMs}`) +
(prewarm ? " prewarm" : ""),
)
await this.ensureAudioModeConfigured()
// A prewarmed stream is silent until its first write, so it interrupts
// other audio then, not now.
if (stopOtherAudio && !prewarm) await this.stopOtherAudio(streamId)
await BluetoothSdk.pcmStreamOpen(streamId, sampleRate, channels, Math.max(0, Math.min(1, volume)), jitterMs)
const stream: StreamState = {
streamId,
appId,
startTime: Date.now(),
ended: false,
started: false,
stopOtherAudio,
onEnded: request.onEnded,
}
this.streams.set(streamId, stream)
if (!prewarm) this.startStreamAudio(stream)
}
/** Interrupt URL playback and every stream that is audible, sparing `exceptStreamId`. */
private async stopOtherAudio(exceptStreamId: string): Promise<void> {
if (this.currentPlayback && !this.currentPlayback.completed) {
console.log("AUDIO: Interrupting current playback for new stream")
this.interruptCurrentPlayback(true)
}
await this.abortAllStreams(exceptStreamId)
}
private startStreamAudio(stream: StreamState, suppressCloudUplink = false): void {
if (stream.started) return
stream.started = true
if (suppressCloudUplink) {
stream.uplinkSuppressionId = `stream:${stream.streamId}`
setAudioCloudUplinkSuppressed(stream.uplinkSuppressionId, true)
} else {
this.releaseTailUplinkSuppressions()
}
// Cancel any pending "stopped" notification and mark our app as playing
// audio. Streams suppress cloud STT only when the caller opts in.
if (this.audioStopDebounceTimer !== null) {
BgTimer.clearTimeout(this.audioStopDebounceTimer)
this.audioStopDebounceTimer = null
}
BluetoothSdk.setOwnAppAudioPlaying(true).catch((e) => {
console.warn("AUDIO: Failed to notify native of stream audio start:", e)
})
// Guarded against the stream ending mid-read, same as the play() path.
void this.ensureGlassesMediaVolumeForA2dpStream(stream)
}
/**
* Append base64 PCM to an open stream. Resolves with the host-side backlog
* in ms; the native write blocks while the backlog is above the
* backpressure ceiling, so awaited writes self-throttle to realtime.
*/
public async writeStreamChunk(streamId: string, base64: string): Promise<{bufferedMs: number}> {
const stream = this.streams.get(streamId)
if (!stream || stream.ended) {
throw new Error(`stream ${streamId} is not open`)
}
const firstWrite = !stream.started
if (firstWrite) {
// A prewarmed stream becomes audible now: interrupt other audio first.
if (stream.stopOtherAudio) await this.stopOtherAudio(streamId)
if (stream.ended) throw new Error(`stream ${streamId} is not open`)
}
try {
const result = await BluetoothSdk.pcmStreamWrite(streamId, base64)
if (firstWrite) this.startStreamAudio(stream)
return result
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
if (firstWrite && /not open/i.test(message)) {
// Native closed this prewarmed stream when the audio route changed
// before it played. That's an ordinary end, not a playback error: the
// caller sees "not open" and opens a fresh stream on the current route.
this.endStream(stream, true, null, 0)
throw new Error(`stream ${streamId} is not open`)
}
this.endStream(stream, false, message, Date.now() - stream.startTime)
throw error
}
}
/** Drain the backlog, then finish. Resolves with the total played duration. */
public async closeStream(streamId: string): Promise<{durationMs?: number}> {
const stream = this.streams.get(streamId)
if (!stream || stream.ended) {
throw new Error(`stream ${streamId} is not open`)
}
try {
const result = await BluetoothSdk.pcmStreamClose(streamId)
this.endStream(stream, true, null, result?.durationMs ?? Date.now() - stream.startTime)
return result ?? {}
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
this.endStream(stream, false, message, Date.now() - stream.startTime)
throw error
}
}
/** Stop immediately, dropping the backlog. Safe on unknown/ended ids. */
public async abortStream(streamId: string): Promise<void> {
const stream = this.streams.get(streamId)
await BluetoothSdk.pcmStreamAbort(streamId).catch((e) => {
console.warn(`AUDIO: Stream abort ${streamId} native call failed:`, e)
})
if (stream) {
this.endStream(stream, true, null, Date.now() - stream.startTime)
}
}
/**
* Abort every audible stream (optionally sparing one about to replace them).
* Prewarmed streams that haven't received audio are not playing anything, so
* they are left alone unless `includeUnstarted` is set.
*/
private async abortAllStreams(exceptStreamId?: string, includeUnstarted = false): Promise<void> {
const streamIds = [...this.streams.values()]
.filter((stream) => stream.streamId !== exceptStreamId && (includeUnstarted || stream.started))
.map((stream) => stream.streamId)
await Promise.all(streamIds.map((streamId) => this.abortStream(streamId)))
}
/** Terminal bookkeeping for a stream: dedup, unregister, notify. */
private endStream(stream: StreamState, success: boolean, error: string | null, durationMs: number | null): void {
if (stream.ended) return
stream.ended = true
this.streams.delete(stream.streamId)
const suppressionId = stream.uplinkSuppressionId
if (suppressionId) {
// Keep the uplink muted while the A2DP tail drains, like URL playback.
this.tailUplinkSuppressions.add(suppressionId)
BgTimer.setTimeout(() => {
if (this.tailUplinkSuppressions.delete(suppressionId)) setAudioCloudUplinkSuppressed(suppressionId, false)
}, AudioPlaybackService.A2DP_TAIL_DRAIN_MS)
}
// Only signal "audio stopped" when nothing else is making noise.
if (stream.started && !this.isPlaying()) {
this.notifyAudioStopDebounced()
void this.restoreGlassesMediaVolume()
}
stream.onEnded(stream.streamId, success, error, durationMs, stream.started)
}
/**
* Stream cloud speech from `url` (raw 16-bit little-endian mono PCM) into the
* native PCM player as it downloads. The audio never crosses into
* JavaScript. `onComplete` fires once: `completed` after the whole body
* played, `interrupted` after cancelPlayback / stopForApp / other audio, or
* `error` on an HTTP or network failure (anything already played stays
* played).
*/
public async playPcmUrl(request: AudioPcmUrlRequest, onComplete: AudioPlaybackCompletion): Promise<void> {
const {requestId, appId, url, sampleRate, volume = 1.0, jitterMs, stopOtherAudio = true} = request
console.log(
`AUDIO: PCM URL ${requestId} from ${appId}: rate=${sampleRate}` +
(jitterMs === undefined ? "" : ` jitterMs=${jitterMs}`),
)
let settled = false
// Stays false unless native reports the whole body played; an abort ends the stream first.
let playedToEnd = false
const finish: AudioPlaybackCompletion = (id, success, error, duration, reason) => {
if (settled) return
settled = true
onComplete(id, success, error, duration, reason)
}
const stream: StreamState = {
streamId: requestId,
appId,
startTime: Date.now(),
ended: false,
started: false,
stopOtherAudio,
onEnded: (id, success, error, durationMs) =>
finish(id, success, error, durationMs, success ? (playedToEnd ? "completed" : "interrupted") : "error"),
}
this.streams.set(requestId, stream)
// Speech counts as playing from the request on, so stop/interrupt reach it.
this.startStreamAudio(stream, request.suppressCloudUplink === true)
try {
await this.ensureAudioModeConfigured()
if (stream.ended) return
if (stopOtherAudio) await this.stopOtherAudio(requestId)
if (stream.ended) return
const result = await BluetoothSdk.pcmStreamPlayUrl(
requestId,
url,
sampleRate,
Math.max(0, Math.min(1, volume)),
jitterMs,
)
playedToEnd = true
this.endStream(stream, true, null, result?.durationMs ?? Date.now() - stream.startTime)
} catch (error) {
// An abort already ended the stream as interrupted; ignore its rejection.
if (stream.ended) return
// Keep the native code (http_error, unsupported_format, network_error,
// "not open") so the caller can tell a refused request from a dropped one.
const code = (error as {code?: unknown} | null)?.code
const text = error instanceof Error ? error.message : String(error)
const message = typeof code === "string" && code && !text.includes(code) ? `${code}: ${text}` : text
console.warn(`AUDIO: PCM URL ${requestId} failed: ${message}`)
this.endStream(stream, false, message, Date.now() - stream.startTime)
}
}
/** Stream twin of ensureGlassesMediaVolumeForA2dp, guarded by stream.ended. */
private async ensureGlassesMediaVolumeForA2dpStream(stream: StreamState): Promise<void> {
if (this.glassesVolumeRestoreLevel !== null) return
try {
const raw = await this.getGlassesMediaVolumeWithTiming()
const level = Number(raw.level)
if (!Number.isFinite(level) || level > AudioPlaybackService.GLASSES_VOLUME_LOW_THRESHOLD) return
if (stream.ended) return
console.log(`AUDIO: Raising glasses media volume for stream (was ${level})`)
await this.setGlassesMediaVolumeWithTiming(AudioPlaybackService.GLASSES_VOLUME_FLOOR)
if (!stream.ended) {
this.glassesVolumeRestoreLevel = level
} else {
await this.setGlassesMediaVolumeWithTiming(level)
}
} catch (e) {
console.warn("AUDIO: Skipping glasses volume bump for stream:", e instanceof Error ? e.message : String(e))
}
}
/**
* Stop playback for a specific app.
* If appId is not provided, stops all playback.
*
* Prewarmed streams that haven't received audio are kept (speaker.stop() has
* nothing of theirs to stop) unless `includeUnstarted` is set, which teardown
* paths use so no native stream outlives its miniapp.
*/
public async stopForApp(appId?: string, options: {includeUnstarted?: boolean} = {}): Promise<void> {
// Settle URL playback before awaiting the native stream aborts below. A
// request still configuring audio has not reached the player yet, so the
// stop must cancel it here; and a play() issued while those aborts run is
// newer than this stop, so it must not be interrupted when they return.
this.cancelPendingPlaybacks(appId)
if (this.currentPlayback && !this.currentPlayback.completed && (!appId || this.currentPlayback.appId === appId)) {
console.log(`AUDIO: Stopping playback for app ${appId || "(all)"}`)
this.interruptCurrentPlayback()
}
// Abort this app's live PCM streams too (miniapp stop/disconnect path).
const streamIds = [...this.streams.values()]
.filter((stream) => (!appId || stream.appId === appId) && (options.includeUnstarted || stream.started))
.map((stream) => stream.streamId)
await Promise.all(streamIds.map((streamId) => this.abortStream(streamId)))
}
/**
* Stop all audio playback
*/
public async stopAll(): Promise<void> {
this.cancelPendingPlaybacks()
if (this.currentPlayback && !this.currentPlayback.completed) {
console.log("AUDIO: Stopping all playback")
this.interruptCurrentPlayback()
}
await this.abortAllStreams(undefined, true)
}
/** Keep requests that have not reached the native player from starting later. */
private cancelPendingPlaybacks(appId?: string): void {
for (const pending of this.pendingPlaybacks.values()) {
if (!appId || pending.appId === appId) pending.cancelled = true
}
}
/**
* Check if audio is currently playing
*/
public isPlaying(): boolean {
return (
(this.currentPlayback !== null && !this.currentPlayback.completed) ||
[...this.streams.values()].some((stream) => stream.started && !stream.ended)
)
}
/**
* Get current playback app IDs (all active)
*/
public getActiveAppIds(): string[] {
const appIds = new Set<string>()
if (this.currentPlayback && !this.currentPlayback.completed && this.currentPlayback.appId) {
appIds.add(this.currentPlayback.appId)
}
for (const stream of this.streams.values()) {
if (stream.started && !stream.ended) appIds.add(stream.appId)
}
return [...appIds]
}
/**
* Get number of active playbacks
*/
public getActiveCount(): number {
const audibleStreams = [...this.streams.values()].filter((stream) => stream.started).length
return (this.currentPlayback && !this.currentPlayback.completed ? 1 : 0) + audibleStreams
}
/**
* Release the player entirely (call when app is shutting down)
*/
public release(): void {
void this.abortAllStreams(undefined, true)
if (this.currentPlayback && !this.currentPlayback.completed) {
this.interruptCurrentPlayback()
} else {
void this.restoreGlassesMediaVolume()
}
if (this.player) {
try {
this.player.remove()
console.log("AUDIO: Released AudioPlayer")
} catch (error) {
console.error("AUDIO: Error releasing player:", error)
}
this.player = null
this.loadedPlayback = null
}
}
}
const audioPlaybackService = AudioPlaybackService.getInstance()
export default audioPlaybackService
|