Open History to see the last commit
1import { RegistryContext, useAtomMount } from "@effect/atom-react";
2import {
3 AudioModule,
4 RecordingPresets,
5 requestRecordingPermissionsAsync,
6 setAudioModeAsync,
7 setIsAudioActiveAsync,
8 type RecorderState,
9 type RecordingStatus,
10} from "expo-audio";
11import { File } from "expo-file-system";
12import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake";
13import {
14 createContext,
15 use,
16 useCallback,
17 useEffect,
18 useId,
19 useRef,
20 useState,
21 type ReactNode,
22} from "react";
23import { AppState, Platform } from "react-native";
24import { AsyncResult } from "effect/reactivity";
25import { useSharedValue } from "react-native-reanimated";
26
27import {
28 microphoneOrder,
29 preferredMicrophoneInput,
30 rememberMicrophones,
31} from "../../lib/microphonePriority";
32import { getLocalVoiceTranscriber } from "../../native/voiceTranscription";
33import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
34import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene";
35import {
36 VOICE_RECORDING_LIMIT_SECONDS,
37 voiceInputBlocksSubmission,
38 type VoiceInputState,
39} from "@t3tools/client-runtime/voice-input";
40import { createLazyVoiceRecorder, type LazyVoiceRecorder } from "./lazyVoiceRecorder";
41import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
42import { VoiceInputSession } from "./voiceInputSession";
43
44const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
45const VOICE_METERING_INTERVAL_MS = 80;
46// The native constructor takes platform-flattened options, as `useAudioRecorder`
47// builds them with expo-audio's internal `createRecordingOptions`.
48const { ios: IOS_RECORDING_OPTIONS, android: ANDROID_RECORDING_OPTIONS } =
49 RecordingPresets.HIGH_QUALITY;
50const VOICE_RECORDING_OPTIONS = {
51 extension: RecordingPresets.HIGH_QUALITY.extension,
52 sampleRate: RecordingPresets.HIGH_QUALITY.sampleRate,
53 numberOfChannels: RecordingPresets.HIGH_QUALITY.numberOfChannels,
54 bitRate: RecordingPresets.HIGH_QUALITY.bitRate,
55 isMeteringEnabled: true,
56 ...(Platform.OS === "ios" ? IOS_RECORDING_OPTIONS : ANDROID_RECORDING_OPTIONS),
57};
58
59async function releaseVoiceRecordingAudio(): Promise<void> {
60 try {
61 await setAudioModeAsync({ allowsRecording: false });
62 } finally {
63 // Expo does not deactivate AVAudioSession when recording stops or its
64 // category changes. Explicit deactivation resumes interrupted app audio.
65 await setIsAudioActiveAsync(false);
66 }
67}
68
69async function configureVoiceRecordingAudio(): Promise<void> {
70 try {
71 await setAudioModeAsync({
72 allowsRecording: true,
73 interruptionMode: "doNotMix",
74 playsInSilentMode: true,
75 shouldPlayInBackground: false,
76 });
77 await setIsAudioActiveAsync(true);
78 } catch (error) {
79 try {
80 await releaseVoiceRecordingAudio();
81 } catch {}
82 throw error;
83 }
84}
85
86const VoiceInputContext = createContext<ReturnType<typeof useVoiceInputRuntime> | null>(null);
87
88export function VoiceInputProvider({ children }: { readonly children: ReactNode }) {
89 const runtime = useVoiceInputRuntime();
90 return <VoiceInputContext value={runtime}>{children}</VoiceInputContext>;
91}
92
93export function useGlobalVoiceInput() {
94 const context = use(VoiceInputContext);
95 if (!context) throw new Error("Voice input provider is missing.");
96 return context;
97}
98
99function useVoiceInputRuntime() {
100 const registry = use(RegistryContext);
101 useAtomMount(mobilePreferencesAtom);
102 useAtomMount(updateMobilePreferencesAtom);
103 const [{ state, ownerKey, label }, setState] = useState({
104 state: INITIAL_STATE,
105 ownerKey: null as string | null,
106 label: null as string | null,
107 });
108 const [focusedOwners, setFocusedOwners] = useState<ReadonlySet<string>>(new Set());
109 const setOwnerFocused = useCallback((key: string, focused: boolean) => {
110 setFocusedOwners((current) => {
111 const next = new Set(current);
112 if (focused) next.add(key);
113 else next.delete(key);
114 return next;
115 });
116 }, []);
117 const [elapsedSeconds, setElapsedSeconds] = useState(0);
118 const keepAwakeId = useId();
119 const keepAwakeSessionRef = useRef(0);
120 const elapsedSecondsRef = useRef(0);
121 const audioLevelsRef = useRef(Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0));
122 const audioLevels = useSharedValue(audioLevelsRef.current);
123 const sessionRef = useRef<VoiceInputSession | null>(null);
124 const recorderRef = useRef<LazyVoiceRecorder<RecorderState> | null>(null);
125
126 if (!sessionRef.current || !recorderRef.current) {
127 const recorder = createLazyVoiceRecorder({
128 create: () => new AudioModule.AudioRecorder(VOICE_RECORDING_OPTIONS),
129 onStatus: (status: RecordingStatus) => {
130 sessionRef.current?.controller.handleRecorderStatus({
131 isFinished: status.isFinished,
132 hasError: status.hasError || status.mediaServicesDidReset === true,
133 error: status.error,
134 url: status.url,
135 });
136 },
137 // Read when recording starts so preference changes do not re-render every composer.
138 selectInput: (inputs) => {
139 const preferences = registry.get(mobilePreferencesAtom);
140 if (!AsyncResult.isSuccess(preferences)) return null;
141 const known = microphoneOrder(preferences.value.microphones);
142 const order = rememberMicrophones(known, inputs);
143 if (order !== known) {
144 registry.set(updateMobilePreferencesAtom, {
145 transform: (current) => ({
146 microphones: rememberMicrophones(microphoneOrder(current.microphones), inputs),
147 }),
148 });
149 }
150 return preferredMicrophoneInput(inputs, order);
151 },
152 });
153 recorderRef.current = recorder;
154 sessionRef.current = new VoiceInputSession({
155 recorder,
156 getTranscriber: getLocalVoiceTranscriber,
157 requestPermission: async () => {
158 const permission = await requestRecordingPermissionsAsync();
159 return { granted: permission.granted, canAskAgain: permission.canAskAgain };
160 },
161 configureRecording: configureVoiceRecordingAudio,
162 releaseRecording: releaseVoiceRecordingAudio,
163 deleteRecording: (uri) => new File(uri).delete(),
164 onStateChange: (nextState) =>
165 setState({
166 state: nextState,
167 ownerKey: sessionRef.current?.ownerKey ?? null,
168 label: sessionRef.current?.label ?? null,
169 }),
170 });
171 }
172
173 const session = sessionRef.current;
174 const controller = session.controller;
175 const recorder = recorderRef.current;
176
177 useEffect(() => {
178 const subscription = AppState.addEventListener("change", (nextState) => {
179 // iOS reports `inactive` while its permission dialog is open. Only the
180 // real background state cancels preparation; recorder status handles
181 // calls and route interruptions during capture.
182 if (nextState === "background") controller.appMovedToBackground();
183 });
184 return () => subscription.remove();
185 }, [controller]);
186
187 useEffect(
188 () => () => {
189 controller.dispose();
190 recorder.release();
191 },
192 [controller, recorder],
193 );
194
195 useEffect(() => {
196 if (state.phase !== "recording") return;
197
198 const tag = `voice-input:${keepAwakeId}:${++keepAwakeSessionRef.current}`;
199 const activation = activateKeepAwakeAsync(tag);
200 void activation.catch(() => {});
201 return () => {
202 // Release after activation settles, even if the recording ends immediately.
203 void activation.then(() => deactivateKeepAwake(tag)).catch(() => {});
204 };
205 }, [keepAwakeId, state.phase]);
206
207 useEffect(() => {
208 if (state.phase !== "preparing" && state.phase !== "recording") return;
209
210 if (audioLevelsRef.current.some((level) => level !== 0)) {
211 audioLevelsRef.current = Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0);
212 audioLevels.value = audioLevelsRef.current;
213 }
214 if (elapsedSecondsRef.current !== 0) {
215 elapsedSecondsRef.current = 0;
216 setElapsedSeconds(0);
217 }
218 if (state.phase !== "recording") return;
219
220 const sampleRecording = () => {
221 if (controller.currentState.phase !== "recording") return;
222 const status = recorder.getStatus();
223 if (!status?.isRecording) return;
224
225 const level = normalizeVoiceInputDecibels(status.metering);
226 const history = audioLevelsRef.current;
227 if (level !== 0 || history.some((sample) => sample !== 0)) {
228 const nextLevels = [...history.slice(1), level];
229 audioLevelsRef.current = nextLevels;
230 audioLevels.value = nextLevels;
231 }
232
233 const nextElapsedSeconds = Math.min(
234 VOICE_RECORDING_LIMIT_SECONDS,
235 Math.max(0, Math.floor(status.durationMillis / 1_000)),
236 );
237 if (nextElapsedSeconds !== elapsedSecondsRef.current) {
238 elapsedSecondsRef.current = nextElapsedSeconds;
239 setElapsedSeconds(nextElapsedSeconds);
240 }
241 };
242
243 sampleRecording();
244 const intervalId = setInterval(sampleRecording, VOICE_METERING_INTERVAL_MS);
245 return () => clearInterval(intervalId);
246 }, [audioLevels, controller, recorder, state.phase]);
247
248 const stop = useCallback(() => controller.stop(), [controller]);
249 const cancel = useCallback(() => controller.cancel(), [controller]);
250
251 return {
252 isAvailable: getLocalVoiceTranscriber() !== null || getNativeShowcaseScene() !== null,
253 state,
254 audioLevels,
255 elapsedSeconds,
256 isBusy: voiceInputBlocksSubmission(state),
257 ownerKey,
258 label,
259 focusedOwners,
260 setOwnerFocused,
261 session,
262 stop,
263 cancel,
264 };
265}