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