How to read ADTS header from file in C++?

1.3k Views Asked by At

How can I read the header of an ADTS encoded aac file? I need it to get the buffer length for each frame to read out the whole aac file. But I can't get the right values. Here is my code to read the header and get the buffer length for each frame(Bit 30 - 43), when assuming big endian:

main(){
  ifstream file("audio_adts.m4a", ios::binary);
  char header[7],buf[1024];
  int framesize;

  while(file.read(header,7)) {
      memset(buf ,0 , 1024);

      /* Get header bit 30 - 42 */
      framesize = (header[3]&240|header[4]|header[5]&1);

      cout << "Framesize including header: "<<framesize<<endl;
      file.read(buf,framesize);

      /*Do something with buffer*/
  }

  return 0;
}

The framesize I get with this code is 65, 45 ,45, 45, -17 and then it stops because of the negative value. The actual framesizes are around 200.

Hexdump of first header:

0x000000: ff f9 50 40 01 3f fc
2

There are 2 best solutions below

0
On

Your extraction of the framesize appears to have the shifts << missing, needed to get the extracted bit into the right locations

The bit masks does not look like they are matching the /*bit 30-42*/ comment.

Also, change the char to unsigned char as you otherwise will run into all kind of sign extension issues when you are doing this type of bit manipulation (which is the cause for your negative value error)

0
On

The way I calculated it:

unsigned int AAC_frame_len = ((AAC_44100_buf[3]&0x03)<<11|(AAC_44100_buf[4]&0xFF)<<3|(AAC_44100_buf[5]&0xE0)>>5);