Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VoiceInputProvider.tsx

250 lines8.9 KB

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