Case:
Input a 512 byte PCM sample into the PCMVisualizer.feed.
Error:
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ RangeError (index): Index out of range: index should be less than 512: 512
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ #0 package:audio_visualizer/audio_visualizer.dart 275:30 feed
│ #1 package:callbuddy/features/commons/widgets/audio_visualizer.dart 27:63 <fn>
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ⛔ dart error
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
The bug
The loop inside the feed function iterates up to min(1024, data.length). Since data.length represents the byte count, the loop runs twice as many times as there are available samples.
As soon as the loop index i exceeds data.length / 2 (the length of data16), the code tries to access an index that does not exist in the Int16List, throwing a RangeError.
Code where error arises
void feed(Uint8List data) {
final byteData = data.buffer.asByteData();
// Correctly creates a view with half the length (e.g., 256 items for 512 bytes)
final data16 = Int16List.view(
byteData.buffer,
byteData.offsetInBytes,
data.length ~/ 2,
);
final input = List<int>.filled(1024, 0);
// BUG HERE: Loop condition uses 'data.length' (bytes) instead of 'data16.length' (samples)
for (int i = 0; i < min(1024, data.length); i++) {
// int16 to uint8
// CRASH: data16[i] throws RangeError when i >= data16.length
final u8 = scale(data16[i], -32768, 32767, 0, 255).round();
input[i] = u8;
}
// ...
}
Case:
Input a 512 byte PCM sample into the PCMVisualizer.feed.
Error:
The bug
The loop inside the
feedfunction iterates up tomin(1024, data.length). Sincedata.lengthrepresents the byte count, the loop runs twice as many times as there are available samples.As soon as the loop index
iexceedsdata.length / 2(the length ofdata16), the code tries to access an index that does not exist in theInt16List, throwing aRangeError.Code where error arises