/**********************************************************************
Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
common.c
**********************************************************************/
/**********************************************************************
 * MPEG/audio coding/decoding software, work in progress              *
 *   NOT for public distribution until verified and approved by the   *
 *   MPEG/audio committee.  For further information, please contact   *
 *   Chad Fogg email: <cfogg@xenon.com>                               *
 *                                                                    *
 * VERSION 4.1                                                        *
 *   changes made since last update:                                  *
 *   date   programmers         comment                               *
 * 2/25/91  Doulas Wong,        start of version 1.0 records          *
 *          Davis Pan                                                 *
 * 5/10/91  W. Joseph Carter    Created this file for all common      *
 *                              functions and global variables.       *
 *                              Ported to Macintosh and Unix.         *
 *                              Added Jean-Georges Fritsch's          *
 *                              "bitstream.c" package.                *
 *                              Added routines to handle AIFF PCM     *
 *                              sound files.                          *
 *                              Added "mem_alloc()" and "mem_free()"  *
 *                              routines for memory allocation        *
 *                              portability.                          *
 *                              Added routines to convert between     *
 *                              Apple SANE extended floating point    *
 *                              format and IEEE double precision      *
 *                              floating point format.  For AIFF.     *
 * 02jul91 dpwe (Aware Inc)     Moved allocation table input here;    *
 *                              Tables read from subdir TABLES_PATH.  *
 *                              Added some debug printout fns (Write*)*
 * 7/10/91 Earle Jennings       replacement of the one float by FLOAT *
 *                              port to MsDos from MacIntosh version  *
 * 8/ 5/91 Jean-Georges Fritsch fixed bug in open_bit_stream_r()      *
 *10/ 1/91 S.I. Sudharsanan,    Ported to IBM AIX platform.           *
 *         Don H. Lee,                                                *
 *         Peter W. Farrett                                           *
 *10/3/91  Don H. Lee           implemented CRC-16 error protection   *
 *                              newly introduced functions are        *
 *                              I_CRC_calc, II_CRC_calc and           *
 *                              update_CRC. Additions and revisions   *
 *                              are marked with dhl for clarity       *
 *10/18/91 Jean-Georges Fritsch fixed bug in update_CRC(),            *
 *                              II_CRC_calc() and I_CRC_calc()        *
 * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
 *                              important fixes involved changing     *
 *                              16-bit ints to long or unsigned in    *
 *                              bit alloc routines for quant of 65535 *
 *                              and passing proper function args.     *
 *                              Removed "Other Joint Stereo" option   *
 *                              and made bitrate be total channel     *
 *                              bitrate, irrespective of the mode.    *
 *                              Fixed many small bugs & reorganized.  *
 * 3/20/92 Jean-Georges Fritsch  fixed bug in start-of-frame search   *
 * 6/15/92 Juan Pineda          added refill_buffer(bs) "n"           *
 *                              initialization                        *
 * 7/08/92 Susanne Ritscher     MS-DOS, MSC6.0 port fixes             *
 * 7/27/92 Mike Li               (re-)Port to MS-DOS                  *
 * 8/19/92 Soren H. Nielsen     Fixed bug in I_CRC_calc and in        *
 *                              II_CRC_calc.  Added function: new_ext *
 *                              for better MS-DOS compatability       *
 * 3/10/93 Kevin Peterson       changed aiff_read_headers to handle   *
 *                              chunks in any order.  now returns     *
 *                              position of sound data in file.       *
 * 3/31/93 Jens Spille          changed IFF_* string compares to use  *
 *                              strcmp()                              *
 * 5/30/93 Masahiro Iwadare     removed the previous modification     *
 *                              for UNIX.                             *
 * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
 *         Daniel Lauzon, and                                         *
 *         Bill Truerniet                                             *
 *--------------------------------------------------------------------*
 *  8/24/93 Masahiro Iwadare    Included IS modification in Layer III.*
 *                              Changed for 1 pass decoding.          *
 *  9/07/93 Toshiyuki Ishino    Integrated Layer III with Ver 3.9.    *
 *--------------------------------------------------------------------*
 * 11/20/93 Masahiro Iwadare    Integrated Layer III with Ver 4.0.    *
 *--------------------------------------------------------------------*
 *  7/14/94 Juergen Koller      rewind of bitbuffer added             *
 *--------------------------------------------------------------------*
 *  1/15/02 Christopher Andrews Cleaned up for 545 project usage:     *
 *                              Removed all support for other layers  *
 *                              and other platforms                   *
 **********************************************************************/

/***********************************************************************
*
*  Global Include Files
*
***********************************************************************/

#include <ctype.h>
#include "common.h"

/***********************************************************************
*
*  Global Variable Definitions
*
***********************************************************************/


long  s_freq[4] = {44100l, 48000l, 32000l, 0l};

int     bitrate[3][15] = {
          {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
          {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384},
          {0,32,40,48,56,64,80,96,112,128,160,192,224,256,320}
        };


/***********************************************************************
*
*  Global Function Definitions
*
***********************************************************************/

int js_bound(lay, m_ext)
int lay, m_ext;
{
static int jsb_table[3][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16},
                                { 0, 4, 8, 16} }; 

    if(lay<1 || lay >3 || m_ext<0 || m_ext>3) {
#ifdef PLATFORM_UNIX
        fprintf(stderr, "js_bound bad layer/modext (%d/%d)\n", lay, m_ext);
#endif
        exit(1);
    }
    return(jsb_table[lay-1][m_ext]);
}


void hdr_to_frps(fr_ps) /* interpret data in hdr str to fields in fr_ps */
frame_params *fr_ps;
{
layer *hdr = fr_ps->header;     /* (or pass in as arg?) */

    fr_ps->actual_mode = hdr->mode;
    fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
    fr_ps->sblimit = SBLIMIT;
    if(hdr->mode == MPG_MD_JOINT_STEREO)
        fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext);
    else
        fr_ps->jsbound = fr_ps->sblimit;
}


/****************************************************************************
* Routines for writing to .wav files
*****************************************************************************/


unsigned int little_endian(unsigned int num){
  unsigned int val = 0;
  int ctr;

   for (ctr = 0; ctr < 4; ctr++)
    val |= (long)((num >> (ctr * 8l)) & 0xff) << (long)((3-ctr) * 8l) ;
   return val;
}


int wav_seek_to_sound_data(buffer)
     FILE *buffer;
{

  if (fseek_(buffer, (sizeof(riff_chunk_t) + sizeof(format_chunk_t) + sizeof(data_chunk_t)) , SEEK_SET) != 0)
    return -1;
   return 0;
}


int wav_write_headers(buffer, wav_ptr)
     FILE *buffer;
     wav_data_t *wav_ptr;
{

  riff_chunk_t rct;
  format_chunk_t fct;
  data_chunk_t dct;
  long data_length;
  int bytes_per_sam;
 
  *(unsigned long *)rct.type = (unsigned long)R_TYPE;
  *(unsigned long *)fct.type = (unsigned long)F_TYPE;
  *(unsigned long *)dct.type = (unsigned long)D_TYPE;
  *(unsigned long *)rct.file_type = (unsigned long)WAVE;

  fct.length = little_endian(0x10);
  fct.mode = 1l << 24l;
  fct.mode |= wav_ptr->numChannels << 8l;
 
  bytes_per_sam = (wav_ptr->sampleSize + 7l)/8l ;
  fct.rate = little_endian(wav_ptr->sampleRate);
 
  fct.bps = little_endian(bytes_per_sam * (wav_ptr->sampleRate) * wav_ptr->numChannels);
  fct.bytes_per_sam = ((bytes_per_sam * wav_ptr->numChannels)) << 8l;
  fct.bits_per_sam = (bytes_per_sam * 8l) << 8l;
  
  data_length = bytes_per_sam * wav_ptr->numChannels * wav_ptr->numSampleFrames;
  dct.length = little_endian(data_length);
  rct.length = little_endian(data_length + sizeof(riff_chunk_t) + sizeof(format_chunk_t));
  
 
  if (fseek_(buffer,0,SEEK_SET) != 0)
    return -1;

 if (fwrite_(&rct,sizeof(riff_chunk_t), 1, buffer) != 1)
    return -1;

 if (fwrite_(&fct,sizeof(format_chunk_t), 1, buffer) != 1)
    return -1;
 
 if (fwrite_(&dct,sizeof(data_chunk_t), 1, buffer) != 1)
    return -1;

  return 0;
}

/*****************************************************************************
*
*  bit_stream.c package
*  Author:  Jean-Georges Fritsch, C-Cube Microsystems
*
*****************************************************************************/

/********************************************************************
  This package provides functions to write (exclusive or read)
  information from (exclusive or to) the bit stream.

  If the bit stream is opened in read mode only the get functions are
  available. If the bit stream is opened in write mode only the put
  functions are available.
********************************************************************/

/*open_bit_stream_w(); open the device to write the bit stream into it    */
/*open_bit_stream_r(); open the device to read the bit stream from it     */
/*close_bit_stream();  close the device containing the bit stream         */
/*alloc_buffer();      open and initialize the buffer;                    */
/*desalloc_buffer();   empty and close the buffer                         */
/*back_track_buffer();     goes back N bits in the buffer                 */
/*unsigned int get1bit();  read 1 bit from the bit stream                 */
/*unsigned long getbits(); read N bits from the bit stream                */
/*unsigned long byte_ali_getbits();   read the next byte aligned N bits from*/
/*                                    the bit stream                        */
/*unsigned long look_ahead(); grep the next N bits in the bit stream without*/
/*                            changing the buffer pointer                   */
/*put1bit(); write 1 bit from the bit stream  */
/*put1bit(); write 1 bit from the bit stream  */
/*putbits(); write N bits from the bit stream */
/*byte_ali_putbits(); write byte aligned the next N bits into the bit stream*/
/*unsigned long sstell(); return the current bit stream length (in bits)    */
/*int end_bs(); return 1 if the end of bit stream reached otherwise 0       */
/*int seek_sync(); return 1 if a sync word was found in the bit stream      */
/*                 otherwise returns 0                                      */

/* refill the buffer from the input device when the buffer becomes empty    */
int refill_buffer(bs)
Bit_stream_struc *bs;   /* bit stream structure */
{
   register int i=bs->buf_size-2-bs->buf_byte_idx;
   register unsigned long n=1;

   while ((i>=0) && (!bs->eob)) {


     n = fread_(&bs->buf[i--], sizeof(unsigned char), 1, bs->pt);
     
     if (!n) {
       bs->eob= i+1;
     }
     
   }
   return 0;
}


unsigned char stc_bitstream_buf[BUFFER_SIZE];

/* open the device to read the bit stream from it */
void open_bit_stream_r(bs, bs_filenam, size)
Bit_stream_struc *bs;   /* bit stream structure */
char *bs_filenam;       /* name of the bit stream file */
int size;               /* size of the buffer */
{

   bs->format = BINARY;
#ifdef PLATFORM_UNIX
   printf ("the bit stream file %s is a BINARY file\n", bs_filenam);
#endif
   
   if ((bs->pt = fopen_(bs_filenam, "rb")) == NULL) {
#ifdef PLATFORM_UNIX
     printf("Could not find \"%s\".\n", bs_filenam);
#endif
     exit(1);
   }

   bs->buf = stc_bitstream_buf;
   bs->buf_size = size;
   
   bs->buf_byte_idx=0;
   bs->buf_bit_idx=0;
   bs->totbit=0;
   bs->mode = READ_MODE;
   bs->eob = FALSE;
   bs->eobs = FALSE;
}

/*close the device containing the bit stream after a read process*/
void close_bit_stream_r(bs)
Bit_stream_struc *bs;   /* bit stream structure */
{
   fclose_(bs->pt);
}

int putmask[9]={0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
int clearmask[9]={0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x0};


int mask[8]={0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};

/*read 1 bit from the bit stream */
unsigned int get1bit(bs)
Bit_stream_struc *bs;   /* bit stream structure */
{
   unsigned int bit;
   register int i;

   bs->totbit++;

   if (!bs->buf_bit_idx) {
        bs->buf_bit_idx = 8;
        bs->buf_byte_idx--;
        if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
             if (bs->eob)
                bs->eobs = TRUE;
             else {
                for (i=bs->buf_byte_idx; i>=0;i--)
                  bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
                refill_buffer(bs);
                bs->buf_byte_idx = bs->buf_size-1;
             }
        }
   }
   bit = bs->buf[bs->buf_byte_idx]&mask[bs->buf_bit_idx-1];
   bit = bit >> (bs->buf_bit_idx-1);
   bs->buf_bit_idx--;
   return(bit);
}


/*read N bit from the bit stream */
unsigned long getbits(bs, N)
Bit_stream_struc *bs;   /* bit stream structure */
int N;                  /* number of bits to read from the bit stream */
{
 unsigned long val=0;
 register int i;
 register int j = N;
 register int k, tmp;

#ifdef PLATFORM_UNIX
 if (N > MAX_LENGTH)
    printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
#endif

 bs->totbit += N;
 while (j > 0) {
   if (!bs->buf_bit_idx) {
        bs->buf_bit_idx = 8;
        bs->buf_byte_idx--;
        if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
             if (bs->eob)
                bs->eobs = TRUE;
             else {
                for (i=bs->buf_byte_idx; i>=0;i--)
                   bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
                refill_buffer(bs);
                bs->buf_byte_idx = bs->buf_size-1;
             }
        }
   }
   k = MIN (j, bs->buf_bit_idx);
   tmp = bs->buf[bs->buf_byte_idx]&putmask[bs->buf_bit_idx];
   tmp = tmp >> (bs->buf_bit_idx-k);
   val |= tmp << (j-k);
   bs->buf_bit_idx -= k;
   j -= k;
 }
 return(val);
}





/*return the current bit stream length (in bits)*/
unsigned long sstell(bs)
Bit_stream_struc *bs;   /* bit stream structure */
{
  return(bs->totbit);
}

/*return the status of the bit stream*/
/* returns 1 if end of bit stream was reached */
/* returns 0 if end of bit stream was not reached */
int end_bs(bs)
Bit_stream_struc *bs;   /* bit stream structure */
{
  return(bs->eobs);
}

/*this function seeks for a byte aligned sync word in the bit stream and
  places the bit stream pointer right after the sync.
  This function returns 1 if the sync was found otherwise it returns 0  */
int seek_sync(bs, sync, N)
Bit_stream_struc *bs;   /* bit stream structure */
long sync;      /* sync word maximum 32 bits */
int N;          /* sync word length */
{
 unsigned long aligning, stell();
 unsigned long val;
 long maxi = (2<<N)-1;

 aligning = sstell(bs)%ALIGNING; /*is this %8 into the file?*/
 
 if (aligning) /*no, so get there*/
    getbits(bs, (int)(ALIGNING-aligning));

  val = getbits(bs, N);
  while (((val&maxi) != sync) && (!end_bs(bs))) {
        val <<= ALIGNING;
        val |= getbits(bs, ALIGNING);
  }
 
 if (end_bs(bs)) return(0);
 else return(1);
}
/*****************************************************************************
*
*  End of bit_stream.c package
*
*****************************************************************************/









static unsigned long offset,totbit=0, buf_byte_idx=0;
static unsigned int buf[BUFSIZE];
static unsigned int buf_bit_idx=8;

/*return the current bit stream length (in bits)*/
unsigned long hsstell()
{
  return(totbit);
}


extern int putmask[9];

/*read N bit from the bit stream */
unsigned long hgetbits(N)
int N;                  /* number of bits to read from the bit stream */
{
 unsigned long val=0;
 register int j = N;
 register int k, tmp;


 totbit += N;
 while (j > 0) {
   if (!buf_bit_idx) {
        buf_bit_idx = 8;
        buf_byte_idx++;
	if (buf_byte_idx > offset)
	  { 
#ifdef PLATFORM_UNIX
	    printf("Buffer overflow !!\n");
#endif
	    exit(3); 
	  }
   }
   k = MIN (j, buf_bit_idx);
   tmp = buf[buf_byte_idx%BUFSIZE]&putmask[buf_bit_idx];
   tmp = tmp >> (buf_bit_idx-k);
   val |= tmp << (j-k);
   buf_bit_idx -= k;
   j -= k;
 }
 return(val);
}

unsigned int hget1bit()
{
return(hgetbits(1));
}

/*write N bits into the bit stream */
void hputbuf(val, N)
unsigned int val;       /* val to write into the buffer */
int N;                  /* number of bits of val */
{
  buf[offset % BUFSIZE] = val;
  offset++;
}

void rewindNbits( N )
int N;
{
   totbit -= N;
   buf_bit_idx += N;
   while( buf_bit_idx >= 8 )
   {  buf_bit_idx -= 8;
      buf_byte_idx--;
   }
}

void rewindNbytes( N )
int N;
{
   totbit -= N*8;
   buf_byte_idx -= N;
}


