home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 6 / AACD06.ISO / AACD / Sound / LAME / Source / musicin.c < prev    next >
C/C++ Source or Header  |  1999-06-03  |  34KB  |  1,123 lines

  1. /**********************************************************************
  2.  * ISO MPEG Audio Subgroup Software Simulation Group (1996)
  3.  * ISO 13818-3 MPEG-2 Audio Encoder - Lower Sampling Frequency Extension
  4.  *
  5.  * $Id: musicin.c,v 1.2 1997/01/19 22:28:29 rowlands Exp $
  6.  *
  7.  * $Log: musicin.c,v $
  8.  * Revision 1.2  1997/01/19 22:28:29  rowlands
  9.  * Layer 3 bug fixes from Seymour Shlien
  10.  *
  11.  * Revision 1.1  1996/02/14 04:04:23  rowlands
  12.  * Initial revision
  13.  *
  14.  * Received from Mike Coleman
  15.  **********************************************************************/
  16. #include <fcntl.h>
  17.  
  18. #include <stdlib.h>
  19. #include "common.h"
  20. #include "globalflags.h"
  21. #include "encoder.h"
  22. #include "l3psy.h"
  23. #include "mdct.h"
  24. #include "loop.h"
  25. #include "l3bitstream.h"
  26. #include "gtkanal.h"
  27. #include "version.h"
  28. #include <assert.h>
  29. #ifdef __FreeBSD__
  30. #include <floatingpoint.h>
  31. #endif
  32. #ifdef linux
  33. #include <fpu_control.h>
  34. #endif
  35.  
  36.  
  37. #include <time.h>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40.  
  41. /* Global flags.  set defaults here, defined extern in common.h */
  42. int autoconvert=FALSE;
  43. int force_ms=FALSE;
  44. int gpsycho=1;
  45. int sfb21=1;
  46. int VBR=0;
  47. int VBR_q=4;
  48. #ifdef _BLADEDLL
  49. int silent=1;
  50. #else
  51. int silent=0;
  52. #endif
  53. int highq=0;
  54. int fast_mode=0;
  55. int allow_diff_short=0;
  56. #ifdef DISTRIB
  57. int gtkflag=1;
  58. #else
  59. int gtkflag=0;
  60. #endif
  61.  
  62. void usage();
  63.  
  64. /* Global variable definitions for "musicin.c" */
  65. struct stat sb;
  66. int firstcall = 1; /* define like this so Dll/BladeMP3EncDll.c can change value */
  67. int target_bitrate;
  68. long totalframes;
  69. int swapbytes = FALSE; /* force byte swapping */
  70. FILE               *musicin;
  71. Bit_stream_struc   bs;
  72. char               *programName;
  73. int iswav=0;
  74.  
  75. short FAR BigBuf[2][2304];
  76.  
  77. FLOAT snr32[32];
  78. L3SBS  FAR     l3_sb_sample;
  79.  
  80. III_side_info_t l3_side;
  81. frame_params fr_ps;
  82. unsigned long num_samples;
  83. int frameNum=0;
  84. #ifdef HAVEGTK
  85. static int MPGLAG=1;
  86. #endif
  87. int original_file_type;  /* 0=WAV, 1=MP3 */
  88. int original_file_fd;    /* file descriptor */
  89.  
  90. /* Implementations */
  91.  
  92. /*********************************************************/
  93. /* Timeconvert: convert given time (in secs) to hh:mm:ss */
  94. /*********************************************************/
  95. void timestatus(int frameNum, int totalframes, int samp_rate)
  96. {   
  97.   int time_so_far;
  98.   int remain,estimated;
  99.   double speedup;
  100.   char str1[20],str2[20],str3[20];
  101.  
  102.   time_so_far = clock()/CLOCKS_PER_SEC;
  103.   /* calc estimated total CPU time */
  104.   estimated = (int)((float)totalframes/(float)frameNum * (float)time_so_far);
  105.   remain=estimated - time_so_far;
  106.  
  107.   /* estimated encoding time / playing time.  (protected from divide by 0) */
  108.   speedup =   (estimated*totalframes*1.152)/
  109.     (1e-12+samp_rate*estimated*estimated);  
  110.   
  111.   sprintf(str1,"%02d:%02d",(time_so_far/60)%60, time_so_far%60);
  112.   sprintf(str2,"%02d:%02d",(remain/60)%60, remain%60);
  113.   sprintf(str3,"%02d:%02d",(estimated/60)%60, estimated%60);
  114.  
  115.   fprintf(stderr, 
  116.       /*"Frame: [%4lu/%4lu]   Encoding Time %5s/%5s  (%.2fx)   ETA %5s\r",  */
  117. "Frame: [%4d/%4d]   Encoding Time %5s/%5s  (%.2fx)   ETA %5s\r", 
  118. frameNum,totalframes,str1,str3,speedup,str2);
  119.     fflush(stderr);
  120. }
  121.  
  122.  
  123.  
  124.  
  125. /************************************************************************
  126. *
  127. * parse_args
  128. *
  129. * PURPOSE:  Sets encoding parameters to the specifications of the
  130. * command line.  Default settings are used for parameters
  131. * not specified in the command line.
  132. *
  133. * If the input file is in AIFF format, the sampling frequency is read
  134. * from the AIFF header.
  135. *
  136. * The input and output filenames are read into #inpath# and #outpath#.
  137. *
  138. ************************************************************************/
  139.  
  140. void
  141. parse_args(argc, argv, fr_ps, psy, num_samples, inPath, outPath)
  142. int     argc;
  143. char    **argv;
  144. frame_params  *fr_ps;
  145. int     *psy;
  146. unsigned long *num_samples;
  147. char    inPath[MAX_NAME_SIZE];
  148. char    outPath[MAX_NAME_SIZE];
  149. {
  150.    FLOAT srate;
  151.    int   brate;
  152.    layer *info = fr_ps->header;
  153.    int   err = 0, i = 0;
  154.    IFF_AIFF pcm_aiff_data;
  155.    long samplerate;
  156.    long soundPosition;
  157.    char ckwav[5]={0,0,0,0,0};
  158.  
  159.    /* preset defaults */
  160.    inPath[0] = '\0';   outPath[0] = '\0';
  161.    info->lay = DFLT_LAY;
  162.    switch(DFLT_MOD) {
  163.       case 's': info->mode = MPG_MD_STEREO; info->mode_ext = 0; break;
  164.       case 'd': info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; break;
  165.       case 'j': info->mode = MPG_MD_JOINT_STEREO; info->mode_ext=0; break;
  166.       case 'm': info->mode = MPG_MD_MONO; info->mode_ext = 0; break;
  167.       default:
  168.          fprintf(stderr, "%s: Bad mode dflt %c\n", programName, DFLT_MOD);
  169.          abort();
  170.    }
  171.    *psy = DFLT_PSY;
  172.    if((info->sampling_frequency = SmpFrqIndex((long)(1000*DFLT_SFQ), &info->version)) < 0) {
  173.       fprintf(stderr, "%s: bad sfrq default %.2f\n", programName, DFLT_SFQ);
  174.       abort();
  175.    }
  176.   info->bitrate_index = 9;
  177.   brate = 0;
  178.    switch(DFLT_EMP) {
  179.       case 'n': info->emphasis = 0; break;
  180.       case '5': info->emphasis = 1; break;
  181.       case 'c': info->emphasis = 3; break;
  182.       default: 
  183.          fprintf(stderr, "%s: Bad emph dflt %c\n", programName, DFLT_EMP);
  184.          abort();
  185.    }
  186.    info->copyright = 0;
  187.    info->original = 1;
  188.    info->error_protection = FALSE;
  189.  
  190.    /* process args */
  191.    while(++i<argc && err == 0) {
  192.       char c, *token, *arg, *nextArg;
  193.       int  argUsed;
  194.  
  195.       token = argv[i];
  196.       if(*token++ == '-') {
  197.          if(i+1 < argc) nextArg = argv[i+1];
  198.          else           nextArg = "";
  199.          argUsed = 0;
  200.      if (! *token) {
  201.        /* The user wants to use stdin and/or stdout. */
  202.        if(inPath[0] == '\0')       strcpy(inPath, argv[i]);
  203.        else if(outPath[0] == '\0') strcpy(outPath, argv[i]);
  204.      } 
  205.          while( (c = *token++) ) {
  206.             if(*token ) arg = token;
  207.             else                             arg = nextArg;
  208.             switch(c) {
  209.                case 'm':        argUsed = 1;
  210.                   if (*arg == 's')
  211.                     { info->mode = MPG_MD_STEREO; info->mode_ext = 0; }
  212.                   else if (*arg == 'd')
  213.                     { info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; }
  214.                   else if (*arg == 'j')
  215.                     { info->mode = MPG_MD_JOINT_STEREO; info->mode_ext=0; }
  216.                   else if (*arg == 'f')
  217.                     { info->mode = MPG_MD_JOINT_STEREO; force_ms=1; info->mode_ext=0; }
  218.                   else if (*arg == 'm')
  219.                     { info->mode = MPG_MD_MONO; info->mode_ext = 0; }
  220.                   else {
  221.                     fprintf(stderr,"%s: -m mode must be s/d/j/f/m not %s\n",
  222.                             programName, arg);
  223.                     err = 1;
  224.                   }
  225.                   break;
  226.                case 'V':        argUsed = 1;   VBR = 1;
  227.                   if (*arg == '0')
  228.                     { VBR_q=0; }
  229.                   else if (*arg == '1')
  230.                     { VBR_q=1; }
  231.                   else if (*arg == '2')
  232.                     { VBR_q=2; }
  233.                   else if (*arg == '3')
  234.                     { VBR_q=3; }
  235.                   else if (*arg == '4')
  236.                     { VBR_q=4; }
  237.                   else if (*arg == '5')
  238.                     { VBR_q=5; }
  239.                   else if (*arg == '6')
  240.                     { VBR_q=6; }
  241.                   else if (*arg == '7')
  242.                     { VBR_q=7; }
  243.                   else if (*arg == '8')
  244.                     { VBR_q=8; }
  245.                   else if (*arg == '9')
  246.                     { VBR_q=9; }
  247.                   else {
  248.                     fprintf(stderr,"%s: -V n must be 0-9 not %s\n",
  249.                             programName, arg);
  250.                     err = 1;
  251.                   }
  252.                   break;
  253.  
  254.                case 's':
  255.                   argUsed = 1;
  256.                   srate = atof( arg );
  257.                   /* samplerate = rint( 1000.0 * srate ); $A  */
  258.                   samplerate = (long) (( 1000.0 * srate ) + 0.5);
  259.                   if( (info->sampling_frequency =
  260.           SmpFrqIndex((long) samplerate, &info->version)) < 0 )
  261.                       err = 1;
  262.                   break;
  263.                   
  264.         case 'b':        
  265.          argUsed = 1;
  266.          brate = atoi(arg); 
  267.          break;
  268.             case 'x':  /* force byte swapping */
  269.           swapbytes=TRUE;
  270.           break;
  271.         case 'a': /* autoconvert input file from stereo to mono - for mono mp3 encoding */
  272.           autoconvert = TRUE;
  273.           break;
  274.         case 'h': 
  275.           highq = TRUE;
  276.           break;
  277.         case 'k': 
  278.           sfb21 = FALSE;
  279.           break;
  280.         case 'd': 
  281.           allow_diff_short = 1;
  282.           break;
  283.         case 'v': 
  284.           VBR = 1;
  285.           gpsycho=1;
  286.           break;
  287.         case 'S': 
  288.           silent = TRUE;
  289.           break;
  290.         case 'f': 
  291.           fast_mode = TRUE;
  292.           break;
  293.         case 'O': 
  294.           gpsycho = FALSE;
  295.           break;
  296. #ifdef HAVEGTK
  297.         case 'g': /* turn on gtk analysis */
  298.           gtkflag = TRUE;
  299. #endif
  300.           break;
  301.         case 'e':        argUsed = 1;
  302.                   if (*arg == 'n')                    info->emphasis = 0;
  303.                   else if (*arg == '5')               info->emphasis = 1;
  304.                   else if (*arg == 'c')               info->emphasis = 3;
  305.                   else {
  306.                      fprintf(stderr,"%s: -e emp must be n/5/c not %s\n",
  307.                              programName, arg);
  308.                      err = 1;
  309.                   }
  310.                   break;
  311.                 case 'c':       info->copyright = 1; break;
  312.                 case 'o':       info->original  = 0; break;
  313.                 default:        fprintf(stderr,"%s: unrec option %c\n",
  314.                                         programName, c);
  315.                                 err = 1; break;
  316.             }
  317.             if(argUsed) {
  318.                if(arg == token)    token = "";   /* no more from token */
  319.                else                ++i;          /* skip arg we used */
  320.                arg = ""; argUsed = 0;
  321.             }
  322.          }
  323.       }
  324.       else {
  325.          if(inPath[0] == '\0')       strcpy(inPath, argv[i]);
  326.          else if(outPath[0] == '\0') strcpy(outPath, argv[i]);
  327.          else {
  328.             fprintf(stderr,"%s: excess arg %s\n", programName, argv[i]);
  329.             err = 1;
  330.          }
  331.       }
  332.    }
  333.  
  334.    if(err || inPath[0] == '\0') usage();  /* never returns */
  335.  
  336.    if (inPath[0]=='-') silent=1;  /* turn off status - it's broken for stdin */
  337.  
  338.  
  339.    if(outPath[0] == '\0') {
  340.      if (inPath[0]=='-') {
  341.        /* if input is stdin, default output is stdout */
  342.        strcpy(outPath,"-");
  343.      }else {
  344.        strcpy(outPath, inPath);
  345.        strcat(outPath, DFLT_EXT);
  346.      }
  347.      
  348.    }
  349.  
  350. // SPECIAL FOR BLADE ENCODER
  351. #ifdef _BLADEDLL
  352.      open_bit_stream_w(&bs, outPath, BUFFER_SIZE);
  353. #else
  354.    original_file_type=!(strcmp((char *) &inPath[strlen(inPath)-4],".mp3"));
  355.  
  356.    if (original_file_type) {
  357.      /* MP3 file.  */
  358.      totalframes = -1;
  359.      original_file_fd = open(inPath,O_RDONLY);
  360.      if (original_file_fd == -1) {
  361.        fprintf(stderr,"Could not find \"%s\".\n", inPath);
  362.        exit(1);
  363.      }
  364.      if (!gtkflag) {
  365.        fprintf(stderr,"Use option -g to analyze mp3 files.\n");
  366.        exit(1);
  367.      }
  368.      
  369.    }
  370.    else {
  371.      if (!strcmp(inPath, "-")) {
  372.        /* Read from standard input. */
  373.        musicin = stdin;
  374.      } else {
  375.        if ((musicin = fopen(inPath, "rb")) == NULL) {
  376.      fprintf(stderr, "Could not find \"%s\".\n", inPath);
  377.      exit(1);
  378.        }
  379.      }
  380. #ifdef DISTRIB
  381.      outPath="/dev/null";
  382. #endif
  383.      open_bit_stream_w(&bs, outPath, BUFFER_SIZE);
  384.      if ((soundPosition = aiff_read_headers(musicin, &pcm_aiff_data)) != -1) {
  385.        
  386.        fprintf(stderr, "Found Audio IFF sound file headers: ");
  387.        
  388.        aiff_check(inPath, &pcm_aiff_data, &info->version);
  389.        
  390.        if (fseek(musicin, soundPosition, SEEK_SET) != 0) {
  391.      /*
  392.          fprintf(stderr, "Could not seek to PCM sound data in \"%s\".\n", inPath);
  393.          exit(1);
  394.      */
  395.      fprintf(stderr,"Could not seek to PCM sound data in \"%s\".\n",inPath);
  396.      fprintf(stderr,"Crossing Fingers.....\n");
  397.  
  398.        }
  399.        
  400.        info->sampling_frequency = SmpFrqIndex((long)pcm_aiff_data.sampleRate, &info->version);
  401.        fprintf(stderr, "%.1f kHz samples\n",
  402.            pcm_aiff_data.sampleRate/1000);
  403.        
  404.        /* Determine number of samples in sound file */
  405.        
  406.        *num_samples = (long)(pcm_aiff_data.numChannels) *
  407.      (long)(pcm_aiff_data.numSampleFrames);
  408.        
  409.        if ( pcm_aiff_data.numChannels == 1 ) {
  410.      info->mode = MPG_MD_MONO;
  411.      info->mode_ext = 0;
  412.        }
  413.      }
  414.      else {    /* Not using Audio IFF sound file headers. */
  415.        
  416.        if (fseek(musicin, 8, SEEK_SET) != 0) {
  417.      /*
  418.          fprintf(stderr, "Could not seek to PCM sound data in \"%s\".\n", inPath);
  419.          exit(1);
  420.      */
  421.      fprintf(stderr,"Could not seek to PCM sound data in \"%s\".\n",inPath);
  422.      fprintf(stderr,"Crossing Fingers.....\n");
  423.        }
  424.        
  425.        fread(ckwav, 4, 1, musicin);
  426.        if (strncmp(ckwav, "WAVE",4)==0) {
  427.      iswav = 1;
  428.      fseek(musicin, 0x2c, SEEK_SET); /* skip wav file header */
  429.      /* NO PARSING OF WAV HEADERS YET */
  430.      fprintf(stderr, "%s : Found WAV header. Assuming 44.1khz 16bit stereo samples\n",ckwav);
  431.        }
  432.        else {
  433.      fseek(musicin, 0, SEEK_SET);
  434.      fprintf(stderr, "Assuming raw pcm input file");
  435.      if (swapbytes==TRUE)
  436.        fprintf(stderr, " : Forcing byte-swapping\n");
  437.      else
  438.        fprintf(stderr, "\n");
  439.        }
  440.        
  441.        /* Declare sound file to have "infinite" number of samples. */
  442.        *num_samples = MAX_U_32_NUM;
  443.      }
  444.      /* Timing, autoconvert and resampling checks and setup */
  445.      stat(inPath,&sb);
  446.      totalframes = sb.st_size/4608;
  447.      if ((info->mode == MPG_MD_MONO)&&(autoconvert==FALSE))
  448.        totalframes *= 2;
  449.      if (autoconvert==TRUE) {
  450.        fprintf(stderr, "Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
  451.        info->mode = MPG_MD_MONO; 
  452.        info->mode_ext = 0;
  453.      }
  454.    }
  455. #endif // END OF BLADE ENCODER SPECIAL
  456.    
  457.    if ( brate == 0 ) {
  458.      if (VBR) brate = bitrate[info->version][info->lay-1][8];
  459.      else  brate = bitrate[info->version][info->lay-1][9];
  460.    }
  461.    if( (info->bitrate_index = BitrateIndex(info->lay, brate, info->version)) < 0)
  462.        err=1;
  463.    if(err || inPath[0] == '\0') usage();  /* never returns */
  464.    target_bitrate = info->bitrate_index;
  465.    if (info->bitrate_index==14) VBR=0;  /* dont bother with VBR at 320kbs */
  466. }
  467.  
  468. /************************************************************************
  469.  *
  470.  * print_config
  471.  *
  472.  * PURPOSE:  Prints the encoding parameters used
  473.  *
  474.  ************************************************************************/
  475.  
  476. void print_config( frame_params *fr_ps, int *psy, char *inPath, char *outPath)
  477. {
  478.   layer *info = fr_ps->header;
  479. #if 0 
  480.   fprintf(stderr, "Encoding configuration:\n");
  481.   fprintf(stderr, "Algorithm=%s\n", version_names[info->version]);
  482.   if(info->mode != MPG_MD_JOINT_STEREO)
  483.     fprintf(stderr, "Layer=III   mode=%s   extn=%d   psy model=%d\n",
  484.         mode_names[info->mode], info->mode_ext, *psy);
  485.   else fprintf(stderr, "Layer=III   mode=%s   extn=data dependant   psy model=%d\n",
  486.            mode_names[info->mode], *psy);
  487.   fprintf(stderr, "samp frq=%.1f kHz   total bitrate=%d kbps\n",
  488.       s_freq[info->version][info->sampling_frequency],
  489.       bitrate[info->version][info->lay-1][info->bitrate_index]);
  490.   fprintf(stderr, "de-emph=%d   c/right=%d   orig=%d\n",
  491.       info->emphasis, info->copyright, info->original);
  492.   fprintf(stderr, "input file: '%s'   output file: '%s'\n", inPath, outPath);
  493. #endif
  494.   if (original_file_type) {
  495.     fprintf(stderr, "Analyzing %s \n",inPath);
  496.   }
  497.   else {
  498.     fprintf(stderr, "Encoding %s to %s\n",
  499.         (strcmp(inPath, "-")? inPath : "stdin"),
  500.         (strcmp(outPath, "-")? outPath : "stdout"));
  501.     if (VBR)
  502.       fprintf(stderr, "Encoding as %.1f kHz VBR(min: %d kbps) %s MPEG-1 LayerIII file\n",
  503.           s_freq[info->version][info->sampling_frequency],
  504.           bitrate[info->version][info->lay-1][info->bitrate_index],
  505.           mode_names[info->mode]);
  506.     else
  507.       fprintf(stderr, "Encoding as %.1f kHz %d kbps %s MPEG-1 LayerIII file\n",
  508.           s_freq[info->version][info->sampling_frequency],
  509.           bitrate[info->version][info->lay-1][info->bitrate_index],
  510.           mode_names[info->mode]);
  511.   }
  512. }
  513.  
  514.  
  515. #ifdef HAVEGTK
  516. int readframe()
  517. {
  518.   int j,ch,stereo,out=0;
  519.   short mpg123pcm[2][1152];
  520.   static int frameNum=0;
  521.  
  522.   stereo = fr_ps.stereo;
  523.   frameNum++;
  524.  
  525.   /* create a 1 frame lag so MP3 analysis syncs with WAV analysis */
  526.   if (frameNum == 1 ) out=1152;
  527.   else out=decode1file(original_file_fd,mpg123pcm,stereo);
  528.  
  529.  
  530.   /* delay pcm data by yet another frame */
  531.   for ( ch = 0; ch < stereo; ch++ ) {
  532.     for ( j = 0; j < DECDELAY; j++ )
  533.       pinfo->pcmdata2[ch][j] = pinfo->pcmdata2[ch][j+1152];
  534.     for ( j = 0; j < 1152; j++ ) {
  535.       pinfo->pcmdata2[ch][j+DECDELAY] = mpg123pcm[ch][j];
  536.     }
  537.   }
  538.   MPGLAG = 2;
  539.   pinfo->frameNum = frameNum;
  540.   pinfo->mpglag = MPGLAG;
  541.   return out;
  542. }
  543. #endif
  544.  
  545.  
  546.  
  547.  
  548. int makeframe()
  549. {
  550.   static unsigned long frameBits, sentBits = 0;
  551.   static unsigned long bitsPerSlot;
  552.   static double frac_SpF;
  553.   static double slot_lag;
  554.   static int mode_gr;
  555.   static int mpg123count=0;
  556.  
  557.   int j,ch,gr,mean_bits;
  558.   double xr[2][2][576];
  559.   double xr_dec[2][2][576];
  560.   double pe[2][2];
  561.   double pe3[2];
  562.   int l3_enc[2][2][576];
  563.   III_psy_ratio ratio,ratio3;
  564.   III_scalefac_t scalefac;
  565.   int blocktype[2];
  566.   int blocktype3[2];
  567.   int bitsPerFrame;
  568.   short *win_buf[2];
  569.   double win_que[2][HAN_SIZE];
  570.   int stereo;
  571.   int iread;
  572.   layer *info;
  573.   int i;
  574.  
  575. #ifdef HAVEGTK
  576.   char mpg123bs[BUFFER_SIZE];
  577.   short mpg123pcm[2][1152];
  578. #endif
  579.   int check_ms_stereo;
  580.   int bit_rate;
  581.   double samp;
  582.   double ms_ener_ratio[2];
  583.  
  584.  
  585.   stereo = fr_ps.stereo;
  586.   info = fr_ps.header;
  587. #ifdef HAVEGTK
  588.   if (gtkflag) {
  589.     pinfo->frameNum = frameNum;
  590.     pinfo->sampfreq=s_freq[info->version][info->sampling_frequency]*1000.0;
  591.   }
  592. #endif
  593.  
  594.   info->mode_ext = 0; 
  595.  
  596.   /* use m/s stereo? */
  597.   check_ms_stereo =   ((info->mode == MPG_MD_JOINT_STEREO) && 
  598.                (!force_ms) &&
  599.                (stereo==2) &&
  600.                (gpsycho));
  601.  
  602.   info->bitrate_index = target_bitrate;
  603.   bit_rate = bitrate[info->version][info->lay-1][info->bitrate_index];
  604.   samp =      s_freq[info->version][info->sampling_frequency];
  605.   
  606.   if (firstcall)  {    
  607.     double avg_slots_per_frame;
  608.     unsigned long samplesPerFrame;
  609.     int whole_SpF;
  610.     firstcall = 0;
  611.     mpg123count=0;
  612.  
  613.  
  614.     /* Figure average number of 'slots' per frame. */
  615.     /* Bitrate means TOTAL for both channels, not per side. */
  616.     bitsPerSlot = 8;
  617.     samplesPerFrame = info->version == 1 ? 1152 : 576;
  618.     avg_slots_per_frame = ((double)samplesPerFrame /samp) *
  619.       ((double)bit_rate /  (double)bitsPerSlot);
  620.     whole_SpF = (int) avg_slots_per_frame;
  621.     frac_SpF  = avg_slots_per_frame - (double)whole_SpF;
  622.     slot_lag  = -frac_SpF;
  623.     info->padding = 1;
  624.     if (fabs(frac_SpF) < 1e-9) info->padding = 0;
  625.     mode_gr = (info->version == 1) ? 2 : 1;  /* mode_gr = 2 */
  626.     if (mode_gr != 2) exit(-99);
  627.  
  628.     #ifndef _BLADEDLL
  629.         // AF, modified this code, so it will read to first samples into the lower halve of 
  630.         // the buffer, this way it is easier to support the _BLADEDLL hack
  631.         iread = get_audio(musicin,&BigBuf[0][0],&BigBuf[1][0],num_samples,fr_ps.stereo,fr_ps.header);
  632.     #else
  633.         // Don't read the data, it is already in the BugBuf
  634.         {
  635.         extern int nBladeBufferSize;
  636.         iread=nBladeBufferSize;
  637.         }
  638.     #endif
  639.  
  640.     /* we are still working with short int, so we cannot devide by
  641.     * sqrt(2) (overflow).  divide by 2, rescale later */
  642.     if (force_ms)
  643.     {
  644.         // AF: Correct the lower halve of the buffer, instead of the upper halve
  645.         for (i=0; i< 1152; i++)
  646.         {
  647.             double mid = (BigBuf[0][i]+BigBuf[1][i])/(2.0);
  648.             double side= (BigBuf[0][i]-BigBuf[1][i])/(2.0);
  649.             BigBuf[0][i]=mid;
  650.             BigBuf[1][i]=side;
  651.  
  652.         }
  653.     }
  654.   }
  655. #ifndef _BLADEDLL
  656.   else
  657.   {
  658.     // AF: If not the first call, do shift the data
  659.     // Shift the data from the upper halve of the BigBuf to to lower halve
  660.     for (ch=0; ch<2; ch++)
  661.         for (i=0; i<1152; i++)
  662.             BigBuf[ch][i]=BigBuf[ch][i+1152];
  663.   }
  664.     // Read the sam
  665.     iread = get_audio(musicin,&BigBuf[0][1152],&BigBuf[1][1152],num_samples,fr_ps.stereo,fr_ps.header);
  666. #else
  667.     {
  668.     // Don't read the data, it is already in the BugBuf
  669.     extern int nBladeBufferSize;
  670.     iread=nBladeBufferSize;
  671.     }
  672. #endif
  673.  
  674.  
  675.  
  676.   /********************** padding *****************************/
  677.   if (VBR) {
  678.   /* leave info_padding as it was set above */
  679.   } else {
  680.     if (frac_SpF != 0) {
  681.       if (slot_lag > (frac_SpF-1.0) ) {
  682.     slot_lag -= frac_SpF;
  683.     info->padding = 0;
  684.       }
  685.       else {
  686.     info->padding = 1;
  687.     slot_lag += (1-frac_SpF);
  688.       }
  689.     }
  690.   }
  691.  
  692.  
  693.  
  694.  
  695.  
  696.   /********************** process InputBuffer *****************************/
  697.   frameNum++;
  698.  
  699.   if (force_ms)
  700.     for (i=0; i< 1152; i++) {
  701.       double mid = (BigBuf[0][1152+i]+BigBuf[1][1152+i])/(2.0);
  702.       double side= (BigBuf[0][1152+i]-BigBuf[1][1152+i])/(2.0);
  703.       BigBuf[0][1152+i]=mid;
  704.       BigBuf[1][1152+i]=side;
  705.     }
  706.  
  707.   if (frameNum%10==0 && !gtkflag && !silent) {
  708.     timestatus(frameNum,totalframes,s_freq[info->version][info->sampling_frequency]);
  709.   }
  710.  
  711.   
  712.   /***************************** Layer 3 **********************************/
  713.   win_buf[0] = &BigBuf[0][0];
  714.   win_buf[1] = &BigBuf[1][0];
  715.  
  716.   
  717.   if (!fast_mode) {  
  718.   /* psychoacoustic model */
  719.   /* this mess will be cleaned up in the future.  It is coded like this
  720.    * to maintain original ISO and GPSYCHO psy-models
  721.    */
  722.   short int *bufp[2];  /* address of beginninf of left & right granule */
  723.   gr = 0;  
  724.   if (frameNum ==1 ) {
  725.     /* prime the psy-model pump */
  726.     for ( ch = 0; ch < stereo; ch++ ) 
  727.       bufp[ch]=&BigBuf[ch][gr*576];
  728.     L3psycho_anal( bufp,stereo,gr, info,
  729.            s_freq[info->version][info->sampling_frequency] * 1000.0,
  730.            check_ms_stereo,&ms_ener_ratio[0],
  731.            ratio.l[gr], ratio.s[gr],
  732.            pe[gr], blocktype);
  733.     if (!gpsycho) {
  734.       for ( ch = 0; ch < stereo; ch++ ) 
  735.     l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
  736.     }
  737.   } else {
  738.     if (!gpsycho){
  739.       memcpy(&ratio,&ratio3,sizeof(ratio));
  740.       for ( ch = 0; ch < stereo; ch++ ) {
  741.     pe[gr][ch]=pe3[ch];
  742.     l3_side.gr[0].ch[ch].tt.block_type=blocktype3[ch];
  743.       }
  744.     }
  745.   }
  746.  
  747.   gr = 1;  
  748.   for ( ch = 0; ch < stereo; ch++ ) 
  749.     bufp[ch]=&BigBuf[ch][gr*576];
  750.   L3psycho_anal( bufp, stereo,gr, info,
  751.          s_freq[info->version][info->sampling_frequency] * 1000.0,
  752.          check_ms_stereo,&ms_ener_ratio[0],
  753.          ratio.l[gr], ratio.s[gr],
  754.          pe[gr], blocktype);
  755.   for ( ch = 0; ch < stereo; ch++ ) {
  756.     if (gpsycho) {
  757.       /* data returned for gr=0: memcpy */
  758.       pe[0][ch]=pe[1][ch];
  759.       memcpy(&ratio.l[0][ch][0],&ratio.l[1][ch][0],sizeof(ratio.l[gr][ch]));
  760.       memcpy(&ratio.s[0][ch][0],&ratio.s[1][ch][0],sizeof(ratio.s[gr][ch]));
  761.       l3_side.gr[0].ch[ch].tt.block_type=blocktype[ch];
  762.     } else {
  763.       l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
  764.     }
  765.   }
  766.   /* do a third call */
  767.   gr = 0;  
  768.   for ( ch = 0; ch < stereo; ch++ ) 
  769.     bufp[ch]=&BigBuf[ch][1152 + gr*576];
  770.   L3psycho_anal( bufp, stereo,gr, info,
  771.          s_freq[info->version][info->sampling_frequency] * 1000.0,
  772.          check_ms_stereo,&ms_ener_ratio[1],
  773.          ratio3.l[gr], ratio3.s[gr],
  774.          pe3, blocktype3);
  775.   for ( ch = 0; ch < stereo; ch++ ) {
  776.     if (gpsycho) {
  777.       /* data returned for gr=1, prev. frame.  memcpy */
  778.       pe[1][ch]=pe3[ch];
  779.       memcpy(&ratio.l[1][ch][0],&ratio3.l[0][ch][0],sizeof(ratio3.l[0][ch]));
  780.       memcpy(&ratio.s[1][ch][0],&ratio3.s[0][ch][0],sizeof(ratio3.s[0][ch]));
  781.       l3_side.gr[1].ch[ch].tt.block_type=blocktype3[ch];
  782.     }
  783.   }
  784.   }
  785.  
  786.   /* block type flags */
  787.   for( gr = 0; gr < mode_gr; gr++ ) {
  788.     for ( ch = 0; ch < stereo; ch++ ) {
  789.       gr_info *cod_info = &l3_side.gr[gr].ch[ch].tt;
  790.       cod_info->mixed_block_flag = 0;     /* never used by this model */
  791.       if (cod_info->block_type == NORM_TYPE )
  792.     cod_info->window_switching_flag = 0;
  793.       else
  794.     cod_info->window_switching_flag = 1;
  795.     }
  796.   }
  797.  
  798.   
  799.   /* polyphase filtering  */
  800.   for( gr = 0; gr < mode_gr; gr++ )
  801.     for ( ch = 0; ch < stereo; ch++ )
  802.       for ( j = 0; j < 18; j++ )   {
  803.     window_subband( &win_buf[ch], &win_que[ch][0], ch );
  804.     filter_subband( &win_que[ch][0],  &(l3_sb_sample)[ch][gr+1][j][0] ); }
  805.   
  806.   /* apply mdct to the polyphase outputs */
  807.   mdct_sub( &l3_sb_sample, xr, stereo, &l3_side, mode_gr );
  808.  
  809.  
  810.   /* data was scaled by 1/2.  fix so effectively it was scaled by 1/sqrt(2) */
  811.   if (force_ms) {
  812.     for ( gr = 0; gr < mode_gr; gr++ )
  813.       for ( ch = 0; ch < stereo; ch++ ) 
  814.     for (i =0 ; i< 576; i++) 
  815.       xr[gr][ch][i] *= sqrt(2.0);
  816.   }
  817.  
  818.  
  819.   if (check_ms_stereo) {
  820.     /* make sure block type is the same in each channel */
  821.     check_ms_stereo = 
  822.       (l3_side.gr[0].ch[0].tt.block_type==l3_side.gr[0].ch[1].tt.block_type) &&
  823.       (l3_side.gr[1].ch[0].tt.block_type==l3_side.gr[1].ch[1].tt.block_type);
  824.   }
  825.  
  826.   if (check_ms_stereo) {
  827.     if ((ms_ener_ratio[0]+ms_ener_ratio[1])<.7 ) info->mode_ext = 2;
  828.   }
  829.  
  830. #ifdef HAVEGTK
  831.   if (gtkflag) { 
  832.     for ( gr = 0; gr < mode_gr; gr++ )
  833.       for ( ch = 0; ch < stereo; ch++ ) {
  834.     pinfo->ms_ratio[gr]=ms_ener_ratio[gr];
  835.     pinfo->blocktype[gr][ch]=
  836.       l3_side.gr[gr].ch[ch].tt.block_type;
  837.     for ( j = 0; j < 576; j++ ) pinfo->xr[gr][ch][j]=xr[gr][ch][j];
  838.       }
  839.   }
  840. #endif
  841.  
  842.   
  843.   /* bit and noise allocation */
  844.   iteration_loop( pe, ms_ener_ratio, xr, &ratio, &l3_side, l3_enc, 
  845.      xr_dec, &scalefac, &fr_ps);
  846.  
  847.  
  848.   /* flag for our ms_stereo with psy-model on mid & side channels */
  849.   if (force_ms) info->mode_ext = 2;
  850.  
  851.  
  852.   /*  write the frame to the bitstream  */
  853.   getframebits(info,stereo,&bitsPerFrame,&mean_bits);
  854.   III_format_bitstream( bitsPerFrame, &fr_ps, l3_enc, &l3_side, 
  855.             &scalefac, &bs, xr, NULL, 0 );
  856.  
  857.  
  858.   frameBits = sstell( &bs ) - sentBits;
  859.  
  860.   
  861.   if ( frameBits % bitsPerSlot )   /* a program failure */
  862.     fprintf( stderr, "Sent %ld bits = %ld slots plus %ld\n",
  863.          frameBits, frameBits/bitsPerSlot,
  864.          frameBits%bitsPerSlot );
  865.   sentBits += frameBits;
  866.  
  867.  
  868. #ifdef HAVEGTK
  869.   /* copy bit buffer into array and send to mpg123 to synthesis the pcm data */
  870.   if (gtkflag) { 
  871.     mpg123count=0;
  872.     for (i=bs.buf_size-1 ; i > bs.buf_byte_idx ; (i-- ))
  873.       mpg123bs[mpg123count++]=bs.buf[i];
  874.     /* re-synthesize pcm data from mp3 frame */
  875.     if (!decode1(mpg123bs,mpg123count,&mpg123pcm,stereo)) {
  876.       if (MPGLAG == MAXMPGLAG) 
  877.     fprintf(stderr, "MAXMPGLAG set too low.  The following frames will be mis-aligned \n");
  878.       else MPGLAG+=1; 
  879.     }
  880.     pinfo->mpglag = MPGLAG;
  881.   }
  882.  
  883.   /* empty data from bit buffer into mp3 file  */
  884.   empty_buffer(&bs, 1+bs.buf_byte_idx);
  885.   bs.buf[bs.buf_byte_idx] = 0;  
  886.   
  887.   if (gtkflag) { 
  888.     for ( ch = 0; ch < stereo; ch++ ) {
  889.       for ( j = 0; j < WINDELAY; j++ )
  890.     pinfo->pcmdata[ch][j] = pinfo->pcmdata[ch][j+1152];
  891.       for ( j = 0; j < 1152; j++ ) {
  892.     pinfo->pcmdata[ch][j+WINDELAY] = BigBuf[ch][j];
  893.       }
  894.     }
  895.     for ( ch = 0; ch < stereo; ch++ ) {
  896.       for ( j = 0; j < DECDELAY; j++ )
  897.     pinfo->pcmdata2[ch][j] = pinfo->pcmdata2[ch][j+1152];
  898.       for ( j = 0; j < 1152; j++ ) {
  899.     pinfo->pcmdata2[ch][j+DECDELAY] = mpg123pcm[ch][j];
  900.       }
  901.     }
  902.     pinfo->frameNum = frameNum;
  903.   }
  904. #endif
  905.   return iread/stereo;
  906. }
  907.  
  908. /************************************************************************
  909. *
  910. * main
  911. *
  912. * PURPOSE:  MPEG-1 Layer III encoder, with
  913. * psychoacoustic models ISO-2 (AT&T) and GPSYCHO
  914. *
  915. * SEMANTICS:  One overlapping frame of audio of up to 2 channels are
  916. * processed at a time in the following order:
  917. * (associated routines are in parentheses)
  918. *
  919. * 1.  Filter sliding window of data to get 32 subband
  920. * samples per channel.
  921. * (window_subband,filter_subband)
  922. *
  923. * 2.  Calculate scalefactors for the frame, and if layer 2,
  924. * also calculate scalefactor select information.
  925. * (*_scale_factor_calc)
  926. *
  927. * 3.  Calculate psychoacoustic masking levels using selected
  928. * psychoacoustic model.
  929. * (*_Psycho_One, psycho_anal)
  930. *
  931. * 4.  Perform iterative bit allocation for subbands with low
  932. * mask_to_noise ratios using masking levels from step 4.
  933. * (*_main_bit_allocation)
  934. *
  935. * 5.  Pack bit allocation and scalefactors onto bitstream.
  936. * (*_encode_bit_alloc,*_encode_scale)
  937. *
  938. * 6.  Quantize subbands and pack them into bitstream
  939. * (*_subband_quantization, *_sample_encoding)
  940. *
  941. ************************************************************************/
  942.  
  943.  
  944.  
  945. int main(argc, argv)
  946. int     argc;
  947. char    **argv;
  948. {
  949.     
  950.     char original_file_name[MAX_NAME_SIZE];
  951.     char encoded_file_name[MAX_NAME_SIZE];
  952.     int model, stereo;
  953.     layer info;
  954.     char lpszVersion[80];
  955.  
  956. #ifdef HAVEGTK
  957.     gtk_init (&argc, &argv);
  958. #endif
  959. #ifdef __FreeBSD__
  960.   {
  961.   fp_except_t mask;
  962.   mask=fpgetmask();
  963.   /*  printf("FreeBSD mask is 0x%x\n",mask); */
  964.   }
  965. #endif
  966. #ifdef linux
  967.   {
  968.   unsigned int mask;
  969.   _FPU_GETCW(mask);
  970.   /* Set the Linux mask to the FreeBSD default mask */
  971.   mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM );
  972.   _FPU_SETCW(mask);
  973.   }
  974. #endif
  975.  
  976.     /* clear buffers */
  977.     memset((char *) BigBuf, 0, sizeof(BigBuf));
  978.     memset((char *) snr32, 0, sizeof(snr32));
  979.  
  980.     // Clear info structure
  981.     memset(&info,0,sizeof(info));
  982.  
  983.     fr_ps.header = &info;
  984.     fr_ps.tab_num = -1;             /* no table loaded */
  985.     fr_ps.alloc = NULL;
  986.     info.version = MPEG_AUDIO_ID;   /* =1   Default: MPEG-1 */
  987.     info.extension = 0;       
  988.  
  989.     /* get version string */
  990.     if (gpsycho && !original_file_type)
  991.         fprintf(stderr,"LAME version %s (www.sulaco.org/mp3) \n",get_lame_version(lpszVersion));
  992.  
  993.  
  994.     programName = argv[0];
  995.     if(argc==1)     /* no command-line args 
  996.        obtain_parameters(&fr_ps, &model, &num_samples,
  997.                          original_file_name, encoded_file_name);*/
  998.       usage();
  999.     else
  1000.     parse_args(argc, argv, &fr_ps, &model, &num_samples,
  1001.            original_file_name, encoded_file_name);
  1002.     print_config(&fr_ps, &model,
  1003.                  original_file_name, encoded_file_name);
  1004.     
  1005.     hdr_to_frps(&fr_ps);
  1006.     stereo = fr_ps.stereo;
  1007.     if (gpsycho && !original_file_type) fprintf(stderr,
  1008.      "using GPSYCHO: GPL'd psycho-acoustic model \n");
  1009.  
  1010. #ifdef HAVEGTK
  1011.     if (gtkflag) gtkcontrol(totalframes,original_file_type,original_file_name,gpsycho); 
  1012.     else 
  1013. #endif
  1014.     while (makeframe());
  1015.  
  1016.     /* clean up if we were analyzing a wav file */
  1017.     if (!original_file_type) {
  1018.       if ( info.lay == 3 ) III_FlushBitstream();
  1019.       close_bit_stream_w( &bs );
  1020.       
  1021.       if (fclose(musicin) != 0){
  1022.     fprintf(stderr, "Could not close \"%s\".\n", original_file_name);
  1023.     exit(2);
  1024.       }
  1025.       frameNum--;
  1026.       timestatus(frameNum,frameNum,s_freq[info.version][info.sampling_frequency]);
  1027.       fprintf(stderr,"\n");
  1028.     }
  1029.     fflush(stderr);
  1030.     exit(0);
  1031. }
  1032.  
  1033. /************************************************************************
  1034. *
  1035. * usage
  1036. *
  1037. * PURPOSE:  Writes command line syntax to the file specified by #stderr#
  1038. *
  1039. ************************************************************************/
  1040.  
  1041. void usage()  /* print syntax & exit */
  1042. {
  1043.   fprintf(stderr,"        LAMER Ain't an Mp3 Encoder (Reconstruction-iso)\n");
  1044.   fprintf(stderr,"        version %s\n",get_lame_version());
  1045.   fprintf(stderr,"        with GPSYCHO psycho-acoustic model (version %s). \n\n",get_psy_version());
  1046.   fprintf(stderr,"USAGE   :  %s [options] <infile> <outfile>\n",programName);
  1047.   fprintf(stderr,"OPTIONS :\n");
  1048.   fprintf(stderr,"          -m mode         (s)tereo, (j)oint, (f)orce or (m)ono  (default %c)\n",DFLT_MOD);
  1049.   fprintf(stderr,"                          force = force ms_stereo on all frames. Faster and\n");
  1050.   fprintf(stderr,"                          uses special Mid & Side masking thresholds\n");
  1051.   fprintf(stderr,"          -s sample freq  frequency of input file (kHz) - default %4.1f\n",DFLT_SFQ);
  1052.   fprintf(stderr,"          -b <bitrate>    set the bitrate, default 128kbps\n");
  1053.   fprintf(stderr,"                          (for VBR, this sets the minimum bitrate)\n");
  1054.   fprintf(stderr,"          -x              force byte-swapping of input\n");
  1055.   fprintf(stderr,"          -a              downmix from stereo to mono file for mono encoding\n");
  1056.   fprintf(stderr,"          -e emp          de-emphasis n/5/c        (default %4c)\n",DFLT_EMP);
  1057.   fprintf(stderr,"          -c              mark as copyright\n");
  1058.   fprintf(stderr,"          -o              mark as non-original\n");
  1059.   fprintf(stderr,"          -f              fast mode (low quality)\n");
  1060.   fprintf(stderr,"          -k              disable sfb=21 cutoff\n");
  1061.   fprintf(stderr,"          -d              allow channels to have different blocktypes\n");
  1062.   fprintf(stderr,"          -v              use variable bitrate (VBR)\n");
  1063.   fprintf(stderr,"          -V n            quality setting for VBR.  default n=%i\n",VBR_q);
  1064.   fprintf(stderr,"                          0=high quality,bigger files. 9=smaller files\n");
  1065.   fprintf(stderr,"          -h              use (maybe) some experimental quality improvements\n");
  1066. #ifdef HAVEGTK
  1067.   fprintf(stderr,"          -g              run graphical analysis on <infile>\n");
  1068. #endif
  1069.   fprintf(stderr,"          -S              don't print progress report\n");
  1070.   fprintf(stderr,"          -O              use original (buggy) ISO psycho-acoustic model \n");
  1071.   fprintf(stderr,"\n<infile> and/or <outfile> can be \"-\", which means stdin/stdout.\n");
  1072.  
  1073.   exit(1);
  1074. }
  1075.  
  1076. /************************************************************************
  1077. *
  1078. * aiff_check
  1079. *
  1080. * PURPOSE:  Checks AIFF header information to make sure it is valid.
  1081. *           Exits if not.
  1082. *
  1083. ************************************************************************/
  1084.  
  1085. void aiff_check( char *file_name, IFF_AIFF *pcm_aiff_data, int *version)
  1086. {
  1087.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  1088.        fprintf(stderr, "Sound data is not PCM in \"%s\".\n", file_name);
  1089.        exit(1);
  1090.     }
  1091.  
  1092.     if(SmpFrqIndex((long)pcm_aiff_data->sampleRate, version) < 0) {
  1093.        fprintf(stderr, "in \"%s\".\n", file_name);
  1094.        exit(1);
  1095.     }
  1096.  
  1097.     if (pcm_aiff_data->sampleSize != sizeof(short) * BITS_IN_A_BYTE) {
  1098.         fprintf(stderr, "Sound data is not %d bits in \"%s\".\n",
  1099.         sizeof(short) * BITS_IN_A_BYTE, file_name);
  1100.         exit(1);
  1101.     }
  1102.  
  1103.     if (pcm_aiff_data->numChannels != MONO &&
  1104.         pcm_aiff_data->numChannels != STEREO) {
  1105.        fprintf(stderr, "Sound data is not mono or stereo in \"%s\".\n",
  1106.            file_name);
  1107.        exit(1);
  1108.     }
  1109.  
  1110.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  1111.        fprintf(stderr, "Block size is not %d bytes in \"%s\".\n",
  1112.            0, file_name);
  1113.        exit(1);
  1114.     }
  1115.  
  1116.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  1117.        fprintf(stderr, "Block offset is not %d bytes in \"%s\".\n",
  1118.            0, file_name);
  1119.        exit(1);
  1120.     }
  1121. }
  1122.  
  1123.