Open History to see the last commit
1import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
2import { useAtomValue } from "@effect/atom-react";
3import { AudioModule, RecordingPresets, type RecordingStatus } from "expo-audio";
4import { File } from "expo-file-system";
5import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake";
6import { useSyncExternalStore } from "react";
7import { Platform } from "react-native";
8import { Effect } from "effect";
9import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
10import { makeMutable } from "react-native-reanimated";
11
12import {
13 type MicrophoneEntry,
14 microphoneOrder,
15 preferredMicrophoneInput,
16 rememberMicrophones,
17} from "../../lib/microphonePriority";
18import { getLocalVoiceTranscriber } from "../../native/voiceTranscription";
19import { createVoiceRecorder } from "../../native/voiceRecorder";
20import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences";
21import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene";
22import {
23 voiceInputBlocksSubmission,
24 type VoiceTranscriber,
25} from "@t3tools/client-runtime/voice-input";
26import { createLazyVoiceRecorder } from "./lazyVoiceRecorder";
27import { VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
28import { VoiceInputSession } from "./voiceInputSession";
29import { createVoiceRecordingPermission } from "./voiceRecordingPermission";
30import { voiceRouteAtom } from "./voiceDestination";
31import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
32import {
33 acquireAudioSession,
34 activateAudioSession,
35 releaseAudioSession,
36} from "../../lib/audioSession";
37
38// The native constructor expects platform-flattened options, as built by useAudioRecorder.
39const { ios: IOS_RECORDING_OPTIONS, android: ANDROID_RECORDING_OPTIONS } =
40 RecordingPresets.HIGH_QUALITY;
41const VOICE_RECORDING_OPTIONS = {
42 extension: RecordingPresets.HIGH_QUALITY.extension,
43 sampleRate: RecordingPresets.HIGH_QUALITY.sampleRate,
44 numberOfChannels: RecordingPresets.HIGH_QUALITY.numberOfChannels,
45 bitRate: RecordingPresets.HIGH_QUALITY.bitRate,
46 isMeteringEnabled: true,
47 ...(Platform.OS === "ios" ? IOS_RECORDING_OPTIONS : ANDROID_RECORDING_OPTIONS),
48};
49
50function keepScreenAwake(tag: string): () => void {
51 const activation = activateKeepAwakeAsync(tag);
52 void activation.catch(() => {});
53 // Release after activation settles, even if the recording ends immediately.
54 return () => void activation.then(() => deactivateKeepAwake(tag)).catch(() => {});
55}
56
57export const deviceMicrophoneOrder = (saved?: ReadonlyArray<MicrophoneEntry>) =>
58 microphoneOrder(saved, Platform.OS === "android" ? "android" : "ios");
59
60/** "checking" until the first availability probe settles; re-probed on foreground. */
61export const localVoiceTranscriberAtom = makePermissionStatusAtom<
62 VoiceTranscriber | null | "checking"
63>({
64 label: "mobile:voice-input:transcriber",
65 initial: "checking",
66 read: () => getLocalVoiceTranscriber().catch(() => null),
67}).pipe(Atom.keepAlive);
68
69const voiceInputAvailableAtom = Atom.make((get) => {
70 const route = get(voiceRouteAtom);
71 if (route) return route.transcriber !== null;
72 const transcriber = get(localVoiceTranscriberAtom);
73 return transcriber !== null && transcriber !== "checking";
74});
75
76/**
77 * The app has one microphone and one dictation at a time, so the session
78 * lives for the registry's lifetime rather than any screen's.
79 */
80export const voiceInputAtom = Atom.make((get) => {
81 const registry = get.registry;
82 // Mounted so the recorder can read known microphones synchronously.
83 get.mount(mobilePreferencesAtom);
84 const audioLevels = makeMutable<ReadonlyArray<number>>(
85 Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0),
86 );
87 let keepAwakeSequence = 0;
88 let audioToken: ReturnType<typeof acquireAudioSession> | null = null;
89 let recordingMicrophoneOrder: ReadonlyArray<MicrophoneEntry> | null = null;
90 const permission = createVoiceRecordingPermission(() => {
91 void session.controller.appMovedToBackground();
92 });
93 const recorder = createLazyVoiceRecorder({
94 getDestination: () => (registry.get(voiceRouteAtom) === null ? "local" : "environment"),
95 create: (destination) =>
96 destination === "local"
97 ? createVoiceRecorder(VOICE_RECORDING_OPTIONS)
98 : new AudioModule.AudioRecorder(VOICE_RECORDING_OPTIONS),
99 onStatus: (status: RecordingStatus) => {
100 session.controller.handleRecorderStatus({
101 isFinished: status.isFinished,
102 hasError: status.hasError || status.mediaServicesDidReset === true,
103 error: status.error,
104 url: status.url,
105 });
106 },
107 selectInput: (inputs) => {
108 const known = recordingMicrophoneOrder;
109 if (!known) return null;
110 const order = rememberMicrophones(known, inputs);
111 if (order !== known) {
112 void runAtomCommand(registry, saveMobilePreferences, {
113 transform: (current) => ({
114 microphones: rememberMicrophones(deviceMicrophoneOrder(current.microphones), inputs),
115 }),
116 });
117 }
118 return preferredMicrophoneInput(inputs, order);
119 },
120 });
121 const session: VoiceInputSession = new VoiceInputSession({
122 recorder,
123 getTranscriber: () => {
124 const route = registry.get(voiceRouteAtom);
125 if (route) return route.transcriber;
126 const transcriber = registry.get(localVoiceTranscriberAtom);
127 return transcriber === "checking" ? null : transcriber;
128 },
129 requestPermission: permission.requestPermission,
130 configureRecording: async () => {
131 const token = acquireAudioSession("recording");
132 audioToken = token;
133 try {
134 const current = registry.get(mobilePreferencesAtom);
135 const preferences = AsyncResult.isSuccess(current)
136 ? current.value
137 : await Effect.runPromise(
138 AtomRegistry.getResult(registry, mobilePreferencesAtom).pipe(
139 Effect.orElseSucceed(() => null),
140 ),
141 );
142 recordingMicrophoneOrder = preferences
143 ? deviceMicrophoneOrder(preferences.microphones)
144 : null;
145 const builtInMicFirst =
146 Platform.OS === "ios" && recordingMicrophoneOrder?.[0]?.kind === "builtIn";
147 await activateAudioSession(token, { allowBluetoothRecording: !builtInMicFirst });
148 } catch (error) {
149 await releaseAudioSession(token).catch(() => {});
150 throw error;
151 }
152 },
153 releaseRecording: async () => {
154 if (audioToken) await releaseAudioSession(audioToken);
155 audioToken = null;
156 },
157 deleteRecording: (uri) => new File(uri).delete(),
158 sampleRecording: () => {
159 const status = recorder.getStatus();
160 return status?.isRecording
161 ? { durationMillis: status.durationMillis, metering: status.metering }
162 : null;
163 },
164 publishAudioLevels: (levels) => audioLevels.set(levels),
165 keepAwake: () => keepScreenAwake(`voice-input:${++keepAwakeSequence}`),
166 });
167 get.subscribe(voiceRouteAtom, () => session.controller.cancel());
168 get.addFinalizer(() => {
169 permission.dispose();
170 session.dispose();
171 recorder.release();
172 });
173 return { session, audioLevels };
174}).pipe(Atom.keepAlive, Atom.withLabel("mobile:voice-input"));
175
176export function useGlobalVoiceInput() {
177 const { session, audioLevels } = useAtomValue(voiceInputAtom);
178 const isTranscriberAvailable = useAtomValue(voiceInputAvailableAtom);
179 const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot);
180 return {
181 ...snapshot,
182 isAvailable: isTranscriberAvailable || getNativeShowcaseScene() !== null,
183 audioLevels,
184 isBusy: voiceInputBlocksSubmission(snapshot.state),
185 session,
186 stop: () => session.controller.stop(),
187 cancel: () => session.controller.cancel(),
188 };
189}