home *** CD-ROM | disk | FTP | other *** search
/ Magazyn Amiga 5 / MA_Cover_5.iso / ppc / wos_mpeg_encode / mpegaudio / common.c next >
Encoding:
C/C++ Source or Header  |  1998-05-04  |  44.9 KB  |  1,459 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. common.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 4.0                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 2/25/91  Doulas Wong,        start of version 1.0 records          *
  15.  *          Davis Pan                                                 *
  16.  * 5/10/91  W. Joseph Carter    Created this file for all common      *
  17.  *                              functions and global variables.       *
  18.  *                              Ported to Macintosh and Unix.         *
  19.  *                              Added Jean-Georges Fritsch's          *
  20.  *                              "bitstream.c" package.                *
  21.  *                              Added routines to handle AIFF PCM     *
  22.  *                              sound files.                          *
  23.  *                              Added "mem_alloc()" and "mem_free()"  *
  24.  *                              routines for memory allocation        *
  25.  *                              portability.                          *
  26.  *                              Added routines to convert between     *
  27.  *                              Apple SANE extended floating point    *
  28.  *                              format and IEEE double precision      *
  29.  *                              floating point format.  For AIFF.     *
  30.  * 02jul91 dpwe (Aware Inc)     Moved allocation table input here;    *
  31.  *                              Tables read from subdir TABLES_PATH.  *
  32.  *                              Added some debug printout fns (Write*)*
  33.  * 7/10/91 Earle Jennings       replacement of the one float by FLOAT *
  34.  *                              port to MsDos from MacIntosh version  *
  35.  * 8/ 5/91 Jean-Georges Fritsch fixed bug in open_bit_stream_r()      *
  36.  *10/ 1/91 S.I. Sudharsanan,    Ported to IBM AIX platform.           *
  37.  *         Don H. Lee,                                                *
  38.  *         Peter W. Farrett                                           *
  39.  *10/3/91  Don H. Lee           implemented CRC-16 error protection   *
  40.  *                              newly introduced functions are        *
  41.  *                              I_CRC_calc, II_CRC_calc and           *
  42.  *                              update_CRC. Additions and revisions   *
  43.  *                              are marked with dhl for clarity       *
  44.  *10/18/91 Jean-Georges Fritsch fixed bug in update_CRC(),            *
  45.  *                              II_CRC_calc() and I_CRC_calc()        *
  46.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  47.  *                              important fixes involved changing     *
  48.  *                              16-bit ints to long or unsigned in    *
  49.  *                              bit alloc routines for quant of 65535 *
  50.  *                              and passing proper function args.     *
  51.  *                              Removed "Other Joint Stereo" option   *
  52.  *                              and made bitrate be total channel     *
  53.  *                              bitrate, irrespective of the mode.    *
  54.  *                              Fixed many small bugs & reorganized.  *
  55.  * 3/20/92 Jean-Georges Fritsch  fixed bug in start-of-frame search   *
  56.  * 6/15/92 Juan Pineda          added refill_buffer(bs) "n"           *
  57.  *                              initialization                        *
  58.  * 7/08/92 Susanne Ritscher     MS-DOS, MSC6.0 port fixes             *
  59.  * 7/27/92 Mike Li               (re-)Port to MS-DOS                  *
  60.  * 8/19/92 Soren H. Nielsen     Fixed bug in I_CRC_calc and in        *
  61.  *                              II_CRC_calc.  Added function: new_ext *
  62.  *                              for better MS-DOS compatability       *
  63.  * 3/10/93 Kevin Peterson       changed aiff_read_headers to handle   *
  64.  *                              chunks in any order.  now returns     *
  65.  *                              position of sound data in file.       *
  66.  * 3/31/93 Jens Spille          changed IFF_* string compares to use  *
  67.  *                              strcmp()                              *
  68.  * 5/30/93 Masahiro Iwadare     ?? the previous modification does not *
  69.  *                                work. recovered to the original. ?? *
  70.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  71.  *         Daniel Lauzon, and                                         *
  72.  *         Bill Truerniet                                             *
  73.  **********************************************************************/
  74.  
  75. /***********************************************************************
  76. *
  77. *  Global Include Files
  78. *
  79. ***********************************************************************/
  80.  
  81. #include        "common.h"
  82.  
  83. #ifdef  MACINTOSH
  84.  
  85. #include        <SANE.h>
  86. #include        <pascal.h>
  87.  
  88. #endif
  89.  
  90. #include <ctype.h>
  91.  
  92. /***********************************************************************
  93. *
  94. *  Global Variable Definitions
  95. *
  96. ***********************************************************************/
  97.  
  98. char *mode_names[4] = { "stereo", "j-stereo", "dual-ch", "single-ch" };
  99. char *layer_names[3] = { "I", "II", "III" };
  100.  
  101. double  s_freq[4] = {44.1, 48, 32, 0};
  102.  
  103. int     bitrate[3][15] = {
  104.           {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
  105.           {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384},
  106.           {0,32,40,48,56,64,80,96,112,128,160,192,224,256,320}
  107.         };
  108.  
  109. double FAR multiple[64] = {
  110. 2.00000000000000, 1.58740105196820, 1.25992104989487,
  111. 1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
  112. 0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
  113. 0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
  114. 0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
  115. 0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
  116. 0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
  117. 0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
  118. 0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
  119. 0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
  120. 0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
  121. 0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
  122. 0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
  123. 0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
  124. 0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
  125. 0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
  126. 1E-20
  127. };
  128.  
  129. /***********************************************************************
  130. *
  131. *  Global Function Definitions
  132. *
  133. ***********************************************************************/
  134.  
  135. /* The system uses a variety of data files.  By opening them via this
  136.    function, we can accommodate various locations. */
  137.  
  138. FILE *OpenTableFile(char *name)
  139. {
  140. char fulname[80];
  141. char *envdir;
  142. FILE *f;
  143.  
  144.      fulname[0] = '\0';
  145.  
  146. #ifdef TABLES_PATH
  147.        strcpy(fulname, TABLES_PATH);   /* default relative path for tables */
  148. #endif /* TABLES_PATH */          /* (includes terminal path seperator */
  149.  
  150. #ifdef UNIX                       /* envir. variables for UNIX only */
  151.        {
  152.         char *getenv();
  153.  
  154.         envdir = getenv(MPEGTABENV);   /* check for environment */
  155.         if(envdir != NULL)
  156.             strcpy(fulname, envdir);
  157.         strcat(fulname, PATH_SEPARATOR);  /* add a "/" on the end */
  158.       }
  159. #endif /* UNIX */
  160.  
  161.     strcat(fulname, name);
  162.     if( (f=fopen(fulname,"r"))==NULL ) {
  163.         fprintf(stderr,"OpenTable: could not find %s\n", fulname);
  164.  
  165. #ifdef UNIX
  166.           if(envdir != NULL)
  167.             fprintf(stderr,"Check %s directory '%s'\n",MPEGTABENV, envdir);
  168.           else
  169.             fprintf(stderr,"Check local directory './%s' or setenv %s\n",
  170.                     TABLES_PATH, MPEGTABENV);
  171. #else /* not unix : no environment variables */
  172.  
  173. #ifdef TABLES_PATH
  174.             fprintf(stderr,"Check local directory './%s'\n",TABLES_PATH);
  175. #endif /* TABLES_PATH */
  176.  
  177. #endif /* UNIX */
  178.  
  179.     }
  180.     return f;
  181. }
  182.  
  183. /***********************************************************************
  184. /*
  185. /* Read one of the data files ("alloc_*") specifying the bit allocation/
  186. /* quatization parameters for each subband in layer II encoding
  187. /*
  188. /**********************************************************************/
  189.  
  190. int read_bit_alloc(int table, al_table *alloc)        /* read in table, return # subbands */
  191. {
  192.         unsigned int a, b, c, d, i, j;
  193.         FILE *fp;
  194.         char name[16], t[80];
  195.         int sblim;
  196.  
  197.         strcpy(name, "alloc_0");
  198.  
  199.         switch (table) {
  200.                 case 0 : name[6] = '0';         break;
  201.                 case 1 : name[6] = '1';         break;
  202.                 case 2 : name[6] = '2';         break;
  203.                 case 3 : name[6] = '3';         break;
  204.                 default : name[6] = '0';
  205.         }
  206.  
  207.         if (!(fp = OpenTableFile(name))) {
  208.                 printf("Please check bit allocation table %s\n", name);
  209.                 exit(1);
  210.         }
  211.  
  212.         printf("using bit allocation table %s\n", name);
  213.  
  214.         fgets(t, 80, fp);
  215.         sscanf(t, "%d\n", &sblim);
  216.         while (!feof(fp)) {
  217.                 fgets(t, 80, fp);
  218.                 sscanf(t, "%d %d %d %d %d %d\n", &i, &j, &a, &b, &c, &d);
  219.                         (*alloc)[i][j].steps = a;
  220.                         (*alloc)[i][j].bits  = b;
  221.                         (*alloc)[i][j].group = c;
  222.                         (*alloc)[i][j].quant = d;
  223.         }
  224.         fclose(fp);
  225.         return sblim;
  226. }
  227.  
  228. /***********************************************************************
  229. /*
  230. /* Using the decoded info the appropriate possible quantization per
  231. /* subband table is loaded
  232. /*
  233. /**********************************************************************/
  234.  
  235. int pick_table(frame_params *fr_ps)   /* choose table, load if necess, return # sb's */
  236. {
  237.         int table, lay, ws, bsp, br_per_ch, sfrq;
  238.         int sblim = fr_ps->sblimit;     /* return current value if no load */
  239.  
  240.         lay = fr_ps->header->lay - 1;
  241.         bsp = fr_ps->header->bitrate_index;
  242.         br_per_ch = bitrate[lay][bsp] / fr_ps->stereo;
  243.         ws = fr_ps->header->sampling_frequency;
  244.         sfrq = s_freq[ws];
  245.         /* decision rules refer to per-channel bitrates (kbits/sec/chan) */
  246.         if ((sfrq == 48 && br_per_ch >= 56) ||
  247.             (br_per_ch >= 56 && br_per_ch <= 80)) table = 0;
  248.         else if (sfrq != 48 && br_per_ch >= 96) table = 1;
  249.         else if (sfrq != 32 && br_per_ch <= 48) table = 2;
  250.         else table = 3;
  251.         if (fr_ps->tab_num != table) {
  252.            if (fr_ps->tab_num >= 0)
  253.               mem_free((void **)&(fr_ps->alloc));
  254.            fr_ps->alloc = (al_table FAR *) mem_alloc(sizeof(al_table),
  255.                                                          "alloc");
  256.            sblim = read_bit_alloc(fr_ps->tab_num = table, fr_ps->alloc);
  257.         }
  258.         return sblim;
  259. }
  260.  
  261. int js_bound(int lay, int m_ext)
  262. {
  263. static int jsb_table[3][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16},
  264.                                 { 0, 4, 8, 16} };  /* lay+m_e -> jsbound */
  265.  
  266.     if(lay<1 || lay >3 || m_ext<0 || m_ext>3) {
  267.         fprintf(stderr, "js_bound bad layer/modext (%d/%d)\n", lay, m_ext);
  268.         exit(1);
  269.     }
  270.     return(jsb_table[lay-1][m_ext]);
  271. }
  272.  
  273. void hdr_to_frps(frame_params *fr_ps) /* interpret data in hdr str to fields in fr_ps */
  274. {
  275. layer *hdr = fr_ps->header;     /* (or pass in as arg?) */
  276.  
  277.     fr_ps->actual_mode = hdr->mode;
  278.     fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
  279.     if (hdr->lay == 2)          fr_ps->sblimit = pick_table(fr_ps);
  280.     else                        fr_ps->sblimit = SBLIMIT;
  281.     if(hdr->mode == MPG_MD_JOINT_STEREO)
  282.         fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext);
  283.     else
  284.         fr_ps->jsbound = fr_ps->sblimit;
  285.     /* alloc, tab_num set in pick_table */
  286. }
  287.  
  288. void WriteHdr(frame_params *fr_ps, FILE *s)
  289. {
  290. layer *info = fr_ps->header;
  291.  
  292.    fprintf(s, "HDR:  s=FFF, id=%X, l=%X, ep=%X, br=%X, sf=%X, pd=%X, ",
  293.            info->version, info->lay, !info->error_protection,
  294.            info->bitrate_index, info->sampling_frequency, info->padding);
  295.    fprintf(s, "pr=%X, m=%X, js=%X, c=%X, o=%X, e=%X\n",
  296.            info->extension, info->mode, info->mode_ext,
  297.            info->copyright, info->original, info->emphasis);
  298.    fprintf(s, "layer=%s, tot bitrate=%d, sfrq=%.1f, mode=%s, ",
  299.            layer_names[info->lay-1], bitrate[info->lay-1][info->bitrate_index],
  300.            s_freq[info->sampling_frequency], mode_names[info->mode]);
  301.    fprintf(s, "sblim=%d, jsbd=%d, ch=%d\n",
  302.            fr_ps->sblimit, fr_ps->jsbound, fr_ps->stereo);
  303.    fflush(s);
  304. }
  305.  
  306. void WriteBitAlloc(unsigned int bit_alloc[2][SBLIMIT], frame_params *f_p, FILE *s)
  307. {
  308. int i,j;
  309. int st = f_p->stereo;
  310. int sbl = f_p->sblimit;
  311. int jsb = f_p->jsbound;
  312.  
  313.     fprintf(s, "BITA ");
  314.     for(i=0; i<sbl; ++i) {
  315.         if(i == jsb) fprintf(s,"-");
  316.         for(j=0; j<st; ++j)
  317.             fprintf(s, "%1x", bit_alloc[j][i]);
  318.     }
  319.     fprintf(s, "\n");   fflush(s);
  320. }
  321.  
  322. void WriteScale(unsigned int bit_alloc[2][SBLIMIT], unsigned int scfsi[2][SBLIMIT], unsigned int scalar[2][3][SBLIMIT], frame_params *fr_ps, FILE *s)
  323. {
  324. int stereo  = fr_ps->stereo;
  325. int sblimit = fr_ps->sblimit;
  326. int lay     = fr_ps->header->lay;
  327. int i,j,k;
  328.  
  329.         if(lay == 2) {
  330.             fprintf(s, "SFSI ");
  331.             for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  332.                 if (bit_alloc[k][i])  fprintf(s,"%d",scfsi[k][i]);
  333.             fprintf(s, "\nSCFs ");
  334.             for (k=0;k<stereo;k++) {
  335.                 for (i=0;i<sblimit;i++)
  336.                     if (bit_alloc[k][i])
  337.                         switch (scfsi[k][i]) {
  338.                           case 0: for (j=0;j<3;j++)
  339.                                   fprintf(s,"%2d%c",scalar[k][j][i],
  340.                                           (j==2)?';':'-');
  341.                                   break;
  342.                           case 1:
  343.                           case 3: fprintf(s,"%2d-",scalar[k][0][i]);
  344.                                   fprintf(s,"%2d;",scalar[k][2][i]);
  345.                                   break;
  346.                           case 2: fprintf(s,"%2d;",scalar[k][0][i]);
  347.                         }
  348.                 fprintf(s, "\n");
  349.             }
  350.         }
  351.         else{   /* lay == 1 */
  352.             fprintf(s, "SCFs ");
  353.             for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  354.                 if (bit_alloc[k][i])  fprintf(s,"%2d;",scalar[k][0][i]);
  355.             fprintf(s, "\n");
  356.         }
  357. }
  358.  
  359. void WriteSamples(int ch, unsigned int FAR sample[SBLIMIT], unsigned int bit_alloc[SBLIMIT], frame_params *fr_ps, FILE *s)
  360. {
  361. int i;
  362. int stereo = fr_ps->stereo;
  363. int sblimit = fr_ps->sblimit;
  364.  
  365.         fprintf(s, "SMPL ");
  366.         for (i=0;i<sblimit;i++)
  367.                 if ( bit_alloc[i] != 0)
  368.                     fprintf(s, "%d:", sample[i]);
  369.         if(ch==(stereo-1) )     fprintf(s, "\n");
  370.         else                    fprintf(s, "\t");
  371. }
  372.  
  373. int NumericQ(char *s) /* see if a string lookd like a numeric argument */
  374. {
  375. char    c;
  376.  
  377.     while( (c = *s++)!='\0' && isspace((int)c)) /* strip leading ws */
  378.         ;
  379.     if( c == '+' || c == '-' )
  380.         c = *s++;               /* perhaps skip leading + or - */
  381.     return isdigit((int)c);
  382. }
  383.  
  384. int BitrateIndex(int layr, int bRate)   /* convert bitrate in kbps to index */
  385. {
  386. int     index = 0;
  387. int     found = 0;
  388.  
  389.     while(!found && index<15)   {
  390.         if(bitrate[layr-1][index] == bRate)
  391.             found = 1;
  392.         else
  393.             ++index;
  394.     }
  395.     if(found)
  396.         return(index);
  397.     else {
  398.         fprintf(stderr, "BitrateIndex: %d (layer %d) is not a legal bitrate\n",
  399.                 bRate, layr);
  400.         return(-1);     /* Error! */
  401.     }
  402. }
  403.  
  404. int SmpFrqIndex(long sRate)  /* convert samp frq in Hz to index */
  405. {
  406.     if(sRate == 44100L)
  407.         return(0);
  408.     else if(sRate == 48000L)
  409.         return(1);
  410.     else if(sRate == 32000L)
  411.         return(2);
  412.     else {
  413.         fprintf(stderr, "SmpFrqIndex: %ld is not a legal sample rate\n", sRate);
  414.         return(-1);      /* Error! */
  415.     }
  416. }
  417.  
  418. /*******************************************************************************
  419. *
  420. *  Allocate number of bytes of memory equal to "block".
  421. *
  422. *******************************************************************************/
  423.  
  424. void  FAR *mem_alloc(unsigned long block, char *item)
  425. {
  426.  
  427.     void    *ptr;
  428.  
  429. #ifdef  MACINTOSH
  430.     ptr = NewPtr(block);
  431. #endif
  432.  
  433. #ifdef MSC60
  434.     /*ptr = (void FAR *) _fmalloc((unsigned int)block);*/ /* far memory, 92-07-08 sr */
  435.     ptr = (void FAR *) malloc((unsigned int)block); /* far memory, 93-08-24 ss */
  436. #endif
  437.  
  438. #if ! defined (MACINTOSH) && ! defined (MSC60)
  439.     ptr = (void FAR *) malloc(block);
  440. #endif
  441.  
  442.     if (ptr != NULL){
  443. #ifdef  MSC60
  444.         _fmemset(ptr, 0, (unsigned int)block); /* far memory, 92-07-08 sr */
  445. #else
  446.         memset(ptr, 0, block);
  447. #endif
  448.     }
  449.     else{
  450.         printf("Unable to allocate %s\n", item);
  451.         exit(0);
  452.     }
  453.     return(ptr);
  454. }
  455.  
  456.  
  457. /****************************************************************************
  458. *
  459. *  Free memory pointed to by "*ptr_addr".
  460. *
  461. *****************************************************************************/
  462.  
  463. void    mem_free(void **ptr_addr)
  464. {
  465.  
  466.     if (*ptr_addr != NULL){
  467. #ifdef  MACINTOSH
  468.         DisposPtr(*ptr_addr);
  469. #else
  470.         free(*ptr_addr);
  471. #endif
  472.         *ptr_addr = NULL;
  473.     }
  474.  
  475. }
  476.  
  477. /*******************************************************************************
  478. *
  479. *  Check block of memory all equal to a single byte, else return FALSE
  480. *
  481. *******************************************************************************/
  482.  
  483. int memcheck(char *array, int test, int num)
  484. {
  485.  int i=0;
  486.  
  487.    while (array[i] == test && i<num) i++;
  488.    if (i==num) return TRUE;
  489.    else return FALSE;
  490. }
  491.  
  492. /****************************************************************************
  493. *
  494. *  Routines to convert between the Apple SANE extended floating point format
  495. *  and the IEEE double precision floating point format.  These routines are
  496. *  called from within the Audio Interchange File Format (AIFF) routines.
  497. *
  498. *****************************************************************************/
  499.  
  500. /*
  501. *** Apple's 80-bit SANE extended has the following format:
  502.  
  503.  1       15      1            63
  504. +-+-------------+-+-----------------------------+
  505. |s|       e     |i|            f                |
  506. +-+-------------+-+-----------------------------+
  507.   msb        lsb   msb                       lsb
  508.  
  509. The value v of the number is determined by these fields as follows:
  510. If 0 <= e < 32767,              then v = (-1)^s * 2^(e-16383) * (i.f).
  511. If e == 32767 and f == 0,       then v = (-1)^s * (infinity), regardless of i.
  512. If e == 32767 and f != 0,       then v is a NaN, regardless of i.
  513.  
  514. *** IEEE Draft Standard 754 Double Precision has the following format:
  515.  
  516. MSB
  517. +-+---------+-----------------------------+
  518. |1| 11 Bits |           52 Bits           |
  519. +-+---------+-----------------------------+
  520.  ^     ^                ^
  521.  |     |                |
  522.  Sign  Exponent         Mantissa
  523. */
  524.  
  525. /*****************************************************************************
  526. *
  527. *  double_to_extended()
  528. *
  529. *  Purpose:     Convert from IEEE double precision format to SANE extended
  530. *               format.
  531. *
  532. *  Passed:      Pointer to the double precision number and a pointer to what
  533. *               will hold the Apple SANE extended format value.
  534. *
  535. *  Outputs:     The SANE extended format pointer will be filled with the
  536. *               converted value.
  537. *
  538. *  Returned:    Nothing.
  539. *
  540. *****************************************************************************/
  541.  
  542. void    double_to_extended(double *pd, char ps[10])
  543. {
  544.  
  545. #ifdef  MACINTOSH
  546.  
  547.         x96tox80(pd, (extended *) ps);
  548.  
  549. #else
  550.  
  551. register unsigned long  top2bits;
  552.  
  553. register unsigned short *ps2;
  554. register IEEE_DBL       *p_dbl;
  555. register SANE_EXT       *p_ext;
  556.  
  557.    p_dbl = (IEEE_DBL *) pd;
  558.    p_ext = (SANE_EXT *) ps;
  559.    top2bits = p_dbl->hi & 0xc0000000;
  560.    p_ext->l1 = ((p_dbl->hi >> 4) & 0x3ff0000) | top2bits;
  561.    p_ext->l1 |= ((p_dbl->hi >> 5) & 0x7fff) | 0x8000;
  562.    p_ext->l2 = (p_dbl->hi << 27) & 0xf8000000;
  563.    p_ext->l2 |= ((p_dbl->lo >> 5) & 0x07ffffff);
  564.    ps2 = (unsigned short *) & (p_dbl->lo);
  565.    ps2++;
  566.    p_ext->s1 = (*ps2 << 11) & 0xf800;
  567.  
  568. #endif
  569.  
  570. }
  571.  
  572. /*****************************************************************************
  573. *
  574. *  extended_to_double()
  575. *
  576. *  Purpose:     Convert from SANE extended format to IEEE double precision
  577. *               format.
  578. *
  579. *  Passed:      Pointer to the Apple SANE extended format value and a pointer
  580. *               to what will hold the the IEEE double precision number.
  581. *
  582. *  Outputs:     The IEEE double precision format pointer will be filled with
  583. *               the converted value.
  584. *
  585. *  Returned:    Nothing.
  586. *
  587. *****************************************************************************/
  588.  
  589. void    extended_to_double(char ps[10], double *pd)
  590. {
  591.  
  592. #ifdef  MACINTOSH
  593.  
  594.    x80tox96((extended *) ps, pd);
  595.  
  596. #else
  597.  
  598. register unsigned long  top2bits;
  599.  
  600. register IEEE_DBL       *p_dbl;
  601. register SANE_EXT       *p_ext;
  602.  
  603.    p_dbl = (IEEE_DBL *) pd;
  604.    p_ext = (SANE_EXT *) ps;
  605.    top2bits = p_ext->l1 & 0xc0000000;
  606.    p_dbl->hi = ((p_ext->l1 << 4) & 0x3ff00000) | top2bits;
  607.    p_dbl->hi |= (p_ext->l1 << 5) & 0xffff0;
  608.    p_dbl->hi |= (p_ext->l2 >> 27) & 0x1f;
  609.    p_dbl->lo = (p_ext->l2 << 5) & 0xffffffe0;
  610.    p_dbl->lo |= (unsigned long) ((p_ext->s1 >> 11) & 0x1f);
  611.  
  612. #endif
  613.  
  614. }
  615.  
  616.  
  617. /****  for debugging 
  618. showchar(str)
  619. char str[4];
  620. {
  621. int i;
  622. for (i=0;i<4;i++) printf("%c",str[i]);
  623. printf("\n");
  624. }
  625. ****/
  626.  
  627. /*****************************************************************************
  628. *
  629. *  Read Audio Interchange File Format (AIFF) headers.
  630. *
  631. *****************************************************************************/
  632.  
  633. int             aiff_read_headers(FILE *file_ptr, IFF_AIFF *aiff_ptr)
  634. {
  635.  
  636. register char   i;
  637. register long   seek_offset;
  638. register long   sound_position;
  639.  
  640. char            temp_sampleRate[10];
  641.  
  642. ChunkHeader     Header;
  643. Chunk           FormChunk;
  644. CommonChunk     CommChunk;
  645. SoundDataChunk  SndDChunk;
  646.  
  647.    if (fseek(file_ptr, 0, SEEK_SET) != 0)
  648.       return(-1);
  649.  
  650.    if (fread(&FormChunk, sizeof(Chunk), 1, file_ptr) != 1)
  651.       return(-1);
  652.  
  653. #ifdef IFF_LONG 
  654.    if (*(unsigned long *) FormChunk.ckID != IFF_ID_FORM ||
  655.        *(unsigned long *) FormChunk.formType != IFF_ID_AIFF)
  656.       return(-1);
  657. #else
  658.  
  659.    if (strncmp(FormChunk.ckID,IFF_ID_FORM,4) ||
  660.        strncmp(FormChunk.formType,IFF_ID_AIFF,4))
  661.       return(-1);
  662. #endif
  663.  
  664.    /*
  665.     * chunks need not be in any particular order
  666.     */
  667.  
  668.    while (fread(&Header, sizeof(ChunkHeader), 1, file_ptr) == 1) {
  669.  
  670. #ifdef IFF_LONG  
  671.       if (*(unsigned long *)Header.ckID == IFF_ID_COMM) {
  672.  
  673. #else
  674.       if (strncmp(Header.ckID,IFF_ID_COMM,4) == 0) {
  675. #endif
  676.  
  677.          /*
  678.           * read comm chunk
  679.           */
  680.          if (fread(&CommChunk.numChannels, sizeof(short), 1, file_ptr) != 1)
  681.             return(-1);
  682.  
  683.          if (fread(&CommChunk.numSampleFrames, sizeof(unsigned long), 1,
  684.                    file_ptr) != 1)
  685.             return(-1);
  686.  
  687.          if (fread(&CommChunk.sampleSize, sizeof(short), 1, file_ptr) != 1)
  688.             return(-1);
  689.  
  690.          if (fread(CommChunk.sampleRate, sizeof(char[10]), 1, file_ptr) != 1)
  691.             return(-1);
  692.  
  693.          for (i = 0; i < sizeof(char[10]); i++)
  694.             temp_sampleRate[i] = CommChunk.sampleRate[i];
  695.  
  696.          extended_to_double(temp_sampleRate, &aiff_ptr->sampleRate);
  697.  
  698.          aiff_ptr->numChannels = CommChunk.numChannels;
  699.          aiff_ptr->numSampleFrames = CommChunk.numSampleFrames;
  700.          aiff_ptr->sampleSize = CommChunk.sampleSize;
  701.  
  702. #ifdef IFF_LONG 
  703.       } else if (*(unsigned long *)Header.ckID == IFF_ID_SSND) { 
  704. #else
  705.       } else if (strncmp(Header.ckID,IFF_ID_SSND,4) == 0) {
  706. #endif
  707.          /*
  708.           * read ssnd chunk
  709.           */
  710.          if (fread(&SndDChunk.offset, sizeof(long), 1, file_ptr) != 1)
  711.             return(-1);
  712.  
  713.          if (fread(&SndDChunk.blockSize, sizeof(long), 1, file_ptr) != 1)
  714.             return(-1);
  715.  
  716.          aiff_ptr->blkAlgn.offset = SndDChunk.offset;
  717.          aiff_ptr->blkAlgn.blockSize = SndDChunk.blockSize;
  718.          aiff_ptr->sampleType = *(unsigned long *)Header.ckID;
  719.          
  720.          /*
  721.           * record position of sound data
  722.           */
  723.  
  724.          sound_position = ftell(file_ptr);
  725.  
  726.          /*
  727.           * skip over sound data to look at remaining chunks
  728.           */
  729.  
  730.          seek_offset = Header.ckSize - sizeof(SoundDataChunk) +
  731.             sizeof(ChunkHeader);
  732.  
  733.          if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  734.             return(-1);
  735.  
  736.       } else {
  737.  
  738.          /*
  739.           * skip unknown chunk
  740.           */
  741.  
  742.          seek_offset = Header.ckSize;
  743.  
  744.          if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  745.             return(-1);
  746.  
  747.       }
  748.  
  749.    }
  750.  
  751.    return(sound_position);
  752.  
  753. }
  754.  
  755. /*****************************************************************************
  756. *
  757. *  Seek past some Audio Interchange File Format (AIFF) headers to sound data.
  758. *
  759. *****************************************************************************/
  760.  
  761. int   aiff_seek_to_sound_data(FILE *file_ptr)
  762. {
  763.  
  764.    if (fseek(file_ptr, sizeof(Chunk) + sizeof(SoundDataChunk), SEEK_SET) != 0)
  765.       return(-1);
  766.  
  767.    return(0);
  768.  
  769. }
  770.  
  771. /*******************************************************************************
  772. *
  773. *  Write Audio Interchange File Format (AIFF) headers.
  774. *
  775. *******************************************************************************/
  776.  
  777. int             aiff_write_headers(FILE *file_ptr, IFF_AIFF *aiff_ptr)
  778. {
  779.  
  780. register char   i;
  781. register long   seek_offset;
  782.  
  783. char            temp_sampleRate[10];
  784.  
  785. Chunk           FormChunk;
  786. CommonChunk     CommChunk;
  787. SoundDataChunk  SndDChunk;
  788.  
  789. #ifdef IFF_LONG 
  790.    *(unsigned long *) FormChunk.ckID     = IFF_ID_FORM;
  791.    *(unsigned long *) FormChunk.formType = IFF_ID_AIFF;
  792.    *(unsigned long *) CommChunk.ckID     = IFF_ID_COMM;
  793. #else
  794.    strncpy(FormChunk.ckID,IFF_ID_FORM,4);
  795.    strncpy(FormChunk.formType,IFF_ID_AIFF,4);
  796.    strncpy(CommChunk.ckID,IFF_ID_COMM,4);
  797. #endif
  798.  
  799.    double_to_extended(&aiff_ptr->sampleRate, temp_sampleRate);
  800.  
  801.    for (i = 0; i < sizeof(char[10]); i++)
  802.       CommChunk.sampleRate[i] = temp_sampleRate[i];
  803.  
  804.    CommChunk.numChannels             = aiff_ptr->numChannels;
  805.    CommChunk.numSampleFrames         = aiff_ptr->numSampleFrames;
  806.    CommChunk.sampleSize              = aiff_ptr->sampleSize;
  807.    SndDChunk.offset                  = aiff_ptr->blkAlgn.offset;
  808.    SndDChunk.blockSize               = aiff_ptr->blkAlgn.blockSize;
  809.    *(unsigned long *) SndDChunk.ckID = aiff_ptr->sampleType;
  810.  
  811.    CommChunk.ckSize = sizeof(CommChunk.numChannels) +
  812.       sizeof(CommChunk.numSampleFrames) + sizeof(CommChunk.sampleSize) +
  813.       sizeof(CommChunk.sampleRate);
  814.  
  815.    SndDChunk.ckSize = sizeof(SoundDataChunk) - sizeof(ChunkHeader) +
  816.       (CommChunk.sampleSize + BITS_IN_A_BYTE - 1) / BITS_IN_A_BYTE *
  817.       CommChunk.numChannels * CommChunk.numSampleFrames;
  818.  
  819.    FormChunk.ckSize = sizeof(Chunk) + SndDChunk.ckSize + sizeof(ChunkHeader) +
  820.       CommChunk.ckSize;
  821.  
  822.    if (fseek(file_ptr, 0, SEEK_SET) != 0)
  823.       return(-1);
  824.  
  825.    if (fwrite(&FormChunk, sizeof(Chunk), 1, file_ptr) != 1)
  826.       return(-1);
  827.  
  828.    if (fwrite(&SndDChunk, sizeof(SoundDataChunk), 1, file_ptr) != 1)
  829.       return(-1);
  830.  
  831.    seek_offset = SndDChunk.ckSize - sizeof(SoundDataChunk) +
  832.       sizeof(ChunkHeader);
  833.  
  834.    if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  835.       return(-1);
  836.  
  837.    if (fwrite(CommChunk.ckID, sizeof(ID), 1, file_ptr) != 1)
  838.       return(-1);
  839.  
  840.    if (fwrite(&CommChunk.ckSize, sizeof(long), 1, file_ptr) != 1)
  841.       return(-1);
  842.  
  843.    if (fwrite(&CommChunk.numChannels, sizeof(short), 1, file_ptr) != 1)
  844.       return(-1);
  845.  
  846.    if (fwrite(&CommChunk.numSampleFrames, sizeof(unsigned long), 1,
  847.               file_ptr) != 1)
  848.       return(-1);
  849.  
  850.    if (fwrite(&CommChunk.sampleSize, sizeof(short), 1, file_ptr) != 1)
  851.       return(-1);
  852.  
  853.    if (fwrite(CommChunk.sampleRate, sizeof(char[10]), 1, file_ptr) != 1)
  854.       return(-1);
  855.  
  856.    return(0);
  857.  
  858. }
  859.  
  860. /*****************************************************************************
  861. *
  862. *  bit_stream.c package
  863. *  Author:  Jean-Georges Fritsch, C-Cube Microsystems
  864. *
  865. *****************************************************************************/
  866.  
  867. /********************************************************************
  868.   This package provides functions to write (exclusive or read)
  869.   information from (exclusive or to) the bit stream.
  870.  
  871.   If the bit stream is opened in read mode only the get functions are
  872.   available. If the bit stream is opened in write mode only the put
  873.   functions are available.
  874. ********************************************************************/
  875.  
  876. /*open_bit_stream_w(); open the device to write the bit stream into it    */
  877. /*open_bit_stream_r(); open the device to read the bit stream from it     */
  878. /*close_bit_stream();  close the device containing the bit stream         */
  879. /*alloc_buffer();      open and initialize the buffer;                    */
  880. /*desalloc_buffer();   empty and close the buffer                         */
  881. /*back_track_buffer();     goes back N bits in the buffer                 */
  882. /*unsigned int get1bit();  read 1 bit from the bit stream                 */
  883. /*unsigned long getbits(); read N bits from the bit stream                */
  884. /*unsigned long byte_ali_getbits();   read the next byte aligned N bits from*/
  885. /*                                    the bit stream                        */
  886. /*unsigned long look_ahead(); grep the next N bits in the bit stream without*/
  887. /*                            changing the buffer pointer                   */
  888. /*put1bit(); write 1 bit from the bit stream  */
  889. /*put1bit(); write 1 bit from the bit stream  */
  890. /*putbits(); write N bits from the bit stream */
  891. /*byte_ali_putbits(); write byte aligned the next N bits into the bit stream*/
  892. /*unsigned long sstell(); return the current bit stream length (in bits)    */
  893. /*int end_bs(); return 1 if the end of bit stream reached otherwise 0       */
  894. /*int seek_sync(); return 1 if a sync word was found in the bit stream      */
  895. /*                 otherwise returns 0                                      */
  896.  
  897. /* refill the buffer from the input device when the buffer becomes empty    */
  898. int refill_buffer(Bit_stream_struc *bs)
  899. {
  900.    register int i=bs->buf_size-2-bs->buf_byte_idx;
  901.    register unsigned long n=1;
  902.    register int index=0;
  903.    char val[2];
  904.  
  905.    while ((i>=0) && (!bs->eob)) {
  906.  
  907.       if (bs->format == BINARY)
  908.          n = fread(&bs->buf[i--], sizeof(unsigned char), 1, bs->pt);
  909.  
  910.       else {
  911.          while((index < 2) && n) {
  912.             n = fread(&val[index], sizeof(char), 1, bs->pt);
  913.             switch (val[index]) {
  914.                   case 0x30:
  915.                   case 0x31:
  916.                   case 0x32:
  917.                   case 0x33:
  918.                   case 0x34:
  919.                   case 0x35:
  920.                   case 0x36:
  921.                   case 0x37:
  922.                   case 0x38:
  923.                   case 0x39:
  924.                   case 0x41:
  925.                   case 0x42:
  926.                   case 0x43:
  927.                   case 0x44:
  928.                   case 0x45:
  929.                   case 0x46:
  930.                   index++;
  931.                   break;
  932.                   default: break;
  933.             }
  934.          }
  935.  
  936.          if (val[0] <= 0x39)   bs->buf[i] = (val[0] - 0x30) << 4;
  937.                  else  bs->buf[i] = (val[0] - 0x37) << 4;
  938.          if (val[1] <= 0x39)   bs->buf[i--] |= (val[1] - 0x30);
  939.                  else  bs->buf[i--] |= (val[1] - 0x37);
  940.          index = 0;
  941.       }
  942.  
  943.       if (!n) {
  944.          bs->eob= i+1;
  945.       }
  946.  
  947.     }
  948. }
  949.  
  950. static char *he = "0123456789ABCDEF";
  951.  
  952. /* empty the buffer to the output device when the buffer becomes full */
  953. void empty_buffer(Bit_stream_struc *bs, int minimum)
  954. {
  955.    register int i;
  956.  
  957. #if BS_FORMAT == BINARY
  958.    for (i=bs->buf_size-1;i>=minimum;i--)
  959.       fwrite(&bs->buf[i], sizeof(unsigned char), 1, bs->pt);
  960. #else
  961.    for (i=bs->buf_size-1;i>=minimum;i--) {
  962.        char val[2];
  963.        val[0] = he[((bs->buf[i] >> 4) & 0x0F)];
  964.        val[1] = he[(bs->buf[i] & 0x0F)];
  965.        fwrite(val, sizeof(char), 2, bs->pt);
  966.    }
  967. #endif
  968.  
  969.    for (i=minimum-1; i>=0; i--)
  970.        bs->buf[bs->buf_size - minimum + i] = bs->buf[i];
  971.  
  972.    bs->buf_byte_idx = bs->buf_size -1 - minimum;
  973.    bs->buf_bit_idx = 8;
  974. }
  975.  
  976. /* open the device to write the bit stream into it */
  977. void open_bit_stream_w(Bit_stream_struc *bs, char *bs_filenam, int size)
  978. {
  979.    if ((bs->pt = fopen(bs_filenam, "wb")) == NULL) {
  980.       printf("Could not create \"%s\".\n", bs_filenam);
  981.       exit(1);
  982.    }
  983.    alloc_buffer(bs, size);
  984.    bs->buf_byte_idx = size-1;
  985.    bs->buf_bit_idx=8;
  986.    bs->totbit=0;
  987.    bs->mode = WRITE_MODE;
  988.    bs->eob = FALSE;
  989.    bs->eobs = FALSE;
  990. }
  991.  
  992. /* open the device to read the bit stream from it */
  993. void open_bit_stream_r(Bit_stream_struc *bs, char *bs_filenam, int size)
  994. {
  995.    register unsigned long n;
  996.    register unsigned char flag = 1;
  997.    unsigned char val;
  998.  
  999.    if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1000.       printf("Could not find \"%s\".\n", bs_filenam);
  1001.       exit(1);
  1002.    }
  1003.  
  1004.    do {
  1005.      n = fread(&val, sizeof(unsigned char), 1, bs->pt);
  1006.      switch (val) {
  1007.       case 0x30:
  1008.       case 0x31:
  1009.       case 0x32:
  1010.       case 0x33:
  1011.       case 0x34:
  1012.       case 0x35:
  1013.       case 0x36:
  1014.       case 0x37:
  1015.       case 0x38:
  1016.       case 0x39:
  1017.       case 0x41:
  1018.       case 0x42:
  1019.       case 0x43:
  1020.       case 0x44:
  1021.       case 0x45:
  1022.       case 0x46:
  1023.       case 0xa:  /* \n */
  1024.       case 0xd:  /* cr */
  1025.       case 0x1a:  /* sub */
  1026.           break;
  1027.  
  1028.       default: /* detection of an binary character */
  1029.           flag--;
  1030.           break;
  1031.      }
  1032.  
  1033.    } while (flag & n);
  1034.  
  1035.    if (flag) {
  1036.       printf ("the bit stream file %s is an ASCII file\n", bs_filenam);
  1037.       bs->format = ASCII;
  1038.    }
  1039.    else {
  1040.       bs->format = BINARY;
  1041.       printf ("the bit stream file %s is a BINARY file\n", bs_filenam);
  1042.    }
  1043.  
  1044.    fclose(bs->pt);
  1045.  
  1046.    if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1047.       printf("Could not find \"%s\".\n", bs_filenam);
  1048.       exit(1);
  1049.    }
  1050.  
  1051.    alloc_buffer(bs, size);
  1052.    bs->buf_byte_idx=0;
  1053.    bs->buf_bit_idx=0;
  1054.    bs->totbit=0;
  1055.    bs->mode = READ_MODE;
  1056.    bs->eob = FALSE;
  1057.    bs->eobs = FALSE;
  1058. }
  1059.  
  1060. /*close the device containing the bit stream after a read process*/
  1061. void close_bit_stream_r(Bit_stream_struc *bs)
  1062. {
  1063.    fclose(bs->pt);
  1064.    desalloc_buffer(bs);
  1065. }
  1066.  
  1067. /*close the device containing the bit stream after a write process*/
  1068. void close_bit_stream_w(Bit_stream_struc *bs)
  1069. {
  1070.    empty_buffer(bs, bs->buf_byte_idx);
  1071.    fclose(bs->pt);
  1072.    desalloc_buffer(bs);
  1073. }
  1074.  
  1075. /*open and initialize the buffer; */
  1076. void alloc_buffer(Bit_stream_struc *bs, int size)
  1077. {
  1078.    bs->buf = (unsigned char FAR *) mem_alloc(size*sizeof(unsigned
  1079.               char), "buffer");
  1080.    bs->buf_size = size;
  1081. }
  1082.  
  1083. /*empty and close the buffer */
  1084. void desalloc_buffer(Bit_stream_struc *bs)
  1085. {
  1086.    free(bs->buf);
  1087. }
  1088.  
  1089. int putmask[9]={0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  1090. int clearmask[9]={0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x0};
  1091.  
  1092. void back_track_buffer(Bit_stream_struc *bs, int N) /* goes back N bits in the buffer */
  1093. {
  1094.    int tmp = N - (N/8)*8;
  1095.    register int i;
  1096.  
  1097.    bs->totbit -= N;
  1098.    for (i=bs->buf_byte_idx;i< bs->buf_byte_idx+N/8-1;i++) bs->buf[i] = 0;
  1099.    bs->buf_byte_idx += N/8;
  1100.    if ( (tmp + bs->buf_bit_idx) <= 8) {
  1101.       bs->buf_bit_idx += tmp;
  1102.    }
  1103.    else {
  1104.       bs->buf_byte_idx ++;
  1105.       bs->buf_bit_idx += (tmp - 8);
  1106.    }
  1107.    bs->buf[bs->buf_byte_idx] &= clearmask[bs->buf_bit_idx];
  1108. }
  1109.  
  1110. int mask[8]={0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
  1111.  
  1112. /*read 1 bit from the bit stream */
  1113. unsigned int get1bit(Bit_stream_struc *bs)
  1114. {
  1115.    unsigned int bit;
  1116.    register int i;
  1117.  
  1118.    bs->totbit++;
  1119.  
  1120.    if (!bs->buf_bit_idx) {
  1121.         bs->buf_bit_idx = 8;
  1122.         bs->buf_byte_idx--;
  1123.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1124.              if (bs->eob)
  1125.                 bs->eobs = TRUE;
  1126.              else {
  1127.                 for (i=bs->buf_byte_idx; i>=0;i--)
  1128.                   bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1129.                 refill_buffer(bs);
  1130.                 bs->buf_byte_idx = bs->buf_size-1;
  1131.              }
  1132.         }
  1133.    }
  1134.    bit = bs->buf[bs->buf_byte_idx]&mask[bs->buf_bit_idx-1];
  1135.    bit = bit >> (bs->buf_bit_idx-1);
  1136.    bs->buf_bit_idx--;
  1137.    return(bit);
  1138. }
  1139.  
  1140. /*write 1 bit from the bit stream */
  1141. void put1bit(Bit_stream_struc *bs, int bit)
  1142. {
  1143.    bs->totbit++;
  1144.  
  1145.    bs->buf[bs->buf_byte_idx] |= (bit&0x1) << (bs->buf_bit_idx-1);
  1146.    bs->buf_bit_idx--;
  1147.    if (!bs->buf_bit_idx) {
  1148.        bs->buf_bit_idx = 8;
  1149.        bs->buf_byte_idx--;
  1150.        if (bs->buf_byte_idx < 0)
  1151.           empty_buffer(bs, MINIMUM);
  1152.        bs->buf[bs->buf_byte_idx] = 0;
  1153.    }
  1154. }
  1155.  
  1156. /*look ahead for the next N bits from the bit stream */
  1157. unsigned long look_ahead(Bit_stream_struc *bs, int N)
  1158. {
  1159.  unsigned long val=0;
  1160.  register int j = N;
  1161.  register int k, tmp;
  1162.  register int bit_idx = bs->buf_bit_idx;
  1163.  register int byte_idx = bs->buf_byte_idx;
  1164.  
  1165.  if (N > MAX_LENGTH)
  1166.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1167.  
  1168.  while (j > 0) {
  1169.     if (!bit_idx) {
  1170.         bit_idx = 8;
  1171.         byte_idx--;
  1172.     }
  1173.     k = MIN (j, bit_idx);
  1174.     tmp = bs->buf[byte_idx]&putmask[bit_idx];
  1175.     tmp = tmp >> (bit_idx-k);
  1176.     val |= tmp << (j-k);
  1177.     bit_idx -= k;
  1178.     j -= k;
  1179.  }
  1180.  return(val);
  1181. }
  1182.  
  1183. /*read N bit from the bit stream */
  1184. unsigned long getbits(Bit_stream_struc *bs, int N)
  1185. {
  1186.  unsigned long val=0;
  1187.  register int i;
  1188.  register int j = N;
  1189.  register int k, tmp;
  1190.  
  1191.  if (N > MAX_LENGTH)
  1192.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1193.  
  1194.  bs->totbit += N;
  1195.  while (j > 0) {
  1196.    if (!bs->buf_bit_idx) {
  1197.         bs->buf_bit_idx = 8;
  1198.         bs->buf_byte_idx--;
  1199.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1200.              if (bs->eob)
  1201.                 bs->eobs = TRUE;
  1202.              else {
  1203.                 for (i=bs->buf_byte_idx; i>=0;i--)
  1204.                    bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1205.                 refill_buffer(bs);
  1206.                 bs->buf_byte_idx = bs->buf_size-1;
  1207.              }
  1208.         }
  1209.    }
  1210.    k = MIN (j, bs->buf_bit_idx);
  1211.    tmp = bs->buf[bs->buf_byte_idx]&putmask[bs->buf_bit_idx];
  1212.    tmp = tmp >> (bs->buf_bit_idx-k);
  1213.    val |= tmp << (j-k);
  1214.    bs->buf_bit_idx -= k;
  1215.    j -= k;
  1216.  }
  1217.  return(val);
  1218. }
  1219.  
  1220. /*write N bits into the bit stream */
  1221. void putbits(Bit_stream_struc *bs, unsigned int val, int N)
  1222. {
  1223.  register int j = N;
  1224.  register int k, tmp;
  1225.  
  1226.  if (N > MAX_LENGTH)
  1227.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1228.  
  1229.  bs->totbit += N;
  1230.  while (j > 0) {
  1231.    k = MIN(j, bs->buf_bit_idx);
  1232.    tmp = val >> (j-k);
  1233.    bs->buf[bs->buf_byte_idx] |= (tmp&putmask[k]) << (bs->buf_bit_idx-k);
  1234.    bs->buf_bit_idx -= k;
  1235.    if (!bs->buf_bit_idx) {
  1236.        bs->buf_bit_idx = 8;
  1237.        bs->buf_byte_idx--;
  1238.        if (bs->buf_byte_idx < 0)
  1239.           empty_buffer(bs, MINIMUM);
  1240.        bs->buf[bs->buf_byte_idx] = 0;
  1241.    }
  1242.    j -= k;
  1243.  }
  1244. }
  1245.  
  1246. /*write N bits byte aligned into the bit stream */
  1247. void byte_ali_putbits(Bit_stream_struc *bs, unsigned int val, int N)
  1248. {
  1249.  unsigned long aligning, sstell();
  1250.  
  1251.  if (N > MAX_LENGTH)
  1252.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1253.  aligning = sstell(bs)%8;
  1254.  if (aligning)
  1255.      putbits(bs, (unsigned int)0, (int)(8-aligning)); 
  1256.  
  1257.  putbits(bs, val, N);
  1258. }
  1259.  
  1260. /*read the next bute aligned N bits from the bit stream */
  1261. unsigned long byte_ali_getbits(Bit_stream_struc *bs, int N)
  1262. {
  1263.  unsigned long aligning, sstell();
  1264.  
  1265.  if (N > MAX_LENGTH)
  1266.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1267.  aligning = sstell(bs)%8;
  1268.  if (aligning)
  1269.     getbits(bs, (int)(8-aligning));
  1270.  
  1271.  return(getbits(bs, N));
  1272. }
  1273.  
  1274. /*return the current bit stream length (in bits)*/
  1275. unsigned long sstell(Bit_stream_struc *bs)
  1276. {
  1277.   return(bs->totbit);
  1278. }
  1279.  
  1280. /*return the status of the bit stream*/
  1281. /* returns 1 if end of bit stream was reached */
  1282. /* returns 0 if end of bit stream was not reached */
  1283. int end_bs(Bit_stream_struc *bs)
  1284. {
  1285.   return(bs->eobs);
  1286. }
  1287.  
  1288. /*this function seeks for a byte aligned sync word in the bit stream and
  1289.   places the bit stream pointer right after the sync.
  1290.   This function returns 1 if the sync was found otherwise it returns 0  */
  1291. int seek_sync(Bit_stream_struc *bs, long sync, int N)
  1292. {
  1293.  double pow();
  1294.  unsigned long aligning, stell();
  1295.  unsigned long val;
  1296.  long maxi = (int)pow(2.0, (FLOAT)N) - 1;
  1297.  
  1298.  aligning = sstell(bs)%ALIGNING;
  1299.  if (aligning)
  1300.     getbits(bs, (int)(ALIGNING-aligning));
  1301.  
  1302.   val = getbits(bs, N);
  1303.   while (((val&maxi) != sync) && (!end_bs(bs))) {
  1304.         val <<= ALIGNING;
  1305.         val |= getbits(bs, ALIGNING);
  1306.   }
  1307.  
  1308.  if (end_bs(bs)) return(0);
  1309.  else return(1);
  1310. }
  1311. /*****************************************************************************
  1312. *
  1313. *  End of bit_stream.c package
  1314. *
  1315. *****************************************************************************/
  1316.  
  1317. /*****************************************************************************
  1318. *
  1319. *  CRC error protection package
  1320. *
  1321. *****************************************************************************/
  1322.  
  1323. void I_CRC_calc(frame_params *fr_ps, unsigned int bit_alloc[2][SBLIMIT],unsigned int *crc)
  1324. {
  1325.         int i, k;
  1326.         layer *info = fr_ps->header;
  1327.         int stereo  = fr_ps->stereo;
  1328.         int jsbound = fr_ps->jsbound;
  1329.  
  1330.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  1331.         update_CRC(info->bitrate_index, 4, crc);
  1332.         update_CRC(info->sampling_frequency, 2, crc);
  1333.         update_CRC(info->padding, 1, crc);
  1334.         update_CRC(info->extension, 1, crc);
  1335.         update_CRC(info->mode, 2, crc);
  1336.         update_CRC(info->mode_ext, 2, crc);
  1337.         update_CRC(info->copyright, 1, crc);
  1338.         update_CRC(info->original, 1, crc);
  1339.         update_CRC(info->emphasis, 2, crc);
  1340.  
  1341.         for (i=0;i<SBLIMIT;i++)
  1342.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  1343.                         update_CRC(bit_alloc[k][i], 4, crc);
  1344. }
  1345.  
  1346. void II_CRC_calc(frame_params *fr_ps, unsigned int bit_alloc[2][SBLIMIT], unsigned int scfsi[2][SBLIMIT], unsigned int *crc)
  1347. {
  1348.         int i, k;
  1349.         layer *info = fr_ps->header;
  1350.         int stereo  = fr_ps->stereo;
  1351.         int sblimit = fr_ps->sblimit;
  1352.         int jsbound = fr_ps->jsbound;
  1353.         al_table *alloc = fr_ps->alloc;
  1354.  
  1355.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  1356.         update_CRC(info->bitrate_index, 4, crc);
  1357.         update_CRC(info->sampling_frequency, 2, crc);
  1358.         update_CRC(info->padding, 1, crc);
  1359.         update_CRC(info->extension, 1, crc);
  1360.         update_CRC(info->mode, 2, crc);
  1361.         update_CRC(info->mode_ext, 2, crc);
  1362.         update_CRC(info->copyright, 1, crc);
  1363.         update_CRC(info->original, 1, crc);
  1364.         update_CRC(info->emphasis, 2, crc);
  1365.  
  1366.         for (i=0;i<sblimit;i++)
  1367.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  1368.                         update_CRC(bit_alloc[k][i], (*alloc)[i][0].bits, crc);
  1369.  
  1370.         for (i=0;i<sblimit;i++)
  1371.                 for (k=0;k<stereo;k++)
  1372.                         if (bit_alloc[k][i])
  1373.                                 update_CRC(scfsi[k][i], 2, crc);
  1374. }
  1375.  
  1376. void update_CRC(unsigned int data, unsigned int length, unsigned int *crc)
  1377. {
  1378.         unsigned int  masking, carry;
  1379.  
  1380.         masking = 1 << length;
  1381.  
  1382.         while((masking >>= 1)){
  1383.                 carry = *crc & 0x8000;
  1384.                 *crc <<= 1;
  1385.                 if (!carry ^ !(data & masking))
  1386.                         *crc ^= CRC16_POLYNOMIAL;
  1387.         }
  1388.         *crc &= 0xffff;
  1389. }
  1390.  
  1391. /*****************************************************************************
  1392. *
  1393. *  End of CRC error protection package
  1394. *
  1395. *****************************************************************************/
  1396.  
  1397. #ifdef  MACINTOSH
  1398. /*****************************************************************************
  1399. *
  1400. *  Set Macintosh file attributes.
  1401. *
  1402. *****************************************************************************/
  1403.  
  1404. void    set_mac_file_attr(fileName, vRefNum, creator, fileType)
  1405. char    fileName[MAX_NAME_SIZE];
  1406. short   vRefNum;
  1407. OsType  creator;
  1408. OsType  fileType;
  1409. {
  1410.  
  1411. short   theFile;
  1412. char    pascal_fileName[MAX_NAME_SIZE];
  1413. FInfo   fndrInfo;
  1414.  
  1415.         CtoPstr(strcpy(pascal_fileName, fileName));
  1416.  
  1417.         FSOpen(pascal_fileName, vRefNum, &theFile);
  1418.         GetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1419.         fndrInfo.fdCreator = creator;
  1420.         fndrInfo.fdType = fileType;
  1421.         SetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1422.         FSClose(theFile);
  1423.  
  1424. }
  1425. #endif
  1426.  
  1427.  
  1428. #ifdef  MS_DOS
  1429. /* ------------------------------------------------------------------------
  1430. new_ext.
  1431. Puts a new extension name on a file name <filename>.
  1432. Removes the last extension name, if any.
  1433. 92-08-19 shn
  1434. ------------------------------------------------------------------------ */
  1435. char *new_ext(char *filename, char *extname)
  1436. {
  1437.   int found, dotpos;
  1438.   char newname[80];
  1439.  
  1440.   /* First, strip the extension */
  1441.   dotpos=strlen(filename); found=0;
  1442.   do
  1443.   {
  1444.     switch (filename[dotpos])
  1445.     {
  1446.       case '.' : found=1; break;
  1447.       case '\\':                  /* used by MS-DOS */
  1448.       case '/' :                  /* used by UNIX */
  1449.       case ':' : found=-1; break; /* used by MS-DOS in drive designation */
  1450.       default  : dotpos--; if (dotpos<0) found=-1; break;
  1451.     }
  1452.   } while (found==0);
  1453.   if (found==-1) strcpy(newname,filename);
  1454.   if (found== 1) strncpy(newname,filename,dotpos); newname[dotpos]='\0';
  1455.   strcat(newname,extname);
  1456.   return(newname);
  1457. }
  1458. #endif
  1459.