Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » finding the first frame in an mp3 file

This thread is locked; no one can reply to it. rss feed Print
finding the first frame in an mp3 file
kazzmir
Member #1,786
December 2001
avatar

I wrote a small streaming mp3 server and I'd like to know what the bitrate of the mp3 is, so according to various sites( like http://www.mp3-tech.org/programmer/frame_header.html ) I should be able to read the first 4 bytes of the frame and figure things out from there. That works fine as long as I can find the first frame but therein lies my problem: how do I find the first frame?

I googled around for a bit and looked at the sources to mpg123 but the code is a huge mess and hard to work through. As a quick hack I searched for the first byte of value 255( the frame sync byte ) which works for a handful of mp3's but some mp3's have a 255 somewhere in the id3 tag part or whatever which results in me calculating bogus bitrate values.

ixilom
Member #7,167
April 2006
avatar

This might be what you are looking for clicky

___________________________________________
Democracy in Sweden? Not since 2008-Jun-18.
<someone> The lesbians next door bought me a rolex for my birthday.
<someone> I think they misunderstood when I said I wanna watch...

Kitty Cat
Member #2,815
October 2002
avatar

MPEG audio isn't very intuitive. Unlike video and system streams, it doesn't use markers, it's just raw compressed data. However, the way you check for a header is:

/* This should give a good guess if we have an MPEG audio header */
if(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
   ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
   ((header[2]>>2)&0x3) != 0x3)
    /* got mpeg audio header */;

Note that that's an array of bytes read directly (not endian converted). If the above check fails, then you shift by one byte (header[0] = header[1];header[1] = header[2];header[2] = header[3];), put the next byte into header[3], and check again (ad infinitum, until you get tired of looking).

This can lead to false positives, though, if it's not actually an MPEG audio stream, or possibly even with compressed audio data that happens to take the form of a header.

--
"Do not meddle in the affairs of cats, for they are subtle and will pee on your computer." -- Bruce Graham

Go to: