home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 4 / AACD04.ISO / AACD / Sound / LAME / Source / common.c next >
C/C++ Source or Header  |  1999-06-02  |  24KB  |  784 lines

  1. /**********************************************************************
  2.  * ISO MPEG Audio Subgroup Software Simulation Group (1996)
  3.  * ISO 13818-3 MPEG-2 Audio Encoder - Lower Sampling Frequency Extension
  4.  *
  5.  * $Id: common.c,v 1.2 1997/01/19 22:28:29 rowlands Exp $
  6.  *
  7.  * $Log: common.c,v $
  8.  * Revision 1.2  1997/01/19 22:28:29  rowlands
  9.  * Layer 3 bug fixes from Seymour Shlien
  10.  *
  11.  * Revision 1.1  1996/02/14 04:04:23  rowlands
  12.  * Initial revision
  13.  *
  14.  * Received from Mike Coleman
  15.  **********************************************************************/
  16.  
  17.  
  18. /***********************************************************************
  19. *
  20. *  Global Include Files
  21. *
  22. ***********************************************************************/
  23.  
  24. #include    "common.h"
  25. #include    <string.h> /* 1995-07-11 shn */
  26. #include    <ctype.h>
  27. #include    <assert.h>
  28. #include <stdlib.h>
  29.  
  30. /***********************************************************************
  31. *
  32. *  Global Variable Definitions
  33. *
  34. ***********************************************************************/
  35.  
  36. char *mode_names[4] = { "stereo", "j-stereo", "dual-ch", "single-ch" };
  37. char *layer_names[3] = { "I", "II", "III" };
  38. char *version_names[2] = { "MPEG-2 LSF", "MPEG-1" };
  39.  
  40. /* 1: MPEG-1, 0: MPEG-2 LSF, 1995-07-11 shn */
  41. double  s_freq[2][4] = {{22.05, 24, 16, 0}, {44.1, 48, 32, 0}};
  42.  
  43. /* 1: MPEG-1, 0: MPEG-2 LSF, 1995-07-11 shn */
  44. int     bitrate[2][3][15] = {
  45.           {{0,32,48,56,64,80,96,112,128,144,160,176,192,224,256},
  46.            {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160},
  47.            {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160}},
  48.       {{0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
  49.            {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384},
  50.            {0,32,40,48,56,64,80,96,112,128,160,192,224,256,320}}
  51.         };
  52.  
  53. double FAR multiple[64] = {
  54. 2.00000000000000, 1.58740105196820, 1.25992104989487,
  55. 1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
  56. 0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
  57. 0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
  58. 0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
  59. 0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
  60. 0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
  61. 0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
  62. 0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
  63. 0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
  64. 0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
  65. 0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
  66. 0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
  67. 0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
  68. 0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
  69. 0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
  70. 1E-20
  71. };
  72.  
  73. enum byte_order NativeByteOrder = order_unknown;
  74.  
  75. /***********************************************************************
  76. *
  77. *  Global Function Definitions
  78. *
  79. ***********************************************************************/
  80.  
  81.  
  82. /***********************************************************************
  83.  * compute bitsperframe and mean_bits for a layer III frame 
  84.  **********************************************************************/
  85. void getframebits(layer *info, int stereo, int *bitsPerFrame, int *mean_bits) {
  86.   int whole_SpF;
  87.   double bit_rate,samp;
  88.   int samplesPerFrame,bitsPerSlot;
  89.   int sideinfo_len;
  90.   int mode_gr;
  91.   
  92.   samp =      s_freq[info->version][info->sampling_frequency];
  93.   bit_rate = bitrate[info->version][info->lay-1][info->bitrate_index];
  94.   samplesPerFrame = info->version == 1 ? 1152 : 576;
  95.   bitsPerSlot = 8;
  96.   mode_gr = (info->version == 1) ? 2 : 1;  /* mode_gr = 2 */
  97.   
  98.   /* determine the mean bitrate for main data */
  99.   sideinfo_len = 32;
  100.   if ( info->version == 1 )
  101.     {   /* MPEG 1 */
  102.       if ( stereo == 1 )
  103.     sideinfo_len += 136;
  104.       else
  105.     sideinfo_len += 256;
  106.     }
  107.   else
  108.     {   /* MPEG 2 */
  109.       if ( stereo == 1 )
  110.     sideinfo_len += 72;
  111.       else
  112.     sideinfo_len += 136;
  113.     }
  114.   
  115.   
  116.   
  117.   
  118.   whole_SpF =  (samplesPerFrame /samp)*(bit_rate /  (double)bitsPerSlot);
  119.   *bitsPerFrame = 8 * whole_SpF + (info->padding * 8);
  120.   *mean_bits = (*bitsPerFrame - sideinfo_len) / mode_gr;
  121. }
  122.  
  123.  
  124.  
  125.  
  126. /* jsbound is ignored for layer 3 */
  127.  
  128. int js_bound(lay, m_ext)
  129. int lay, m_ext;
  130. {
  131. static int jsb_table[3][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16},
  132.                                 { 0, 4, 8, 16} };  /* lay+m_e -> jsbound */
  133.  
  134.     if(lay<1 || lay >3 || m_ext<0 || m_ext>3) {
  135.       if (m_ext!=10) /* mark taylor 5/99 added mode=10 */
  136.     {
  137.       fprintf(stderr, "js_bound bad layer/modext (%d/%d)\n", lay, m_ext);
  138.       exit(1);
  139.     }
  140.     }
  141.     return(jsb_table[lay-1][m_ext]);
  142. }
  143.  
  144.  
  145. void hdr_to_frps(fr_ps) /* interpret data in hdr str to fields in fr_ps */
  146. frame_params *fr_ps;
  147. {
  148. layer *hdr = fr_ps->header;     /* (or pass in as arg?) */
  149.  
  150.     fr_ps->actual_mode = hdr->mode;
  151.     fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
  152.     if (hdr->lay == 2){    
  153.       printf("Only Layer 3 supported\n");
  154.       exit(-1);}
  155.     else                        fr_ps->sblimit = SBLIMIT;
  156.     if(hdr->mode == MPG_MD_JOINT_STEREO)
  157.         fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext);
  158.     else
  159.         fr_ps->jsbound = fr_ps->sblimit;
  160.     /* alloc, tab_num set in pick_table */
  161. }
  162.  
  163.  
  164. void WriteHdr(fr_ps, s)
  165. frame_params *fr_ps;
  166. FILE *s;
  167. {
  168. layer *info = fr_ps->header;
  169.  
  170.    fprintf(s, "HDR: s=FFF, id=%X, l=%X, ep=%s, br=%X, sf=%X, pd=%X, ",
  171.            info->version, info->lay, ((info->error_protection) ? "on" : "off"),
  172.            info->bitrate_index, info->sampling_frequency, info->padding);
  173.    fprintf(s, "pr=%X, m=%X, js=%X, c=%X, o=%X, e=%X\n",
  174.            info->extension, info->mode, info->mode_ext,
  175.            info->copyright, info->original, info->emphasis);
  176.    fprintf(s, "alg.=%s, layer=%s, tot bitrate=%d, sfrq=%.1f\n",
  177.            version_names[info->version], layer_names[info->lay-1],
  178.        bitrate[info->version][info->lay-1][info->bitrate_index],
  179.            s_freq[info->version][info->sampling_frequency]);
  180.    fprintf(s, "mode=%s, sblim=%d, jsbd=%d, ch=%d\n",
  181.            mode_names[info->mode], fr_ps->sblimit, fr_ps->jsbound, fr_ps->stereo);
  182.    fflush(s);
  183. }
  184.  
  185.  
  186.  
  187. int BitrateIndex(layr, bRate, version)   /* convert bitrate in kbps to index */
  188. int     layr;           /* 1 or 2 */
  189. int     bRate;          /* legal rates from 32 to 448 */
  190. int    version;    /* MPEG-1 or MPEG-2 LSF */
  191. {
  192. int     index = 0;
  193. int     found = 0;
  194.  
  195.     while(!found && index<15)   {
  196.         if(bitrate[version][layr-1][index] == bRate)
  197.             found = 1;
  198.         else
  199.             ++index;
  200.     }
  201.     if(found)
  202.         return(index);
  203.     else {
  204.         fprintf(stderr, "BitrateIndex: %d (layer %d) is not a legal bitrate\n",
  205.                 bRate, layr);
  206.         return(-1);     /* Error! */
  207.     }
  208. }
  209.  
  210. int SmpFrqIndex(sRate, version)  /* convert samp frq in Hz to index */
  211. long sRate;             /* legal rates 16000, 22050, 24000, 32000, 44100, 48000 */
  212. int  *version;
  213. {
  214.     if (sRate == 44100L) {
  215.         *version = MPEG_AUDIO_ID; return(0);
  216.     }
  217.     else if (sRate == 48000L) {
  218.         *version = MPEG_AUDIO_ID; return(1);
  219.     }
  220.     else if (sRate == 32000L) {
  221.         *version = MPEG_AUDIO_ID; return(2);
  222.     }
  223.     else if (sRate == 24000L) {
  224.         *version = MPEG_PHASE2_LSF; return(1);
  225.     }
  226.     else if (sRate == 22050L) {
  227.         *version = MPEG_PHASE2_LSF; return(0);
  228.     }
  229.     else if (sRate == 16000L) {
  230.         *version = MPEG_PHASE2_LSF; return(2);
  231.     }
  232.     else {
  233.         fprintf(stderr, "SmpFrqIndex: %ld is not a legal sample rate\n", sRate);
  234.         return(-1);     /* Error! */
  235.     }
  236. }
  237.  
  238. /*******************************************************************************
  239. *
  240. *  Allocate number of bytes of memory equal to "block".
  241. *
  242. *******************************************************************************/
  243.  
  244. void  FAR *mem_alloc(block, item)
  245. unsigned long   block;
  246. char            *item;
  247. {
  248.  
  249.     void    *ptr;
  250.  
  251.     ptr = (void FAR *) malloc(block<<1); /* allocate twice as much memory as needed. fixes dodgy
  252.                         memory problem on most systems */
  253.  
  254.     if (ptr != NULL){
  255.         memset(ptr, 0, block);
  256.     }
  257.     else{
  258.         printf("Unable to allocate %s\n", item);
  259.         exit(0);
  260.     }
  261.     return(ptr);
  262. }
  263.  
  264.  
  265. /****************************************************************************
  266. *
  267. *  Free memory pointed to by "*ptr_addr".
  268. *
  269. *****************************************************************************/
  270.  
  271. void    mem_free(ptr_addr)
  272. void    **ptr_addr;
  273. {
  274.  
  275.     if (*ptr_addr != NULL){
  276.         free(*ptr_addr);
  277.         *ptr_addr = NULL;
  278.     }
  279.  
  280. }
  281.  
  282.  
  283. /*****************************************************************************
  284. *
  285. *  Routines to determine byte order and swap bytes
  286. *
  287. *****************************************************************************/
  288.  
  289. enum byte_order DetermineByteOrder()
  290. {
  291.     char s[ sizeof(long) + 1 ];
  292.     union
  293.     {
  294.         long longval;
  295.         char charval[ sizeof(long) ];
  296.     } probe;
  297.     probe.longval = 0x41424344L;  /* ABCD in ASCII */
  298.     strncpy( s, probe.charval, sizeof(long) );
  299.     s[ sizeof(long) ] = '\0';
  300.     /* fprintf( stderr, "byte order is %s\n", s ); */
  301.     if ( strcmp(s, "ABCD") == 0 )
  302.         return order_bigEndian;
  303.     else
  304.         if ( strcmp(s, "DCBA") == 0 )
  305.             return order_littleEndian;
  306.         else
  307.             return order_unknown;
  308. }
  309.  
  310. void SwapBytesInWords( short *loc, int words )
  311. {
  312.     int i;
  313.     short thisval;
  314.     char *dst, *src;
  315.     src = (char *) &thisval;
  316.     for ( i = 0; i < words; i++ )
  317.     {
  318.         thisval = *loc;
  319.         dst = (char *) loc++;
  320.         dst[0] = src[1];
  321.         dst[1] = src[0];
  322.     }
  323. }
  324.  
  325. /*****************************************************************************
  326.  *
  327.  *  Read Audio Interchange File Format (AIFF) headers.
  328.  *
  329.  *****************************************************************************/
  330.  
  331. int aiff_read_headers( FILE *file_ptr, IFF_AIFF *aiff_ptr )
  332. {
  333.     int chunkSize, subSize, sound_position;
  334.     
  335.     if ( fseek(file_ptr, 0, SEEK_SET) != 0 )
  336.         return -1;
  337.     
  338.     if ( Read32BitsHighLow(file_ptr) != IFF_ID_FORM )
  339.         return -1;
  340.     
  341.     chunkSize = Read32BitsHighLow( file_ptr );
  342.     
  343.     if ( Read32BitsHighLow(file_ptr) != IFF_ID_AIFF )
  344.         return -1;
  345.     
  346.     sound_position = 0;
  347.     while ( chunkSize > 0 )
  348.     {
  349.         chunkSize -= 4;
  350.         switch ( Read32BitsHighLow(file_ptr) )
  351.     {
  352.             
  353.           case IFF_ID_COMM:
  354.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  355.             aiff_ptr->numChannels = Read16BitsHighLow( file_ptr );
  356.             subSize -= 2;
  357.             aiff_ptr->numSampleFrames = Read32BitsHighLow( file_ptr );
  358.             subSize -= 4;
  359.             aiff_ptr->sampleSize = Read16BitsHighLow( file_ptr );
  360.             subSize -= 2;
  361.             aiff_ptr->sampleRate  = ReadIeeeExtendedHighLow( file_ptr );
  362.             subSize -= 10;
  363.             while ( subSize > 0 )
  364.         {
  365.                 getc( file_ptr );
  366.                 subSize -= 1;
  367.         }
  368.             break;
  369.             
  370.           case IFF_ID_SSND:
  371.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  372.             aiff_ptr->blkAlgn.offset = Read32BitsHighLow( file_ptr );
  373.             subSize -= 4;
  374.             aiff_ptr->blkAlgn.blockSize = Read32BitsHighLow( file_ptr );
  375.             subSize -= 4;
  376.             sound_position = ftell( file_ptr ) + aiff_ptr->blkAlgn.offset;
  377.             if ( fseek(file_ptr, (long) subSize, SEEK_CUR) != 0 )
  378.                 return -1;
  379.             aiff_ptr->sampleType = IFF_ID_SSND;
  380.             break;
  381.             
  382.           default:
  383.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  384.             while ( subSize > 0 )
  385.         {
  386.                 getc( file_ptr );
  387.                 subSize -= 1;
  388.         }
  389.             break;
  390.     }
  391.     }
  392.     return sound_position;
  393. }
  394.  
  395. /*****************************************************************************
  396.  *
  397.  *  Seek past some Audio Interchange File Format (AIFF) headers to sound data.
  398.  *
  399.  *****************************************************************************/
  400.  
  401. int aiff_seek_to_sound_data( FILE *file_ptr )
  402. {
  403.     if ( fseek(file_ptr, AIFF_FORM_HEADER_SIZE + AIFF_SSND_HEADER_SIZE, SEEK_SET) != 0 )
  404.         return(-1);
  405.     return(0);
  406. }
  407.  
  408. /*******************************************************************************
  409.  *
  410.  *  Write Audio Interchange File Format (AIFF) headers.
  411.  *
  412.  *******************************************************************************/
  413.  
  414. int aiff_write_headers( FILE *file_ptr, IFF_AIFF *aiff_ptr )
  415. {
  416.     int chunkSize;
  417.     int sampleBytes = (aiff_ptr->sampleSize / 8) + (aiff_ptr->sampleSize % 8 ? 1 : 0);
  418.     
  419.     if ( fseek(file_ptr, 0L, SEEK_SET) != 0 )
  420.         return -1;
  421.     
  422.     /* write FORM chunk */
  423.     chunkSize = 8 + 18 + 8 + aiff_ptr->numChannels * aiff_ptr->numSampleFrames * sampleBytes;
  424.     Write32BitsHighLow( file_ptr, IFF_ID_FORM );
  425.     Write32BitsHighLow( file_ptr, chunkSize );
  426.     Write32BitsHighLow( file_ptr, IFF_ID_AIFF );
  427.     /* write COMM chunk */
  428.     Write32BitsHighLow( file_ptr, IFF_ID_COMM );
  429.     Write32BitsHighLow( file_ptr, 18 ); /* chunk size */
  430.     Write16BitsHighLow( file_ptr, aiff_ptr->numChannels );
  431.     Write32BitsHighLow( file_ptr, aiff_ptr->numSampleFrames );
  432.     Write16BitsHighLow( file_ptr, aiff_ptr->sampleSize );
  433.     WriteIeeeExtendedHighLow( file_ptr, aiff_ptr->sampleRate );
  434.     /* write SSND chunk header */
  435.     chunkSize = 8 + aiff_ptr->numChannels * aiff_ptr->numSampleFrames * sampleBytes;
  436.     Write32BitsHighLow( file_ptr, IFF_ID_SSND );
  437.     Write32BitsHighLow( file_ptr, chunkSize );
  438.     Write32BitsHighLow( file_ptr, 0 ); /* offset */
  439.     Write32BitsHighLow( file_ptr, 0 ); /* block size */
  440.     return 0;
  441. }
  442.  
  443. /*****************************************************************************
  444. *
  445. *  bit_stream.c package
  446. *  Author:  Jean-Georges Fritsch, C-Cube Microsystems
  447. *
  448. *****************************************************************************/
  449.  
  450. /********************************************************************
  451.   This package provides functions to write (exclusive or read)
  452.   information from (exclusive or to) the bit stream.
  453.  
  454.   If the bit stream is opened in read mode only the get functions are
  455.   available. If the bit stream is opened in write mode only the put
  456.   functions are available.
  457. ********************************************************************/
  458.  
  459. /*open_bit_stream_w(); open the device to write the bit stream into it    */
  460. /*open_bit_stream_r(); open the device to read the bit stream from it     */
  461. /*close_bit_stream();  close the device containing the bit stream         */
  462. /*alloc_buffer();      open and initialize the buffer;                    */
  463. /*desalloc_buffer();   empty and close the buffer                         */
  464. /*back_track_buffer();     goes back N bits in the buffer                 */
  465. /*unsigned int get1bit();  read 1 bit from the bit stream                 */
  466. /*unsigned long look_ahead(); grep the next N bits in the bit stream without*/
  467. /*                            changing the buffer pointer                   */
  468. /*put1bit(); write 1 bit from the bit stream  */
  469. /*put1bit(); write 1 bit from the bit stream  */
  470. /*putbits(); write N bits from the bit stream */
  471. /*unsigned long sstell(); return the current bit stream length (in bits)    */
  472. /*int end_bs(); return 1 if the end of bit stream reached otherwise 0       */
  473. /*int seek_sync(); return 1 if a sync word was found in the bit stream      */
  474. /*                 otherwise returns 0                                      */
  475.  
  476. /* refill the buffer from the input device when the buffer becomes empty    */
  477. int refill_buffer(bs)
  478. Bit_stream_struc *bs;   /* bit stream structure */
  479. {
  480.    register int i=bs->buf_size-2-bs->buf_byte_idx;
  481.    register unsigned long n=1;
  482.    register int index=0;
  483.    char val[2];
  484.  
  485. #ifndef _BLADEDLL
  486.    while ((i>=0) && (!bs->eob)) {
  487.  
  488.       if (bs->format == BINARY)
  489.          n = fread(&bs->buf[i--], sizeof(unsigned char), 1, bs->pt);
  490.  
  491.       else {
  492.          while((index < 2) && n) {
  493.             n = fread(&val[index], sizeof(char), 1, bs->pt);
  494.             switch (val[index]) {
  495.                   case 0x30:
  496.                   case 0x31:
  497.                   case 0x32:
  498.                   case 0x33:
  499.                   case 0x34:
  500.                   case 0x35:
  501.                   case 0x36:
  502.                   case 0x37:
  503.                   case 0x38:
  504.                   case 0x39:
  505.                   case 0x41:
  506.                   case 0x42:
  507.                   case 0x43:
  508.                   case 0x44:
  509.                   case 0x45:
  510.                   case 0x46:
  511.                   index++;
  512.                   break;
  513.                   default: break;
  514.             }
  515.          }
  516.  
  517.          if (val[0] <= 0x39)   bs->buf[i] = (val[0] - 0x30) << 4;
  518.                  else  bs->buf[i] = (val[0] - 0x37) << 4;
  519.          if (val[1] <= 0x39)   bs->buf[i--] |= (val[1] - 0x30);
  520.                  else  bs->buf[i--] |= (val[1] - 0x37);
  521.          index = 0;
  522.       }
  523.  
  524.       if (!n) {
  525.          bs->eob= i+1;
  526.       }
  527.  
  528.     }
  529. #endif
  530.    return 0;
  531. }
  532.  
  533.  
  534. /* empty the buffer to the output device when the buffer becomes full */
  535. /* mt 3/99: modified so we can call empty_buffer even if buffer is not full */
  536. void empty_buffer(bs, minimum)
  537. Bit_stream_struc *bs;   /* bit stream structure */
  538. int minimum;            /* end of the buffer to empty */
  539. {
  540.    register int i;
  541.  
  542. #ifndef DISTRIB
  543. #if BS_FORMAT == BINARY
  544.    for (i=bs->buf_size-1;i>=minimum;i--) 
  545.    {
  546.     #ifdef _BLADEDLL
  547.         if (bs->nOutBufPos<BUFFER_SIZE)
  548.         {
  549.             bs->pbtOutBuf[bs->nOutBufPos++]=bs->buf[i];
  550.         }
  551.         else
  552.         {
  553.             assert(0);
  554.         }
  555.     #else
  556.       fwrite(&bs->buf[i], sizeof(unsigned char), 1, bs->pt);
  557.     #endif // _BLADEDLL
  558.    }
  559. #else
  560.    static char *he = "0123456789ABCDEF";
  561.  
  562.    for (i=bs->buf_size-1;i>=minimum;i--) {
  563.        char val[2];
  564.        val[0] = he[((bs->buf[i] >> 4) & 0x0F)];
  565.        val[1] = he[(bs->buf[i] & 0x0F)];
  566.        fwrite(val, sizeof(char), 2, bs->pt);
  567.    }
  568. #endif // BS_FORMAT==BINARY
  569.  
  570.     #ifndef _BLADEDLL
  571.         // NEW SS to assist in debugging
  572.         // Only file for files, not for the output buffer
  573.         fflush(bs->pt); 
  574.     #endif
  575. #endif
  576.  
  577.    /* for (i=minimum-1; i>=0; i--) */
  578.    for (i=minimum-1; i>=bs->buf_byte_idx+1; i--)
  579.        bs->buf[bs->buf_size - minimum + i] = bs->buf[i];
  580.  
  581.    /*   bs->buf_byte_idx = bs->buf_size -1 - minimum; */
  582.    bs->buf_byte_idx = bs->buf_size -1 - minimum + bs->buf_byte_idx + 1;
  583.    bs->buf_bit_idx = 8;
  584. }
  585.  
  586. /* open the device to write the bit stream into it */
  587. void open_bit_stream_w(bs, bs_filenam, size)
  588. Bit_stream_struc *bs;   /* bit stream structure */
  589. char *bs_filenam;       /* name of the bit stream file */
  590. int size;               /* size of the buffer */
  591. {
  592. #ifdef _BLADEDLL
  593.   // Initialize output buffer
  594.   bs->pbtOutBuf=NULL;
  595.   bs->nOutBufPos=0;
  596. #else
  597.   if (!strcmp(bs_filenam, "-")) {
  598.     /* Write to standard output. */
  599.     bs->pt = stdout;
  600.   } else {
  601.     if ((bs->pt = fopen(bs_filenam, "wb")) == NULL) {
  602.       printf("Could not create \"%s\".\n", bs_filenam);
  603.       exit(1);
  604.     }
  605.   }
  606. #endif
  607.    alloc_buffer(bs, size);
  608.    bs->buf_byte_idx = size-1;
  609.    bs->buf_bit_idx=8;
  610.    bs->totbit=0;
  611.    bs->mode = WRITE_MODE;
  612.    bs->eob = FALSE;
  613.    bs->eobs = FALSE;
  614. }
  615.  
  616.  
  617. /*close the device containing the bit stream after a write process*/
  618. void close_bit_stream_w(bs)
  619. Bit_stream_struc *bs;   /* bit stream structure */
  620. {
  621.     // Flush last bytes
  622.    empty_buffer(bs, bs->buf_byte_idx);
  623.  
  624. #ifndef _BLADEDLL
  625.    // Close the file
  626.    fclose(bs->pt);
  627. #endif // _BLADEDLL
  628.  
  629.    // Deallocate all buffers
  630.    desalloc_buffer(bs);
  631. }
  632.  
  633. /*open and initialize the buffer; */
  634. void alloc_buffer(bs, size)
  635. Bit_stream_struc *bs;   /* bit stream structure */
  636. int size;
  637. {
  638.    bs->buf = (unsigned char FAR *) mem_alloc(size*sizeof(unsigned
  639.               char), "buffer");
  640.    bs->buf_size = size;
  641. }
  642.  
  643. /*empty and close the buffer */
  644. void desalloc_buffer(bs)
  645. Bit_stream_struc *bs;   /* bit stream structure */
  646. {
  647.    free(bs->buf);
  648. }
  649.  
  650. int putmask[9]={0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  651. int clearmask[9]={0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x0};
  652. int mask[8]={0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
  653.  
  654. #if 0
  655. /*read 1 bit from the bit stream */
  656. unsigned int get1bit(bs)
  657. Bit_stream_struc *bs;   /* bit stream structure */
  658. {
  659.    unsigned int bit;
  660.    register int i;
  661.  
  662.    bs->totbit++;
  663.  
  664.    if (!bs->buf_bit_idx) {
  665.         bs->buf_bit_idx = 8;
  666.         bs->buf_byte_idx--;
  667.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  668.              if (bs->eob)
  669.                 bs->eobs = TRUE;
  670.              else {
  671.                 for (i=bs->buf_byte_idx; i>=0;i--)
  672.                   bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  673.                 refill_buffer(bs);
  674.                 bs->buf_byte_idx = bs->buf_size-1;
  675.              }
  676.         }
  677.    }
  678.    bit = bs->buf[bs->buf_byte_idx]&mask[bs->buf_bit_idx-1];
  679.    bit = bit >> (bs->buf_bit_idx-1);
  680.    bs->buf_bit_idx--;
  681.    return(bit);
  682. }
  683. #endif
  684.  
  685. /*write 1 bit from the bit stream */
  686. void put1bit(bs, bit)
  687. Bit_stream_struc *bs;   /* bit stream structure */
  688. int bit;                /* bit to write into the buffer */
  689. {
  690.    bs->totbit++;
  691.  
  692.    bs->buf[bs->buf_byte_idx] |= (bit&0x1) << (bs->buf_bit_idx-1);
  693.    bs->buf_bit_idx--;
  694.    if (!bs->buf_bit_idx) {
  695.        bs->buf_bit_idx = 8;
  696.        bs->buf_byte_idx--;
  697.        if (bs->buf_byte_idx < 0)
  698.           empty_buffer(bs, MINIMUM);
  699.        bs->buf[bs->buf_byte_idx] = 0;
  700.    }
  701. }
  702.  
  703. /*look ahead for the next N bits from the bit stream */
  704. unsigned long look_ahead(bs, N)
  705. Bit_stream_struc *bs;   /* bit stream structure */
  706. int N;                  /* number of bits to read from the bit stream */
  707. {
  708.  unsigned long val=0;
  709.  register int j = N;
  710.  register int k, tmp;
  711.  register int bit_idx = bs->buf_bit_idx;
  712.  register int byte_idx = bs->buf_byte_idx;
  713.  
  714.  if (N > MAX_LENGTH)
  715.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  716.  
  717.  while (j > 0) {
  718.     if (!bit_idx) {
  719.         bit_idx = 8;
  720.         byte_idx--;
  721.     }
  722.     k = Min (j, bit_idx);
  723.     tmp = bs->buf[byte_idx]&putmask[bit_idx];
  724.     tmp = tmp >> (bit_idx-k);
  725.     val |= tmp << (j-k);
  726.     bit_idx -= k;
  727.     j -= k;
  728.  }
  729.  return(val);
  730. }
  731.  
  732. /*write N bits into the bit stream */
  733. void putbits(bs, val, N)
  734. Bit_stream_struc *bs;   /* bit stream structure */
  735. unsigned int val;       /* val to write into the buffer */
  736. int N;                  /* number of bits of val */
  737. {
  738.  register int j = N;
  739.  register int k, tmp;
  740.  
  741.  if (N > MAX_LENGTH)
  742.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  743.  
  744.  bs->totbit += N;
  745.  while (j > 0) {
  746.    k = Min(j, bs->buf_bit_idx);
  747.    tmp = val >> (j-k);
  748.    bs->buf[bs->buf_byte_idx] |= (tmp&putmask[k]) << (bs->buf_bit_idx-k);
  749.    bs->buf_bit_idx -= k;
  750.    if (!bs->buf_bit_idx) {
  751.        bs->buf_bit_idx = 8;
  752.        bs->buf_byte_idx--;
  753.        if (bs->buf_byte_idx < 0)
  754.           empty_buffer(bs, MINIMUM);
  755.        bs->buf[bs->buf_byte_idx] = 0;
  756.    }
  757.    j -= k;
  758.  }
  759. }
  760.  
  761.  
  762. /*return the current bit stream length (in bits)*/
  763. unsigned long sstell(bs)
  764. Bit_stream_struc *bs;   /* bit stream structure */
  765. {
  766.   return(bs->totbit);
  767. }
  768.  
  769. /*return the status of the bit stream*/
  770. /* returns 1 if end of bit stream was reached */
  771. /* returns 0 if end of bit stream was not reached */
  772. int end_bs(bs)
  773. Bit_stream_struc *bs;   /* bit stream structure */
  774. {
  775.   return(bs->eobs);
  776. }
  777.  
  778. /*****************************************************************************
  779. *
  780. *  End of bit_stream.c package
  781. *
  782. *****************************************************************************/
  783.  
  784.