forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapture_controller.dart
More file actions
2630 lines (2314 loc) · 103 KB
/
Copy pathcapture_controller.dart
File metadata and controls
2630 lines (2314 loc) · 103 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:omi/utils/platform/platform_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:collection/collection.dart';
import 'package:flutter_provider_utilities/flutter_provider_utilities.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:omi/backend/http/api/conversations.dart';
import 'package:omi/backend/preferences.dart';
import 'package:omi/services/auth_service.dart';
import 'package:omi/services/bridges/ble_bridge.dart';
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/backend/schema/conversation.dart';
import 'package:omi/backend/schema/geolocation.dart';
import 'package:omi/backend/schema/message.dart';
import 'package:omi/backend/schema/person.dart';
import 'package:omi/backend/schema/structured.dart';
import 'package:omi/backend/schema/transcript_segment.dart';
import 'package:omi/env/env.dart';
import 'package:omi/models/custom_stt_config.dart';
import 'package:omi/providers/device_onboarding_provider.dart';
import 'package:omi/services/capture/capture_external_actions.dart';
import 'package:omi/services/capture/capture_metrics_tracker.dart';
import 'package:omi/services/capture/conversation_source_for_device.dart';
import 'package:omi/services/capture/conversation_location_capture.dart';
import 'package:omi/utils/audio/foreground.dart';
import 'package:omi/services/capture/native_batch_geolocation.dart';
import 'package:omi/services/capture/native_ble_stream_config.dart';
import 'package:omi/services/capture/freemium_threshold_tracker.dart';
import 'package:omi/services/capture/recording_lifecycle_telemetry.dart';
import 'package:omi/services/connectivity_service.dart';
import 'package:omi/services/services.dart';
import 'package:omi/services/voice_playback/omi_voice_playback_service.dart';
import 'package:omi/services/sockets/transcription_service.dart';
import 'package:omi/services/audio_sources/audio_source.dart';
import 'package:omi/services/audio_sources/ble_device_source.dart';
import 'package:omi/services/devices/connectors/limitless_connection.dart';
import 'package:omi/services/devices/models.dart';
import 'package:omi/services/audio_sources/phone_mic_source.dart';
import 'package:omi/services/wals.dart';
import 'package:omi/utils/alerts/app_snackbar.dart';
import 'package:omi/utils/batch_recording.dart';
import 'package:omi/utils/enums.dart';
import 'package:omi/utils/image/image_utils.dart';
import 'package:omi/utils/l10n_extensions.dart';
import 'package:omi/services/battery_widget_service.dart';
import 'package:omi/utils/logger.dart';
import 'package:omi/app_globals.dart';
import 'package:omi/backend/schema/message_event.dart'
show
MessageEvent,
MessageServiceStatusEvent,
ConversationProcessingStartedEvent,
ConversationEvent,
LastConversationEvent,
SpeakerLabelSuggestionEvent,
TranslationEvent,
PhotoProcessingEvent,
PhotoDescribedEvent,
FreemiumThresholdReachedEvent,
SegmentsDeletedEvent;
class CaptureController extends ChangeNotifier
with MessageNotifierMixin
implements ITransctiptSegmentSocketServiceListener {
static const MethodChannel _nativeBleTranscriptChannel = MethodChannel('com.friend.ios/native_ble_transcript');
static const int _maxInProgressConversationRefreshAttempts = 30;
static const Duration _inProgressConversationRefreshInterval = Duration(seconds: 2);
final ConversationLocationCapture _conversationLocationCapture;
final Future<void> Function()? _inProgressConversationLoader;
final Future<BleAudioCodec> Function(String deviceId)? _audioCodecLoader;
final Future<bool> Function()? _microphonePermissionRequester;
final IMicRecorderService? _phoneMicBatchRecorder;
Geolocation? _sessionGeolocation;
int _sessionGeolocationGeneration = 0;
bool _sessionGeolocationPublishedToWal = false;
late final NativeBatchGeolocationPreferenceFence _phoneBatchGeolocationPreference =
NativeBatchGeolocationPreferenceFence(writer: _writePhoneBatchGeolocationPreference);
final RecordingLifecycleTelemetry _recordingTelemetry;
CaptureExternalActions externalActions;
DeviceOnboardingProvider? deviceOnboardingProvider;
// Cache refresh for backend-created persons
Future<void>? _peopleRefreshFuture;
TranscriptSegmentSocketService? _socket;
Timer? _keepAliveTimer;
static const Duration _rejectedTokenRefreshInterval = Duration(seconds: 30);
DateTime? _lastRejectedTokenRefreshAt;
DateTime? _keepAliveLastExecutedAt;
Timer? _inProgressConversationRefreshTimer;
int _inProgressConversationRefreshAttempts = 0;
bool _isRefreshingInProgressConversation = false;
IWalService get _wal => ServiceManager.instance().wal;
AudioSource? _activeSource;
bool _isWalSupported = false;
bool get isWalSupported => _isWalSupported;
StreamSubscription<bool>? _connectionStateListener;
bool _isConnected = ConnectivityService().isConnected;
get isConnected => _isConnected;
String? microphoneName;
double microphoneLevel = 0.0;
bool get outOfCredits => externalActions.isOutOfCredits ?? false;
String? get topConversationId => externalActions.topConversationId;
final FreemiumThresholdTracker _freemiumThreshold = FreemiumThresholdTracker();
bool get freemiumThresholdReached => _freemiumThreshold.reached;
int get freemiumRemainingSeconds => _freemiumThreshold.remainingSeconds;
/// Whether user needs to take action (e.g., setup on-device STT)
bool get freemiumRequiresUserAction => _freemiumThreshold.requiresUserAction;
List<MessageEvent> _transcriptionServiceStatuses = [];
List<MessageEvent> get transcriptionServiceStatuses => _transcriptionServiceStatuses;
MessageServiceStatusEvent? _terminalTranscriptionFailure;
MessageServiceStatusEvent? get terminalTranscriptionFailure => _terminalTranscriptionFailure;
// When custom STT is configured, its polling socket keeps
// buffering audio locally and retrying instead of tearing the transcription
// socket down on every failure (see PurePollingSocket). Surface that local
// state here so the recording UI can show "offline, buffering" instead of
// silently showing "Listening" while nothing is actually being transcribed.
PurePollingSocket? get _activeCustomSttPollingSocket {
final socket = _socket?.socket;
if (socket is CompositeTranscriptionSocket) {
final primary = socket.primarySocket;
return primary is PurePollingSocket ? primary : null;
}
return socket is PurePollingSocket ? socket : null;
}
/// How long the custom STT endpoint has been unreachable, or null if it is
/// not in use or is currently healthy.
Duration? get customSttBufferingDuration {
final since = _activeCustomSttPollingSocket?.bufferingSince;
return since == null ? null : DateTime.now().difference(since);
}
// Phone mic WAL: buffer for splitting variable-sized PCM chunks into fixed-size frames
bool _phoneMicWalActive = false;
// True while a phone-mic Transcribe Later (batch) session is running: the
// native recorder writes .bin files directly, so no socket/WAL/AudioSource is
// active. Distinct from the Live phone-mic path (_phoneMicWalActive).
bool _phoneMicBatchActive = false;
bool get isPhoneMicBatchRecording => _phoneMicBatchActive;
bool _isLoadingInProgressConversation = false;
late final CaptureMetricsTracker _metrics = CaptureMetricsTracker(onNotify: notifyListeners);
double get bleReceiveRateKbps => _metrics.bleReceiveRateKbps;
double get wsSendRateKbps => _metrics.wsSendRateKbps;
int get lifetimeBleBytesReceived => _metrics.lifetimeBleBytesReceived;
int get lifetimeWsSocketBytesSent => _metrics.lifetimeWsSocketBytesSent;
/// Call this in initState of a widget that needs BLE/WS metrics
void addMetricsListener() {
_metrics.addMetricsListener();
}
/// Call this in dispose of a widget that uses BLE/WS metrics
void removeMetricsListener() {
_metrics.removeMetricsListener();
}
void setMetricsAppActive(bool active) {
_metrics.setAppActive(active);
}
/// Check if any segment has a personId not in local cache.
/// Uses Set difference for O(N+M) complexity instead of O(N*M).
bool _hasMissingPerson(List<TranscriptSegment> segments) {
final cachedIds = SharedPreferencesUtil().cachedPeople.map((p) => p.id).toSet();
final segmentPersonIds = segments.map((s) => s.personId).whereType<String>().toSet();
return segmentPersonIds.difference(cachedIds).isNotEmpty;
}
CaptureController({
CaptureExternalActions? externalActions,
ConversationLocationCapture? conversationLocationCapture,
Future<void> Function()? inProgressConversationLoader,
Future<BleAudioCodec> Function(String deviceId)? audioCodecLoader,
Future<bool> Function()? microphonePermissionRequester,
IMicRecorderService? phoneMicBatchRecorder,
RecordingLifecycleTelemetry? recordingTelemetry,
}) : externalActions = externalActions ?? const NoopCaptureExternalActions(),
_conversationLocationCapture = conversationLocationCapture ??
ConversationLocationCapture(onNewlyGranted: _startAndroidLocationForegroundTask),
_inProgressConversationLoader = inProgressConversationLoader,
_audioCodecLoader = audioCodecLoader,
_microphonePermissionRequester = microphonePermissionRequester,
_phoneMicBatchRecorder = phoneMicBatchRecorder,
_recordingTelemetry = recordingTelemetry ?? RecordingLifecycleTelemetry() {
// Restore a persisted device mute so it survives an app kill/restart. When
// the device reconnects, streamDeviceRecording() reads _isPaused as
// `wasPaused` and re-applies the mute instead of silently resuming.
_isPaused = SharedPreferencesUtil().deviceMuted;
_connectionStateListener = ConnectivityService().onConnectionChange.listen((bool isConnected) {
onConnectionStateChanged(isConnected);
});
BleBridge.instance.addBatchRecordingFinalizedListener(_onOfflineRecordingFinalized);
}
static Future<void> _startAndroidLocationForegroundTask() async {
if (!Platform.isAndroid) return;
await ForegroundUtil.initializeForegroundService();
await ForegroundUtil.startForegroundTask();
}
// True while the audio session is interrupted (phone call, Siri, alarm).
// On iOS the native recorder detects and recovers interruptions itself and
// reports them via onInterruption; Dart only mirrors the state so the UI and
// the socket keepalive stay in sync — it never restarts capture for them.
bool _micInterrupted = false;
void _onMicInterruption(bool began) {
// Live phone mic drives an AudioSource; batch has none (_activeSource stays
// null) but still needs its interruption state mirrored.
if (_activeSource is! PhoneMicSource && !_phoneMicBatchActive) return;
_micInterrupted = began;
if (began) {
updateRecordingState(RecordingState.interrupted);
} else if (_phoneMicBatchActive) {
// Batch has no onRecording callback to restore the state; native already
// resumed, so flip back to record here.
updateRecordingState(RecordingState.record);
}
// On end (Live), native capture has already resumed; onRecording restores
// RecordingState.record once frames flow again.
notifyListeners();
}
bool _phoneMicRestartInFlight = false;
bool _phoneMicBatchRestartInFlight = false;
Future<void> _restartPhoneMicRecording() async {
if (_phoneMicRestartInFlight) return;
_phoneMicRestartInFlight = true;
try {
ServiceManager.instance().phoneMic.stop();
// Re-assert interrupted so the recorder's stop callback doesn't overwrite it.
updateRecordingState(RecordingState.interrupted);
// _activeSource is cleared if the user manually stopped — bail in that case.
if (_activeSource is! PhoneMicSource) return;
// Use _resumeMicRecording (not streamRecording) to preserve existing socket/segments.
await _resumeMicRecording();
} catch (e, st) {
Logger.error('[CaptureProvider] _restartPhoneMicRecording failed: $e\n$st');
} finally {
_phoneMicRestartInFlight = false;
}
}
// Restarts mic only — preserves existing socket and conversation segments.
Future<void> _resumeMicRecording() async {
updateRecordingState(RecordingState.initialising);
_activeSource = PhoneMicSource();
_phoneMicWalActive = true;
await ServiceManager.instance().phoneMic.start(
onByteReceived: (bytes) {
final frames = _activeSource?.processBytes(bytes) ?? [];
for (final frame in frames) {
_wal.getSyncs().phone.onFrameCaptured(frame);
if (_socket?.state == SocketServiceState.connected) {
_socket?.send(frame.payload);
_wal.getSyncs().phone.markFrameSynced(frame.syncKey);
}
}
},
onRecording: () {
updateRecordingState(RecordingState.record);
},
onStop: () {
if (!_micInterrupted) {
updateRecordingState(RecordingState.stop);
}
},
onInitializing: () {
updateRecordingState(RecordingState.initialising);
},
onStalled: _onMicStalled,
onInterruption: _onMicInterruption,
);
}
void _onMicStalled() {
if (_activeSource is! PhoneMicSource) return;
if (_micInterrupted) return; // silence during an interruption is expected
if (recordingState == RecordingState.record ||
recordingState == RecordingState.initialising ||
recordingState == RecordingState.stop) {
updateRecordingState(RecordingState.interrupted);
}
if (recordingState == RecordingState.interrupted) {
_restartPhoneMicRecording();
}
}
/// Foreground return hook for phone-mic capture (#4706).
///
/// Native `appBecameActive` owns dead-engine rebuild. Dart only soft-rearms
/// the stall clock so suspended timers don't false-trigger stop→start (which
/// would race native recovery and restart a healthy session).
void onAppResumed() {
if (_activeSource is! PhoneMicSource && !_phoneMicBatchActive) return;
if (_micInterrupted || _phoneMicRestartInFlight) return;
ServiceManager.instance().phoneMic.probeStallAfterForeground();
}
void updateExternalActions(CaptureExternalActions? actions) {
externalActions = actions ?? const NoopCaptureExternalActions();
notifyListeners();
}
BtDevice? _recordingDevice;
BtDevice? _sessionRecordingDevice;
String? _getConversationSourceFromDevice() {
return conversationSourceForDeviceType(_recordingDevice?.type);
}
ServerConversation? _conversation;
List<TranscriptSegment> segments = [];
List<ConversationPhoto> photos = [];
/// Unix timestamp (seconds) when the current capture session started.
/// Used to scope WAL queries to only this session's audio.
int _sessionStartSeconds = 0;
/// Stable identity for the active live-capture session. Unlike a transcript
/// segment ID, this does not change when the backend revises or deletes
/// segments during the capture.
String? get activeCaptureSessionId => _sessionStartSeconds == 0 ? null : 'live-$_sessionStartSeconds';
/// Client-minted UUID shared by capture, `/v4/listen`, and the resulting
/// conversation so the pipeline can be joined without timing heuristics.
String? get activeRecordingId => _recordingTelemetry.recordingId;
@visibleForTesting
set testSessionStartSeconds(int v) => _sessionStartSeconds = v;
/// Unix timestamp (seconds) when the current offline/batch device-recording
/// session started. Set only in offline mode (the websocket path that sets
/// [_sessionStartSeconds] is skipped there); drives the "captured so far"
/// timer on the offline capture card. 0 when not offline-recording.
int _offlineSessionStartSeconds = 0;
int? get offlineRecordingStartedAt => _offlineSessionStartSeconds == 0 ? null : _offlineSessionStartSeconds;
/// Wall-clock seconds when the current recording was muted, or null when not
/// muted — the "captured so far" timer freezes at this point.
int? _offlineMuteStartedAt;
bool get offlineMuted => SharedPreferencesUtil().batchMuted;
/// Elapsed seconds of the *current* recording for the capture-card timer:
/// frozen while muted, and reset on each cut (manual or the 15-min rotation).
int? get offlineRecordingElapsedSeconds {
if (_offlineSessionStartSeconds == 0) return null;
final end = _offlineMuteStartedAt ?? (DateTime.now().millisecondsSinceEpoch ~/ 1000);
final secs = end - _offlineSessionStartSeconds;
return secs < 0 ? 0 : secs;
}
int get _nowSeconds => DateTime.now().millisecondsSinceEpoch ~/ 1000;
/// Mute/unmute Transcribe Later capture. The native writer drops packets while
/// muted and resumes into the same recording; the card timer freezes meanwhile.
void toggleOfflineMute() {
if (SharedPreferencesUtil().batchMuted) {
if (_offlineMuteStartedAt != null) {
_offlineSessionStartSeconds += _nowSeconds - _offlineMuteStartedAt!;
_offlineMuteStartedAt = null;
}
SharedPreferencesUtil().batchMuted = false;
} else {
_offlineMuteStartedAt = _nowSeconds;
SharedPreferencesUtil().batchMuted = true;
}
notifyListeners();
}
/// Manually finalize the current recording and start a fresh one. The native
/// writer cuts on the next packet; the timer resets immediately for feedback.
void startNewOfflineRecording() {
SharedPreferencesUtil().batchCutRequested = true;
if (SharedPreferencesUtil().batchMuted) SharedPreferencesUtil().batchMuted = false;
_offlineSessionStartSeconds = _nowSeconds;
_offlineMuteStartedAt = null;
notifyListeners();
}
void _onOfflineRecordingFinalized(String _) {
if (_offlineSessionStartSeconds == 0) return;
_offlineSessionStartSeconds = _nowSeconds;
_offlineMuteStartedAt = SharedPreferencesUtil().batchMuted ? _nowSeconds : null;
notifyListeners();
}
/// Preserved session start for auto-sync after socket-driven conversation completion.
/// Set before _resetStateVariables() clears _sessionStartSeconds, consumed on ConversationEvent.
int _pendingAutoSyncSessionStart = 0;
/// Fallback timer that fires if ConversationEvent doesn't arrive within 30s.
Timer? _autoSyncFallbackTimer;
/// The conversation ID from ConversationProcessingStartedEvent, kept for fallback sync.
String? _pendingAutoSyncConversationId;
/// Future tracking the in-progress _finalizeAndStampSession(), so the next
/// coordinated transfer wake cannot run before the durable stamp is ready.
Future<void>? _pendingFinalizeAndStamp;
/// Set in onClosed() when the socket drops during active device recording.
/// Consumed in _initiateWebsocket() to trigger onNetworkSocketReconnected()
/// on the device connection (e.g. Limitless re-sends enable-data-stream).
bool _socketReconnectPending = false;
/// How many transcription socket attempts are running, per configuration.
/// The keep-alive timer's callback is async, so a tick could start the same
/// attempt again before the previous one finished and open a duplicate
/// /v4/listen session (issue #11305). Only an identical repeat is dropped:
/// an attempt with different parameters is a new intent (starting phone mic,
/// a codec change), and a forced one replaces the socket outright.
final Map<String, int> _websocketInitInFlight = {};
int _websocketInitGeneration = 0;
/// Returns unsynced WALs belonging to the current capture session.
/// Empty when all frames have been streamed successfully (clean UI).
List<Wal> get unsyncedSessionWals {
if (_sessionStartSeconds == 0) return [];
return _wal.getSyncs().phone.getSessionUnsyncedWals(_sessionStartSeconds);
}
/// Seconds of audio still in memory buffer (not yet chunked/flushed to disk).
int get inFlightAudioSeconds => _wal.getSyncs().phone.getInFlightSeconds();
// Version counter for segments/photos content changes. Incremented on in-place mutations
// (e.g., translation updates, photo description changes) to signal UI rebuilds when
// list length and last-text remain unchanged.
int _segmentsPhotosVersion = 0;
int get segmentsPhotosVersion => _segmentsPhotosVersion;
Map<String, SpeakerLabelSuggestionEvent> suggestionsBySegmentId = {};
List<String> taggingSegmentIds = [];
bool hasTranscripts = false;
StreamSubscription? _bleBytesStream;
StreamSubscription? _blePhotoStream;
get bleBytesStream => _bleBytesStream;
StreamSubscription? _bleButtonStream;
DateTime? _voiceCommandSession;
List<List<int>> _commandBytes = [];
bool _isProcessingButtonEvent = false; // Guard to prevent overlapping button operations
Timer? _voiceCommandTimeoutTimer; // 30s auto-end timer for voice questions
StreamSubscription? _storageStream;
get storageStream => _storageStream;
RecordingState recordingState = RecordingState.stop;
bool _isPaused = false;
bool get isPaused => _isPaused;
bool get isCallActive => _micInterrupted;
// Flag to star the conversation when it ends
bool _starOngoingConversation = false;
bool get isConversationMarkedForStarring => _starOngoingConversation;
void markConversationForStarring() {
_starOngoingConversation = true;
notifyListeners();
}
void unmarkConversationForStarring() {
_starOngoingConversation = false;
notifyListeners();
}
bool _transcriptServiceReady = false;
// The transcript service readiness is driven solely by the socket lifecycle
// (set true on subscribe, false on close). The `&& _isConnected` gate was
// removed (#6311): ConnectivityService can flicker false during a WiFi↔cellular
// handoff or a brief DNS hiccup even while the WebSocket is alive and segments
// are flowing, which made the UI show "Recording, reconnecting" over healthy
// transcription. The socket is the authoritative connectivity signal.
bool get transcriptServiceReady => _transcriptServiceReady;
// having a connected device or using the phone's mic for recording.
// Includes `interrupted` so the keep-alive/reconnect path keeps running
// while the phone mic is in a transiently-broken state (e.g., iOS audio
// session interruption after an incoming call).
bool get recordingDeviceServiceReady =>
_recordingDevice != null ||
recordingState == RecordingState.record ||
recordingState == RecordingState.interrupted ||
recordingState == RecordingState.systemAudioRecord;
bool get havingRecordingDevice => _recordingDevice != null;
BtDevice? get recordingDevice => _recordingDevice;
void setHasTranscripts(bool value) {
hasTranscripts = value;
notifyListeners();
}
void setConversationCreating(bool value) {
Logger.debug('set Conversation creating $value');
// ConversationCreating = value;
notifyListeners();
}
void _updateRecordingDevice(BtDevice? device) {
Logger.debug('connected device changed from ${_recordingDevice?.id} to ${device?.id}');
_recordingDevice = device;
if (device == null) _endOfflineSession();
notifyListeners();
}
void updateRecordingDevice(BtDevice? device) {
_updateRecordingDevice(device);
}
Future _resetStateVariables() async {
_stopInProgressConversationRefresh();
segments = [];
photos = [];
hasTranscripts = false;
suggestionsBySegmentId = {};
_conversation = null;
taggingSegmentIds = [];
_sessionStartSeconds = 0;
_endOfflineSession();
notifyListeners();
}
void _endOfflineSession() {
_offlineSessionStartSeconds = 0;
_offlineMuteStartedAt = null;
if (SharedPreferencesUtil().batchMuted) SharedPreferencesUtil().batchMuted = false;
if (SharedPreferencesUtil().batchCutRequested) SharedPreferencesUtil().batchCutRequested = false;
}
Future<void> onRecordProfileSettingChanged() async {
await _resetState();
}
static bool supportsTranscribeLater(DeviceType? type) {
return type == DeviceType.omi ||
type == DeviceType.openglass ||
type == DeviceType.friendPendant ||
type == DeviceType.limitless;
}
bool get deviceSupportsTranscribeLater => supportsTranscribeLater(_recordingDevice?.type);
// The phone microphone can capture Transcribe Later (batch) audio where a
// native recorder module exists — iOS (AVAudioEngine) and Android (AudioRecord).
static bool get phoneMicSupportsTranscribeLater => Platform.isIOS || Platform.isAndroid;
Future<bool> setBatchMode(bool enabled) async {
if (SharedPreferencesUtil().batchModeEnabled == enabled) return true;
// With batch on the realtime socket is suppressed for every device type, so a
// device without a batch capture path would record nothing at all.
if (enabled && _recordingDevice != null && !deviceSupportsTranscribeLater) {
Logger.debug('[setBatchMode] refused: ${_recordingDevice?.type} has no Transcribe Later support');
return false;
}
SharedPreferencesUtil().batchModeEnabled = enabled;
PlatformManager.instance.analytics.transcribeLaterToggled(enabled: enabled);
final docs = await getApplicationDocumentsDirectory();
await SharedPreferencesUtil().saveString('batchAudioDir', docs.path);
// Only re-enable native streaming when turning batch OFF, a device with a
// native BLE route is connected, and background mode is opted in.
final enableNativeStreaming = _shouldEnableNativeBackgroundStreaming;
await SharedPreferencesUtil().saveBool('nativeBleStreamingEnabled', enableNativeStreaming);
await _applyLimitlessRealtimeSuppression(enabled);
notifyListeners();
// A phone-mic session's mode is fixed at start, so a mid-session toggle
// must roll the session into a fresh one — otherwise _resetState() tears
// the socket down under a still-running Live session (no transcript, audio
// silently diverted to the offline WAL) and the UI keeps the Live card.
final phoneMicSessionActive = _phoneMicBatchActive || _activeSource is PhoneMicSource;
if (phoneMicSessionActive) {
try {
await stopStreamRecording(reason: 'mode_changed');
await streamRecording();
} catch (e, st) {
Logger.error('[CaptureProvider] mode-switch session roll failed: $e\n$st');
}
return true;
}
try {
await onRecordProfileSettingChanged();
} catch (_) {}
return true;
}
Future<void> _applyLimitlessRealtimeSuppression(bool suppressed) async {
final device = _recordingDevice;
if (device == null || device.type != DeviceType.limitless) return;
try {
final connection = await ServiceManager.instance().device.ensureConnection(device.id);
if (connection is LimitlessDeviceConnection) {
await connection.setRealtimeAudioSuppressed(suppressed);
}
} catch (e) {
Logger.debug('[batch] limitless realtime suppression toggle failed: $e');
}
}
// Interactive device onboarding needs the realtime transcript + voice paths, which Transcribe
// Later (batch mode) disables. Flipping batchModeEnabled off also re-opens the native->Dart audio
// forward — the native BatchAudioWriter gate reads this same pref — so BLE audio reaches Dart again.
// Skips the transcribeLaterToggled analytic on purpose; the persisted flag drives a crash-safe restore.
Future<void> suspendBatchModeForOnboarding() async {
if (SharedPreferencesUtil().batchModeSuspendedForOnboarding) return;
if (!SharedPreferencesUtil().batchModeEnabled) return;
SharedPreferencesUtil().batchModeSuspendedForOnboarding = true;
SharedPreferencesUtil().batchModeEnabled = false;
await _applyLimitlessRealtimeSuppression(false);
notifyListeners();
try {
await onRecordProfileSettingChanged();
} catch (_) {}
}
Future<void> restoreBatchModeAfterOnboarding() async {
if (!SharedPreferencesUtil().batchModeSuspendedForOnboarding) return;
SharedPreferencesUtil().batchModeSuspendedForOnboarding = false;
SharedPreferencesUtil().batchModeEnabled = true;
await _applyLimitlessRealtimeSuppression(true);
notifyListeners();
try {
await onRecordProfileSettingChanged();
} catch (_) {}
}
/// Called when transcription settings are changed (e.g., custom STT provider)
/// This resets the socket connection to use the new configuration
Future<void> onTranscriptionSettingsChanged() async {
Logger.debug("Transcription settings changed, refreshing socket connection...");
await _reconcileNativeBackgroundStreamingPolicy();
// Handle device recording
if (_recordingDevice != null) {
await _socket?.stop(reason: 'transcription settings changed');
BleAudioCodec codec = await _getAudioCodec(_recordingDevice!.id);
await _initiateWebsocket(audioCodec: codec, force: true, source: _getConversationSourceFromDevice());
return;
}
// Handle phone mic recording
if (recordingState == RecordingState.record) {
await _socket?.stop(reason: 'transcription settings changed');
await _initiateWebsocket(
audioCodec: BleAudioCodec.pcm16,
sampleRate: 16000,
force: true,
source: ConversationSource.phone.name,
);
return;
}
}
Future<void> changeAudioRecordProfile({
required BleAudioCodec audioCodec,
int? sampleRate,
int? channels,
bool? isPcm,
String? source,
}) async {
await _resetState();
await _initiateWebsocket(
audioCodec: audioCodec,
sampleRate: sampleRate,
channels: channels,
isPcm: isPcm,
source: source,
);
}
Future<void> _initiateWebsocket({
required BleAudioCodec audioCodec,
int? sampleRate,
int? channels,
bool? isPcm,
bool force = false,
String? source,
}) async {
// Resolve the defaults here so two callers that spell the same
// configuration differently (null vs the value it defaults to) share a key.
final effectiveSampleRate = sampleRate ?? mapCodecToSampleRate(audioCodec);
final effectiveChannels =
channels ?? ((audioCodec == BleAudioCodec.pcm16 || audioCodec == BleAudioCodec.pcm8) ? 1 : 2);
final attemptKey =
'$audioCodec|$effectiveSampleRate|$effectiveChannels|$isPcm|$source|${_recordingTelemetry.recordingId}';
if (!force && _websocketInitInFlight.containsKey(attemptKey)) {
Logger.debug('initiateWebsocket skipped - an identical connection attempt is already in flight');
return;
}
// Counted, because a forced attempt can share the key of the non-forced one
// it is replacing; whichever finishes first must not ungate the other.
_websocketInitInFlight.update(attemptKey, (running) => running + 1, ifAbsent: () => 1);
final generation = ++_websocketInitGeneration;
try {
await _connectTranscriptionSocket(
audioCodec: audioCodec,
sampleRate: effectiveSampleRate,
channels: effectiveChannels,
isPcm: isPcm,
force: force,
source: source,
generation: generation,
);
} finally {
final running = (_websocketInitInFlight[attemptKey] ?? 1) - 1;
if (running > 0) {
_websocketInitInFlight[attemptKey] = running;
} else {
_websocketInitInFlight.remove(attemptKey);
}
}
}
/// Opens the transcription socket. Overridden in tests to control the timing
/// of an attempt; production always goes through the socket service pool.
@visibleForTesting
Future<TranscriptSegmentSocketService?> openConversationSocket({
required BleAudioCodec codec,
required int sampleRate,
required String language,
required bool force,
String? source,
String? clientConversationId,
CustomSttConfig? customSttConfig,
}) {
return ServiceManager.instance().socket.conversation(
codec: codec,
sampleRate: sampleRate,
language: language,
force: force,
source: source,
clientConversationId: clientConversationId,
customSttConfig: customSttConfig,
geolocation: _sessionGeolocation,
);
}
Future<void> _connectTranscriptionSocket({
required BleAudioCodec audioCodec,
required int sampleRate,
required int channels,
bool? isPcm,
bool force = false,
String? source,
required int generation,
}) async {
Logger.debug('initiateWebsocket in capture_provider');
// Batch (offline) mode: never open the realtime transcription socket. The
// native layer stores incoming BLE audio to local .bin files instead, and
// the user uploads recordings later. See _saveNativeBleStreamConfig.
if (SharedPreferencesUtil().batchModeEnabled) {
Logger.debug('Batch mode enabled — skipping transcription websocket');
return;
}
BleAudioCodec codec = audioCodec;
Logger.debug('is ws null: ${_socket == null}');
Logger.debug('Initiating WebSocket with: codec=$codec, sampleRate=$sampleRate, channels=$channels, isPcm=$isPcm');
// Get language and custom STT config
String language =
SharedPreferencesUtil().hasSetPrimaryLanguage ? SharedPreferencesUtil().userPrimaryLanguage : "multi";
final customSttConfig = SharedPreferencesUtil().customSttConfig;
Logger.debug('Custom STT enabled: ${customSttConfig.isEnabled}, provider: ${customSttConfig.provider}');
// Check codec compatibility for custom STT - fallback to default if incompatible
CustomSttConfig? effectiveConfig = customSttConfig.isEnabled ? customSttConfig : null;
if (effectiveConfig != null && !TranscriptSocketServiceFactory.isCodecSupportedForCustomStt(codec)) {
if (TranscriptSocketServiceFactory.shouldBlockUnsupportedCodecFallback(codec, effectiveConfig)) {
Logger.warning(
'[CustomSTT] Codec $codec is unsupported; refusing Omi fallback because raw audio forwarding is disabled',
);
final previousSocket = _socket;
_socket = null;
_transcriptServiceReady = false;
try {
await previousSocket?.stop(reason: 'unsupported custom STT codec with raw audio forwarding disabled');
} catch (e, stack) {
Logger.error('[CustomSTT] Failed to stop the previous socket after blocking Omi fallback: $e\n$stack');
}
await _reconcileNativeBackgroundStreamingPolicy();
notifyListeners();
_startKeepAliveServices();
return;
}
Logger.debug('[CustomSTT] Codec $codec not supported, falling back to Omi');
effectiveConfig = null;
}
// Connect to the transcript socket
final socket = await openConversationSocket(
codec: codec,
sampleRate: sampleRate,
language: language,
force: force,
source: source,
clientConversationId: _recordingTelemetry.recordingId,
customSttConfig: effectiveConfig,
);
if (socket == null) {
_startKeepAliveServices();
Logger.debug("Can not create new conversation socket");
return;
}
if (generation != _websocketInitGeneration) {
await socket.stop(reason: 'stale transcription socket attempt');
return;
}
_socket = socket;
_socket?.subscribe(this, this);
_transcriptServiceReady = true;
if (_sessionStartSeconds == 0) {
_sessionStartSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
}
// Notify the device connection that the socket reconnected after a network
// outage so it can re-enable streaming if needed (e.g. Limitless pendant).
// Guard on deviceRecord: skip if the user has paused — no point waking the
// device when _bleBytesStream is cancelled and audio would just be dropped.
if (_socketReconnectPending && _recordingDevice != null && recordingState == RecordingState.deviceRecord) {
_socketReconnectPending = false;
final conn = await ServiceManager.instance().device.ensureConnection(_recordingDevice!.id);
await conn?.onNetworkSocketReconnected();
}
await _loadInProgressConversation();
await _drainNativeBleTranscriptMessages();
_startInProgressConversationRefresh();
notifyListeners();
}
void _processVoiceCommandBytes(String deviceId, List<List<int>> data) async {
if (data.isEmpty) {
Logger.debug("voice frames is empty");
return;
}
if (_recordingDevice == null) {
Logger.debug("Recording device is null, cannot process voice command");
return;
}
BleAudioCodec codec = await _getAudioCodec(_recordingDevice!.id);
await externalActions.sendVoiceMessageStreamToServer(
data,
onFirstChunkRecived: () {
_playSpeakerHaptic(deviceId, 2);
},
codec: codec,
// Device-button voice → speak the reply aloud (BG/lock-screen safe).
// Gated by SharedPreferencesUtil().voiceResponseEnabled inside the service.
playResponseAudio: true,
);
}
// Start a 15s timeout timer for voice commands - auto-ends if user forgets to tap again
void _startVoiceCommandTimeout(String deviceId) {
_voiceCommandTimeoutTimer?.cancel();
_voiceCommandTimeoutTimer = Timer(const Duration(seconds: 15), () {
debugPrint("Voice command timeout - auto-ending session after 15s");
if (_voiceCommandSession != null) {
_endVoiceCommandSession(deviceId);
}
});
}
// End voice command session and process the collected audio
void _endVoiceCommandSession(String deviceId) {
_voiceCommandTimeoutTimer?.cancel();
_voiceCommandTimeoutTimer = null;
_voiceCommandSession = null;
var data = List<List<int>>.from(_commandBytes);
_commandBytes = [];
_processVoiceCommandBytes(deviceId, data);
}
Future streamButton(String deviceId) async {
Logger.debug('streamButton in capture_provider');
_bleButtonStream?.cancel();
_bleButtonStream = await _getBleButtonListener(
deviceId,
onButtonReceived: (List<int> value) {
final snapshot = List<int>.from(value);
if (snapshot.isEmpty || snapshot.length < 4) return;
var buttonState = ByteData.view(
Uint8List.fromList(snapshot.sublist(0, 4).reversed.toList()).buffer,
).getUint32(0);
Logger.debug("device button $buttonState");
// Intercept for interactive device onboarding
if (deviceOnboardingProvider?.isOnboardingActive == true) {
deviceOnboardingProvider!.onButtonEvent(buttonState);
// For step 1 (ask question), let single-tap fall through to normal voice command handling
if (deviceOnboardingProvider!.currentStep == 1 && buttonState == 1) {
// Fall through to normal single-tap handling below
} else {
return;
}
}
// double tap
if (buttonState == 2) {
Logger.debug("Double tap detected");
// Guard: ignore if already processing a button event
if (_isProcessingButtonEvent) {
Logger.debug("Double tap: already processing, ignoring");
return;
}
int doubleTapAction = SharedPreferencesUtil().doubleTapAction;
if (doubleTapAction == 1) {
// Pause/resume recording
Logger.debug("Double tap: toggling pause/mute");
_isProcessingButtonEvent = true;
if (_isPaused) {
PlatformManager.instance.analytics.omiDoubleTap(feature: 'unmute');
resumeDeviceRecording().then((_) {
_isProcessingButtonEvent = false;
}).catchError((e) {
Logger.debug("Error resuming device recording: $e");
_isProcessingButtonEvent = false;
});
} else {
PlatformManager.instance.analytics.omiDoubleTap(feature: 'mute');
pauseDeviceRecording().then((_) {
_isProcessingButtonEvent = false;
}).catchError((e) {
Logger.debug("Error pausing device recording: $e");
_isProcessingButtonEvent = false;
});
}
} else if (doubleTapAction == 2) {
// Star ongoing conversation (doesn't end it)
Logger.debug("Double tap: marking conversation for starring");
if (!_starOngoingConversation) {
markConversationForStarring();
PlatformManager.instance.analytics.omiDoubleTap(feature: 'star_conversation');
// Haptic feedback to confirm
HapticFeedback.mediumImpact();
} else {
// Toggle off if already marked
unmarkConversationForStarring();
PlatformManager.instance.analytics.omiDoubleTap(feature: 'unstar_conversation');
HapticFeedback.lightImpact();
}
} else {
// End conversation and process (default)
Logger.debug("Double tap: processing conversation");
PlatformManager.instance.analytics.omiDoubleTap(feature: 'process_conversation');
forceProcessingCurrentConversation();
}
return;
}
// Single tap (buttonState == 1) - toggle voice question mode