Open History to see the last commit
1import { requireOptionalNativeModule } from "expo";
2import type { RecorderState, RecordingStatus } from "expo-audio";
3import { msg, type Msg } from "gt-react-native";
4import { Platform } from "react-native";
5import type { NativeVoiceRecorder } from "../features/voice-input/lazyVoiceRecorder";
6import { m } from "../i18n/messages";
7
8import {
9 VoiceTranscriptionError,
10 throwIfVoiceTranscriptionAborted,
11 type VoiceTranscriber,
12} from "@t3tools/client-runtime/voice-input";
13
14type PreparedGoogleTranscription = { readonly locale: string; readonly mode: number };
15
16type GoogleTranscriptionModule = {
17 checkAvailability(): Promise<boolean>;
18 prepare(id: number): Promise<PreparedGoogleTranscription>;
19 transcribe(id: number, uri: string, locale: string, mode: number): Promise<string>;
20 cancel(id: number): Promise<void>;
21 readonly LiveVoiceRecorder?: new () => NativeVoiceRecorder<RecordingStatus, RecorderState>;
22 startLive?(id: number, uri: string, locale: string, mode: number): Promise<string>;
23};
24
25const native = requireOptionalNativeModule<GoogleTranscriptionModule>("T3VoiceTranscription");
26
27const nativeErrorMessages: Readonly<Record<string, string | Msg>> = {
28 unavailable: msg("On-device voice transcription is not available for this device language."),
29 storage: msg("Not enough storage for on-device dictation. Free device storage and retry."),
30 quota: msg("On-device speech quota reached. Let the device rest or charge it, then retry."),
31 "no-speech": msg("No speech was detected. Speak again and retry dictation."),
32 busy: msg("On-device speech is busy. Wait for it to finish, then retry dictation."),
33 "needs-update": msg`Update ${{ platform: "Android" }} and its on-device speech services, then retry dictation.`,
34 "download-failed": msg("Speech model download failed. Check your network connection and retry."),
35 "audio-overflow": msg(
36 "The speech engine could not process the complete recording. No text was added. Retry dictation.",
37 ),
38 "incomplete-audio": msg(
39 "Speech recognition could not process the complete recording. No text was added. Retry dictation.",
40 ),
41};
42
43let nextOperationId = 0;
44
45export function createLiveVoiceRecorder() {
46 return Number(Platform.Version) >= 31 && native?.LiveVoiceRecorder
47 ? new native.LiveVoiceRecorder()
48 : null;
49}
50
51export async function getLocalVoiceTranscriber(): Promise<VoiceTranscriber | null> {
52 if (!native || !(await native.checkAvailability())) return null;
53 const module = native;
54 return {
55 prepare: async ({ signal }) => {
56 const prepared = await runOperation(module, signal, "preparation-failed", (id) =>
57 module.prepare(id),
58 );
59 const startLive = module.startLive?.bind(module);
60 return {
61 locale: prepared.locale,
62 ...(module.LiveVoiceRecorder && startLive
63 ? {
64 start: (uri: string, { signal }: { signal: AbortSignal }) =>
65 runOperation(module, signal, "transcription-failed", (id) =>
66 startLive(id, uri, prepared.locale, prepared.mode),
67 ),
68 }
69 : {}),
70 transcribe: (uri, { signal }) =>
71 runOperation(module, signal, "transcription-failed", (id) =>
72 module.transcribe(id, uri, prepared.locale, prepared.mode),
73 ),
74 };
75 },
76 };
77}
78
79async function runOperation<T>(
80 module: GoogleTranscriptionModule,
81 signal: AbortSignal,
82 fallbackCode: "preparation-failed" | "transcription-failed",
83 operation: (id: number) => Promise<T>,
84): Promise<T> {
85 throwIfVoiceTranscriptionAborted(signal);
86 const id = ++nextOperationId;
87 let cancellation: Promise<void> | undefined;
88 const abort = () => {
89 cancellation = module.cancel(id).catch(() => {});
90 };
91 signal.addEventListener("abort", abort, { once: true });
92 try {
93 const result = await operation(id);
94 throwIfVoiceTranscriptionAborted(signal);
95 return result;
96 } catch (error) {
97 throwIfVoiceTranscriptionAborted(signal);
98 const code =
99 typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
100 throw new VoiceTranscriptionError({
101 code: code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,
102 message:
103 m(typeof code === "string" ? nativeErrorMessages[code] : undefined) ??
104 (fallbackCode === "preparation-failed"
105 ? m(
106 msg`Voice transcription could not prepare this language. Check ${{ service: "Google speech services" }} and try again.`,
107 )
108 : m(msg("Voice transcription failed."))),
109 cause: error,
110 });
111 } finally {
112 signal.removeEventListener("abort", abort);
113 await cancellation;
114 }
115}