home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 13 / AACD13.ISO / AACD / Sound / LAME / src / get_audio.c < prev    next >
C/C++ Source or Header  |  2000-08-06  |  32KB  |  1,099 lines

  1. #include "util.h"
  2. #include "get_audio.h"
  3. #include "portableio.h"
  4. #include "gtkanal.h"
  5. #include "timestatus.h"
  6.  
  7. #if (defined LIBSNDFILE || defined LAMESNDFILE)
  8.  
  9. #ifdef _WIN32
  10. /* needed to set stdin to binary on windoze machines */
  11. #include <io.h>
  12. #endif
  13.  
  14. #ifdef __riscos__
  15. #include <kernel.h>
  16. #include <sys/swis.h>
  17. #endif
  18.  
  19.  
  20. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304],int frame_size, int samples_to_read);
  21. int read_samples_mp3(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int num_chan);
  22. int read_samples_ogg(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int num_chan);
  23.  
  24.  
  25. void lame_init_infile(lame_global_flags *gfp)
  26. {
  27.   lame_internal_flags *gfc=gfp->internal_flags;
  28.   /* open the input file */
  29.   gfc->count_samples_carefully=0;
  30.   gfp->musicin=OpenSndFile(gfp);
  31. }
  32. void lame_close_infile(lame_global_flags *gfp)
  33. {
  34.   CloseSndFile(gfp->input_format,gfp->musicin);
  35. }
  36.  
  37.  
  38.  
  39.  
  40. /************************************************************************
  41. *
  42. * lame_readframe()
  43. *
  44. * PURPOSE:  reads a frame of audio data from a file to the buffer,
  45. *   aligns the data for future processing, and separates the
  46. *   left and right channels
  47. *
  48. *
  49. ************************************************************************/
  50. int lame_readframe(lame_global_flags *gfp,short int Buffer[2][1152])
  51. {
  52.   int iread;
  53.   lame_internal_flags *gfc=gfp->internal_flags;
  54.  
  55.  
  56.   /* note: if input is gfp->stereo and output is mono, get_audio()
  57.    * will return  .5*(L+R) in channel 0,  and nothing in channel 1. */
  58.   iread = get_audio(gfp,Buffer,gfc->stereo);
  59.  
  60.   /* check to see if we overestimated/underestimated totalframes */
  61.   if (iread==0)  gfp->totalframes = Min(gfp->totalframes,gfp->frameNum+2);
  62.   if (gfp->frameNum > (gfp->totalframes-1)) gfp->totalframes = gfp->frameNum;
  63.  
  64.   /* normally, frame counter is incremented every time we encode a frame, but: */
  65.   if (gfp->decode_only) ++gfp->frameNum;
  66.   return iread;
  67. }
  68.  
  69.  
  70.  
  71.  
  72.  
  73. /************************************************************************
  74. *
  75. * get_audio()
  76. *
  77. * PURPOSE:  reads a frame of audio data from a file to the buffer,
  78. *   aligns the data for future processing, and separates the
  79. *   left and right channels
  80. *
  81. *
  82. ************************************************************************/
  83. int get_audio(lame_global_flags *gfp,short buffer[2][1152],int stereo)
  84. {
  85.  
  86.   int        j;
  87.   short    insamp[2304];
  88.   int samples_read;
  89.   int framesize,samples_to_read;
  90.   unsigned long remaining;
  91.   lame_internal_flags *gfc=gfp->internal_flags;
  92.   int num_channels = gfp->num_channels;
  93.  
  94.   /* NOTE: LAME can now handle arbritray size input data packets,
  95.    * so there is no reason to read the input data in chuncks of
  96.    * size "gfp->framesize".  EXCEPT:  the LAME graphical frame analyzer 
  97.    * will get out of sync if we read more than framesize worth of data.
  98.    */
  99.   framesize = gfp->framesize;
  100.  
  101.   samples_to_read = framesize;
  102.   if (gfc->count_samples_carefully) {
  103.     /* if this flag has been set, then we are carefull to read
  104.      * exactly num_samples and no more.  This is usefull for .wav and .aiff
  105.      * files which have id3 or other tags at the end.  Note that if you
  106.      * are using LIBSNDFILE, this is not necessary */
  107.     remaining=gfp->num_samples-Min(gfp->num_samples,gfc->num_samples_read);
  108.     if (remaining < (unsigned long)framesize)
  109.       samples_to_read = remaining;
  110.   }
  111.  
  112.  
  113.   if (gfp->input_format==sf_mp3) {
  114.     /* decode an mp3 file for the input */
  115.     samples_read=read_samples_mp3(gfp,gfp->musicin,buffer,num_channels);
  116.   } else if (gfp->input_format==sf_ogg) {
  117.     samples_read=read_samples_ogg(gfp,gfp->musicin,buffer,num_channels);
  118.   }else{
  119.     samples_read = read_samples_pcm(gfp,insamp,num_channels*framesize,num_channels*samples_to_read);
  120.     samples_read /=num_channels;
  121.  
  122.     for(j=0;j<framesize;j++) {
  123.       buffer[0][j] = insamp[num_channels*j];
  124.       if (num_channels==2) buffer[1][j] = insamp[2*j+1];
  125.       else buffer[1][j]=0;
  126.     }
  127.   }
  128.  
  129.   /* dont count things in this case to avoid overflows */
  130.   if (gfp->num_samples!=MAX_U_32_NUM) gfc->num_samples_read += samples_read;
  131.   return(samples_read);
  132.  
  133. }
  134.  
  135.  
  136.   
  137.  
  138.  
  139.  
  140. int read_samples_ogg(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int stereo)
  141. {
  142. #ifdef HAVEVORBIS
  143.   int j,out=0;
  144.   lame_internal_flags *gfc=gfp->internal_flags;
  145.   mp3data_struct mp3data;
  146.  
  147.   out=lame_decode_ogg_fromfile(musicin,mpg123pcm[0],mpg123pcm[1],&mp3data);
  148.   /* out = -1:  error, probably EOF */
  149.   /* out = 0:   not possible with lame_decode_fromfile() */
  150.   /* out = number of output samples */
  151.  
  152.   if (out==-1) {
  153.     for ( j = 0; j < 1152; j++ ) {
  154.       mpg123pcm[0][j] = 0;
  155.       mpg123pcm[1][j] = 0;
  156.     }
  157.   }
  158.  
  159.   if (out==-1) return 0;
  160.  
  161.   gfp->brate=mp3data.bitrate;
  162.   if (gfp->num_channels != mp3data.stereo) {
  163.     ERRORF("Error: number of channels has changed in mp3 file - not supported. \n");
  164.   }
  165.   if (gfp->in_samplerate != mp3data.samplerate) {
  166.     ERRORF("Error: samplerate has changed in mp3 file - not supported. \n");
  167.   }
  168.  
  169.  
  170.   return out;
  171. #else
  172.   return -1; /* wanna read ogg without vorbis support? */
  173. #endif
  174. }
  175.  
  176.  
  177. int read_samples_mp3(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int stereo)
  178. {
  179. #if (defined  AMIGA_MPEGA || defined HAVEMPGLIB)
  180.   int j,out=0;
  181.   lame_internal_flags *gfc=gfp->internal_flags;
  182.   mp3data_struct mp3data;
  183.  
  184.   out=lame_decode_fromfile(musicin,mpg123pcm[0],mpg123pcm[1],&mp3data);
  185.   /* out = -1:  error, probably EOF */
  186.   /* out = 0:   not possible with lame_decode_fromfile() */
  187.   /* out = number of output samples */
  188.  
  189.   if (out==-1) {
  190.     for ( j = 0; j < 1152; j++ ) {
  191.       mpg123pcm[0][j] = 0;
  192.       mpg123pcm[1][j] = 0;
  193.     }
  194.   }
  195.  
  196.  
  197.   if (gfc->pinfo != NULL) {
  198.     int ch;
  199.     /* add a delay of framesize-DECDELAY, which will make the total delay
  200.      * exactly one frame, so we can sync MP3 output with WAV input */
  201.     for ( ch = 0; ch < stereo; ch++ ) {
  202.       for ( j = 0; j < gfp->framesize-DECDELAY; j++ )
  203.     gfc->pinfo->pcmdata2[ch][j] = gfc->pinfo->pcmdata2[ch][j+gfp->framesize];
  204.       for ( j = 0; j < gfp->framesize; j++ )
  205.     gfc->pinfo->pcmdata2[ch][j+gfp->framesize-DECDELAY] = mpg123pcm[ch][j];
  206.     }
  207.  
  208.   gfc->pinfo->frameNum123 = gfp->frameNum-1;
  209.   gfc->pinfo->frameNum = gfp->frameNum;
  210.   }
  211.  
  212.   if (out==-1) return 0;
  213.  
  214.   gfp->brate=mp3data.bitrate;
  215.   if (gfp->num_channels != mp3data.stereo) {
  216.     ERRORF("Error: number of channels has changed in mp3 file - not supported. \n");
  217.   }
  218.   if (gfp->in_samplerate != mp3data.samplerate) {
  219.     ERRORF("Error: samplerate has changed in mp3 file - not supported. \n");
  220.   }
  221.   return out;
  222.  
  223. #endif
  224. }
  225.  
  226.  
  227.  
  228.  
  229.  
  230. void WriteWav(FILE *f,long bytes,int srate,int ch){
  231.   /* quick and dirty */
  232.   fwrite("RIFF",1,4,f);               /*  0-3 */
  233.   Write32BitsLowHigh(f,bytes+44-8);
  234.   fwrite("WAVEfmt ",1,8,f);           /*  8-15 */
  235.   Write32BitsLowHigh(f,16);
  236.   Write16BitsLowHigh(f,1);
  237.   Write16BitsLowHigh(f,ch);
  238.   Write32BitsLowHigh(f,srate);
  239.   Write32BitsLowHigh(f,srate*ch*2);
  240.   Write16BitsLowHigh(f,4);
  241.   Write16BitsLowHigh(f,16);
  242.   fwrite("data",1,4,f);               /* 36-39 */
  243.   Write32BitsLowHigh(f,bytes);
  244. }
  245.  
  246. /* the simple lame decoder */
  247. /* After calling lame_init(), lame_init_params() and
  248.  * lame_init_infile(), call this routine to read the input MP3 file
  249.  * and output .wav data to the specified file pointer*/
  250. /* lame_decoder will ignore the first 528 samples, since these samples
  251.  * represent the mpglib delay (and are all 0).  skip = number of additional
  252.  * samples to skip, to (for example) compensate for the encoder delay */
  253. int lame_decoder(lame_global_flags *gfp,FILE *outf,int skip)
  254. {
  255.   short int Buffer[2][1152];
  256.   int iread;
  257.   long wavsize=2147483647L;  /* max for a signed long */
  258.  
  259.   if (gfp->input_format==sf_mp3) {
  260.     /* mp3 decoder has a 528 sample delay, plus user supplied "skip" */
  261.     skip+=528 + 1;
  262.     MSGF("input:    %s %.1fkHz MPEG%i %i channel LayerIII\n",
  263.       (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  264.       gfp->in_samplerate/1000.0,2-gfp->version,gfp->num_channels);
  265.  
  266.   }else{
  267.     /* other formats have no delay */
  268.     skip=0;
  269.     MSGF("input:    %s %.1fkHz %i channel\n",
  270.       (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  271.       gfp->in_samplerate/1000.0,gfp->num_channels);
  272.   }
  273.  
  274.   MSGF("output:   %s (wav format)\n",
  275.     (strcmp(gfp->outPath, "-")? gfp->outPath : "stdout"));
  276.   if (skip>0)
  277.     MSGF("skipping initial %i samples (encoder + decoder delay)\n",skip);
  278.   if (!gfp->disable_waveheader)
  279.     WriteWav(outf,wavsize,gfp->in_samplerate,gfp->num_channels);
  280.   wavsize=-skip;
  281.   do {
  282.     int i;
  283.     /* read in 'iread' samples */
  284.     iread=lame_readframe(gfp,Buffer);
  285.     wavsize += iread;
  286.     if (!gfp->silent)
  287.       decoder_progress(gfp);
  288.     for (i=0; i<iread; ++i) {
  289.       if (skip) {
  290.         --skip;
  291.       } else {
  292.         if (gfp->disable_waveheader) {
  293.           if (gfp->swapbytes) {
  294.             WriteBytesSwapped(outf,(char *)&Buffer[0][i],sizeof(short));
  295.             if (gfp->num_channels==2)
  296.               WriteBytesSwapped(outf,(char *)&Buffer[1][i],sizeof(short));
  297.           } else {
  298.             WriteBytes(outf,(char *)&Buffer[0][i],sizeof(short));
  299.             if (gfp->num_channels==2)
  300.               WriteBytes(outf,(char *)&Buffer[1][i],sizeof(short));
  301.           }
  302.         } else {
  303.           Write16BitsLowHigh(outf,Buffer[0][i]);
  304.           if (gfp->num_channels==2)
  305.             Write16BitsLowHigh(outf,Buffer[1][i]);
  306.         }
  307.       }
  308.     }
  309.   } while (iread);
  310.   if (wavsize<0) wavsize=0;
  311.   wavsize *= 2*gfp->num_channels;
  312.   decoder_progress_finish(gfp);
  313.   /* if outf is seekable, rewind and adjust length */
  314.   if (!fseek(outf,0,SEEK_SET))
  315.     if (!gfp->disable_waveheader)
  316.       WriteWav(outf,wavsize,gfp->in_samplerate,gfp->num_channels);
  317.   fclose(outf);
  318.  
  319.   return 0;
  320. }
  321.  
  322.  
  323. #endif  /* LAMESNDFILE or LIBSNDFILE */
  324.  
  325.  
  326.  
  327.  
  328. #ifdef LIBSNDFILE
  329. /*
  330. ** Copyright (C) 1999 Albert Faber
  331. **
  332.  * This library is free software; you can redistribute it and/or
  333.  * modify it under the terms of the GNU Library General Public
  334.  * License as published by the Free Software Foundation; either
  335.  * version 2 of the License, or (at your option) any later version.
  336.  *
  337.  * This library is distributed in the hope that it will be useful,
  338.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  339.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  340.  * Library General Public License for more details.
  341.  *
  342.  * You should have received a copy of the GNU Library General Public
  343.  * License along with this library; if not, write to the
  344.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  345.  * Boston, MA 02111-1307, USA.
  346.  */
  347.  
  348.  
  349. #include <stdio.h>
  350.  
  351.  
  352.  
  353.  
  354. void CloseSndFile(sound_file_format input,FILE *musicin)
  355. {
  356.   SNDFILE *gs_pSndFileIn=(SNDFILE*)musicin;
  357.   if (input==sf_mp3) {
  358. #ifndef AMIGA_MPEGA
  359.     if (fclose(musicin) != 0){
  360.       ERRORF("Could not close audio input file\n");
  361.       LAME_FATAL_EXIT();
  362.     }
  363. #endif
  364.   }else{
  365.     if (gs_pSndFileIn)
  366.     {
  367.         if (sf_close(gs_pSndFileIn) !=0)
  368.         {
  369.             ERRORF("Could not close sound file \n");
  370.             LAME_FATAL_EXIT();
  371.         }
  372.     }
  373.   }
  374. }
  375.  
  376.  
  377.  
  378. FILE * OpenSndFile(lame_global_flags *gfp)
  379. {
  380.   lame_internal_flags *gfc=gfp->internal_flags;
  381.   const char* lpszFileName = gfp->inPath;
  382.   FILE * musicin;
  383.   SNDFILE *gs_pSndFileIn;
  384.   SF_INFO gs_wfInfo;
  385.   mp3data_struct mp3data;
  386.  
  387.   gfc->input_bitrate=0;
  388.   if (gfp->input_format==sf_mp3) {
  389. #ifdef AMIGA_MPEGA
  390.     if (-1==lame_decode_initfile(lpszFileName,&mp3data)) {
  391.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  392.       LAME_ERROR_EXIT();
  393.     }
  394. #endif
  395. #ifdef HAVEMPGLIB
  396.     if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  397.       ERRORF("Could not find \"%s\".\n", lpszFileName);
  398.       LAME_ERROR_EXIT();
  399.     }
  400.     if (-1==lame_decode_initfile(musicin,&mp3data)) {
  401.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  402.       LAME_ERROR_EXIT();
  403.     }
  404. #endif
  405.  
  406.     gfp->num_channels=mp3data.stereo;
  407.     gfp->in_samplerate=mp3data.samplerate;
  408.     gfc->input_bitrate=mp3data.bitrate;
  409.     gfp->num_samples=mp3data.nsamp;
  410.   }else if (gfp->input_format==sf_ogg) {
  411. #ifdef HAVEVORBIS
  412.     if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  413.       ERRORF("Could not find \"%s\".\n", lpszFileName);
  414.       LAME_ERROR_EXIT();
  415.     }
  416.     if (-1==lame_decode_ogg_initfile(musicin,&mp3data)) {
  417.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  418.       LAME_ERROR_EXIT();
  419.     }
  420.     gfp->num_channels=0;
  421.     gfp->in_samplerate=0;
  422.     gfc->input_bitrate=0;
  423.     gfp->num_samples=0;
  424. #else
  425.     ERRORF("LAME not compiled with libvorbis support.\n");
  426.     LAME_ERROR_EXIT();
  427. #endif
  428.  
  429.  
  430.   } else {
  431.  
  432.     /* Try to open the sound file */
  433.     /* set some defaults incase input is raw PCM */
  434.     gs_wfInfo.seekable=(gfp->input_format!=sf_raw);  /* if user specified -r, set to not seekable */
  435.     gs_wfInfo.samplerate=gfp->in_samplerate;
  436.     gs_wfInfo.pcmbitwidth=16;
  437.     gs_wfInfo.channels=gfp->num_channels;
  438.     if (DetermineByteOrder()==order_littleEndian) {
  439.       if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_BE;
  440.       else gs_wfInfo.format=SF_FORMAT_RAW_LE;
  441.     } else {
  442.       if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_LE;
  443.       else gs_wfInfo.format=SF_FORMAT_RAW_BE;
  444.     }
  445.  
  446.     gs_pSndFileIn=sf_open_read(lpszFileName,&gs_wfInfo);
  447.     musicin = (SNDFILE *) gs_pSndFileIn;
  448.  
  449.         /* Check result */
  450.     if (gs_pSndFileIn==NULL)
  451.     {
  452.             sf_perror(gs_pSndFileIn);
  453.         ERRORF("Could not open sound file \"%s\".\n", lpszFileName);
  454.         LAME_ERROR_EXIT();
  455.     }
  456.  
  457.     if ((gs_wfInfo.format==SF_FORMAT_RAW_LE) ||
  458.     (gs_wfInfo.format==SF_FORMAT_RAW_BE))
  459.       gfp->input_format=sf_raw;
  460.  
  461. #ifdef _DEBUG_SND_FILE
  462.     DEBUGF("\n\nSF_INFO structure\n");
  463.     DEBUGF("samplerate        :%d\n",gs_wfInfo.samplerate);
  464.     DEBUGF("samples           :%d\n",gs_wfInfo.samples);
  465.     DEBUGF("channels          :%d\n",gs_wfInfo.channels);
  466.     DEBUGF("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
  467.     DEBUGF("format            :");
  468.  
  469.     /* new formats from sbellon@sbellon.de  1/2000 */
  470.         if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_WAV)
  471.       DEBUGF("Microsoft WAV format (big endian). ");
  472.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AIFF)
  473.       DEBUGF("Apple/SGI AIFF format (little endian). ");
  474.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AU)
  475.       DEBUGF("Sun/NeXT AU format (big endian). ");
  476.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AULE)
  477.       DEBUGF("DEC AU format (little endian). ");
  478.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_RAW)
  479.       DEBUGF("RAW PCM data. ");
  480.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_PAF)
  481.       DEBUGF("Ensoniq PARIS file format. ");
  482.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_SVX)
  483.       DEBUGF("Amiga IFF / SVX8 / SV16 format. ");
  484.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_NIST)
  485.       DEBUGF("Sphere NIST format. ");
  486.  
  487.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM)
  488.       DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
  489.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_FLOAT)
  490.       DEBUGF("32 bit Intel x86 floats.");
  491.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ULAW)
  492.       DEBUGF("U-Law encoded.");
  493.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ALAW)
  494.       DEBUGF("A-Law encoded.");
  495.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_IMA_ADPCM)
  496.       DEBUGF("IMA ADPCM.");
  497.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_MS_ADPCM)
  498.       DEBUGF("Microsoft ADPCM.");
  499.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_BE)
  500.       DEBUGF("Big endian PCM data.");
  501.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_LE)
  502.       DEBUGF("Little endian PCM data.");
  503.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_S8)
  504.       DEBUGF("Signed 8 bit PCM.");
  505.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_U8)
  506.       DEBUGF("Unsigned 8 bit PCM.");
  507.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_FIB)
  508.       DEBUGF("SVX Fibonacci Delta encoding.");
  509.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_EXP)
  510.       DEBUGF("SVX Exponential Delta encoding.");
  511.  
  512.  
  513.  
  514.  
  515.     DEBUGF("\n");
  516.     DEBUGF("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
  517.     DEBUGF("sections          :%d\n",gs_wfInfo.sections);
  518.     DEBUGF("seekable          :\n",gs_wfInfo.seekable);
  519. #endif
  520.  
  521.     gfp->num_samples = gs_wfInfo.samples;
  522.     gfp->num_channels = gs_wfInfo.channels;
  523.     gfp->in_samplerate = gs_wfInfo.samplerate;
  524.     gfc->pcmbitwidth=gs_wfInfo.pcmbitwidth;
  525.   }
  526.  
  527.   if (gfp->num_samples==MAX_U_32_NUM) {
  528.     struct stat sb;
  529. #ifdef __riscos__
  530.     _kernel_swi_regs reg;
  531. #endif
  532.  
  533.     /* try to figure out num_samples */
  534. #ifndef __riscos__
  535.     if (0==stat(lpszFileName,&sb)) {
  536. #else /* __riscos__ */
  537.     reg.r[0]=17;
  538.     reg.r[1]=(int) lpszFileName;
  539.     _kernel_swi(OS_File,®,®);
  540.     if (reg.r[0] == 1) {
  541.       sb.st_size=reg.r[4];
  542. #endif /* __riscos__ */
  543.  
  544.       /* try file size, assume 2 bytes per sample */
  545.       if (gfp->input_format == sf_mp3) {
  546.     FLOAT totalseconds = (sb.st_size*8.0/(1000.0*gfc->input_bitrate));
  547.     gfp->num_samples= totalseconds*gfp->in_samplerate;
  548.       }else{
  549.     gfp->num_samples = sb.st_size/(2*gfp->num_channels);
  550.       }
  551.     }
  552.   }
  553.  
  554.  
  555.   return musicin;
  556. }
  557.  
  558.  
  559. /************************************************************************
  560. *
  561. * read_samples()
  562. *
  563. * PURPOSE:  reads the PCM samples from a file to the buffer
  564. *
  565. *  SEMANTICS:
  566. * Reads #samples_read# number of shorts from #musicin# filepointer
  567. * into #sample_buffer[]#.  Returns the number of samples read.
  568. *
  569. ************************************************************************/
  570.  
  571. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304],int frame_size,int samples_to_read)
  572. {
  573.     int         samples_read;
  574.     int            rcode;
  575.     lame_internal_flags *gfc=gfp->internal_flags;
  576.     SNDFILE * gs_pSndFileIn;
  577.     gs_pSndFileIn = (SNDFILE *)gfp->musicin;
  578.  
  579.     samples_read=sf_read_short(gs_pSndFileIn,sample_buffer,samples_to_read);
  580.     rcode = samples_read;
  581.  
  582.     if (8==gfc->pcmbitwidth)
  583.       for (; samples_read > 0; sample_buffer[--samples_read] *= 256);
  584.  
  585.     return(rcode);
  586. }
  587.  
  588.  
  589. #endif /* ifdef LIBSNDFILE */
  590. #ifdef LAMESNDFILE
  591.  
  592. /************************************************************************
  593.  ************************************************************************
  594.  ************************************************************************
  595.  ************************************************************************
  596.  ************************************************************************
  597.  ************************************************************************
  598.  *
  599.  * OLD ISO/LAME routines follow.  Used if you dont have LIBSNDFILE
  600.  * or for stdin/stdout support
  601.  *
  602.  ************************************************************************
  603.  ************************************************************************
  604.  ************************************************************************
  605.  ************************************************************************
  606.  ************************************************************************
  607.  ************************************************************************/
  608.  
  609.  
  610.  
  611. /************************************************************************
  612. *
  613. * read_samples()
  614. *
  615. * PURPOSE:  reads the PCM samples from a file to the buffer
  616. *
  617. *  SEMANTICS:
  618. * Reads #samples_read# number of shorts from #musicin# filepointer
  619. * into #sample_buffer[]#.  Returns the number of samples read.
  620. *
  621. ************************************************************************/
  622.  
  623. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304], int frame_size,int samples_to_read)
  624. {
  625.     lame_internal_flags *gfc=gfp->internal_flags;
  626.     int samples_read;
  627.     int iswav=(gfp->input_format==sf_wave);
  628.  
  629.     if (16==gfc->pcmbitwidth) {
  630.       samples_read = fread(sample_buffer, 2, (unsigned int)samples_to_read, gfp->musicin);
  631.     }else if (8==gfc->pcmbitwidth) {
  632.       unsigned char temp[2304];
  633.       int i;
  634.       samples_read = fread(temp, 1, (unsigned int)samples_to_read, gfp->musicin);
  635.       for (i=0 ; i<samples_read; ++i) {
  636.     /* note: 8bit .wav samples are unsigned */
  637.     sample_buffer[i]=((short int)temp[i]-127)*256;
  638.       }
  639.     }else{
  640.       ERRORF("Only 8 and 16 bit input files supported \n");
  641.       LAME_ERROR_EXIT();
  642.     }
  643.     if (ferror(gfp->musicin)) {
  644.       ERRORF("Error reading input file\n");
  645.       LAME_ERROR_EXIT();
  646.     }
  647.  
  648.  
  649.     /*
  650.        Samples are big-endian. If this is a little-endian machine
  651.        we must swap
  652.      */
  653.     if ( NativeByteOrder == order_unknown )
  654.       {
  655.     NativeByteOrder = DetermineByteOrder();
  656.     if ( NativeByteOrder == order_unknown )
  657.       {
  658.         ERRORF("byte order not determined\n" );
  659.         LAME_ERROR_EXIT();
  660.       }
  661.       }
  662.     /* intel=littleEndian */
  663.     if (!iswav && ( NativeByteOrder == order_littleEndian ))
  664.       SwapBytesInWords( sample_buffer, samples_read );
  665.  
  666.     if (iswav && ( NativeByteOrder == order_bigEndian ))
  667.       SwapBytesInWords( sample_buffer, samples_read );
  668.  
  669.     if (gfp->swapbytes==TRUE)
  670.       SwapBytesInWords( sample_buffer, samples_read );
  671.  
  672.  
  673.     return samples_read;
  674. }
  675.  
  676.  
  677.  
  678. /* AIFF Definitions */
  679.  
  680. #define IFF_ID_FORM 0x464f524d /* "FORM" */
  681. #define IFF_ID_AIFF 0x41494646 /* "AIFF" */
  682. #define IFF_ID_COMM 0x434f4d4d /* "COMM" */
  683. #define IFF_ID_SSND 0x53534e44 /* "SSND" */
  684. #define IFF_ID_MPEG 0x4d504547 /* "MPEG" */
  685.  
  686.  
  687. #define WAV_ID_RIFF 0x52494646 /* "RIFF" */
  688. #define WAV_ID_WAVE 0x57415645 /* "WAVE" */
  689. #define WAV_ID_FMT  0x666d7420 /* "fmt " */
  690. #define WAV_ID_DATA 0x64617461 /* "data" */
  691.  
  692. typedef struct fmt_chunk_data_struct {
  693.     short    format_tag;             /* Format category */
  694.     u_short channels;             /* Number of channels */
  695.     u_long    samples_per_sec;     /* Sampling rate */
  696.     u_long    avg_bytes_per_sec;     /* For buffer estimation */
  697.     u_short block_align;         /* Data block size */
  698.     u_short bits_per_sample;     /* for PCM data, anyway... */
  699. } fmt_chunk_data;
  700.  
  701.  
  702.  
  703.  
  704.  
  705.  
  706.  
  707. /*****************************************************************************
  708.  *
  709.  *    Read Microsoft Wave headers
  710.  *
  711.  *    By the time we get here the first 32-bits of the file have already been
  712.  *    read, and we're pretty sure that we're looking at a WAV file.
  713.  *
  714.  *****************************************************************************/
  715.  
  716. static int
  717. parse_wave_header(lame_global_flags *gfp,FILE *sf)
  718. {
  719.     lame_internal_flags *gfc=gfp->internal_flags;
  720.     fmt_chunk_data wave_info;
  721.     int is_wav = 0;
  722.     long data_length = 0, file_length, subSize = 0;
  723.     int loop_sanity = 0;
  724.  
  725.     memset(&wave_info, 0, sizeof(wave_info));
  726.  
  727.     file_length = Read32BitsHighLow(sf);
  728.  
  729.     if (Read32BitsHighLow(sf) != WAV_ID_WAVE)
  730.         return 0;
  731.  
  732.     for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
  733.         u_int type = Read32BitsHighLow(sf);
  734.  
  735.         if (type == WAV_ID_FMT) {
  736.             subSize = Read32BitsLowHigh(sf);
  737.             if (subSize < 16) {
  738.               /*DEBUGF(
  739.                 "'fmt' chunk too short (only %ld bytes)!", subSize);  */
  740.                 return 0;
  741.             }
  742.  
  743.             wave_info.format_tag        = Read16BitsLowHigh(sf);
  744.             subSize -= 2;
  745.             wave_info.channels            = Read16BitsLowHigh(sf);
  746.             subSize -= 2;
  747.             wave_info.samples_per_sec    = Read32BitsLowHigh(sf);
  748.             subSize -= 4;
  749.             wave_info.avg_bytes_per_sec = Read32BitsLowHigh(sf);
  750.             subSize -= 4;
  751.             wave_info.block_align        = Read16BitsLowHigh(sf);
  752.             subSize -= 2;
  753.             wave_info.bits_per_sample    = Read16BitsLowHigh(sf);
  754.             subSize -= 2;
  755.  
  756.             /* DEBUGF("   skipping %d bytes\n", subSize); */
  757.  
  758.             if (subSize > 0) {
  759.                 if (fskip(sf, (long)subSize, SEEK_CUR) != 0 )
  760.                     return 0;
  761.             };
  762.  
  763.         } else if (type == WAV_ID_DATA) {
  764.             subSize = Read32BitsLowHigh(sf);
  765.             data_length = subSize;
  766.             is_wav = 1;
  767.             /* We've found the audio data.    Read no further! */
  768.             break;
  769.  
  770.         } else {
  771.             subSize = Read32BitsLowHigh(sf);
  772.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 ) return 0;
  773.         }
  774.     }
  775.  
  776.     if (is_wav) {
  777.         /* make sure the header is sane */
  778.         gfp->num_channels  = wave_info.channels;
  779.         gfp->in_samplerate = wave_info.samples_per_sec;
  780.         gfc->pcmbitwidth = wave_info.bits_per_sample;
  781.         gfp->num_samples   = data_length / (wave_info.channels * wave_info.bits_per_sample / 8);
  782.     }
  783.     return is_wav;
  784. }
  785.  
  786.  
  787.  
  788. /************************************************************************
  789. *
  790. * aiff_check
  791. *
  792. * PURPOSE:    Checks AIFF header information to make sure it is valid.
  793. *            Exits if not.
  794. *
  795. ************************************************************************/
  796.  
  797. static void
  798. aiff_check2(const char *file_name, IFF_AIFF *pcm_aiff_data)
  799. {
  800.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  801.        ERRORF("Sound data is not PCM in \"%s\".\n", file_name);
  802.        LAME_ERROR_EXIT();
  803.     }
  804.  
  805.     if (pcm_aiff_data->sampleSize != sizeof(short) * BITS_IN_A_BYTE) {
  806.         ERRORF("Sound data is not %d bits in \"%s\".\n",
  807.                 (unsigned int) sizeof(short) * BITS_IN_A_BYTE, file_name);
  808.         LAME_ERROR_EXIT();
  809.     }
  810.  
  811.     if (pcm_aiff_data->numChannels != 1 &&
  812.         pcm_aiff_data->numChannels != 2) {
  813.        ERRORF("Sound data is not mono or stereo in \"%s\".\n",
  814.                file_name);
  815.        LAME_ERROR_EXIT();
  816.     }
  817.  
  818.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  819.        ERRORF("Block size is not %d bytes in \"%s\".\n",
  820.                0, file_name);
  821.        LAME_ERROR_EXIT();
  822.     }
  823.  
  824.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  825.        ERRORF("Block offset is not %d bytes in \"%s\".\n",
  826.                0, file_name);
  827.        LAME_ERROR_EXIT();
  828.     }
  829. }
  830.  
  831. /*****************************************************************************
  832.  *
  833.  *    Read Audio Interchange File Format (AIFF) headers.
  834.  *
  835.  *    By the time we get here the first 32-bits of the file have already been
  836.  *    read, and we're pretty sure that we're looking at an AIFF file.
  837.  *
  838.  *****************************************************************************/
  839.  
  840. static int
  841. parse_aiff_header(lame_global_flags *gfp,FILE *sf)
  842. {
  843.     lame_internal_flags *gfc=gfp->internal_flags;
  844.     int is_aiff = 0;
  845.     long chunkSize = 0, subSize = 0;
  846.     IFF_AIFF aiff_info;
  847.  
  848.     memset(&aiff_info, 0, sizeof(aiff_info));
  849.     chunkSize = Read32BitsHighLow(sf);
  850.  
  851.     if ( Read32BitsHighLow(sf) != IFF_ID_AIFF )
  852.         return 0;
  853.  
  854.     while ( chunkSize > 0 )
  855.     {
  856.         u_int type = 0;
  857.         chunkSize -= 4;
  858.  
  859.         type = Read32BitsHighLow(sf);
  860.  
  861.         /* DEBUGF(
  862.             "found chunk type %08x '%4.4s'\n", type, (char*)&type); */
  863.  
  864.         /* don't use a switch here to make it easier to use 'break' for SSND */
  865.         if (type == IFF_ID_COMM) {
  866.             subSize = Read32BitsHighLow(sf);
  867.             chunkSize -= subSize;
  868.  
  869.             aiff_info.numChannels      = Read16BitsHighLow(sf);
  870.             subSize -= 2;
  871.             aiff_info.numSampleFrames = Read32BitsHighLow(sf);
  872.             subSize -= 4;
  873.             aiff_info.sampleSize      = Read16BitsHighLow(sf);
  874.             subSize -= 2;
  875.             aiff_info.sampleRate      = ReadIeeeExtendedHighLow(sf);
  876.             subSize -= 10;
  877.  
  878.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 )
  879.                 return 0;
  880.  
  881.         } else if (type == IFF_ID_SSND) {
  882.             subSize = Read32BitsHighLow(sf);
  883.             chunkSize -= subSize;
  884.  
  885.             aiff_info.blkAlgn.offset    = Read32BitsHighLow(sf);
  886.             subSize -= 4;
  887.             aiff_info.blkAlgn.blockSize = Read32BitsHighLow(sf);
  888.             subSize -= 4;
  889.  
  890.             if (fskip(sf, (long) aiff_info.blkAlgn.offset, SEEK_CUR) != 0 )
  891.                 return 0;
  892.  
  893.             aiff_info.sampleType = IFF_ID_SSND;
  894.             is_aiff = 1;
  895.  
  896.             /* We've found the audio data.    Read no further! */
  897.             break;
  898.  
  899.         } else {
  900.             subSize = Read32BitsHighLow(sf);
  901.             chunkSize -= subSize;
  902.  
  903.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 )
  904.                 return 0;
  905.         }
  906.     }
  907.  
  908.     /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
  909.     if (is_aiff) {
  910.         /* make sure the header is sane */
  911.         aiff_check2("name", &aiff_info);
  912.         gfp->num_channels  = aiff_info.numChannels;
  913.         gfp->in_samplerate = aiff_info.sampleRate;
  914.         gfc->pcmbitwidth =   aiff_info.sampleSize;
  915.         gfp->num_samples   = aiff_info.numSampleFrames;
  916.     }
  917.     return is_aiff;
  918. }
  919.  
  920.  
  921.  
  922. /************************************************************************
  923. *
  924. * parse_file_header
  925. *
  926. * PURPOSE: Read the header from a bytestream.  Try to determine whether
  927. *           it's a WAV file or AIFF without rewinding, since rewind
  928. *           doesn't work on pipes and there's a good chance we're reading
  929. *           from stdin (otherwise we'd probably be using libsndfile).
  930. *
  931. * When this function returns, the file offset will be positioned at the
  932. * beginning of the sound data.
  933. *
  934. ************************************************************************/
  935.  
  936. void parse_file_header(lame_global_flags *gfp,FILE *sf)
  937. {
  938.   lame_internal_flags *gfc=gfp->internal_flags;
  939.  
  940.     u_int type = 0;
  941.     type = Read32BitsHighLow(sf);
  942.     /*
  943.     DEBUGF(
  944.         "First word of input stream: %08x '%4.4s'\n", type, (char*) &type); 
  945.     */
  946.     gfc->count_samples_carefully=0;
  947.     gfp->input_format = sf_raw;
  948.  
  949.     if (type == WAV_ID_RIFF) {
  950.         /* It's probably a WAV file */
  951.         if (parse_wave_header(gfp,sf)) {
  952.             gfp->input_format = sf_wave;
  953.             gfc->count_samples_carefully=1;
  954.         }
  955.  
  956.     } else if (type == IFF_ID_FORM) {
  957.         /* It's probably an AIFF file */
  958.         if (parse_aiff_header(gfp,sf)) {
  959.             gfp->input_format = sf_aiff;
  960.             gfc->count_samples_carefully=1;
  961.         }
  962.     }
  963.     if (gfp->input_format==sf_raw) {
  964.       /*
  965.       ** Assume it's raw PCM.     Since the audio data is assumed to begin
  966.       ** at byte zero, this will unfortunately require seeking.
  967.       */
  968.       if (fseek(sf, 0L, SEEK_SET) != 0) {
  969.         /* ignore errors */
  970.       }
  971.       gfp->input_format = sf_raw;
  972.     }
  973. }
  974.  
  975.  
  976.  
  977. void CloseSndFile(sound_file_format input,FILE * musicin)
  978. {
  979.   if (fclose(musicin) != 0){
  980.     ERRORF("Could not close audio input file\n");
  981.     LAME_FATAL_EXIT();
  982.   }
  983. }
  984.  
  985.  
  986.  
  987.  
  988.  
  989. FILE * OpenSndFile(lame_global_flags *gfp)
  990. {
  991.   lame_internal_flags *gfc=gfp->internal_flags;
  992.   const char* inPath = gfp->inPath;
  993.   FILE * musicin;
  994.   struct stat sb;
  995.   mp3data_struct mp3data;
  996.  
  997.   /* set the defaults from info incase we cannot determine them from file */
  998.   gfp->num_samples=MAX_U_32_NUM;
  999.   gfc->input_bitrate=0;
  1000.  
  1001.  
  1002.   if (!strcmp(inPath, "-")) {
  1003.     /* Read from standard input. */
  1004. #ifdef __EMX__
  1005.     _fsetmode(stdin,"b");
  1006. #elif (defined  __BORLANDC__)
  1007.     setmode(_fileno(stdin), O_BINARY);
  1008. #elif (defined  __CYGWIN__)
  1009.     setmode(fileno(stdin), _O_BINARY);
  1010. #elif (defined _WIN32)
  1011.     _setmode(_fileno(stdin), _O_BINARY);
  1012. #endif
  1013.     musicin = stdin;
  1014.   } else {
  1015.     if ((musicin = fopen(inPath, "rb")) == NULL) {
  1016.       ERRORF("Could not find \"%s\".\n", inPath);
  1017.       LAME_ERROR_EXIT();
  1018.     }
  1019.   }
  1020.  
  1021.   if (gfp->input_format==sf_mp3) {
  1022. #ifdef AMIGA_MPEGA
  1023.     if (-1==lame_decode_initfile(inPath,&mp3data)) {
  1024.       ERRORF("Error reading headers in mp3 input file %s.\n", inPath);
  1025.       LAME_ERROR_EXIT();
  1026.     }
  1027. #endif
  1028. #ifdef HAVEMPGLIB
  1029.     if (-1==lame_decode_initfile(musicin,&mp3data)) {
  1030.       ERRORF("Error reading headers in mp3 input file %s.\n", inPath);
  1031.       LAME_ERROR_EXIT();
  1032.     }
  1033. #endif
  1034.     gfp->num_channels=mp3data.stereo;
  1035.     gfp->in_samplerate=mp3data.samplerate;
  1036.     gfc->input_bitrate=mp3data.bitrate;
  1037.     gfp->num_samples=mp3data.nsamp;
  1038.   }else if (gfp->input_format==sf_ogg) {
  1039. #ifdef HAVEVORBIS
  1040.     if (-1==lame_decode_ogg_initfile(musicin,&mp3data)) {
  1041.       ERRORF("Error reading headers in ogg input file %s.\n", inPath);
  1042.       LAME_ERROR_EXIT();
  1043.     }
  1044.     gfp->num_channels=mp3data.stereo;
  1045.     gfp->in_samplerate=mp3data.samplerate;
  1046.     gfc->input_bitrate=mp3data.bitrate;
  1047.     gfp->num_samples=mp3data.nsamp;
  1048. #else
  1049.     ERRORF("LAME not compiled with libvorbis support.\n");
  1050.     LAME_ERROR_EXIT();
  1051. #endif
  1052.  }else{
  1053.    if (gfp->input_format != sf_raw) {
  1054.      parse_file_header(gfp,musicin);
  1055.    }
  1056.  
  1057.    if (gfp->input_format==sf_raw) {
  1058.      /* assume raw PCM */
  1059.      MSGF("Assuming raw pcm input file");
  1060.      if (gfp->swapbytes==TRUE)
  1061.        MSGF(" : Forcing byte-swapping\n");
  1062.      else
  1063.        MSGF("\n");
  1064.    }
  1065.  }
  1066.  
  1067.   if (gfp->num_samples==MAX_U_32_NUM && musicin != stdin) {
  1068. #ifdef __riscos__
  1069.     _kernel_swi_regs reg;
  1070. #endif
  1071.  
  1072.     /* try to figure out num_samples */
  1073. #ifndef __riscos__
  1074.     if (0==stat(inPath,&sb)) {
  1075. #else
  1076.     reg.r[0]=17;
  1077.     reg.r[1]=(int) inPath;
  1078.     _kernel_swi(OS_File,®,®);
  1079.     if (reg.r[0] == 1) {
  1080.       sb.st_size=reg.r[4];
  1081. #endif
  1082.  
  1083.       /* try file size, assume 2 bytes per sample */
  1084.       if (gfp->input_format == sf_mp3) {
  1085.     if (gfc->input_bitrate>0) {
  1086.       FLOAT totalseconds = (sb.st_size*8.0/(1000.0*gfc->input_bitrate));
  1087.       gfp->num_samples= totalseconds*gfp->in_samplerate;
  1088.     }
  1089.       }else{
  1090.     gfp->num_samples = sb.st_size/(2*gfp->num_channels);
  1091.       }
  1092.     }
  1093.   }
  1094.   return musicin;
  1095. }
  1096. #endif  /* LAMESNDFILE */
  1097.  
  1098.  
  1099.