forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio_player_utils.dart
More file actions
450 lines (365 loc) · 14.3 KB
/
Copy pathaudio_player_utils.dart
File metadata and controls
450 lines (365 loc) · 14.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
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:opus_dart/opus_dart.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:omi/utils/share_sheet.dart';
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/app_globals.dart';
import 'package:omi/services/wals.dart';
import 'package:omi/utils/alerts/app_snackbar.dart';
import 'package:omi/utils/l10n_extensions.dart';
import 'package:omi/utils/logger.dart';
/// Parse length-prefixed binary frames: [4-byte LE uint32 length][payload] per frame.
/// Used by both Opus and PCM WAL binary files.
@visibleForTesting
List<Uint8List> parseLengthPrefixedFrames(Uint8List data) {
List<Uint8List> frames = [];
int offset = 0;
while (offset < data.length - 4) {
final lengthBytes = data.sublist(offset, offset + 4);
final length = ByteData.sublistView(Uint8List.fromList(lengthBytes)).getUint32(0, Endian.little);
offset += 4;
if (offset + length > data.length) break;
final frameData = data.sublist(offset, offset + length);
frames.add(Uint8List.fromList(frameData));
offset += length;
}
return frames;
}
class AudioPlayerUtils extends ChangeNotifier {
// Singleton pattern
static final AudioPlayerUtils _instance = AudioPlayerUtils._internal();
static AudioPlayerUtils get instance => _instance;
factory AudioPlayerUtils() => _instance;
AudioPlayerUtils._internal();
FlutterSoundPlayer? _audioPlayer;
String? _currentPlayingId;
bool _isProcessingAudio = false;
Duration _currentPosition = Duration.zero;
Duration _totalDuration = Duration.zero;
StreamSubscription<PlaybackDisposition>? _positionSubscription;
final Map<String, String> _audioFileCache = {};
String? get currentPlayingId => _currentPlayingId;
bool get isProcessingAudio => _isProcessingAudio;
Duration get currentPosition => _currentPosition;
Duration get totalDuration => _totalDuration;
double get playbackProgress {
if (_totalDuration.inMilliseconds <= 0) return 0.0;
final progress = _currentPosition.inMilliseconds.toDouble() / _totalDuration.inMilliseconds.toDouble();
return progress.clamp(0.0, 1.0);
}
/// Lazily initialize the audio player only when needed
Future<void> _ensurePlayerInitialized() async {
if (_audioPlayer != null) return;
_audioPlayer = FlutterSoundPlayer();
if (_audioPlayer != null && !_audioPlayer!.isOpen()) {
await _audioPlayer!.openPlayer();
// onProgress emits nothing unless a subscription interval is set (default 0ms).
await _audioPlayer!.setSubscriptionDuration(const Duration(milliseconds: 100));
}
}
bool isPlaying(String id) => _currentPlayingId == id;
bool canPlayOrShare(Wal wal) {
if (wal.storage == WalStorage.sdcard && wal.fileNum == -1) {
return false;
}
return (wal.filePath != null && wal.filePath!.isNotEmpty) ||
wal.data.isNotEmpty ||
wal.storage == WalStorage.sdcard;
}
Future<void> togglePlayback(Wal wal) async {
if (!canPlayOrShare(wal)) {
Logger.error('AudioPlayerUtils: Audio file not available for playback, WAL ${wal.id}');
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.audioPlaybackUnavailable ?? 'Audio file is not available for playback',
);
return;
}
if (_isProcessingAudio) return;
if (isPlaying(wal.id)) {
await _stopPlayback();
return;
}
await _startPlayback(wal);
}
Future<void> _stopPlayback() async {
await _audioPlayer?.stopPlayer();
_currentPlayingId = null;
_currentPosition = Duration.zero;
_totalDuration = Duration.zero;
_positionSubscription?.cancel();
notifyListeners();
}
Future<void> _startPlayback(Wal wal) async {
_isProcessingAudio = true;
_currentPosition = Duration.zero;
_totalDuration = Duration.zero;
notifyListeners();
// Initialize player lazily on first use
await _ensurePlayerInitialized();
final audioFilePath = await _getOrCreateAudioFile(wal);
if (audioFilePath == null) {
_resetPlaybackState();
Logger.error('AudioPlayerUtils: Unable to create playable audio file for WAL ${wal.id}');
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.audioPlaybackFailed ??
'Unable to play audio. The file may be corrupted or missing.',
);
return;
}
_currentPlayingId = wal.id;
_isProcessingAudio = false;
await _audioPlayer?.startPlayer(fromURI: audioFilePath, whenFinished: () => _onPlaybackFinished());
_setupPositionTracking(wal);
}
void _onPlaybackFinished() {
Logger.debug('Audio playback finished');
_resetPlaybackState();
}
void _resetPlaybackState() {
_currentPlayingId = null;
_currentPosition = Duration.zero;
_totalDuration = Duration.zero;
_isProcessingAudio = false;
_positionSubscription?.cancel();
notifyListeners();
}
void _setupPositionTracking(Wal wal) {
_positionSubscription?.cancel();
_positionSubscription = _audioPlayer?.onProgress?.listen((disposition) {
if (_currentPlayingId == wal.id) {
_currentPosition = disposition.position;
_totalDuration = disposition.duration;
notifyListeners();
}
});
Timer.periodic(const Duration(milliseconds: 100), (timer) {
if (_currentPlayingId != wal.id || !(_audioPlayer?.isPlaying ?? false)) {
timer.cancel();
return;
}
if (_totalDuration.inMilliseconds > 0) {
final estimatedPosition = _currentPosition + const Duration(milliseconds: 100);
if (estimatedPosition <= _totalDuration) {
_currentPosition = estimatedPosition;
notifyListeners();
}
}
});
_totalDuration = Duration(seconds: wal.seconds);
notifyListeners();
}
Future<void> shareAsAudio(Wal wal) async {
if (!canPlayOrShare(wal)) {
throw Exception('Audio file not available for sharing');
}
final audioFilePath = await _getOrCreateAudioFile(wal, forSharing: true);
if (audioFilePath == null) {
throw Exception('Unable to create shareable audio file');
}
final result = await Share.shareXFiles(
[XFile(audioFilePath)],
text:
'Omi Audio Recording - ${DateTime.fromMillisecondsSinceEpoch(wal.timerStart * 1000).toString().split('.')[0]}',
// No widget to anchor to here; the fallback is only required to be non-zero.
sharePositionOrigin: shareSheetOrigin(),
);
if (result.status == ShareResultStatus.success) {
Logger.debug('Audio file shared successfully');
}
}
Future<String?> _getOrCreateAudioFile(Wal wal, {bool forSharing = false}) async {
final cacheKey = forSharing ? '${wal.id}_share' : wal.id;
if (!forSharing && _audioFileCache.containsKey(cacheKey)) {
final cachedPath = _audioFileCache[cacheKey]!;
if (File(cachedPath).existsSync()) {
return cachedPath;
}
}
// Sharing reuses the already-decoded playback file (e.g. the one produced when
// the waveform loaded) instead of decoding the whole recording again.
if (forSharing) {
final playbackCached = _audioFileCache[wal.id];
if (playbackCached != null && File(playbackCached).existsSync()) {
return playbackCached;
}
}
final audioFilePath = await _getAudioFilePath(wal);
if (audioFilePath == null) return null;
String? processedFilePath;
if (wal.codec.isOpusSupported()) {
processedFilePath = await _decodeOpusToWav(wal, audioFilePath, forSharing: forSharing);
} else {
processedFilePath = await _convertPcmToWav(wal, audioFilePath, forSharing: forSharing);
}
if (processedFilePath != null && !forSharing) {
_audioFileCache[cacheKey] = processedFilePath;
}
return processedFilePath;
}
Future<String?> _getAudioFilePath(Wal wal) async {
if (wal.filePath != null && wal.filePath!.isNotEmpty) {
final fullPath = await Wal.getFilePath(wal.filePath);
if (fullPath != null) {
final file = File(fullPath);
if (file.existsSync()) return fullPath;
}
}
if (wal.data.isNotEmpty) {
return await _createTempFileFromMemoryData(wal);
}
return null;
}
Future<String?> _createTempFileFromMemoryData(Wal wal) async {
final tempDir = await getTemporaryDirectory();
final tempFilePath = '${tempDir.path}/temp_${wal.id}_${DateTime.now().millisecondsSinceEpoch}.bin';
List<int> data = [];
for (int i = 0; i < wal.data.length; i++) {
var frame = wal.data[i];
final byteFrame = ByteData(frame.length);
for (int j = 0; j < frame.length; j++) {
byteFrame.setUint8(j, frame[j]);
}
data.addAll(Uint32List.fromList([frame.length]).buffer.asUint8List());
data.addAll(byteFrame.buffer.asUint8List());
}
final file = File(tempFilePath);
await file.writeAsBytes(data);
return tempFilePath;
}
Future<String?> _decodeOpusToWav(Wal wal, String opusFilePath, {bool forSharing = false}) async {
final file = File(opusFilePath);
if (!file.existsSync()) return null;
final opusData = await file.readAsBytes();
final opusFrames = parseLengthPrefixedFrames(opusData);
if (opusFrames.isEmpty) return null;
final decoder = SimpleOpusDecoder(sampleRate: wal.sampleRate, channels: wal.channel);
List<Uint8List> pcmFrames = [];
for (final opusFrame in opusFrames) {
try {
final pcmFrame = decoder.decode(input: opusFrame);
pcmFrames.add(Uint8List.fromList(pcmFrame.buffer.asUint8List()));
} catch (e) {
Logger.warning('AudioPlayerUtils: skipping corrupted Opus frame for WAL ${wal.id}: $e');
}
}
if (pcmFrames.isEmpty) return null;
final totalLength = pcmFrames.fold<int>(0, (sum, frame) => sum + frame.length);
final combinedPcm = Uint8List(totalLength);
int writeOffset = 0;
for (final frame in pcmFrames) {
combinedPcm.setRange(writeOffset, writeOffset + frame.length, frame);
writeOffset += frame.length;
}
return await _createWavFile(pcmData: combinedPcm, wal: wal, bitsPerSample: 16, forSharing: forSharing);
}
Future<String?> _convertPcmToWav(Wal wal, String pcmFilePath, {bool forSharing = false}) async {
final file = File(pcmFilePath);
if (!file.existsSync()) return null;
final pcmFileData = await file.readAsBytes();
final pcmFrames = parseLengthPrefixedFrames(pcmFileData);
if (pcmFrames.isEmpty) return null;
final totalLength = pcmFrames.fold<int>(0, (sum, frame) => sum + frame.length);
final combinedPcm = Uint8List(totalLength);
int writeOffset = 0;
for (final frame in pcmFrames) {
combinedPcm.setRange(writeOffset, writeOffset + frame.length, frame);
writeOffset += frame.length;
}
final bitsPerSample = wal.codec == BleAudioCodec.pcm16 ? 16 : 8;
return await _createWavFile(pcmData: combinedPcm, wal: wal, bitsPerSample: bitsPerSample, forSharing: forSharing);
}
Future<String> _createWavFile({
required Uint8List pcmData,
required Wal wal,
required int bitsPerSample,
bool forSharing = false,
}) async {
final tempDir = await getTemporaryDirectory();
final fileName = forSharing
? wal.getFileName().replaceAll('.bin', '.wav')
: 'audio_${DateTime.now().millisecondsSinceEpoch}.wav';
final wavFilePath = '${tempDir.path}/$fileName';
final wavData = _createWavHeader(
pcmData: pcmData,
sampleRate: wal.sampleRate,
channels: wal.channel,
bitsPerSample: bitsPerSample,
);
await File(wavFilePath).writeAsBytes(wavData);
return wavFilePath;
}
Uint8List _createWavHeader({
required Uint8List pcmData,
required int sampleRate,
required int channels,
required int bitsPerSample,
}) {
const int wavHeaderSize = 44;
final int frameSize = ((bitsPerSample + 7) ~/ 8) * channels;
final int fileSize = wavHeaderSize + pcmData.length;
final ByteData header = ByteData(wavHeaderSize);
const Endian endian = Endian.little;
header.setUint32(4, fileSize - 8, endian);
header.setUint32(16, 16, endian);
header.setUint16(20, 1, endian);
header.setUint16(22, channels, endian);
header.setUint32(24, sampleRate, endian);
header.setUint32(28, sampleRate * frameSize, endian);
header.setUint16(32, frameSize, endian);
header.setUint16(34, bitsPerSample, endian);
header.setUint32(40, pcmData.length, endian);
final Uint8List headerBytes = header.buffer.asUint8List();
headerBytes.setAll(0, ascii.encode('RIFF'));
headerBytes.setAll(8, ascii.encode('WAVE'));
headerBytes.setAll(12, ascii.encode('fmt '));
headerBytes.setAll(36, ascii.encode('data'));
final Uint8List wavFile = Uint8List(fileSize);
wavFile.setAll(0, headerBytes);
wavFile.setAll(wavHeaderSize, pcmData);
return wavFile;
}
Future<void> seekToPosition(Duration position) async {
if (_audioPlayer != null && _currentPlayingId != null) {
await _audioPlayer!.seekToPlayer(position);
_currentPosition = position;
notifyListeners();
}
}
Future<void> skipForward({Duration duration = const Duration(seconds: 10)}) async {
if (_audioPlayer != null && _currentPlayingId != null) {
final newPosition = _currentPosition + duration;
final clampedPosition = newPosition > _totalDuration ? _totalDuration : newPosition;
await seekToPosition(clampedPosition);
}
}
Future<void> skipBackward({Duration duration = const Duration(seconds: 10)}) async {
if (_audioPlayer != null && _currentPlayingId != null) {
final newPosition = _currentPosition - duration;
final clampedPosition = newPosition < Duration.zero ? Duration.zero : newPosition;
await seekToPosition(clampedPosition);
}
}
String? getCachedAudioPath(String id) => _audioFileCache[id];
Future<String?> ensureAudioFileExists(Wal wal) async {
final cacheKey = wal.id;
if (_audioFileCache.containsKey(cacheKey)) {
final cachedPath = _audioFileCache[cacheKey]!;
if (File(cachedPath).existsSync()) {
return cachedPath;
}
}
return await _getOrCreateAudioFile(wal, forSharing: false);
}
@override
void dispose() {
_positionSubscription?.cancel();
_audioPlayer?.closePlayer();
super.dispose();
}
}