home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 24 / AACD 24.iso / AACD / Sound / LAME / WarpOS / src / frontend / get_audio.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-07-01  |  48.3 KB  |  1,628 lines

  1. /*
  2.  *    Get Audio routines source file
  3.  *
  4.  *    Copyright (c) 1999 Albert L Faber
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Library General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  14.  * Library General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Library General Public
  17.  * License along with this library; if not, write to the
  18.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19.  * Boston, MA 02111-1307, USA.
  20.  */
  21.  
  22. /* $Id: get_audio.c,v 1.76 2001/07/01 20:04:32 markt Exp $ */
  23.  
  24.  
  25. #ifdef HAVE_CONFIG_H
  26. # include <config.h>
  27. #endif
  28.  
  29. #include <assert.h>
  30.  
  31. #ifdef HAVE_LIMITS_H
  32. # include <limits.h>
  33. #endif
  34.  
  35. #include <stdio.h>
  36.  
  37. #ifdef STDC_HEADERS
  38. # include <stdlib.h>
  39. # include <string.h>
  40. #else
  41. # ifndef HAVE_STRCHR
  42. #  define strchr index
  43. #  define strrchr rindex
  44. # endif
  45. char   *strchr(), *strrchr();
  46. # ifndef HAVE_MEMCPY
  47. #  define memcpy(d, s, n) bcopy ((s), (d), (n))
  48. #  define memmove(d, s, n) bcopy ((s), (d), (n))
  49. # endif
  50. #endif
  51.  
  52. #define         MAX_U_32_NUM            0xFFFFFFFF
  53.  
  54.  
  55. #include <math.h>
  56. #include <sys/stat.h>
  57.  
  58. #include "lame.h"
  59. #include "main.h"
  60. #include "get_audio.h"
  61. #include "portableio.h"
  62. #include "timestatus.h"
  63. #include "lametime.h"
  64.  
  65. #ifdef WITH_DMALLOC
  66. #include <dmalloc.h>
  67. #endif
  68.  
  69.  
  70. /* global data for get_audio.c. */
  71. int     count_samples_carefully;
  72. int     pcmbitwidth;
  73. unsigned int num_samples_read;
  74. FILE   *musicin;
  75.  
  76.  
  77. #ifdef AMIGA_MPEGA
  78. int     lame_decode_initfile(const char *fullname,
  79.                              mp3data_struct * const mp3data);
  80. #else
  81. int     lame_decode_initfile(FILE * const fd, mp3data_struct * const mp3data);
  82. #endif
  83.  
  84. /* read mp3 file until mpglib returns one frame of PCM data */
  85. int     lame_decode_fromfile(FILE * fd, short int pcm_l[], short int pcm_r[],
  86.                              mp3data_struct * mp3data);
  87.  
  88. /* and for Vorbis: */
  89. int     lame_decode_ogg_initfile( lame_global_flags*  gfp,
  90.                                   FILE*               fd,
  91.                                   mp3data_struct*     mp3data );
  92. int     lame_decode_ogg_fromfile( lame_global_flags*  gfc,
  93.                                   FILE*               fd,
  94.                                   short int           pcm_l[],
  95.                                   short int           pcm_r[],
  96.                                   mp3data_struct*     mp3data );
  97.  
  98.  
  99. static int read_samples_pcm(FILE * musicin, int sample_buffer[2304],
  100.                             int frame_size, int samples_to_read);
  101. static int read_samples_mp3(lame_global_flags * gfp, FILE * musicin,
  102.                             short int mpg123pcm[2][1152], int num_chan);
  103. static int read_samples_ogg(lame_global_flags * gfp, FILE * musicin,
  104.                             short int mpg123pcm[2][1152], int num_chan);
  105. void    CloseSndFile(sound_file_format input, FILE * musicin);
  106. FILE   *OpenSndFile(lame_global_flags * gfp, char *);
  107.  
  108.  
  109. /* Replacement for forward fseek(,,SEEK_CUR), because fseek() fails on pipes */
  110.  
  111.  
  112. static int
  113. fskip(FILE * fp, long offset, int whence)
  114. {
  115. #ifndef PIPE_BUF
  116.     char    buffer[4096];
  117. #else
  118.     char    buffer[PIPE_BUF];
  119. #endif
  120.     int     read;
  121.  
  122.     if (0 == fseek(fp, offset, whence))
  123.         return 0;
  124.  
  125.     if (whence != SEEK_CUR || offset < 0) {
  126.         fprintf(stderr,
  127.                 "fskip problem: Mostly the return status of functions is not evaluate so it is more secure to polute <stderr>.\n");
  128.         return -1;
  129.     }
  130.  
  131.     while (offset > 0) {
  132.         read = offset > sizeof(buffer) ? sizeof(buffer) : offset;
  133.         if ((read = fread(buffer, 1, read, fp)) <= 0)
  134.             return -1;
  135.         offset -= read;
  136.     }
  137.  
  138.     return 0;
  139. }
  140.  
  141.  
  142. FILE   *
  143. init_outfile(char *outPath, int decode)
  144. {
  145.     FILE   *outf;
  146. #ifdef __riscos__
  147.     char   *p;
  148. #endif
  149.  
  150.     /* open the output file */
  151.     if (0 == strcmp(outPath, "-")) {
  152.         lame_set_stream_binary_mode(outf = stdout);
  153.     }
  154.     else {
  155.         if ((outf = fopen(outPath, "wb+")) == NULL)
  156.             return NULL;
  157. #ifdef __riscos__
  158.         /* Assign correct file type */
  159.         for (p = outPath; *p; p++) /* ugly, ugly to modify a string */
  160.             switch (*p) {
  161.             case '.':
  162.                 *p = '/';
  163.                 break;
  164.             case '/':
  165.                 *p = '.';
  166.                 break;
  167.             }
  168.         SetFiletype(outPath, decode ? 0xFB1 /*WAV*/ : 0x1AD /*AMPEG*/);
  169. #endif
  170.     }
  171.     return outf;
  172. }
  173.  
  174.  
  175.  
  176.  
  177.  
  178.  
  179. void
  180. init_infile(lame_global_flags * gfp, char *inPath)
  181. {
  182.     /* open the input file */
  183.     count_samples_carefully = 0;
  184.     num_samples_read=0;
  185.     pcmbitwidth = 16;
  186.     musicin = OpenSndFile(gfp, inPath);
  187. }
  188.  
  189. void
  190. close_infile(void)
  191. {
  192.     CloseSndFile(input_format, musicin);
  193. }
  194.  
  195.  
  196. void
  197. SwapBytesInWords(short *ptr, int short_words)
  198. {                       /* Some speedy code */
  199.     unsigned long val;
  200.     unsigned long *p = (unsigned long *) ptr;
  201.  
  202. #ifndef lint
  203. # if defined(CHAR_BIT)
  204. #  if CHAR_BIT != 8
  205. #   error CHAR_BIT != 8
  206. #  endif
  207. # else
  208. #  error can not determine number of bits in a char
  209. # endif
  210. #endif /* lint */
  211.  
  212.     assert(sizeof(short) == 2);
  213.  
  214.  
  215. #if defined(SIZEOF_UNSIGNED_LONG) && SIZEOF_UNSIGNED_LONG == 4
  216.     for (; short_words >= 2; short_words -= 2, p++) {
  217.         val = *p;
  218.         *p = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0x00FF00FF);
  219.     }
  220.     ptr = (short *) p;
  221.     for (; short_words >= 1; short_words -= 1, ptr++) {
  222.         val = *ptr;
  223.         *ptr = ((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF);
  224.     }
  225. #elif defined(SIZEOF_UNSIGNED_LONG) && SIZEOF_UNSIGNED_LONG == 8
  226.     for (; short_words >= 4; short_words -= 4, p++) {
  227.         val = *p;
  228.         *p =
  229.             ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) &
  230.                                                  0x00FF00FF00FF00FF);
  231.     }
  232.     ptr = (short *) p;
  233.     for (; short_words >= 1; short_words -= 1, ptr++) {
  234.         val = *ptr;
  235.         *ptr = ((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF);
  236.     }
  237. #else
  238. # ifdef SIZEOF_UNSIGNED_LONG
  239. #  warning Using unoptimized SwapBytesInWords().
  240. # endif
  241.     for (; short_words >= 1; short_words -= 1, ptr++) {
  242.         val = *ptr;
  243.         *ptr = ((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF);
  244.     }
  245. #endif
  246.  
  247.     assert(short_words == 0);
  248. }
  249.  
  250.  
  251.  
  252. static int
  253. get_audio_common( lame_global_flags * const gfp,
  254.           int buffer[2][1152], short buffer16[2][1152] );
  255.  
  256. /************************************************************************
  257. *
  258. * get_audio()
  259. *
  260. * PURPOSE:  reads a frame of audio data from a file to the buffer,
  261. *   aligns the data for future processing, and separates the
  262. *   left and right channels
  263. *
  264. ************************************************************************/
  265. int
  266. get_audio( lame_global_flags * const gfp, int buffer[2][1152] )
  267. {
  268.     return( get_audio_common( gfp, buffer, NULL ) );
  269. }
  270.  
  271. /*
  272.   get_audio16 - behave as the original get_audio function, with a limited
  273.                 16 bit per sample output
  274. */
  275. int
  276. get_audio16( lame_global_flags * const gfp, short buffer[2][1152] )
  277. {
  278.     return( get_audio_common( gfp, NULL, buffer ) );
  279. }
  280.  
  281. /************************************************************************
  282.   get_audio_common - central functionality of get_audio*
  283.     in: gfp
  284.         buffer    output to the int buffer or 16-bit buffer
  285.    out: buffer    int output    (if buffer != NULL)
  286.         buffer16  16-bit output (if buffer == NULL) 
  287. returns: samples read
  288. note: either buffer or buffer16 must be allocated upon call
  289. */
  290. static int
  291. get_audio_common( lame_global_flags * const gfp,
  292.           int buffer[2][1152], short buffer16[2][1152] )
  293. {
  294.     int     num_channels = lame_get_num_channels( gfp );
  295.     int     insamp[2 * 1152];
  296.     short   buf_tmp16[2][1152];
  297.     int     samples_read;
  298.     int     framesize;
  299.     int     samples_to_read;
  300.     unsigned int remaining, tmp_num_samples;
  301.     int     i;
  302.     int     *p;
  303.  
  304.     /* 
  305.      * NOTE: LAME can now handle arbritray size input data packets,
  306.      * so there is no reason to read the input data in chuncks of
  307.      * size "framesize".  EXCEPT:  the LAME graphical frame analyzer 
  308.      * will get out of sync if we read more than framesize worth of data.
  309.      */
  310.  
  311.     samples_to_read = framesize = lame_get_framesize(gfp);
  312.     assert(framesize <= 1152);
  313.  
  314.     /* get num_samples */
  315.     tmp_num_samples = lame_get_num_samples( gfp );
  316.  
  317.     /* if this flag has been set, then we are carefull to read
  318.      * exactly num_samples and no more.  This is useful for .wav and .aiff
  319.      * files which have id3 or other tags at the end.  Note that if you
  320.      * are using LIBSNDFILE, this is not necessary 
  321.      */
  322.     if (count_samples_carefully) {
  323.         remaining = tmp_num_samples - Min(tmp_num_samples, num_samples_read);
  324.         if (remaining < framesize)
  325.             samples_to_read = remaining;
  326.     }
  327.  
  328.     switch (input_format) {
  329.     case sf_mp1:
  330.     case sf_mp2:
  331.     case sf_mp3:
  332.     if( buffer != NULL )
  333.         samples_read = read_samples_mp3( gfp, musicin,
  334.                          buf_tmp16, num_channels );
  335.     else
  336.         samples_read = read_samples_mp3( gfp, musicin,
  337.                          buffer16, num_channels );
  338.         break;
  339.     case sf_ogg:
  340.     if( buffer != NULL )
  341.         samples_read = read_samples_ogg( gfp, musicin,
  342.                          buf_tmp16, num_channels );
  343.     else
  344.         samples_read = read_samples_ogg( gfp, musicin,
  345.                          buffer16, num_channels );
  346.         break;
  347.     default:
  348.         samples_read =
  349.             read_samples_pcm(musicin, insamp, num_channels * framesize,
  350.                              num_channels * samples_to_read);
  351.     p = insamp + samples_read;
  352.         samples_read /= num_channels;
  353.     if( buffer != NULL ) {    /* output to int buffer */
  354.         if( num_channels == 2 ) {
  355.         for( i = samples_read; --i >= 0; ) {
  356.             buffer[1][i] = *--p;
  357.              buffer[0][i] = *--p;
  358.         }
  359.         } else if( num_channels == 1 ) {
  360.         memset( buffer[1], 0, samples_read * sizeof(int) );
  361.         for( i = samples_read; --i >= 0; ) {
  362.              buffer[0][i] = *--p;
  363.         }
  364.         } else
  365.         assert(0);
  366.     } else {        /* convert from int; output to 16-bit buffer */
  367.         if( num_channels == 2 ) {
  368.         for( i = samples_read; --i >= 0; ) {
  369.             buffer16[1][i] = *--p >> (8 * sizeof(int) - 16);
  370.              buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
  371.         }
  372.         } else if( num_channels == 1 ) {
  373.         memset( buffer16[1], 0, samples_read * sizeof(short) );
  374.         for( i = samples_read; --i >= 0; ) {
  375.              buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
  376.         }
  377.         } else
  378.         assert(0);
  379.     }
  380.     }
  381.  
  382.     if( input_format == sf_mp1 || input_format == sf_mp2 || 
  383.         input_format == sf_mp3 || input_format == sf_ogg ) {
  384.                 /* LAME mp3 and ogg input routines currently */
  385.                 /*  only accept up to 16 bit samples */
  386.     if( buffer != NULL ) {
  387.         for( i = samples_read; --i >= 0; )
  388.         buffer[0][i] = buf_tmp16[0][i] << (8 * sizeof(int) - 16);
  389.         if( num_channels == 2 ) {
  390.         for( i = samples_read; --i >= 0; )
  391.             buffer[1][i] = buf_tmp16[1][i] << (8 * sizeof(int) - 16);
  392.         } else if( num_channels == 1 ) {
  393.         memset( buffer[1], 0, samples_read * sizeof(int) );
  394.         } else
  395.         assert(0);
  396.     }
  397.     }
  398.  
  399.  
  400.     /* if num_samples = MAX_U_32_NUM, then it is considered infinitely long.
  401.        Don't count the samples */
  402.     if ( tmp_num_samples != MAX_U_32_NUM )
  403.         num_samples_read += samples_read;
  404.  
  405.     return samples_read;
  406. }
  407.  
  408.  
  409.  
  410. int
  411. read_samples_ogg(lame_global_flags * const gfp,
  412.                  FILE * const musicin,
  413.                  short int oggpcm[2][1152], const int stereo)
  414. {
  415.     int     out = 0;
  416.  
  417. #ifdef HAVE_VORBIS
  418.     static const char type_name[] = "Ogg Vorbis file";
  419.  
  420.     out =
  421.         lame_decode_ogg_fromfile( gfp,
  422.                                   musicin,
  423.                                   oggpcm[0],
  424.                                   oggpcm[1],
  425.                                   &mp3input_data );
  426.     /*
  427.      * out < 0:  error, probably EOF
  428.      * out = 0:  not possible with lame_decode_fromfile() ???
  429.      * out > 0:  number of output samples
  430.      */
  431.  
  432.     if (out < 0) {
  433.         memset(oggpcm, 0, sizeof(**oggpcm) * 2 * 1152);
  434.         return 0;
  435.     }
  436.  
  437.     if (lame_get_num_channels( gfp ) != mp3input_data.stereo)
  438.         fprintf(stderr,
  439.                 "Error: number of channels has changed in %s - not supported\n",
  440.                 type_name);
  441.     if ( lame_get_in_samplerate( gfp ) != mp3input_data.samplerate )
  442.         fprintf(stderr,
  443.                 "Error: sample frequency has changed in %s - not supported\n",
  444.                 type_name);
  445.  
  446. #else
  447.     out = -1;           /* wanna read ogg without vorbis support? */
  448. #endif
  449.  
  450.     return out;
  451. }
  452.  
  453.  
  454. int
  455. read_samples_mp3(lame_global_flags * const gfp,
  456.                  FILE * const musicin, short int mpg123pcm[2][1152], int stereo)
  457. {
  458.     int     out;
  459. #if defined(AMIGA_MPEGA)  ||  defined(HAVE_MPGLIB)
  460.     static const char type_name[] = "MP3 file";
  461.  
  462.     out =
  463.         lame_decode_fromfile(musicin, mpg123pcm[0], mpg123pcm[1],
  464.                              &mp3input_data);
  465.     /*
  466.      * out < 0:  error, probably EOF
  467.      * out = 0:  not possible with lame_decode_fromfile() ???
  468.      * out > 0:  number of output samples
  469.      */
  470.     if (out < 0) {
  471.         memset(mpg123pcm, 0, sizeof(**mpg123pcm) * 2 * 1152);
  472.         return 0;
  473.     }
  474.  
  475.     if ( lame_get_num_channels( gfp ) != mp3input_data.stereo )
  476.         fprintf(stderr,
  477.                 "Error: number of channels has changed in %s - not supported\n",
  478.                 type_name);
  479.     if ( lame_get_in_samplerate( gfp ) != mp3input_data.samplerate )
  480.         fprintf(stderr,
  481.                 "Error: sample frequency has changed in %s - not supported\n",
  482.                 type_name);
  483.  
  484. #else
  485.     out = -1;
  486. #endif
  487.     return out;
  488. }
  489.  
  490.  
  491. int
  492. WriteWaveHeader(FILE * const fp, const int pcmbytes,
  493.                 const int freq, const int channels, const int bits)
  494. {
  495.     int     bytes = (bits + 7) / 8;
  496.  
  497.     /* quick and dirty, but documented */
  498.     fwrite("RIFF", 1, 4, fp); // label
  499.     Write32BitsLowHigh(fp, pcmbytes + 44 - 8); // length in bytes without header
  500.     fwrite("WAVEfmt ", 2, 4, fp); // 2 labels
  501.     Write32BitsLowHigh(fp, 2 + 2 + 4 + 4 + 2 + 2); // length of PCM format declaration area
  502.     Write16BitsLowHigh(fp, 1); // is PCM?
  503.     Write16BitsLowHigh(fp, channels); // number of channels
  504.     Write32BitsLowHigh(fp, freq); // sample frequency in [Hz]
  505.     Write32BitsLowHigh(fp, freq * channels * bytes); // bytes per second
  506.     Write16BitsLowHigh(fp, channels * bytes); // bytes per sample time
  507.     Write16BitsLowHigh(fp, bits); // bits per sample
  508.     fwrite("data", 1, 4, fp); // label
  509.     Write32BitsLowHigh(fp, pcmbytes); // length in bytes of raw PCM data
  510.  
  511.     return ferror(fp) ? -1 : 0;
  512. }
  513.  
  514.  
  515.  
  516.  
  517. #if defined(LIBSNDFILE)
  518.  
  519. #if 0                   /* currently disabled */
  520. # include "sndfile.h"   // prototype for sf_get_lib_version()
  521. void
  522. print_sndlib_version(FILE * fp)
  523. {
  524.     char    tmp[80];
  525.     sf_get_lib_version(tmp, sizeof(tmp));
  526.     fprintf(fp,
  527.             "Input handled by %s  (http://www.zip.com.au/~erikd/libsndfile/)\n",
  528.             tmp);
  529. }
  530. #endif
  531.  
  532. /*
  533. ** Copyright (C) 1999 Albert Faber
  534. **
  535.  * This library is free software; you can redistribute it and/or
  536.  * modify it under the terms of the GNU Library General Public
  537.  * License as published by the Free Software Foundation; either
  538.  * version 2 of the License, or (at your option) any later version.
  539.  *
  540.  * This library is distributed in the hope that it will be useful,
  541.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  542.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  543.  * Library General Public License for more details.
  544.  *
  545.  * You should have received a copy of the GNU Library General Public
  546.  * License along with this library; if not, write to the
  547.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  548.  * Boston, MA 02111-1307, USA.
  549.  */
  550.  
  551.  
  552.  
  553.  
  554.  
  555.  
  556. void
  557. CloseSndFile(sound_file_format input, FILE * musicin)
  558. {
  559.     SNDFILE *gs_pSndFileIn = (SNDFILE *) musicin;
  560.     if (input == sf_mp1 || input == sf_mp2 || input == sf_mp3) {
  561. #ifndef AMIGA_MPEGA
  562.         if (fclose(musicin) != 0) {
  563.             fprintf(stderr, "Could not close audio input file\n");
  564.             exit(2);
  565.         }
  566. #endif
  567.     }
  568.     else {
  569.         if (gs_pSndFileIn) {
  570.             if (sf_close(gs_pSndFileIn) != 0) {
  571.                 fprintf(stderr, "Could not close sound file \n");
  572.                 exit(2);
  573.             }
  574.         }
  575.     }
  576. }
  577.  
  578.  
  579.  
  580. FILE   *
  581. OpenSndFile(lame_global_flags * gfp, char *inPath)
  582. {
  583.     char   *lpszFileName = inPath;
  584.     FILE   *musicin;
  585.     SNDFILE *gs_pSndFileIn;
  586.     SF_INFO gs_wfInfo;
  587.  
  588.     if (input_format == sf_mp1 ||
  589.         input_format == sf_mp2 || input_format == sf_mp3) {
  590. #ifdef AMIGA_MPEGA
  591.         if (-1 == lame_decode_initfile(lpszFileName, &mp3input_data)) {
  592.             fprintf(stderr, "Error reading headers in mp3 input file %s.\n",
  593.                     lpszFileName);
  594.             exit(1);
  595.         }
  596. #endif
  597. #ifdef HAVE_MPGLIB
  598.         if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  599.             fprintf(stderr, "Could not find \"%s\".\n", lpszFileName);
  600.             exit(1);
  601.         }
  602.         if (-1 == lame_decode_initfile(musicin, &mp3input_data)) {
  603.             fprintf(stderr, "Error reading headers in mp3 input file %s.\n",
  604.                     lpszFileName);
  605.             exit(1);
  606.         }
  607. #endif
  608.  
  609.         if( -1 == lame_set_num_channels( gfp, mp3input_data.stereo ) ) {
  610.             fprintf( stderr,
  611.                      "Unsupported number of channels: %ud\n",
  612.                      mp3input_data.stereo );
  613.             exit( 1 );
  614.         }
  615.         (void) lame_set_in_samplerate( gfp, mp3input_data.samplerate );
  616.         (void) lame_set_num_samples( gfp, mp3input_data.nsamp );
  617.     }
  618.     else if (input_format == sf_ogg) {
  619. #ifdef HAVE_VORBIS
  620.         if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  621.             fprintf(stderr, "Could not find \"%s\".\n", lpszFileName);
  622.             exit(1);
  623.         }
  624.         if ( -1 == lame_decode_ogg_initfile( gfp,
  625.                                              musicin,
  626.                                              &mp3input_data ) ) {
  627.             fprintf(stderr, "Error reading headers in mp3 input file %s.\n",
  628.                     lpszFileName);
  629.             exit(1);
  630.         }
  631. #else
  632.         fprintf(stderr, "LAME not compiled with libvorbis support.\n");
  633.         exit(1);
  634. #endif
  635.  
  636.  
  637.     }
  638.     else {
  639.  
  640.         /* Try to open the sound file */
  641.         /* set some defaults incase input is raw PCM */
  642.         gs_wfInfo.seekable = (input_format != sf_raw); /* if user specified -r, set to not seekable */
  643.         gs_wfInfo.samplerate = lame_get_in_samplerate( gfp );
  644.         gs_wfInfo.pcmbitwidth = in_bitwidth;
  645.         gs_wfInfo.channels = lame_get_num_channels( gfp );
  646.  
  647.     if (in_bitwidth == 8) {
  648.         if (in_signed)
  649.         gs_wfInfo.format = SF_FORMAT_RAW_S8;
  650.         else
  651.         gs_wfInfo.format = SF_FORMAT_RAW_U8;
  652.  
  653.     } else {
  654.         if (!in_signed) {
  655.         fputs("Unsigned input only supported with bitwidth 8\n", stderr);
  656.         exit(1);
  657.         }
  658.         if (in_endian != order_unknown) {
  659.         if (in_endian == order_littleEndian)
  660.             gs_wfInfo.format = SF_FORMAT_RAW_LE;
  661.         else
  662.             gs_wfInfo.format = SF_FORMAT_RAW_BE;
  663.         } else {
  664. #ifndef WORDS_BIGENDIAN
  665.         /* little endian */
  666.         if (swapbytes)
  667.             gs_wfInfo.format = SF_FORMAT_RAW_BE;
  668.         else
  669.             gs_wfInfo.format = SF_FORMAT_RAW_LE;
  670. #else
  671.         if (swapbytes)
  672.             gs_wfInfo.format = SF_FORMAT_RAW_LE;
  673.         else
  674.             gs_wfInfo.format = SF_FORMAT_RAW_BE;
  675. #endif
  676.         }
  677.     }
  678.  
  679.         gs_pSndFileIn = sf_open_read(lpszFileName, &gs_wfInfo);
  680.         musicin = (SNDFILE *) gs_pSndFileIn;
  681.  
  682.         /* Check result */
  683.         if (gs_pSndFileIn == NULL) {
  684.             sf_perror(gs_pSndFileIn);
  685.             fprintf(stderr, "Could not open sound file \"%s\".\n",
  686.                     lpszFileName);
  687.             exit(1);
  688.         }
  689.  
  690.         if ((gs_wfInfo.format == SF_FORMAT_RAW_LE) ||
  691.             (gs_wfInfo.format == SF_FORMAT_RAW_BE) ||
  692.         (gs_wfInfo.format == SF_FORMAT_RAW_S8) ||
  693.         (gs_wfInfo.format == SF_FORMAT_RAW_U8))
  694.         input_format = sf_raw;
  695.  
  696. #ifdef _DEBUG_SND_FILE
  697.         DEBUGF("\n\nSF_INFO structure\n");
  698.         DEBUGF("samplerate        :%d\n", gs_wfInfo.samplerate);
  699.         DEBUGF("samples           :%d\n", gs_wfInfo.samples);
  700.         DEBUGF("channels          :%d\n", gs_wfInfo.channels);
  701.         DEBUGF("pcmbitwidth       :%d\n", gs_wfInfo.pcmbitwidth);
  702.         DEBUGF("format            :");
  703.  
  704.         /* new formats from sbellon@sbellon.de  1/2000 */
  705.  
  706.         switch (gs_wfInfo.format & SF_FORMAT_TYPEMASK) {
  707.         case SF_FORMAT_WAV:
  708.             DEBUGF("Microsoft WAV format (big endian). ");
  709.             break;
  710.         case SF_FORMAT_AIFF:
  711.             DEBUGF("Apple/SGI AIFF format (little endian). ");
  712.             break;
  713.         case SF_FORMAT_AU:
  714.             DEBUGF("Sun/NeXT AU format (big endian). ");
  715.             break;
  716.         case SF_FORMAT_AULE:
  717.             DEBUGF("DEC AU format (little endian). ");
  718.             break;
  719.         case SF_FORMAT_RAW:
  720.             DEBUGF("RAW PCM data. ");
  721.             break;
  722.         case SF_FORMAT_PAF:
  723.             DEBUGF("Ensoniq PARIS file format. ");
  724.             break;
  725.         case SF_FORMAT_SVX:
  726.             DEBUGF("Amiga IFF / SVX8 / SV16 format. ");
  727.             break;
  728.         case SF_FORMAT_NIST:
  729.             DEBUGF("Sphere NIST format. ");
  730.             break;
  731.         default:
  732.             assert(0);
  733.             break;
  734.         }
  735.  
  736.         switch (gs_wfInfo.format & SF_FORMAT_SUBMASK) {
  737.         case SF_FORMAT_PCM:
  738.             DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
  739.             break;
  740.         case SF_FORMAT_FLOAT:
  741.             DEBUGF("32 bit Intel x86 floats.");
  742.             break;
  743.         case SF_FORMAT_ULAW:
  744.             DEBUGF("U-Law encoded.");
  745.             break;
  746.         case SF_FORMAT_ALAW:
  747.             DEBUGF("A-Law encoded.");
  748.             break;
  749.         case SF_FORMAT_IMA_ADPCM:
  750.             DEBUGF("IMA ADPCM.");
  751.             break;
  752.         case SF_FORMAT_MS_ADPCM:
  753.             DEBUGF("Microsoft ADPCM.");
  754.             break;
  755.         case SF_FORMAT_PCM_BE:
  756.             DEBUGF("Big endian PCM data.");
  757.             break;
  758.         case SF_FORMAT_PCM_LE:
  759.             DEBUGF("Little endian PCM data.");
  760.             break;
  761.         case SF_FORMAT_PCM_S8:
  762.             DEBUGF("Signed 8 bit PCM.");
  763.             break;
  764.         case SF_FORMAT_PCM_U8:
  765.             DEBUGF("Unsigned 8 bit PCM.");
  766.             break;
  767.         case SF_FORMAT_SVX_FIB:
  768.             DEBUGF("SVX Fibonacci Delta encoding.");
  769.             break;
  770.         case SF_FORMAT_SVX_EXP:
  771.             DEBUGF("SVX Exponential Delta encoding.");
  772.             break;
  773.         default:
  774.             assert(0);
  775.             break;
  776.         }
  777.  
  778.         DEBUGF("\n");
  779.         DEBUGF("pcmbitwidth       :%d\n", gs_wfInfo.pcmbitwidth);
  780.         DEBUGF("sections          :%d\n", gs_wfInfo.sections);
  781.         DEBUGF("seekable          :\n", gs_wfInfo.seekable);
  782. #endif
  783.  
  784.         (void) lame_set_num_samples( gfp, gs_wfInfo.samples );
  785.         if( -1 == lame_set_num_channels( gfp, gs_wfInfo.channels ) ) {
  786.             fprintf( stderr,
  787.                      "Unsupported number of channels: %ud\n",
  788.                      gs_wfInfo.channels );
  789.             exit( 1 );
  790.         }
  791.         (void) lame_set_in_samplerate( gfp, gs_wfInfo.samplerate );
  792.         pcmbitwidth = gs_wfInfo.pcmbitwidth;
  793.     }
  794.  
  795.     if (lame_get_num_samples( gfp ) == MAX_U_32_NUM) {
  796.         /* try to figure out num_samples */
  797.         double  flen = lame_get_file_size( lpszFileName );
  798.  
  799.         if (flen >= 0) {
  800.             /* try file size, assume 2 bytes per sample */
  801.             if (input_format == sf_mp1 ||
  802.                 input_format == sf_mp2 || input_format == sf_mp3) {
  803.         if (mp3input_data.bitrate>0) {
  804.             double  totalseconds =
  805.             (flen * 8.0 / (1000.0 * mp3input_data.bitrate));
  806.             unsigned long tmp_num_samples =
  807.             totalseconds * lame_get_in_samplerate( gfp );
  808.             
  809.             (void) lame_set_num_samples( gfp, tmp_num_samples );
  810.             mp3input_data.nsamp = tmp_num_samples;
  811.         }
  812.             }
  813.             else {
  814.                 lame_set_num_samples( gfp,
  815.                     flen / (2 * lame_get_num_channels( gfp )) );
  816.             }
  817.         }
  818.     }
  819.  
  820.  
  821.     return musicin;
  822. }
  823.  
  824.  
  825. /************************************************************************
  826. *
  827. * read_samples()
  828. *
  829. * PURPOSE:  reads the PCM samples from a file to the buffer
  830. *
  831. *  SEMANTICS:
  832. * Reads #samples_read# number of shorts from #musicin# filepointer
  833. * into #sample_buffer[]#.  Returns the number of samples read.
  834. *
  835. ************************************************************************/
  836.  
  837. static int
  838. read_samples_pcm(FILE * const musicin, int sample_buffer[2304],
  839.                  int frame_size /* unused */ , int samples_to_read)
  840. {
  841.     int     i;
  842.     int     samples_read;
  843.  
  844.     samples_read =
  845.         sf_read_int((SNDFILE *) musicin, sample_buffer, samples_to_read);
  846.  
  847.     switch (pcmbitwidth) {
  848.     case 8:
  849.         for (i = 0; i < samples_read; i++)
  850.             sample_buffer[i] <<= (8 * sizeof(int) - 8);
  851.         break;
  852.     case 16:
  853.         for (i = 0; i < samples_read; i++)
  854.             sample_buffer[i] <<= (8 * sizeof(int) - 16);
  855.         break;
  856.     case 24:
  857.         for (i = 0; i < samples_read; i++)
  858.             sample_buffer[i] <<= (8 * sizeof(int) - 24);
  859.     break;
  860.     default:
  861.         fprintf(stderr, "Only 8, 16, and 24 bit input files supported \n");
  862.         exit(1);
  863.     }
  864.  
  865.     return samples_read;
  866. }
  867.  
  868.  
  869. #else /* defined(LIBSNDFILE) */
  870.  
  871. /************************************************************************
  872.  ************************************************************************
  873.  ************************************************************************
  874.  ************************************************************************
  875.  ************************************************************************
  876.  ************************************************************************
  877.  *
  878.  * OLD ISO/LAME routines follow.  Used if you dont have LIBSNDFILE
  879.  * or for stdin/stdout support
  880.  *
  881.  ************************************************************************
  882.  ************************************************************************
  883.  ************************************************************************
  884.  ************************************************************************
  885.  ************************************************************************
  886.  ************************************************************************/
  887.  
  888.  
  889.  
  890. /************************************************************************
  891. unpack_read_samples - read and unpack signed low-to-high byte or unsigned
  892.                       single byte input. (used for read_samples function)
  893.                       Output integers are stored in the native byte order
  894.                       (little or big endian).  -jd
  895.   in: samples_to_read
  896.       bytes_per_sample
  897.       swap_order    - set for high-to-low byte order input stream
  898.  i/o: pcm_in
  899.  out: sample_buffer  (must be allocated up to samples_to_read upon call)
  900. returns: number of samples read
  901. */
  902. static int
  903. unpack_read_samples( const int samples_to_read, const int bytes_per_sample,
  904.              const int swap_order, int *sample_buffer, FILE *pcm_in )
  905. {
  906.     int samples_read;
  907.     int i;
  908.     int *op;            /* output pointer */
  909.     unsigned char *ip = (unsigned char *) sample_buffer; /* input pointer */
  910.     const int b = sizeof(int) * 8;
  911.  
  912. #define GA_URS_IFLOOP( ga_urs_bps ) \
  913.     if( bytes_per_sample == ga_urs_bps ) \
  914.     for( i = samples_read * bytes_per_sample; (i -= bytes_per_sample) >=0;)
  915.     
  916.  
  917.     samples_read = fread( sample_buffer, bytes_per_sample, 
  918.               samples_to_read, pcm_in);
  919.     op = sample_buffer + samples_read;
  920.  
  921.     GA_URS_IFLOOP( 1 )
  922.     *--op = (ip[i] ^ 0x80)<<(b-8) | 0x7f<<(b-16);/* convert from unsigned*/
  923.     if( swap_order == 0 ) {
  924.     GA_URS_IFLOOP( 2 )
  925.         *--op = ip[i]<<(b-16) | ip[i+1]<<(b-8); 
  926.     GA_URS_IFLOOP( 3 )
  927.         *--op = ip[i]<<(b-24) | ip[i+1]<<(b-16) | ip[i+2]<<(b-8);
  928.     } else {
  929.     GA_URS_IFLOOP( 2 )
  930.         *--op = ip[i]<<(b-8) | ip[i+1]<<(b-16); 
  931.     GA_URS_IFLOOP( 3 )
  932.         *--op = ip[i]<<(b-8) | ip[i+1]<<(b-16) | ip[i+2]<<(b-24);
  933.     }
  934. #undef GA_URS_IFLOOP
  935.     return( samples_read );
  936. }
  937.  
  938.  
  939.  
  940. /************************************************************************
  941. *
  942. * read_samples()
  943. *
  944. * PURPOSE:  reads the PCM samples from a file to the buffer
  945. *
  946. *  SEMANTICS:
  947. * Reads #samples_read# number of shorts from #musicin# filepointer
  948. * into #sample_buffer[]#.  Returns the number of samples read.
  949. *
  950. ************************************************************************/
  951.  
  952. int
  953. read_samples_pcm(FILE * musicin, int sample_buffer[2304], int frame_size,
  954.                  int samples_to_read)
  955. {
  956.     int     samples_read;
  957.     int     iswav = (input_format == sf_wave);
  958.     int     hi_lo_order;    /* byte order of input stream */
  959.  
  960.     if( (24 == pcmbitwidth) || (16 == pcmbitwidth) ) {
  961.                 /* assume only recognized wav files are */
  962.                 /*  in little endian byte order */
  963.     hi_lo_order = (!iswav == !swapbytes);
  964.     if( 16 == pcmbitwidth )
  965.         samples_read = unpack_read_samples(samples_to_read, 2, hi_lo_order,
  966.                            sample_buffer, musicin );
  967.     else            /* ( 24 == pcmbitwidth ) */
  968.         samples_read = unpack_read_samples(samples_to_read, 3, hi_lo_order,
  969.                            sample_buffer, musicin );
  970.     } else if( 8 == pcmbitwidth ) {
  971.     samples_read = unpack_read_samples( samples_to_read, 1, 0,
  972.                         sample_buffer, musicin );
  973.     } else {
  974.         fprintf(stderr, "Only 8, 16, and 24 bit input files supported \n");
  975.         exit(1);
  976.     }
  977.     if (ferror(musicin)) {
  978.         fprintf(stderr, "Error reading input file\n");
  979.         exit(1);
  980.     }
  981.  
  982.     return samples_read;
  983. }
  984.  
  985.  
  986.  
  987. /* AIFF Definitions */
  988.  
  989. #define IFF_ID_FORM 0x464f524d /* "FORM" */
  990. #define IFF_ID_AIFF 0x41494646 /* "AIFF" */
  991. #define IFF_ID_AIFC 0x41494643 /* "AIFC" */
  992. #define IFF_ID_COMM 0x434f4d4d /* "COMM" */
  993. #define IFF_ID_SSND 0x53534e44 /* "SSND" */
  994. #define IFF_ID_MPEG 0x4d504547 /* "MPEG" */
  995.  
  996. #define IFF_ID_NONE 0x4e4f4e45 /* "NONE" */ /* AIFF-C data format */
  997. #define IFF_ID_2CBE 0x74776f73 /* "twos" */ /* AIFF-C data format */
  998. #define IFF_ID_2CLE 0x736f7774 /* "sowt" */ /* AIFF-C data format */
  999.  
  1000. #define WAV_ID_RIFF 0x52494646 /* "RIFF" */
  1001. #define WAV_ID_WAVE 0x57415645 /* "WAVE" */
  1002. #define WAV_ID_FMT  0x666d7420 /* "fmt " */
  1003. #define WAV_ID_DATA 0x64617461 /* "data" */
  1004.  
  1005.  
  1006.  
  1007.  
  1008. /*****************************************************************************
  1009.  *
  1010.  *    Read Microsoft Wave headers
  1011.  *
  1012.  *    By the time we get here the first 32-bits of the file have already been
  1013.  *    read, and we're pretty sure that we're looking at a WAV file.
  1014.  *
  1015.  *****************************************************************************/
  1016.  
  1017. static int
  1018. parse_wave_header(lame_global_flags * gfp, FILE * sf)
  1019. {
  1020.     int     format_tag = 0;
  1021.     int     channels = 0;
  1022.     int     block_align = 0;
  1023.     int     bits_per_sample = 0;
  1024.     int     samples_per_sec = 0;
  1025.     int     avg_bytes_per_sec = 0;
  1026.  
  1027.  
  1028.     int     is_wav = 0;
  1029.     long    data_length = 0, file_length, subSize = 0;
  1030.     int     loop_sanity = 0;
  1031.  
  1032.     file_length = Read32BitsHighLow(sf);
  1033.  
  1034.     if (Read32BitsHighLow(sf) != WAV_ID_WAVE)
  1035.         return 0;
  1036.  
  1037.     for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
  1038.         int     type = Read32BitsHighLow(sf);
  1039.  
  1040.         if (type == WAV_ID_FMT) {
  1041.             subSize = Read32BitsLowHigh(sf);
  1042.             if (subSize < 16) {
  1043.                 /*DEBUGF(
  1044.                    "'fmt' chunk too short (only %ld bytes)!", subSize);  */
  1045.                 return 0;
  1046.             }
  1047.  
  1048.             format_tag = Read16BitsLowHigh(sf);
  1049.             subSize -= 2;
  1050.             channels = Read16BitsLowHigh(sf);
  1051.             subSize -= 2;
  1052.             samples_per_sec = Read32BitsLowHigh(sf);
  1053.             subSize -= 4;
  1054.             avg_bytes_per_sec = Read32BitsLowHigh(sf);
  1055.             subSize -= 4;
  1056.             block_align = Read16BitsLowHigh(sf);
  1057.             subSize -= 2;
  1058.             bits_per_sample = Read16BitsLowHigh(sf);
  1059.             subSize -= 2;
  1060.  
  1061.             /* DEBUGF("   skipping %d bytes\n", subSize); */
  1062.  
  1063.             if (subSize > 0) {
  1064.                 if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
  1065.                     return 0;
  1066.             };
  1067.  
  1068.         }
  1069.         else if (type == WAV_ID_DATA) {
  1070.             subSize = Read32BitsLowHigh(sf);
  1071.             data_length = subSize;
  1072.             is_wav = 1;
  1073.             /* We've found the audio data. Read no further! */
  1074.             break;
  1075.  
  1076.         }
  1077.         else {
  1078.             subSize = Read32BitsLowHigh(sf);
  1079.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
  1080.                 return 0;
  1081.         }
  1082.     }
  1083.  
  1084.     if (format_tag != 1) {
  1085.     return 0; /* oh no! non-supported format  */
  1086.     }
  1087.  
  1088.  
  1089.     if (is_wav) {
  1090.         /* make sure the header is sane */
  1091.         if( -1 == lame_set_num_channels( gfp, channels ) ) {
  1092.             fprintf( stderr,
  1093.                      "Unsupported number of channels: %ud\n",
  1094.                      channels );
  1095.             exit( 1 );
  1096.         }
  1097.         (void) lame_set_in_samplerate( gfp, samples_per_sec );
  1098.         pcmbitwidth = bits_per_sample;
  1099.         (void) lame_set_num_samples( gfp,
  1100.             data_length / (channels * ((bits_per_sample+7) / 8)) );
  1101.     }
  1102.     return is_wav;
  1103. }
  1104.  
  1105.  
  1106.  
  1107. /************************************************************************
  1108. * aiff_check2
  1109. *
  1110. * PURPOSE:    Checks AIFF header information to make sure it is valid.
  1111. *            returns 0 on success, 1 on errors
  1112. ************************************************************************/
  1113.  
  1114. int
  1115. aiff_check2(const char *file_name, IFF_AIFF * const pcm_aiff_data)
  1116. {
  1117.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  1118.         fprintf(stderr, "Sound data is not PCM in '%s'\n", file_name);
  1119.         return 1;
  1120.     }
  1121.     if (pcm_aiff_data->sampleSize != sizeof(short) * CHAR_BIT) {
  1122.         fprintf(stderr, "Sound data is not %i bits in '%s'\n",
  1123.                 sizeof(short) * CHAR_BIT, file_name);
  1124.         return 1;
  1125.     }
  1126.     if (pcm_aiff_data->numChannels != 1 && pcm_aiff_data->numChannels != 2) {
  1127.         fprintf(stderr, "Sound data is not mono or stereo in '%s'\n",
  1128.                 file_name);
  1129.         return 1;
  1130.     }
  1131.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  1132.         fprintf(stderr, "Block size is not 0 bytes in '%s'\n", file_name);
  1133.         return 1;
  1134.     }
  1135.     /* A bug, since we correctly skip the offset earlier in the code.
  1136.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  1137.         fprintf(stderr, "Block offset is not 0 bytes in '%s'\n", file_name);
  1138.         return 1;
  1139.     } */
  1140.  
  1141.     return 0;
  1142. }
  1143.  
  1144. /*****************************************************************************
  1145.  *
  1146.  *    Read Audio Interchange File Format (AIFF) headers.
  1147.  *
  1148.  *    By the time we get here the first 32 bits of the file have already been
  1149.  *    read, and we're pretty sure that we're looking at an AIFF file.
  1150.  *
  1151.  *****************************************************************************/
  1152.  
  1153. static int
  1154. parse_aiff_header(lame_global_flags * gfp, FILE * sf)
  1155. {
  1156.     int     is_aiff = 0;
  1157.     long    chunkSize = 0, subSize = 0, typeID = 0, dataType = 0;
  1158.     IFF_AIFF aiff_info;
  1159.  
  1160.     memset(&aiff_info, 0, sizeof(aiff_info));
  1161.     chunkSize = Read32BitsHighLow(sf);
  1162.  
  1163.     typeID = Read32BitsHighLow(sf);
  1164.     if ((typeID != IFF_ID_AIFF)&&(typeID != IFF_ID_AIFC))
  1165.         return 0;
  1166.  
  1167.     while (chunkSize > 0) {
  1168.         int     type = Read32BitsHighLow(sf);
  1169.         chunkSize -= 4;
  1170.  
  1171.         /* DEBUGF(
  1172.            "found chunk type %08x '%4.4s'\n", type, (char*)&type); */
  1173.  
  1174.         /* don't use a switch here to make it easier to use 'break' for SSND */
  1175.         if (type == IFF_ID_COMM) {
  1176.             subSize = Read32BitsHighLow(sf);
  1177.             chunkSize -= subSize;
  1178.  
  1179.             aiff_info.numChannels = Read16BitsHighLow(sf);
  1180.             subSize -= 2;
  1181.             aiff_info.numSampleFrames = Read32BitsHighLow(sf);
  1182.             subSize -= 4;
  1183.             aiff_info.sampleSize = Read16BitsHighLow(sf);
  1184.             subSize -= 2;
  1185.             aiff_info.sampleRate = ReadIeeeExtendedHighLow(sf);
  1186.             subSize -= 10;
  1187.  
  1188.             if (typeID == IFF_ID_AIFC) {
  1189.                 dataType = Read32BitsHighLow(sf);
  1190.                 subSize -= 4;
  1191.  
  1192.                 if ((dataType != IFF_ID_2CLE) && 
  1193.                     (dataType != IFF_ID_2CBE) &&
  1194.                     (dataType != IFF_ID_NONE))
  1195.                     return 0;
  1196.                     
  1197.                 if (aiff_info.sampleSize == 16)
  1198.                     swapbytes = (!swapbytes == (dataType == IFF_ID_2CLE));
  1199.             }
  1200.             
  1201.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
  1202.                 return 0;
  1203.         }
  1204.         else if (type == IFF_ID_SSND) {
  1205.             subSize = Read32BitsHighLow(sf);
  1206.             chunkSize -= subSize;
  1207.  
  1208.             aiff_info.blkAlgn.offset = Read32BitsHighLow(sf);
  1209.             subSize -= 4;
  1210.             aiff_info.blkAlgn.blockSize = Read32BitsHighLow(sf);
  1211.             subSize -= 4;
  1212.  
  1213.             if (fskip(sf, (long) aiff_info.blkAlgn.offset, SEEK_CUR) != 0)
  1214.                 return 0;
  1215.  
  1216.             aiff_info.sampleType = IFF_ID_SSND;
  1217.             is_aiff = 1;
  1218.  
  1219.             /* We've found the audio data. Read no further! */
  1220.             break;
  1221.  
  1222.         }
  1223.         else {
  1224.             subSize = Read32BitsHighLow(sf);
  1225.             chunkSize -= subSize;
  1226.  
  1227.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
  1228.                 return 0;
  1229.         }
  1230.     }
  1231.  
  1232.     /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
  1233.     if (is_aiff) {
  1234.         /* make sure the header is sane */
  1235.         if (0 != aiff_check2("name" /*???????????? */ , &aiff_info))
  1236.             return 0;
  1237.         if( -1 == lame_set_num_channels( gfp, aiff_info.numChannels ) ) {
  1238.             fprintf( stderr,
  1239.                      "Unsupported number of channels: %ud\n",
  1240.                      aiff_info.numChannels );
  1241.             exit( 1 );
  1242.         }
  1243.         (void) lame_set_in_samplerate( gfp, aiff_info.sampleRate );
  1244.         pcmbitwidth = aiff_info.sampleSize;
  1245.         (void) lame_set_num_samples( gfp, aiff_info.numSampleFrames );
  1246.     }
  1247.     return is_aiff;
  1248. }
  1249.  
  1250.  
  1251.  
  1252. /************************************************************************
  1253. *
  1254. * parse_file_header
  1255. *
  1256. * PURPOSE: Read the header from a bytestream.  Try to determine whether
  1257. *           it's a WAV file or AIFF without rewinding, since rewind
  1258. *           doesn't work on pipes and there's a good chance we're reading
  1259. *           from stdin (otherwise we'd probably be using libsndfile).
  1260. *
  1261. * When this function returns, the file offset will be positioned at the
  1262. * beginning of the sound data.
  1263. *
  1264. ************************************************************************/
  1265.  
  1266. void
  1267. parse_file_header(lame_global_flags * gfp, FILE * sf)
  1268. {
  1269.  
  1270.     int     type = Read32BitsHighLow(sf);
  1271.     /*
  1272.        DEBUGF(
  1273.        "First word of input stream: %08x '%4.4s'\n", type, (char*) &type); 
  1274.      */
  1275.     count_samples_carefully = 0;
  1276.     input_format = sf_raw;
  1277.  
  1278.     if (type == WAV_ID_RIFF) {
  1279.         /* It's probably a WAV file */
  1280.         if (parse_wave_header(gfp, sf)) {
  1281.             input_format = sf_wave;
  1282.             count_samples_carefully = 1;
  1283.         } else {
  1284.         fprintf( stderr, "Warning: corrupt or unsupported WAVE format\n"); 
  1285.         }
  1286.     }
  1287.     else if (type == IFF_ID_FORM) {
  1288.         /* It's probably an AIFF file */
  1289.         if (parse_aiff_header(gfp, sf)) {
  1290.             input_format = sf_aiff;
  1291.             count_samples_carefully = 1;
  1292.         }
  1293.     }
  1294.     if (input_format == sf_raw) {
  1295.         /*
  1296.            ** Assume it's raw PCM.  Since the audio data is assumed to begin
  1297.            ** at byte zero, this will unfortunately require seeking.
  1298.          */
  1299.         if (fseek(sf, 0L, SEEK_SET) != 0) {
  1300.             /* ignore errors */
  1301.         }
  1302.         input_format = sf_raw;
  1303.     }
  1304. }
  1305.  
  1306.  
  1307.  
  1308. void
  1309. CloseSndFile(sound_file_format input, FILE * musicin)
  1310. {
  1311.     if (fclose(musicin) != 0) {
  1312.         fprintf(stderr, "Could not close audio input file\n");
  1313.         exit(2);
  1314.     }
  1315. }
  1316.  
  1317.  
  1318.  
  1319.  
  1320.  
  1321. FILE   *
  1322. OpenSndFile(lame_global_flags * gfp, char *inPath)
  1323. {
  1324.     FILE   *musicin;
  1325.  
  1326.     /* set the defaults from info incase we cannot determine them from file */
  1327.     lame_set_num_samples( gfp, MAX_U_32_NUM );
  1328.  
  1329.  
  1330.     if (!strcmp(inPath, "-")) {
  1331.         lame_set_stream_binary_mode(musicin = stdin); /* Read from standard input. */
  1332.     }
  1333.     else {
  1334.         if ((musicin = fopen(inPath, "rb")) == NULL) {
  1335.             fprintf(stderr, "Could not find \"%s\".\n", inPath);
  1336.             exit(1);
  1337.         }
  1338.     }
  1339.  
  1340.     if (input_format == sf_mp1 ||
  1341.         input_format == sf_mp2 || input_format == sf_mp3) {
  1342. #ifdef AMIGA_MPEGA
  1343.         if (-1 == lame_decode_initfile(inPath, &mp3input_data)) {
  1344.             fprintf(stderr, "Error reading headers in mp3 input file %s.\n",
  1345.                     inPath);
  1346.             exit(1);
  1347.         }
  1348. #endif
  1349. #ifdef HAVE_MPGLIB
  1350.         if (-1 == lame_decode_initfile(musicin, &mp3input_data)) {
  1351.             fprintf(stderr, "Error reading headers in mp3 input file %s.\n",
  1352.                     inPath);
  1353.             exit(1);
  1354.         }
  1355. #endif
  1356.         if( -1 == lame_set_num_channels( gfp, mp3input_data.stereo ) ) {
  1357.             fprintf( stderr,
  1358.                      "Unsupported number of channels: %ud\n",
  1359.                      mp3input_data.stereo );
  1360.             exit( 1 );
  1361.         }
  1362.         (void) lame_set_in_samplerate( gfp, mp3input_data.samplerate );
  1363.         (void) lame_set_num_samples( gfp, mp3input_data.nsamp );
  1364.     }
  1365.     else if (input_format == sf_ogg) {
  1366. #ifdef HAVE_VORBIS
  1367.         if ( -1 == lame_decode_ogg_initfile( gfp,
  1368.                                              musicin,
  1369.                                              &mp3input_data ) ) {
  1370.             fprintf(stderr, "Error reading headers in ogg input file %s.\n",
  1371.                     inPath);
  1372.             exit(1);
  1373.         }
  1374.         if( -1 == lame_set_num_channels( gfp, mp3input_data.stereo ) ) {
  1375.             fprintf( stderr,
  1376.                      "Unsupported number of channels: %ud\n",
  1377.                      mp3input_data.stereo );
  1378.             exit( 1 );
  1379.         }
  1380.         (void) lame_set_in_samplerate( gfp, mp3input_data.samplerate );
  1381.         (void) lame_set_num_samples( gfp, mp3input_data.nsamp );
  1382. #else
  1383.         fprintf(stderr, "LAME not compiled with libvorbis support.\n");
  1384.         exit(1);
  1385. #endif
  1386.     }
  1387.     else {
  1388.         if (input_format != sf_raw) {
  1389.             parse_file_header(gfp, musicin);
  1390.         }
  1391.  
  1392.         if (input_format == sf_raw) {
  1393.             /* assume raw PCM */
  1394.             fprintf(stderr, "Assuming raw pcm input file");
  1395.             if (swapbytes)
  1396.                 fprintf(stderr, " : Forcing byte-swapping\n");
  1397.             else
  1398.                 fprintf(stderr, "\n");
  1399.         }
  1400.     }
  1401.  
  1402.  
  1403.     if (lame_get_num_samples( gfp ) == MAX_U_32_NUM && musicin != stdin) {
  1404.  
  1405.         double  flen = lame_get_file_size(inPath); /* try to figure out num_samples */
  1406.  
  1407.         if (flen >= 0) {
  1408.             /* try file size, assume 2 bytes per sample */
  1409.             if (input_format == sf_mp1 ||
  1410.                 input_format == sf_mp2 || input_format == sf_mp3) {
  1411.  
  1412.                 if (mp3input_data.bitrate > 0) {
  1413.                     double  totalseconds =
  1414.                         (flen * 8.0 / (1000.0 * mp3input_data.bitrate));
  1415.                     unsigned long tmp_num_samples =
  1416.                         totalseconds * lame_get_in_samplerate( gfp );
  1417.  
  1418.                     (void) lame_set_num_samples( gfp, tmp_num_samples );
  1419.                     mp3input_data.nsamp = tmp_num_samples;
  1420.                 }
  1421.             }
  1422.             else {
  1423.                 (void) lame_set_num_samples( gfp,
  1424.                     flen / (2 * lame_get_num_channels( gfp )) );
  1425.             }
  1426.         }
  1427.     }
  1428.     return musicin;
  1429. }
  1430. #endif /* defined(LIBSNDFILE) */
  1431.  
  1432.  
  1433.  
  1434.  
  1435.  
  1436. #if defined(HAVE_MPGLIB)
  1437. static int
  1438. check_aid(const unsigned char *header)
  1439. {
  1440.     return 0 == strncmp(header, "AiD\1", 4);
  1441. }
  1442.  
  1443. /*
  1444.  * Please check this and don't kill me if there's a bug
  1445.  * This is a (nearly?) complete header analysis for a MPEG-1/2/2.5 Layer I, II or III
  1446.  * data stream
  1447.  */
  1448.  
  1449. static int
  1450. is_syncword_mp123(const void *const headerptr)
  1451. {
  1452.     const unsigned char *const p = headerptr;
  1453.     static const char abl2[16] =
  1454.         { 0, 7, 7, 7, 0, 7, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8 };
  1455.  
  1456.     if ((p[0] & 0xFF) != 0xFF)
  1457.         return 0;       // first 8 bits must be '1'
  1458.     if ((p[1] & 0xE0) != 0xE0)
  1459.         return 0;       // next 3 bits are also
  1460.     if ((p[1] & 0x18) == 0x08)
  1461.         return 0;       // no MPEG-1, -2 or -2.5
  1462.     if ((p[1] & 0x06) == 0x00)
  1463.         return 0;       // no Layer I, II and III
  1464.     if ((p[2] & 0xF0) == 0xF0)
  1465.         return 0;       // bad bitrate
  1466.     if ((p[2] & 0x0C) == 0x0C)
  1467.         return 0;       // no sample frequency with (32,44.1,48)/(1,2,4)    
  1468.     if ((p[1] & 0x06) == 0x04) // illegal Layer II bitrate/Channel Mode comb
  1469.         if (abl2[p[2] >> 4] & (1 << (p[3] >> 6)))
  1470.             return 0;
  1471.     return 1;
  1472. }
  1473.  
  1474. static int
  1475. is_syncword_mp3(const void *const headerptr)
  1476. {
  1477.     const unsigned char *const p = headerptr;
  1478.  
  1479.     if ((p[0] & 0xFF) != 0xFF)
  1480.         return 0;       // first 8 bits must be '1'
  1481.     if ((p[1] & 0xE0) != 0xE0)
  1482.         return 0;       // next 3 bits are also
  1483.     if ((p[1] & 0x18) == 0x08)
  1484.         return 0;       // no MPEG-1, -2 or -2.5
  1485.     if ((p[1] & 0x06) != 0x02)
  1486.         return 0;       // no Layer III (can be merged with 'next 3 bits are also' test, but don't do this, this decreases readability)
  1487.     if ((p[2] & 0xF0) == 0xF0)
  1488.         return 0;       // bad bitrate
  1489.     if ((p[2] & 0x0C) == 0x0C)
  1490.         return 0;       // no sample frequency with (32,44.1,48)/(1,2,4)    
  1491.     return 1;
  1492. }
  1493.  
  1494.  
  1495. int
  1496. lame_decode_initfile(FILE * fd, mp3data_struct * mp3data)
  1497. {
  1498.     //  VBRTAGDATA pTagData;
  1499.     // int xing_header,len2,num_frames;
  1500.     unsigned char buf[100];
  1501.     int     ret;
  1502.     int     len, aid_header;
  1503.     short int pcm_l[1152], pcm_r[1152];
  1504.  
  1505.     memset(mp3data, 0, sizeof(mp3data_struct));
  1506.     lame_decode_init();
  1507.  
  1508.     len = 4;
  1509.     if (fread(&buf, 1, len, fd) != len)
  1510.         return -1;      /* failed */
  1511.     aid_header = check_aid(buf);
  1512.     if (aid_header) {
  1513.         if (fread(&buf, 1, 2, fd) != 2)
  1514.             return -1;  /* failed */
  1515.         aid_header = (unsigned char) buf[0] + 256 * (unsigned char) buf[1];
  1516.         fprintf(stderr, "Album ID found.  length=%i \n", aid_header);
  1517.         /* skip rest of AID, except for 6 bytes we have already read */
  1518.         fskip(fd, aid_header - 6, SEEK_CUR);
  1519.  
  1520.         /* read 4 more bytes to set up buffer for MP3 header check */
  1521.         len = fread(&buf, 1, 4, fd);
  1522.     }
  1523.  
  1524.  
  1525.     /* look for valid 4 byte MPEG header  */
  1526.     if (len < 4)
  1527.         return -1;
  1528.     while (!is_syncword_mp123(buf)) {
  1529.         int     i;
  1530.         for (i = 0; i < len - 1; i++)
  1531.             buf[i] = buf[i + 1];
  1532.         if (fread(buf + len - 1, 1, 1, fd) != 1)
  1533.             return -1;  /* failed */
  1534.     }
  1535.  
  1536.  
  1537.     // now parse the current buffer looking for MP3 headers.   
  1538.     // (as of 11/00: mpglib modified so that for the first frame where 
  1539.     // headers are parsed, no data will be decoded.  
  1540.     // However, for freeformat, we need to decode an entire frame,
  1541.     // so mp3data->bitrate will be 0 until we have decoded the first
  1542.     // frame.  Cannot decode first frame here because we are not
  1543.     // yet prepared to handle the output.
  1544.     ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
  1545.     if (-1 == ret)
  1546.         return -1;
  1547.  
  1548.     /* repeat until we decode a valid mp3 header.  */
  1549.     while (!mp3data->header_parsed) {
  1550.         len = fread(buf, 1, sizeof(buf), fd);
  1551.         if (len != sizeof(buf))
  1552.             return -1;
  1553.         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
  1554.         if (-1 == ret)
  1555.             return -1;
  1556.     }
  1557.  
  1558.     if (mp3data->bitrate==0) {
  1559.     fprintf(stderr,"Input file is freeformat.\n"); 
  1560.     }
  1561.  
  1562.     if (mp3data->totalframes > 0) {
  1563.         /* mpglib found a Xing VBR header and computed nsamp & totalframes */
  1564.     }
  1565.     else {
  1566.     /* set as unknown.  Later, we will take a guess based on file size
  1567.      * ant bitrate */
  1568.         mp3data->nsamp = MAX_U_32_NUM;
  1569.     }
  1570.  
  1571.  
  1572.     /*
  1573.        fprintf(stderr,"ret = %i NEED_MORE=%i \n",ret,MP3_NEED_MORE);
  1574.        fprintf(stderr,"stereo = %i \n",mp.fr.stereo);
  1575.        fprintf(stderr,"samp = %i  \n",freqs[mp.fr.sampling_frequency]);
  1576.        fprintf(stderr,"framesize = %i  \n",framesize);
  1577.        fprintf(stderr,"bitrate = %i  \n",mp3data->bitrate);
  1578.        fprintf(stderr,"num frames = %ui  \n",num_frames);
  1579.        fprintf(stderr,"num samp = %ui  \n",mp3data->nsamp);
  1580.        fprintf(stderr,"mode     = %i  \n",mp.fr.mode);
  1581.      */
  1582.  
  1583.     return 0;
  1584. }
  1585.  
  1586. /*
  1587. For lame_decode_fromfile:  return code
  1588.   -1     error
  1589.    n     number of samples output.  either 576 or 1152 depending on MP3 file.
  1590.  
  1591.  
  1592. For lame_decode1_headers():  return code
  1593.   -1     error
  1594.    0     ok, but need more data before outputing any samples
  1595.    n     number of samples output.  either 576 or 1152 depending on MP3 file.
  1596. */
  1597. int
  1598. lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[],
  1599.                      mp3data_struct * mp3data)
  1600. {
  1601.     int     ret = 0, len=0;
  1602.     unsigned char buf[1024];
  1603.  
  1604.     /* first see if we still have data buffered in the decoder: */
  1605.     ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
  1606.     if (ret!=0) return ret;
  1607.  
  1608.  
  1609.     /* read until we get a valid output frame */
  1610.     while (1) {
  1611.         len = fread(buf, 1, 1024, fd);
  1612.         if (len == 0) {
  1613.         /* we are done reading the file, but check for buffered data */
  1614.         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
  1615.         if (ret<=0) return -1;  // done with file
  1616.         break;
  1617.     }
  1618.  
  1619.         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
  1620.         if (ret == -1) return -1;
  1621.     if (ret >0) break;
  1622.     }
  1623.     return ret;
  1624. }
  1625. #endif /* defined(HAVE_MPGLIB) */
  1626.  
  1627. /* end of get_audio.c */
  1628.