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