leetreveil/musicmetadata — pull request #52 by DullReferenceException (2014-05-02 03:05:12+00:00)
Title: Fixes for false positive audio frames

In testing out some sample MP3s, I encountered one that would not only parse incorrectly, but it would actually break the parser so it would go into an infinite parse loop; this was because a `NaN` was being passed into `new strtok.BufferType(...)` due to invalid header values. This would cause it to continually read 0 byte buffers, thus never terminating.

This is just another case of a false positive for the frame synchronizer, which is very common. Although you cannot tell for sure when a _real_ audio frame is encountered, there are a few clues. Additionally, it's not guaranteed that the pre-synchronization frames will fall along a four-byte boundary. To improve the synchronization algorithm, I updated the following:

* Frame seeking is changed to be a byte-by-byte scan.
* Continue seeking the first frame if:
* The MPEG version is `01` (reserved).
* The MPEG layer is `00` (reserved).
* The bitrate index is `1111` (bad).
* The sampling rate frequency index is `11` (reserved).

Even after all this, my sample file failed. The matched frame appeared to be an MPEG1 layer 1 frame. Since this library will mostly be used for MP3s, I also added code to continue seeking the first frame if the frame isn't identified as an MPEG1 layer 3 frame. Although this is behavior is defaulted to true, you can override it by setting an `allowNonMP3Frames` option to `true`. Because I introduced a new option that can be consumed by parsers, I changed the parsers so they receive an options object instead of just a boolean flag.

After all these changes, my MP3 can be successfully parsed. I've added a test case and the mp3 to the samples directory to prove it out.