Open History to see the last commit
1import {
2 RecordingPresets,
3 requestRecordingPermissionsAsync,
4 setAudioModeAsync,
5 setIsAudioActiveAsync,
6 useAudioRecorder,
7 type RecordingStatus,
8} from "expo-audio";
9import { File } from "expo-file-system";
10import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake";
11import { useFocusEffect } from "@react-navigation/native";
12import { useCallback, useEffect, useId, useRef, useState } from "react";
13import { AppState } from "react-native";
14import { useSharedValue } from "react-native-reanimated";
15
16import type { ComposerEditorSelection } from "../../components/ComposerEditor";
17import { getLocalVoiceTranscriber } from "../../native/voiceTranscription";
18import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene";
19import {
20 VoiceInputController,
21 VOICE_RECORDING_LIMIT_SECONDS,
22 voiceInputBlocksSubmission,
23 voiceInputFreezesEditor,
24 type VoiceDraftSnapshot,
25 type VoiceInputState,
26} from "@t3tools/client-runtime/voice-input";
27import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
28
29const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
30const VOICE_METERING_INTERVAL_MS = 80;
31const VOICE_RECORDING_OPTIONS = {
32 ...RecordingPresets.HIGH_QUALITY,
33 isMeteringEnabled: true,
34};
35
36async function releaseVoiceRecordingAudio(): Promise<void> {
37 try {
38 await setAudioModeAsync({ allowsRecording: false });
39 } finally {
40 // Expo does not deactivate AVAudioSession when recording stops or its
41 // category changes. Explicit deactivation resumes interrupted app audio.
42 await setIsAudioActiveAsync(false);
43 }
44}
45
46async function configureVoiceRecordingAudio(): Promise<void> {
47 try {
48 await setAudioModeAsync({
49 allowsRecording: true,
50 interruptionMode: "doNotMix",
51 playsInSilentMode: true,
52 shouldPlayInBackground: false,
53 });
54 await setIsAudioActiveAsync(true);
55 } catch (error) {
56 try {
57 await releaseVoiceRecordingAudio();
58 } catch {
59 // Keep the setup error. The controller has not started a recorder yet.
60 }
61 throw error;
62 }
63}
64
65export function useVoiceInputController(input: {
66 readonly ownerKey: string | null;
67 readonly draftMessage: string;
68 readonly selection: ComposerEditorSelection;
69 readonly disabled?: boolean;
70 readonly onChangeDraftMessage: (value: string) => void;
71 readonly onChangeSelection: (selection: ComposerEditorSelection) => void;
72}) {
73 const [state, setState] = useState<VoiceInputState>(INITIAL_STATE);
74 const [elapsedSeconds, setElapsedSeconds] = useState(0);
75 const keepAwakeId = useId();
76 const keepAwakeSessionRef = useRef(0);
77 const elapsedSecondsRef = useRef(0);
78 const audioLevelsRef = useRef(Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0));
79 const audioLevels = useSharedValue(audioLevelsRef.current);
80 const controllerRef = useRef<VoiceInputController | null>(null);
81 const previousDraftRef = useRef({ ownerKey: input.ownerKey, text: input.draftMessage });
82 const revisionRef = useRef(0);
83 if (
84 previousDraftRef.current.ownerKey !== input.ownerKey ||
85 previousDraftRef.current.text !== input.draftMessage
86 ) {
87 previousDraftRef.current = { ownerKey: input.ownerKey, text: input.draftMessage };
88 revisionRef.current += 1;
89 }
90 const latestInputRef = useRef(input);
91 latestInputRef.current = input;
92
93 const handleRecorderStatus = useCallback((status: RecordingStatus) => {
94 controllerRef.current?.handleRecorderStatus({
95 isFinished: status.isFinished,
96 hasError: status.hasError || status.mediaServicesDidReset === true,
97 error: status.error,
98 url: status.url,
99 });
100 }, []);
101 const recorder = useAudioRecorder(VOICE_RECORDING_OPTIONS, handleRecorderStatus);
102
103 if (!controllerRef.current) {
104 controllerRef.current = new VoiceInputController({
105 recorder,
106 getTranscriber: getLocalVoiceTranscriber,
107 requestPermission: async () => {
108 const permission = await requestRecordingPermissionsAsync();
109 return { granted: permission.granted, canAskAgain: permission.canAskAgain };
110 },
111 configureRecording: configureVoiceRecordingAudio,
112 releaseRecording: releaseVoiceRecordingAudio,
113 deleteRecording: (uri) => new File(uri).delete(),
114 readDraft: (): VoiceDraftSnapshot | null => {
115 const current = latestInputRef.current;
116 if (!current.ownerKey) return null;
117 return {
118 ownerKey: current.ownerKey,
119 text: current.draftMessage,
120 selection: current.selection,
121 revision: revisionRef.current,
122 };
123 },
124 commitDraft: (text, selection) => {
125 const current = latestInputRef.current;
126 current.onChangeSelection(selection);
127 current.onChangeDraftMessage(text);
128 },
129 onStateChange: setState,
130 });
131 }
132
133 const controller = controllerRef.current;
134 const previousOwnerRef = useRef(input.ownerKey);
135 useEffect(() => {
136 if (previousOwnerRef.current === input.ownerKey) return;
137 previousOwnerRef.current = input.ownerKey;
138 controller.ownerChanged();
139 }, [controller, input.ownerKey]);
140
141 useFocusEffect(
142 useCallback(
143 () => () => {
144 controller.dispose();
145 },
146 [controller],
147 ),
148 );
149
150 useEffect(() => {
151 const subscription = AppState.addEventListener("change", (nextState) => {
152 // iOS reports `inactive` while its permission dialog is open. Only the
153 // real background state cancels preparation; recorder status handles
154 // calls and route interruptions during capture.
155 if (nextState === "background") controller.appMovedToBackground();
156 });
157 return () => subscription.remove();
158 }, [controller]);
159
160 useEffect(() => () => controller.dispose(), [controller]);
161
162 useEffect(() => {
163 if (state.phase !== "recording") return;
164
165 const tag = `voice-input:${keepAwakeId}:${++keepAwakeSessionRef.current}`;
166 const activation = activateKeepAwakeAsync(tag);
167 void activation.catch(() => {});
168 return () => {
169 // Release after activation settles, even if the recording ends immediately.
170 void activation.then(() => deactivateKeepAwake(tag)).catch(() => {});
171 };
172 }, [keepAwakeId, state.phase]);
173
174 useEffect(() => {
175 if (state.phase !== "preparing" && state.phase !== "recording") return;
176
177 if (audioLevelsRef.current.some((level) => level !== 0)) {
178 audioLevelsRef.current = Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0);
179 audioLevels.value = audioLevelsRef.current;
180 }
181 if (elapsedSecondsRef.current !== 0) {
182 elapsedSecondsRef.current = 0;
183 setElapsedSeconds(0);
184 }
185 if (state.phase !== "recording") return;
186
187 const sampleRecording = () => {
188 if (controller.currentState.phase !== "recording") return;
189 const status = recorder.getStatus();
190 if (!status.isRecording) return;
191
192 const level = normalizeVoiceInputDecibels(status.metering);
193 const history = audioLevelsRef.current;
194 if (level !== 0 || history.some((sample) => sample !== 0)) {
195 const nextLevels = [...history.slice(1), level];
196 audioLevelsRef.current = nextLevels;
197 audioLevels.value = nextLevels;
198 }
199
200 const nextElapsedSeconds = Math.min(
201 VOICE_RECORDING_LIMIT_SECONDS,
202 Math.max(0, Math.floor(status.durationMillis / 1_000)),
203 );
204 if (nextElapsedSeconds !== elapsedSecondsRef.current) {
205 elapsedSecondsRef.current = nextElapsedSeconds;
206 setElapsedSeconds(nextElapsedSeconds);
207 }
208 };
209
210 sampleRecording();
211 const intervalId = setInterval(sampleRecording, VOICE_METERING_INTERVAL_MS);
212 return () => clearInterval(intervalId);
213 }, [audioLevels, controller, recorder, state.phase]);
214
215 const start = useCallback(() => {
216 if (!latestInputRef.current.disabled) void controller.start();
217 }, [controller]);
218 const stop = useCallback(() => controller.stop(), [controller]);
219 const cancel = useCallback(() => controller.cancel(), [controller]);
220
221 return {
222 // Store screenshots show the dictation button even on simulators, whose
223 // on-device transcription is unavailable.
224 isAvailable: getLocalVoiceTranscriber() !== null || getNativeShowcaseScene() !== null,
225 state,
226 audioLevels,
227 elapsedSeconds,
228 isBusy: voiceInputBlocksSubmission(state),
229 freezesEditor: voiceInputFreezesEditor(state),
230 blocksSubmission: voiceInputBlocksSubmission(state),
231 start,
232 stop,
233 cancel,
234 };
235}