1
import 'dart:async';
2
+
3
+import 'package:flutter/foundation.dart';
4
+import 'package:flutter/services.dart';
5
import 'package:flutter_riverpod/flutter_riverpod.dart';
6
import 'package:speech_to_text/speech_to_text.dart';
7
+
8
import '../../../core/logger/app_logger.dart';
9
+import '../utils/stt_error_messages.dart';
10
11
/// Double in dB-ish units (iOS) or 0..1-ish (Android) reported by the
12
/// speech_to_text plugin via `onSoundLevelChange`. Higher = louder.
42
}
43
44
class SttNotifier extends Notifier<SttState> {
45
+ SttNotifier({SpeechToText Function()? speechFactory})
46
+ : _speechFactory = speechFactory ?? SpeechToText.new;
47
+
48
+ /// Delay before re-listening after an `error_client`, giving the platform
49
+ /// recognizer time to release the previous session.
50
+ static const clientErrorRetryDelay = Duration(milliseconds: 300);
51
+
52
+ final SpeechToText Function() _speechFactory;
53
late SpeechToText _speech;
54
bool _isInit = false;
55
Future<bool>? _initialization;
59
// Snapshot of the most recently issued session id. Set to -1 when no
60
// listen() is in flight.
61
int _activeSession = -1;
62
+ // Re-issues the current listen() with the same callbacks. Null when no
63
+ // listen is in flight.
64
+ Future<void> Function()? _relisten;
65
+ bool _retriedClientError = false;
66
+ // Android: use the on-device recognizer instead of the default service.
67
+ // Flipped after an `error_client`, which is what devices without Google
68
+ // speech services (e.g. GrapheneOS) report for the default one (#100).
69
+ bool _useOnDeviceRecognizer = false;
70
+ bool _switchedRecognizerForRetry = false;
71
72
@override
73
SttState build() {
52
- _speech = SpeechToText();
74
+ _speech = _speechFactory();
75
ref.onDispose(() {
76
try {
77
_speech.cancel();
93
onError: (val) {
94
if (!ref.mounted) return;
95
Log.error('STT error: ${val.errorMsg} - permanent: ${val.permanent}');
96
+ if (val.errorMsg == 'error_client' && _retryAfterClientError()) {
97
+ return;
98
+ }
99
+ if (_switchedRecognizerForRetry) {
100
+ // The other recognizer didn't help either; go back to the
101
+ // original one for the next attempt.
102
+ _useOnDeviceRecognizer = !_useOnDeviceRecognizer;
103
+ _switchedRecognizerForRetry = false;
104
+ }
105
state = state.copyWith(error: val.errorMsg, isListening: false);
106
},
107
onStatus: (val) {
128
} catch (e) {
129
if (!ref.mounted) return false;
130
Log.error('STT initialization failed: $e');
100
- state = state.copyWith(isAvailable: false, error: e.toString());
131
+ final noRecognizer =
132
+ e is PlatformException && e.code == 'recognizerNotAvailable';
133
+ state = state.copyWith(
134
+ isAvailable: false,
135
+ error: noRecognizer ? sttUnavailableCode : e.toString(),
136
+ );
137
return false;
138
} finally {
139
_initialization = null;
159
recognizedWords: '',
160
clearError: true,
161
);
162
+ _retriedClientError = false;
163
+ _switchedRecognizerForRetry = false;
164
+ _relisten = () => _listen(
165
+ onResult: onResult,
166
+ onFinal: onFinal,
167
+ onSoundLevelChange: onSoundLevelChange,
168
+ );
169
+ await _relisten!();
170
+ }
171
+
172
+ Future<void> _listen({
173
+ required void Function(String) onResult,
174
+ void Function(String)? onFinal,
175
+ SoundLevelChange? onSoundLevelChange,
176
+ }) async {
177
_session++;
178
_activeSession = _session;
179
199
pauseFor: const Duration(seconds: 5),
200
partialResults: true,
201
cancelOnError: true,
202
+ onDevice: _useOnDeviceRecognizer,
203
),
204
);
205
} catch (e) {
209
}
210
}
211
212
+ /// Retries the current listen once after an `error_client`. On Android the
213
+ /// retry switches between the default and the on-device recognizer.
214
+ /// Returns false when the error should be surfaced instead.
215
+ bool _retryAfterClientError() {
216
+ final relisten = _relisten;
217
+ if (relisten == null || _retriedClientError) return false;
218
+ _retriedClientError = true;
219
+ if (defaultTargetPlatform == TargetPlatform.android) {
220
+ _useOnDeviceRecognizer = !_useOnDeviceRecognizer;
221
+ _switchedRecognizerForRetry = true;
222
+ }
223
+ Log.warning(
224
+ 'STT error_client, retrying once '
225
+ '(onDevice: $_useOnDeviceRecognizer)',
226
+ );
227
+ final session = _session;
228
+ unawaited(() async {
229
+ try {
230
+ await _speech.cancel();
231
+ } catch (e) {
232
+ Log.error('STT cancel before retry failed: $e');
233
+ }
234
+ await Future<void>.delayed(clientErrorRetryDelay);
235
+ // Bail if the caller stopped or restarted listening meanwhile.
236
+ if (!ref.mounted || _session != session || _relisten != relisten) {
237
+ return;
238
+ }
239
+ await relisten();
240
+ }());
241
+ return true;
242
+ }
243
+
244
Future<void> stopListening() async {
245
// Invalidate the current session so any in-flight status callbacks
246
// are ignored.
247
+ _relisten = null;
248
_session++;
249
_activeSession = -1;
250
try {
257
}
258
259
Future<void> cancelListening() async {
260
+ _relisten = null;
261
_session++;
262
_activeSession = -1;
263
try {