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