diff --git a/src/flac/flac-demuxer.ts b/src/flac/flac-demuxer.ts index bf71ee4..5248394 100644 --- a/src/flac/flac-demuxer.ts +++ b/src/flac/flac-demuxer.ts @@ -339,16 +339,34 @@ export class FlacDemuxer extends Demuxer { slice.skip(-2); const lengthIfNextFlacFrameHeaderIsLegit = slice.filePos - startPos; - const nextIsLegit = this.readFlacFrameHeader({ + const nextFrameHeader = this.readFlacFrameHeader({ slice, isFirstPacket: false, }); - if (!nextIsLegit) { + if (!nextFrameHeader) { slice.skip(-1); continue; } + // Ensure the frameOrSampleNum is consecutive. + // https://github.com/Vanilagy/mediabunny/issues/194 + + if (this.blockingBit === 0) { + // Case A: If the stream is fixed block size, this is the frame number, which increments by 1 + if (nextFrameHeader.num - frameHeader.num !== 1) { + slice.skip(-1); + continue; + } + } else { + // Case B: If the stream is variable block size, this is the sample number, which increments by + // amount of samples in a frame. + if (nextFrameHeader.num - frameHeader.num !== frameHeader.blockSize) { + slice.skip(-1); + continue; + } + } + return { num: frameHeader.num, blockSize: frameHeader.blockSize, @@ -442,6 +460,11 @@ export class FlacDemuxer extends Demuxer { return null; } + if (sampleRate !== this.audioInfo.sampleRate) { + // This cannot be a valid FLAC frame, the sample rate is not the same as in the stream info + return null; + } + const size = slice.filePos - startOffset; const crc = readU8(slice);