naudio / NLayer

MPEG 1 & 2 Decoder for Layers 1, 2, & 3
MIT License
124 stars 30 forks source link

First MPEG frame is thrown away #4

Open grimthorpe opened 7 years ago

grimthorpe commented 7 years ago

In MpegStreamReader constructor the first MpegFrame found in the file gets thrown away.

` // find the first Mpeg frame var frame = FindNextFrame(); while (frame != null && !(frame is MpegFrame)) { frame = FindNextFrame(); }

        // if we still don't have a frame, we never sync'ed
        if (frame == null) throw new InvalidDataException("Not a valid MPEG file!");

        // the very next frame "should be" an mpeg frame
        frame = FindNextFrame();

`

If the next frame isn't an MpegFrame then the entire decode fails. At the point before the comment 'the very next frame "should be" an mpeg frame', frame already refers to an MpegFrame so there is no need to read the following one.

This causes me a problem because I am decoding a stream that only contains a single MpegFrame at a time.

ioctlLR commented 7 years ago

The first frame is not thrown away. It is added as the first item in a linked list, to which the second frame found gets added as part of the second call to FindNextFrame()... When the reader needs to return a frame for decoding, it uses the next item in the linked list (starting from the first one).

As far as your use case, you might try commenting out the second call to FindNextFrame() in the constructor to see if that works for you. If so, send us a pull request and we can review it. It's been years since I last touched that code, so I'd want to do quite a bit of testing before committing any changes.

grimthorpe commented 7 years ago

Yes, you are right, it doesn't get thrown away. But as I only have 1 MP3 frame in the data it does fail the test for a 2nd MP3 Frame. Commenting out the FindNextFrame() makes it work for me.