forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaveform_utils.dart
More file actions
244 lines (199 loc) · 6.98 KB
/
Copy pathwaveform_utils.dart
File metadata and controls
244 lines (199 loc) · 6.98 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
import 'dart:io';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:omi/utils/logger.dart';
class WavInfo {
final int sampleRate;
final int channels;
final int bitsPerSample;
final int dataOffset;
final int dataSize;
WavInfo({
required this.sampleRate,
required this.channels,
required this.bitsPerSample,
required this.dataOffset,
required this.dataSize,
});
}
class WaveformUtils {
static final Map<String, List<double>> _waveformCache = {};
static Future<List<double>?> generateWaveform(String cacheKey, String? wavFilePath) async {
Logger.debug('Generating waveform for key $cacheKey');
if (_waveformCache.containsKey(cacheKey)) {
return _waveformCache[cacheKey];
}
if (wavFilePath == null) {
return _generateFallbackWaveform();
}
try {
final waveformData = await _generateWaveformFromWavFile(wavFilePath);
_waveformCache[cacheKey] = waveformData;
return waveformData;
} catch (e) {
Logger.debug('Error generating waveform for key $cacheKey: $e');
return _generateFallbackWaveform();
}
}
static Future<List<double>> _generateWaveformFromWavFile(String wavFilePath) async {
Logger.debug('Generating waveform from WAV file: $wavFilePath');
final file = File(wavFilePath);
if (!file.existsSync()) {
Logger.debug('WAV file does not exist');
return _generateFallbackWaveform();
}
final wavData = await file.readAsBytes();
final wavInfo = _parseWavHeader(wavData);
if (wavInfo == null) {
Logger.debug('Failed to parse WAV header');
return _generateFallbackWaveform();
}
Logger.debug(
'WAV Info: ${wavInfo.sampleRate}Hz, ${wavInfo.channels} channels, ${wavInfo.bitsPerSample} bits, data size: ${wavInfo.dataSize}',
);
final pcmData = wavData.sublist(wavInfo.dataOffset, wavInfo.dataOffset + wavInfo.dataSize);
final samples = _extractSamples(pcmData, wavInfo);
if (samples.isEmpty) {
return _generateFallbackWaveform();
}
Logger.debug('Extracted ${samples.length} samples from WAV file');
return _generateWaveformFromSamples(samples);
}
static List<double> _extractSamples(Uint8List pcmData, WavInfo wavInfo) {
List<double> samples = [];
switch (wavInfo.bitsPerSample) {
case 16:
for (int i = 0; i < pcmData.length - 1; i += 2) {
int sample = pcmData[i] | (pcmData[i + 1] << 8);
if (sample > 32767) sample = sample - 65536;
samples.add(sample / 32768.0);
}
break;
case 8:
for (int i = 0; i < pcmData.length; i++) {
int sample = pcmData[i] - 128;
samples.add(sample / 128.0);
}
break;
case 24:
for (int i = 0; i < pcmData.length - 2; i += 3) {
int sample = pcmData[i] | (pcmData[i + 1] << 8) | (pcmData[i + 2] << 16);
if (sample > 8388607) sample = sample - 16777216;
samples.add(sample / 8388608.0);
}
break;
case 32:
for (int i = 0; i < pcmData.length - 3; i += 4) {
int sample = pcmData[i] | (pcmData[i + 1] << 8) | (pcmData[i + 2] << 16) | (pcmData[i + 3] << 24);
samples.add(sample / 2147483648.0);
}
break;
default:
Logger.debug('Unsupported bits per sample: ${wavInfo.bitsPerSample}');
return [];
}
// Handle multi-channel audio by taking only the first channel
if (wavInfo.channels > 1) {
List<double> monoSamples = [];
for (int i = 0; i < samples.length; i += wavInfo.channels) {
monoSamples.add(samples[i]);
}
samples = monoSamples;
}
return samples;
}
static WavInfo? _parseWavHeader(Uint8List wavData) {
if (wavData.length < 44) {
Logger.debug('WAV file too small');
return null;
}
final riffHeader = String.fromCharCodes(wavData.sublist(0, 4));
if (riffHeader != 'RIFF') {
Logger.debug('Invalid RIFF header: $riffHeader');
return null;
}
final waveFormat = String.fromCharCodes(wavData.sublist(8, 12));
if (waveFormat != 'WAVE') {
Logger.debug('Invalid WAVE format: $waveFormat');
return null;
}
int offset = 12;
int fmtChunkSize = 0;
int sampleRate = 0;
int channels = 0;
int bitsPerSample = 0;
while (offset < wavData.length - 8) {
final chunkId = String.fromCharCodes(wavData.sublist(offset, offset + 4));
final chunkSize = ByteData.sublistView(wavData, offset + 4, offset + 8).getUint32(0, Endian.little);
if (chunkId == 'fmt ') {
fmtChunkSize = chunkSize;
final audioFormat = ByteData.sublistView(wavData, offset + 8, offset + 10).getUint16(0, Endian.little);
channels = ByteData.sublistView(wavData, offset + 10, offset + 12).getUint16(0, Endian.little);
sampleRate = ByteData.sublistView(wavData, offset + 12, offset + 16).getUint32(0, Endian.little);
bitsPerSample = ByteData.sublistView(wavData, offset + 22, offset + 24).getUint16(0, Endian.little);
if (audioFormat != 1) {
Logger.debug('Unsupported audio format: $audioFormat (only PCM supported)');
return null;
}
break;
}
offset += 8 + chunkSize;
if (chunkSize % 2 == 1) offset++;
}
if (fmtChunkSize == 0) {
Logger.debug('fmt chunk not found');
return null;
}
// Find data chunk
offset = 12;
while (offset < wavData.length - 8) {
final chunkId = String.fromCharCodes(wavData.sublist(offset, offset + 4));
final chunkSize = ByteData.sublistView(wavData, offset + 4, offset + 8).getUint32(0, Endian.little);
if (chunkId == 'data') {
return WavInfo(
sampleRate: sampleRate,
channels: channels,
bitsPerSample: bitsPerSample,
dataOffset: offset + 8,
dataSize: chunkSize,
);
}
offset += 8 + chunkSize;
if (chunkSize % 2 == 1) offset++;
}
Logger.debug('data chunk not found');
return null;
}
static List<double> _generateWaveformFromSamples(List<double> samples) {
if (samples.isEmpty) {
return _generateFallbackWaveform();
}
const int targetBars = 100;
final int samplesPerWindow = (samples.length / targetBars).ceil();
List<double> waveformData = [];
for (int i = 0; i < targetBars; i++) {
final startIdx = i * samplesPerWindow;
final endIdx = math.min(startIdx + samplesPerWindow, samples.length);
if (startIdx >= samples.length) break;
double rms = 0.0;
int count = 0;
for (int j = startIdx; j < endIdx; j++) {
rms += samples[j] * samples[j];
count++;
}
if (count > 0) {
rms = math.sqrt(rms / count);
}
final level = math.pow(rms, 0.6).toDouble().clamp(0.02, 1.0);
waveformData.add(level);
}
return waveformData;
}
static List<double> _generateFallbackWaveform() {
return [];
}
static void clearCache() {
_waveformCache.clear();
}
}