18

I'm writing a C++ library for decoding and encoding audio between different formats/codecs. I have a routine for quickly detecting the format before loading the required codec library.

For WAV files one can simple look for the ASCII values "RIFF" and "WAVE" at the start of the file. The same applies to FLAC, we can simply read in the first 4 bytes, which will be "fLaC".

But how can I quickly detect if a file is MP3? I can't rely on the file extension. I also can't try to decode the first MP3 frame, since there might be additional data at the start of the file (eg: ID3, cover image, etc).

Oak Bytes
  • 4,649
  • 4
  • 36
  • 53
goocreations
  • 2,938
  • 8
  • 37
  • 59

1 Answers1

34

Detecting if a file is an MP3 is more complicated than searching for a fixed pattern in the file.

Some concepts

(See http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header for details)

  • MP3 file consists of a series of frames and each frame has a header at the beginning.
  • Header starts at a byte boundary with an 11-bit sync word, which is all 1s. Hence the sync word is either 0xFFE or 0XFFF.
  • Length of each frame is calculated based on the header parameters.

Algorithm to determine if a file is MP3 or not

  • Search for the sync word in the file (0xFFF or 0xFFE).
  • Parse the header parameters.
  • Determine the frame length using the header parameters.
  • Seek to the next frame using the frame length.
  • If you find another sync word after seeking, then the file is most likely an MP3 file.
  • To be sure, repeat the process to find N consecutive MP3 frames. N can be increased for a better hit-rate.
hippietrail
  • 15,848
  • 18
  • 99
  • 158
Oak Bytes
  • 4,649
  • 4
  • 36
  • 53
  • 1
    this doesn't seem to address the issue with cover art/ID3? – micsthepick Dec 22 '21 at 11:23
  • The method works if an MP3 has Cover Art or ID3 as they do not have 0xFFF/0xFFE at frame boundaries (i.e if you find a header pattern in the cover art and extract frame length, you will not find another FFF/FFE pattern at the end of the frame). – Oak Bytes Jan 10 '22 at 12:24
  • This makes it sound like there's some way to include Cover Art in an MP3 other than within the ID3 tag? If there is such a way where can I learn more? If there is not we should make an edit to clarify. – hippietrail Jun 29 '23 at 07:32