forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservices.dart
More file actions
475 lines (404 loc) · 13.3 KB
/
Copy pathservices.dart
File metadata and controls
475 lines (404 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:omi/services/connectivity_service.dart';
import 'package:omi/services/devices.dart';
import 'package:omi/services/mic/mic_arbiter.dart';
import 'package:omi/services/mic/native_mic_recorder_service.dart';
import 'package:omi/services/sockets.dart';
import 'package:omi/services/wals.dart';
import 'package:omi/utils/logger.dart';
class ServiceManager {
late IMicRecorderService _mic;
late IMicRecorderService _phoneMic;
late DeviceService _device;
late ISocketService _socket;
late IWalService _wal;
static ServiceManager? _instance;
static ServiceManager _create() {
ServiceManager sm = ServiceManager();
final micArbiter = MicArbiter();
sm._mic = ArbitratedMic(
inner: MicRecorderBackgroundService(runner: BackgroundService()),
arbiter: micArbiter,
owner: 'mic',
);
// Conversation capture uses the native recorder on iOS (AVAudioEngine) and
// Android (AudioRecord); chat voice memos and the speech profile stay on the
// flutter_sound path via [mic]. The shared arbiter keeps the two stacks from
// contending for the microphone.
sm._phoneMic = (Platform.isIOS || Platform.isAndroid)
? ArbitratedMic(inner: NativeMicRecorderService(), arbiter: micArbiter, owner: 'conversation')
: sm._mic;
sm._device = DeviceService();
sm._socket = SocketServicePool();
sm._wal = WalService();
return sm;
}
static ServiceManager instance() {
if (_instance == null) {
throw Exception("Service manager is not initiated");
}
return _instance!;
}
IMicRecorderService get mic => _mic;
/// The recorder for conversation capture: native on iOS and Android,
/// flutter_sound elsewhere. Chat voice memos and speech profile keep using [mic].
IMicRecorderService get phoneMic => _phoneMic;
DeviceService get device => _device;
ISocketService get socket => _socket;
IWalService get wal => _wal;
static Future<void> init() async {
if (_instance != null) {
throw Exception("Service manager is initiated");
}
_instance = ServiceManager._create();
await ConnectivityService().init();
}
Future<void> start() async {
_device.start();
_wal.start();
}
void deinit() async {
ConnectivityService().dispose();
await _wal.stop();
_mic.stop();
if (!identical(_phoneMic, _mic)) {
_phoneMic.stop();
}
_device.stop();
}
}
enum BackgroundServiceStatus { initiated, running }
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
return true;
}
@pragma('vm:entry-point')
Future onStart(ServiceInstance service) async {
// Recorder
MicRecorderService? recorder;
service.on('recorder.start').listen((event) async {
recorder = MicRecorderService(isInBG: Platform.isAndroid ? true : false);
recorder?.start(
onByteReceived: (bytes) {
Uint8List audioBytes = bytes;
List<dynamic> audioBytesList = audioBytes.toList();
service.invoke("recorder.ui.audioBytes", {"data": audioBytesList});
},
onStop: () {
service.invoke("recorder.ui.stateUpdate", {"state": 'stopped'});
},
onRecording: () {
service.invoke("recorder.ui.stateUpdate", {"state": 'recording'});
},
onStalled: () {
service.invoke("recorder.ui.stalled");
},
);
});
service.on('recorder.stop').listen((event) async {
service.invoke("recorder.ui.stateUpdate", {"state": 'stopped'});
recorder?.stop();
});
service.on('stop').listen((event) async {
if (recorder?.status != RecorderServiceStatus.stop) {
recorder?.stop();
}
service.invoke("recorder.ui.stateUpdate", {"state": 'stopped'});
service.stopSelf();
});
// watchdog
var pongAt = DateTime.now();
service.on('pong').listen((event) async {
pongAt = DateTime.now();
});
Timer.periodic(const Duration(seconds: 5), (timer) async {
if (pongAt.isBefore(DateTime.now().subtract(const Duration(seconds: 15)))) {
// retire
if (recorder?.status != RecorderServiceStatus.stop) {
recorder?.stop();
}
service.invoke("recorder.ui.stateUpdate", {"state": 'stopped'});
service.stopSelf();
return;
}
service.invoke("ui.ping");
});
}
class BackgroundService {
late FlutterBackgroundService _service;
BackgroundServiceStatus? _status;
BackgroundServiceStatus? get status => _status;
Future<void> init() async {
_service = FlutterBackgroundService();
_status = BackgroundServiceStatus.initiated;
await _service.configure(
iosConfiguration: IosConfiguration(autoStart: false, onForeground: onStart, onBackground: onIosBackground),
androidConfiguration: AndroidConfiguration(
autoStart: false,
onStart: onStart,
isForegroundMode: true,
autoStartOnBoot: false,
foregroundServiceTypes: [AndroidForegroundType.microphone],
),
);
_status = BackgroundServiceStatus.initiated;
}
Future<void> ensureRunning() async {
await init();
await start();
}
Future<void> start() async {
_service.startService();
// status
if (await _service.isRunning()) {
_status = BackgroundServiceStatus.running;
}
// heartbeat
_service.on('ui.ping').listen((event) {
_service.invoke("pong");
});
}
void stop() {
Logger.debug("invoke stop");
if (_status == null) return;
_service.invoke("stop");
}
void onStop(ServiceInstance instance) async {
_service.invoke("recorder.stateUpdate", {"state": 'stopped'});
instance.stopSelf();
}
void startRecorder({
required Function(Uint8List bytes) onByteReceived,
Function()? onRecording,
Function()? onStop,
Function()? onInitializing,
Function()? onStalled,
}) {
StreamSubscription? recordAudioByteStream = _service.on('recorder.ui.audioBytes').listen((event) {
Uint8List bytes = Uint8List.fromList(event!['data'].cast<int>());
onByteReceived(bytes);
});
StreamSubscription? recordStalledStream;
if (onStalled != null) {
recordStalledStream = _service.on('recorder.ui.stalled').listen((event) {
onStalled();
});
}
StreamSubscription? recordStateStream;
recordStateStream = _service.on('recorder.ui.stateUpdate').listen((event) {
if (event!['state'] == 'recording') {
if (onRecording != null) {
onRecording();
}
} else if (event['state'] == 'initializing') {
if (onInitializing != null) {
onInitializing();
}
} else if (event['state'] == 'stopped') {
// Close streams
recordAudioByteStream.cancel();
recordStalledStream?.cancel();
recordStateStream?.cancel();
// Callback
if (onStop != null) {
onStop();
}
}
});
// tell service > start record
_service.invoke("recorder.start");
}
void stopRecorder() {
if (_status == null) return;
_service.invoke("recorder.stop");
}
}
enum RecorderServiceStatus { initialising, recording, stop }
abstract class IMicRecorderService {
Future<void> start({
required Function(Uint8List bytes) onByteReceived,
Function()? onRecording,
Function()? onStop,
Function()? onInitializing,
Function()? onStalled,
// Fired with began=true/false around an audio-session interruption. Only
// NativeMicRecorderService emits it — capture resumes natively; Dart just
// mirrors the state.
Function(bool began)? onInterruption,
});
// Transcribe Later capture: audio is opus-encoded and written to WAL-compatible
// .bin files natively (no onByteReceived — nothing streams to Dart). onBatchStalled
// fires when the native liveness feed (onBatchProgress) goes silent; onError
// forwards non-fatal native failures (e.g. batch_storage_full). Requires the native
// recorder (`ServiceManager.phoneMic` on iOS/Android); the flutter_sound
// implementations throw UnsupportedError.
Future<void> startBatch({
Function()? onStop,
Function(bool began)? onInterruption,
Function()? onBatchStalled,
Function(String code, String message)? onError,
});
void stop();
/// Soft-rearm frame/progress liveness after the app returns to foreground.
/// iOS may suspend Dart timers while Stage Manager lets another app steal
/// the mic (#4706). Must not immediately escalate — that races native rebuild
/// and false-restarts healthy sessions. No-op on flutter_sound stacks.
void probeStallAfterForeground();
}
class MicRecorderBackgroundService implements IMicRecorderService {
late BackgroundService _runner;
MicRecorderBackgroundService({required BackgroundService runner}) {
_runner = runner;
}
@override
Future<void> start({
required Function(Uint8List bytes) onByteReceived,
Function()? onRecording,
Function()? onStop,
Function()? onInitializing,
Function()? onStalled,
Function(bool began)? onInterruption,
}) async {
await _runner.ensureRunning();
_runner.startRecorder(
onByteReceived: onByteReceived,
onRecording: onRecording,
onStop: onStop,
onInitializing: onInitializing,
onStalled: onStalled,
);
return;
}
@override
Future<void> startBatch({
Function()? onStop,
Function(bool began)? onInterruption,
Function()? onBatchStalled,
Function(String code, String message)? onError,
}) async {
throw UnsupportedError('batch capture requires the native recorder');
}
@override
void stop() {
_runner.stopRecorder();
}
@override
void probeStallAfterForeground() {}
}
class MicRecorderService implements IMicRecorderService {
// Window without a single audio byte that counts as a stall.
// Phone mic at 16 kHz/PCM16 emits ~10 buffer events per second; 3 s of silence
// is well past any normal jitter and comfortably covers an iOS audio-session
// interruption (the OS pauses the engine, bytes stop flowing immediately).
static const Duration _stallThreshold = Duration(seconds: 3);
static const Duration _stallCheckInterval = Duration(seconds: 1);
RecorderServiceStatus? _status;
late FlutterSoundRecorder _recorder;
late StreamController<Uint8List> _controller;
Function(Uint8List bytes)? _onByteReceived;
Function? _onRecording;
Function? _onStop;
Function? _onStalled;
bool _isInBG = false;
DateTime? _lastByteAt;
Timer? _stallTimer;
bool _stallReported = false;
MicRecorderService({bool isInBG = false}) {
_recorder = FlutterSoundRecorder();
_isInBG = isInBG;
}
get status => _status;
@override
Future<void> start({
required Function(Uint8List bytes) onByteReceived,
Function()? onRecording,
Function()? onStop,
Function()? onInitializing,
Function()? onStalled,
Function(bool began)? onInterruption,
}) async {
if (_status == RecorderServiceStatus.recording) {
throw Exception("Recorder is recording, please stop it before start new recording.");
}
if (_status == RecorderServiceStatus.initialising) {
throw Exception("Recorder is initialising");
}
_status = RecorderServiceStatus.initialising;
// callback
_onByteReceived = onByteReceived;
_onStop = onStop;
_onRecording = onRecording;
_onStalled = onStalled;
if (_onRecording != null) {
_onRecording!();
}
// new record
await _recorder.openRecorder(isBGService: _isInBG);
_controller = StreamController<Uint8List>();
await _recorder.startRecorder(
toStream: _controller.sink,
codec: Codec.pcm16,
numChannels: 1,
sampleRate: 16000,
bufferSize: 8192,
);
_lastByteAt = DateTime.now();
_stallReported = false;
_controller.stream.listen((buffer) {
_lastByteAt = DateTime.now();
_stallReported = false;
if (_onByteReceived != null) {
_onByteReceived!(buffer);
}
});
_stallTimer?.cancel();
_stallTimer = Timer.periodic(_stallCheckInterval, (_) {
// The stream going silent for longer than the threshold means the native
// audio engine has stopped delivering bytes — on iOS this happens when
// AVAudioSession is interrupted (incoming call) and is not resumed.
if (_stallReported || _lastByteAt == null) return;
if (DateTime.now().difference(_lastByteAt!) >= _stallThreshold) {
_stallReported = true;
_onStalled?.call();
}
});
_status = RecorderServiceStatus.recording;
return;
}
@override
Future<void> startBatch({
Function()? onStop,
Function(bool began)? onInterruption,
Function()? onBatchStalled,
Function(String code, String message)? onError,
}) async {
throw UnsupportedError('batch capture requires the native recorder');
}
@override
void stop() {
_stallTimer?.cancel();
_stallTimer = null;
_lastByteAt = null;
_stallReported = false;
_recorder.stopRecorder();
_recorder.closeRecorder();
_controller.close();
// callback
_status = RecorderServiceStatus.stop;
if (_onStop != null) {
_onStop!();
}
_onByteReceived = null;
_onStop = null;
_onRecording = null;
_onStalled = null;
}
@override
void probeStallAfterForeground() {}
}