get_audio.c

Go to the documentation of this file.
00001 /*
00002  *      Get Audio routines source file
00003  *
00004  *      Copyright (c) 1999 Albert L Faber
00005  *
00006  * This library is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2 of the License, or (at your option) any later version.
00010  *
00011  * This library is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Library General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with this library; if not, write to the
00018  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00019  * Boston, MA 02111-1307, USA.
00020  */
00021 
00022 /* $Id: get_audio.c,v 1.114 2007/07/28 00:41:46 robert Exp $ */
00023 
00024 
00025 #ifdef HAVE_CONFIG_H
00026 # include <config.h>
00027 #endif
00028 
00029 #include <assert.h>
00030 
00031 #ifdef HAVE_LIMITS_H
00032 # include <limits.h>
00033 #endif
00034 
00035 #include <stdio.h>
00036 
00037 #ifdef STDC_HEADERS
00038 # include <stdlib.h>
00039 # include <string.h>
00040 #else
00041 # ifndef HAVE_STRCHR
00042 #  define strchr index
00043 #  define strrchr rindex
00044 # endif
00045 char   *strchr(), *strrchr();
00046 # ifndef HAVE_MEMCPY
00047 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
00048 #  define memmove(d, s, n) bcopy ((s), (d), (n))
00049 # endif
00050 #endif
00051 
00052 
00053 #define         MAX_U_32_NUM            0xFFFFFFFF
00054 
00055 
00056 #include <math.h>
00057 #include <sys/stat.h>
00058 
00059 #ifdef __sun__
00060 /* woraround for SunOS 4.x, it has SEEK_* defined here */
00061 #include <unistd.h>
00062 #endif
00063 
00064 #include "lame.h"
00065 #include "main.h"
00066 #include "get_audio.h"
00067 #include "portableio.h"
00068 #include "timestatus.h"
00069 #include "lametime.h"
00070 #include "console.h"
00071 
00072 #ifdef WITH_DMALLOC
00073 #include <dmalloc.h>
00074 #endif
00075 
00076 
00077 /* global data for get_audio.c. */
00078 int     count_samples_carefully;
00079 int     pcmbitwidth;
00080 int     pcmswapbytes = 0;
00081 unsigned int num_samples_read;
00082 FILE   *musicin;
00083 
00084 
00085 #ifdef AMIGA_MPEGA
00086 int     lame_decode_initfile(const char *fullname, mp3data_struct * const mp3data);
00087 #else
00088 int     lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding);
00089 #endif
00090 
00091 /* read mp3 file until mpglib returns one frame of PCM data */
00092 int     lame_decode_fromfile(FILE * fd, short int pcm_l[], short int pcm_r[],
00093                              mp3data_struct * mp3data);
00094 
00095 
00096 static int read_samples_pcm(FILE * musicin, int sample_buffer[2304],
00097                             int frame_size, int samples_to_read);
00098 static int read_samples_mp3(lame_global_flags * const gfp, FILE * const musicin,
00099                             short int mpg123pcm[2][1152], int num_chan);
00100 void    CloseSndFile(sound_file_format input, FILE * musicin);
00101 FILE   *OpenSndFile(lame_global_flags * gfp, char *, int *enc_delay, int *enc_padding);
00102 
00103 
00104 /* Replacement for forward fseek(,,SEEK_CUR), because fseek() fails on pipes */
00105 
00106 
00107 static int
00108 fskip(FILE * fp, long offset, int whence)
00109 {
00110 #ifndef PIPE_BUF
00111     char    buffer[4096];
00112 #else
00113     char    buffer[PIPE_BUF];
00114 #endif
00115     int     read;
00116 
00117 /* S_ISFIFO macro is defined on newer Linuxes */
00118 #ifndef S_ISFIFO
00119 # ifdef _S_IFIFO
00120                 /* _S_IFIFO is defined on Win32 and Cygwin */
00121 #  define       S_ISFIFO(m)     (((m)&_S_IFIFO) == _S_IFIFO)
00122 # endif
00123 #endif
00124 
00125 #ifdef S_ISFIFO
00126     /* fseek is known to fail on pipes with several C-Library implementations
00127        workaround: 1) test for pipe
00128                    2) for pipes, only relatvie seeking is possible
00129                    3)            and only in forward direction!
00130                    else fallback to old code
00131     */
00132     {
00133         int const fd = fileno(fp);
00134         struct stat    file_stat;
00135 
00136         if (fstat(fd, &file_stat) == 0) {
00137             if (S_ISFIFO(file_stat.st_mode)) {
00138                 if (whence != SEEK_CUR || offset < 0) {
00139                     return -1;
00140                 }
00141                 while (offset > 0) {
00142                     size_t const bytes_to_skip = Min(sizeof(buffer), offset);
00143                     size_t const read = fread(buffer, 1, bytes_to_skip, fp);
00144                     if (read < 1) {
00145                         return -1;
00146                     }
00147                     offset -= read;
00148                 }
00149                 return 0;
00150             }
00151         }
00152     }
00153 #endif
00154     if (0 == fseek(fp, offset, whence)){
00155         return 0;
00156     }
00157 
00158     if (whence != SEEK_CUR || offset < 0) {
00159         if (silent < 10) {
00160             error_printf
00161                 ("fskip problem: Mostly the return status of functions is not evaluate so it is more secure to polute <stderr>.\n");
00162         }
00163         return -1;
00164     }
00165 
00166     while (offset > 0) {
00167         read = offset > sizeof(buffer) ? sizeof(buffer) : offset;
00168         if ((read = (int)fread(buffer, 1, read, fp)) <= 0)
00169             return -1;
00170         offset -= read;
00171     }
00172 
00173     return 0;
00174 }
00175 
00176 
00177 FILE   *
00178 init_outfile(char *outPath, int decode)
00179 {
00180     FILE   *outf;
00181 #ifdef __riscos__
00182     char   *p;
00183 #endif
00184 
00185     /* open the output file */
00186     if (0 == strcmp(outPath, "-")) {
00187         lame_set_stream_binary_mode(outf = stdout);
00188     }
00189     else {
00190         if ((outf = fopen(outPath, "w+b")) == NULL)
00191             return NULL;
00192 #ifdef __riscos__
00193         /* Assign correct file type */
00194         for (p = outPath; *p; p++) /* ugly, ugly to modify a string */
00195             switch (*p) {
00196             case '.':
00197                 *p = '/';
00198                 break;
00199             case '/':
00200                 *p = '.';
00201                 break;
00202             }
00203         SetFiletype(outPath, decode ? 0xFB1 /*WAV*/ : 0x1AD /*AMPEG*/);
00204 #endif
00205     }
00206     return outf;
00207 }
00208 
00209 
00210 
00211 
00212 
00213 
00214 void
00215 init_infile(lame_global_flags * gfp, char *inPath, int *enc_delay, int *enc_padding)
00216 {
00217     /* open the input file */
00218     count_samples_carefully = 0;
00219     num_samples_read = 0;
00220     pcmbitwidth = in_bitwidth;
00221     pcmswapbytes = swapbytes;
00222     musicin = OpenSndFile(gfp, inPath, enc_delay, enc_padding);
00223 }
00224 
00225 void
00226 close_infile(void)
00227 {
00228     CloseSndFile(input_format, musicin);
00229 }
00230 
00231 
00232 void
00233 SwapBytesInWords(short *ptr, int short_words)
00234 {                       /* Some speedy code */
00235     unsigned long val;
00236     unsigned long *p = (unsigned long *) ptr;
00237 
00238 #ifndef lint
00239 # if defined(CHAR_BIT)
00240 #  if CHAR_BIT != 8
00241 #   error CHAR_BIT != 8
00242 #  endif
00243 # else
00244 #  error can not determine number of bits in a char
00245 # endif
00246 #endif /* lint */
00247 
00248     assert(sizeof(short) == 2);
00249 
00250 
00251 #if defined(SIZEOF_UNSIGNED_LONG) && SIZEOF_UNSIGNED_LONG == 4
00252     for (; short_words >= 2; short_words -= 2, p++) {
00253         val = *p;
00254         *p = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0x00FF00FF);
00255     }
00256     ptr = (short *) p;
00257     for (; short_words >= 1; short_words -= 1, ptr++) {
00258         val = *ptr;
00259         *ptr = (short)(((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF));
00260     }
00261 #elif defined(SIZEOF_UNSIGNED_LONG) && SIZEOF_UNSIGNED_LONG == 8
00262     for (; short_words >= 4; short_words -= 4, p++) {
00263         val = *p;
00264         *p = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF);
00265     }
00266     ptr = (short *) p;
00267     for (; short_words >= 1; short_words -= 1, ptr++) {
00268         val = *ptr;
00269         *ptr = ((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF);
00270     }
00271 #else
00272 # ifdef SIZEOF_UNSIGNED_LONG
00273 #  warning Using unoptimized SwapBytesInWords().
00274 # endif
00275     for (; short_words >= 1; short_words -= 1, ptr++) {
00276         val = *ptr;
00277         *ptr = ((val << 8) & 0xFF00) | ((val >> 8) & 0x00FF);
00278     }
00279 #endif
00280 
00281     assert(short_words == 0);
00282 }
00283 
00284 
00285 
00286 static int
00287         get_audio_common(lame_global_flags * const gfp,
00288                          int buffer[2][1152], short buffer16[2][1152]);
00289 
00290 /************************************************************************
00291 *
00292 * get_audio()
00293 *
00294 * PURPOSE:  reads a frame of audio data from a file to the buffer,
00295 *   aligns the data for future processing, and separates the
00296 *   left and right channels
00297 *
00298 ************************************************************************/
00299 int
00300 get_audio(lame_global_flags * const gfp, int buffer[2][1152])
00301 {
00302     return (get_audio_common(gfp, buffer, NULL));
00303 }
00304 
00305 /*
00306   get_audio16 - behave as the original get_audio function, with a limited
00307                 16 bit per sample output
00308 */
00309 int
00310 get_audio16(lame_global_flags * const gfp, short buffer[2][1152])
00311 {
00312     return (get_audio_common(gfp, NULL, buffer));
00313 }
00314 
00315 /************************************************************************
00316   get_audio_common - central functionality of get_audio*
00317     in: gfp
00318         buffer    output to the int buffer or 16-bit buffer
00319    out: buffer    int output    (if buffer != NULL)
00320         buffer16  16-bit output (if buffer == NULL) 
00321 returns: samples read
00322 note: either buffer or buffer16 must be allocated upon call
00323 */
00324 static int
00325 get_audio_common(lame_global_flags * const gfp, int buffer[2][1152], short buffer16[2][1152])
00326 {
00327     int     num_channels = lame_get_num_channels(gfp);
00328     int     insamp[2 * 1152];
00329     short   buf_tmp16[2][1152];
00330     int     samples_read;
00331     int     framesize;
00332     int     samples_to_read;
00333     unsigned int remaining, tmp_num_samples;
00334     int     i;
00335     int    *p;
00336 
00337     /* 
00338      * NOTE: LAME can now handle arbritray size input data packets,
00339      * so there is no reason to read the input data in chuncks of
00340      * size "framesize".  EXCEPT:  the LAME graphical frame analyzer 
00341      * will get out of sync if we read more than framesize worth of data.
00342      */
00343 
00344     samples_to_read = framesize = lame_get_framesize(gfp);
00345     assert(framesize <= 1152);
00346 
00347     /* get num_samples */
00348     tmp_num_samples = lame_get_num_samples(gfp);
00349 
00350     /* if this flag has been set, then we are carefull to read
00351      * exactly num_samples and no more.  This is useful for .wav and .aiff
00352      * files which have id3 or other tags at the end.  Note that if you
00353      * are using LIBSNDFILE, this is not necessary 
00354      */
00355     if (count_samples_carefully) {
00356         remaining = tmp_num_samples - Min(tmp_num_samples, num_samples_read);
00357         if (remaining < (unsigned int)framesize && 0 != tmp_num_samples)
00358             /* in case the input is a FIFO (at least it's reproducible with
00359                a FIFO) tmp_num_samples may be 0 and therefore remaining
00360                would be 0, but we need to read some samples, so don't
00361                change samples_to_read to the wrong value in this case */
00362             samples_to_read = remaining;
00363     }
00364 
00365     if (is_mpeg_file_format(input_format)) {
00366         if (buffer != NULL)
00367             samples_read = read_samples_mp3(gfp, musicin, buf_tmp16, num_channels);
00368         else
00369             samples_read = read_samples_mp3(gfp, musicin, buffer16, num_channels);
00370         if (samples_read < 0) {
00371             return samples_read;
00372         }
00373     }
00374     else {
00375         samples_read =
00376             read_samples_pcm(musicin, insamp, num_channels * framesize,
00377                              num_channels * samples_to_read);
00378         if (samples_read < 0) {
00379             return samples_read;
00380         }
00381         p = insamp + samples_read;
00382         samples_read /= num_channels;
00383         if (buffer != NULL) { /* output to int buffer */
00384             if (num_channels == 2) {
00385                 for (i = samples_read; --i >= 0;) {
00386                     buffer[1][i] = *--p;
00387                     buffer[0][i] = *--p;
00388                 }
00389             }
00390             else if (num_channels == 1) {
00391                 memset(buffer[1], 0, samples_read * sizeof(int));
00392                 for (i = samples_read; --i >= 0;) {
00393                     buffer[0][i] = *--p;
00394                 }
00395             }
00396             else
00397                 assert(0);
00398         }
00399         else {          /* convert from int; output to 16-bit buffer */
00400             if (num_channels == 2) {
00401                 for (i = samples_read; --i >= 0;) {
00402                     buffer16[1][i] = *--p >> (8 * sizeof(int) - 16);
00403                     buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
00404                 }
00405             }
00406             else if (num_channels == 1) {
00407                 memset(buffer16[1], 0, samples_read * sizeof(short));
00408                 for (i = samples_read; --i >= 0;) {
00409                     buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
00410                 }
00411             }
00412             else
00413                 assert(0);
00414         }
00415     }
00416 
00417     /* LAME mp3 output 16bit -  convert to int, if necessary */
00418     if (is_mpeg_file_format(input_format)) {
00419         if (buffer != NULL) {
00420             for (i = samples_read; --i >= 0;)
00421                 buffer[0][i] = buf_tmp16[0][i] << (8 * sizeof(int) - 16);
00422             if (num_channels == 2) {
00423                 for (i = samples_read; --i >= 0;)
00424                     buffer[1][i] = buf_tmp16[1][i] << (8 * sizeof(int) - 16);
00425             }
00426             else if (num_channels == 1) {
00427                 memset(buffer[1], 0, samples_read * sizeof(int));
00428             }
00429             else
00430                 assert(0);
00431         }
00432     }
00433 
00434 
00435     /* if num_samples = MAX_U_32_NUM, then it is considered infinitely long.
00436        Don't count the samples */
00437     if (tmp_num_samples != MAX_U_32_NUM)
00438         num_samples_read += samples_read;
00439 
00440     return samples_read;
00441 }
00442 
00443 
00444 
00445 int
00446 read_samples_mp3(lame_global_flags * const gfp,
00447                  FILE * const musicin, short int mpg123pcm[2][1152], int stereo)
00448 {
00449     int     out;
00450 #if defined(AMIGA_MPEGA)  ||  defined(HAVE_MPGLIB)
00451     static const char type_name[] = "MP3 file";
00452 
00453     out = lame_decode_fromfile(musicin, mpg123pcm[0], mpg123pcm[1], &mp3input_data);
00454     /*
00455      * out < 0:  error, probably EOF
00456      * out = 0:  not possible with lame_decode_fromfile() ???
00457      * out > 0:  number of output samples
00458      */
00459     if (out < 0) {
00460         memset(mpg123pcm, 0, sizeof(**mpg123pcm) * 2 * 1152);
00461         return 0;
00462     }
00463 
00464     if (lame_get_num_channels(gfp) != mp3input_data.stereo) {
00465         if (silent < 10) {
00466             error_printf("Error: number of channels has changed in %s - not supported\n",
00467                          type_name);
00468         }
00469         out = -1;
00470     }
00471     if (lame_get_in_samplerate(gfp) != mp3input_data.samplerate) {
00472         if (silent < 10) {
00473             error_printf("Error: sample frequency has changed in %s - not supported\n", type_name);
00474         }
00475         out = -1;
00476     }
00477 #else
00478     out = -1;
00479 #endif
00480     return out;
00481 }
00482 
00483 
00484 int
00485 WriteWaveHeader(FILE * const fp, const int pcmbytes,
00486                 const int freq, const int channels, const int bits)
00487 {
00488     int     bytes = (bits + 7) / 8;
00489 
00490     /* quick and dirty, but documented */
00491     fwrite("RIFF", 1, 4, fp); /* label */
00492     Write32BitsLowHigh(fp, pcmbytes + 44 - 8); /* length in bytes without header */
00493     fwrite("WAVEfmt ", 2, 4, fp); /* 2 labels */
00494     Write32BitsLowHigh(fp, 2 + 2 + 4 + 4 + 2 + 2); /* length of PCM format declaration area */
00495     Write16BitsLowHigh(fp, 1); /* is PCM? */
00496     Write16BitsLowHigh(fp, channels); /* number of channels */
00497     Write32BitsLowHigh(fp, freq); /* sample frequency in [Hz] */
00498     Write32BitsLowHigh(fp, freq * channels * bytes); /* bytes per second */
00499     Write16BitsLowHigh(fp, channels * bytes); /* bytes per sample time */
00500     Write16BitsLowHigh(fp, bits); /* bits per sample */
00501     fwrite("data", 1, 4, fp); /* label */
00502     Write32BitsLowHigh(fp, pcmbytes); /* length in bytes of raw PCM data */
00503 
00504     return ferror(fp) ? -1 : 0;
00505 }
00506 
00507 
00508 
00509 
00510 #if defined(LIBSNDFILE)
00511 
00512 /*
00513 ** Copyright (C) 1999 Albert Faber
00514 **
00515  * This library is free software; you can redistribute it and/or
00516  * modify it under the terms of the GNU Library General Public
00517  * License as published by the Free Software Foundation; either
00518  * version 2 of the License, or (at your option) any later version.
00519  *
00520  * This library is distributed in the hope that it will be useful,
00521  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00522  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00523  * Library General Public License for more details.
00524  *
00525  * You should have received a copy of the GNU Library General Public
00526  * License along with this library; if not, write to the
00527  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00528  * Boston, MA 02111-1307, USA.
00529  */
00530 
00531 
00532 
00533 
00534 
00535 
00536 void
00537 CloseSndFile(sound_file_format input, FILE * musicin)
00538 {
00539     SNDFILE *gs_pSndFileIn = (SNDFILE *) musicin;
00540     if (is_mpeg_file_format(input)) {
00541 #ifndef AMIGA_MPEGA
00542         if (fclose(musicin) != 0) {
00543             if (silent < 10) {
00544                 error_printf("Could not close audio input file\n");
00545             }
00546             exit(2);
00547         }
00548 #endif
00549     }
00550     else {
00551         if (gs_pSndFileIn) {
00552             if (sf_close(gs_pSndFileIn) != 0) {
00553                 if (silent < 10) {
00554                     error_printf("Could not close sound file \n");
00555                 }
00556                 exit(2);
00557             }
00558         }
00559     }
00560 }
00561 
00562 
00563 
00564 FILE   *
00565 OpenSndFile(lame_global_flags * gfp, char *inPath, int *enc_delay, int *enc_padding)
00566 {
00567     char   *lpszFileName = inPath;
00568     FILE   *musicin;
00569     SNDFILE *gs_pSndFileIn = NULL;
00570     SF_INFO gs_wfInfo;
00571 
00572     if (is_mpeg_file_format(input_format)) {
00573 #ifdef AMIGA_MPEGA
00574         if (-1 == lame_decode_initfile(lpszFileName, &mp3input_data)) {
00575             if (silent < 10) {
00576                 error_printf("Error reading headers in mp3 input file %s.\n", lpszFileName);
00577             }
00578             exit(1);
00579         }
00580 #endif
00581 #ifdef HAVE_MPGLIB
00582         if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
00583             if (silent < 10) {
00584                 error_printf("Could not find \"%s\".\n", lpszFileName);
00585             }
00586             exit(1);
00587         }
00588         if (-1 == lame_decode_initfile(musicin, &mp3input_data, &enc_delay, &enc_padding)) {
00589             if (silent < 10) {
00590                 error_printf("Error reading headers in mp3 input file %s.\n", lpszFileName);
00591             }
00592             exit(1);
00593         }
00594 #endif
00595 
00596         if (-1 == lame_set_num_channels(gfp, mp3input_data.stereo)) {
00597             if (silent < 10) {
00598                 error_printf("Unsupported number of channels: %ud\n", mp3input_data.stereo);
00599             }
00600             exit(1);
00601         }
00602         (void) lame_set_in_samplerate(gfp, mp3input_data.samplerate);
00603         (void) lame_set_num_samples(gfp, mp3input_data.nsamp);
00604     }
00605     else if (input_format == sf_ogg) {
00606         if (silent < 10) {
00607             error_printf("sorry, vorbis support in LAME is deprecated.\n");
00608         }
00609         exit(1);
00610     }
00611     else {
00612         /* Try to open the sound file */
00613         memset (&gs_wfInfo, 0, sizeof (gs_wfInfo)) ;
00614         gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
00615 
00616         if (gs_pSndFileIn == NULL) {
00617             if (!in_signed && in_bitwidth != 8) {
00618                 fputs("Unsigned input only supported with bitwidth 8\n", stderr);
00619                 exit(1);
00620             }
00621             /* set some defaults incase input is raw PCM */
00622             gs_wfInfo.seekable = (input_format != sf_raw); /* if user specified -r, set to not seekable */
00623             gs_wfInfo.samplerate = lame_get_in_samplerate(gfp);
00624             gs_wfInfo.channels = lame_get_num_channels(gfp);
00625             gs_wfInfo.format = SF_FORMAT_RAW;
00626             if (in_endian != order_unknown) {
00627                 if (in_endian == order_littleEndian) {
00628                     gs_wfInfo.format |= SF_ENDIAN_LITTLE;
00629                 }
00630                 else {
00631                     gs_wfInfo.format |= SF_ENDIAN_BIG;
00632                 }
00633             }
00634             else {
00635                 /* we will never get here. it seems in_endian is always either little or big endian */
00636 #ifndef WORDS_BIGENDIAN
00637                 /* little endian */
00638                 if (swapbytes)
00639                     gs_wfInfo.format |= SF_ENDIAN_BIG;
00640                 else
00641                     gs_wfInfo.format |= SF_ENDIAN_LITTLE;
00642 #else
00643                 if (swapbytes)
00644                     gs_wfInfo.format |= SF_ENDIAN_LITTLE;
00645                 else
00646                     gs_wfInfo.format |= SF_ENDIAN_BIG;
00647 #endif
00648             }
00649             switch (in_bitwidth) {
00650             case  8: gs_wfInfo.format |= in_signed ? SF_FORMAT_PCM_S8 : SF_FORMAT_PCM_U8; break;
00651             case 16: gs_wfInfo.format |= SF_FORMAT_PCM_16; break;
00652             case 24: gs_wfInfo.format |= SF_FORMAT_PCM_24; break;
00653             case 32: gs_wfInfo.format |= SF_FORMAT_PCM_32; break;
00654             default: break;
00655             }
00656             gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
00657         }
00658 
00659         musicin = (SNDFILE *) gs_pSndFileIn;
00660 
00661         /* Check result */
00662         if (gs_pSndFileIn == NULL) {
00663             sf_perror(gs_pSndFileIn);
00664             if (silent < 10) {
00665                 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
00666             }
00667             exit(1);
00668         }
00669 
00670         if ((gs_wfInfo.format & SF_FORMAT_RAW ) == SF_FORMAT_RAW) {
00671             input_format = sf_raw;
00672         }
00673 
00674 #ifdef _DEBUG_SND_FILE
00675         DEBUGF("\n\nSF_INFO structure\n");
00676         DEBUGF("samplerate        :%d\n", gs_wfInfo.samplerate);
00677         DEBUGF("samples           :%d\n", gs_wfInfo.frames);
00678         DEBUGF("channels          :%d\n", gs_wfInfo.channels);
00679         DEBUGF("format            :");
00680 
00681         /* new formats from sbellon@sbellon.de  1/2000 */
00682 
00683         switch (gs_wfInfo.format & SF_FORMAT_TYPEMASK) {
00684         case SF_FORMAT_WAV:
00685             DEBUGF("Microsoft WAV format (big endian). ");
00686             break;
00687         case SF_FORMAT_AIFF:
00688             DEBUGF("Apple/SGI AIFF format (little endian). ");
00689             break;
00690         case SF_FORMAT_AU:
00691             DEBUGF("Sun/NeXT AU format (big endian). ");
00692             break;
00693             /*
00694         case SF_FORMAT_AULE:
00695             DEBUGF("DEC AU format (little endian). ");
00696             break;
00697             */
00698         case SF_FORMAT_RAW:
00699             DEBUGF("RAW PCM data. ");
00700             break;
00701         case SF_FORMAT_PAF:
00702             DEBUGF("Ensoniq PARIS file format. ");
00703             break;
00704         case SF_FORMAT_SVX:
00705             DEBUGF("Amiga IFF / SVX8 / SV16 format. ");
00706             break;
00707         case SF_FORMAT_NIST:
00708             DEBUGF("Sphere NIST format. ");
00709             break;
00710         default:
00711             assert(0);
00712             break;
00713         }
00714 
00715         switch (gs_wfInfo.format & SF_FORMAT_SUBMASK) {
00716             /*
00717         case SF_FORMAT_PCM:
00718             DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
00719             break;
00720             */
00721         case SF_FORMAT_FLOAT:
00722             DEBUGF("32 bit Intel x86 floats.");
00723             break;
00724         case SF_FORMAT_ULAW:
00725             DEBUGF("U-Law encoded.");
00726             break;
00727         case SF_FORMAT_ALAW:
00728             DEBUGF("A-Law encoded.");
00729             break;
00730         case SF_FORMAT_IMA_ADPCM:
00731             DEBUGF("IMA ADPCM.");
00732             break;
00733         case SF_FORMAT_MS_ADPCM:
00734             DEBUGF("Microsoft ADPCM.");
00735             break;
00736             /*
00737         case SF_FORMAT_PCM_BE:
00738             DEBUGF("Big endian PCM data.");
00739             break;
00740         case SF_FORMAT_PCM_LE:
00741             DEBUGF("Little endian PCM data.");
00742             break;
00743             */
00744         case SF_FORMAT_PCM_S8:
00745             DEBUGF("Signed 8 bit PCM.");
00746             break;
00747         case SF_FORMAT_PCM_U8:
00748             DEBUGF("Unsigned 8 bit PCM.");
00749             break;
00750         case SF_FORMAT_PCM_16:
00751             DEBUGF("Signed 16 bit PCM.");
00752             break;
00753         case SF_FORMAT_PCM_24:
00754             DEBUGF("Signed 24 bit PCM.");
00755             break;
00756         case SF_FORMAT_PCM_32:
00757             DEBUGF("Signed 32 bit PCM.");
00758             break;
00759             /*
00760         case SF_FORMAT_SVX_FIB:
00761             DEBUGF("SVX Fibonacci Delta encoding.");
00762             break;
00763         case SF_FORMAT_SVX_EXP:
00764             DEBUGF("SVX Exponential Delta encoding.");
00765             break;
00766             */
00767         default:
00768             assert(0);
00769             break;
00770         }
00771 
00772         DEBUGF("\n");
00773         DEBUGF("sections          :%d\n", gs_wfInfo.sections);
00774         DEBUGF("seekable          :\n", gs_wfInfo.seekable);
00775 #endif
00776         /* Check result */
00777         if (gs_pSndFileIn == NULL) {
00778             sf_perror(gs_pSndFileIn);
00779             if (silent < 10) {
00780                 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
00781             }
00782             exit(1);
00783         }
00784 
00785 
00786         (void) lame_set_num_samples(gfp, gs_wfInfo.frames);
00787         if (-1 == lame_set_num_channels(gfp, gs_wfInfo.channels)) {
00788             if (silent < 10) {
00789                 error_printf("Unsupported number of channels: %ud\n", gs_wfInfo.channels);
00790             }
00791             exit(1);
00792         }
00793         (void) lame_set_in_samplerate(gfp, gs_wfInfo.samplerate);
00794         pcmbitwidth = 32;
00795     }
00796 
00797     if (lame_get_num_samples(gfp) == MAX_U_32_NUM) {
00798         /* try to figure out num_samples */
00799         double  flen = lame_get_file_size(lpszFileName);
00800 
00801         if (flen >= 0) {
00802             /* try file size, assume 2 bytes per sample */
00803             if (is_mpeg_file_format(input_format)) {
00804                 if (mp3input_data.bitrate > 0) {
00805                     double  totalseconds = (flen * 8.0 / (1000.0 * mp3input_data.bitrate));
00806                     unsigned long tmp_num_samples = totalseconds * lame_get_in_samplerate(gfp);
00807 
00808                     (void) lame_set_num_samples(gfp, tmp_num_samples);
00809                     mp3input_data.nsamp = tmp_num_samples;
00810                 }
00811             }
00812             else {
00813                 lame_set_num_samples(gfp, flen / (2 * lame_get_num_channels(gfp)));
00814             }
00815         }
00816     }
00817 
00818 
00819     return musicin;
00820 }
00821 
00822 
00823 /************************************************************************
00824 *
00825 * read_samples()
00826 *
00827 * PURPOSE:  reads the PCM samples from a file to the buffer
00828 *
00829 *  SEMANTICS:
00830 * Reads #samples_read# number of shorts from #musicin# filepointer
00831 * into #sample_buffer[]#.  Returns the number of samples read.
00832 *
00833 ************************************************************************/
00834 
00835 static int
00836 read_samples_pcm(FILE * const musicin, int sample_buffer[2304],
00837                  int frame_size /* unused */ , int samples_to_read)
00838 {
00839     int     samples_read;
00840 
00841     samples_read = sf_read_int((SNDFILE *) musicin, sample_buffer, samples_to_read);
00842 
00843 #if 0
00844     switch (pcmbitwidth) {
00845     case 8:
00846         for (i = 0; i < samples_read; i++)
00847             sample_buffer[i] <<= (8 * sizeof(int) - 8);
00848         break;
00849     case 16:
00850         for (i = 0; i < samples_read; i++)
00851             sample_buffer[i] <<= (8 * sizeof(int) - 16);
00852         break;
00853     case 24:
00854         for (i = 0; i < samples_read; i++)
00855             sample_buffer[i] <<= (8 * sizeof(int) - 24);
00856         break;
00857     case 32:
00858         break;
00859     default:
00860         if (silent < 10) {
00861             error_printf("Only 8, 16, 24 and 32 bit input files supported \n");
00862         }
00863         exit(1);
00864     }
00865 #endif
00866 
00867     return samples_read;
00868 }
00869 
00870 
00871 #else /* defined(LIBSNDFILE) */
00872 
00873 /************************************************************************
00874  ************************************************************************
00875  ************************************************************************
00876  ************************************************************************
00877  ************************************************************************
00878  ************************************************************************
00879  *
00880  * OLD ISO/LAME routines follow.  Used if you dont have LIBSNDFILE
00881  * or for stdin/stdout support
00882  *
00883  ************************************************************************
00884  ************************************************************************
00885  ************************************************************************
00886  ************************************************************************
00887  ************************************************************************
00888  ************************************************************************/
00889 
00890 
00891 
00892 /************************************************************************
00893 unpack_read_samples - read and unpack signed low-to-high byte or unsigned
00894                       single byte input. (used for read_samples function)
00895                       Output integers are stored in the native byte order
00896                       (little or big endian).  -jd
00897   in: samples_to_read
00898       bytes_per_sample
00899       swap_order    - set for high-to-low byte order input stream
00900  i/o: pcm_in
00901  out: sample_buffer  (must be allocated up to samples_to_read upon call)
00902 returns: number of samples read
00903 */
00904 static int
00905 unpack_read_samples(const int samples_to_read, const int bytes_per_sample,
00906                     const int swap_order, int *sample_buffer, FILE * pcm_in)
00907 {
00908     int     samples_read;
00909     int     i;
00910     int    *op;              /* output pointer */
00911     unsigned char *ip = (unsigned char *) sample_buffer; /* input pointer */
00912     const int b = sizeof(int) * 8;
00913 
00914 #define GA_URS_IFLOOP( ga_urs_bps ) \
00915     if( bytes_per_sample == ga_urs_bps ) \
00916         for( i = samples_read * bytes_per_sample; (i -= bytes_per_sample) >=0;)
00917 
00918 
00919     samples_read = (int)fread(sample_buffer, bytes_per_sample, samples_to_read, pcm_in);
00920     op = sample_buffer + samples_read;
00921 
00922     GA_URS_IFLOOP(1)
00923         * --op = (ip[i] ^ 0x80) << (b - 8) | 0x7f << (b - 16); /* convert from unsigned */
00924     if (swap_order == 0) {
00925         GA_URS_IFLOOP(2)
00926             * --op = ip[i] << (b - 16) | ip[i + 1] << (b - 8);
00927         GA_URS_IFLOOP(3)
00928             * --op = ip[i] << (b - 24) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 8);
00929         GA_URS_IFLOOP(4)
00930             * --op =
00931             ip[i] << (b - 32) | ip[i + 1] << (b - 24) | ip[i + 2] << (b - 16) | ip[i + 3] << (b -
00932                                                                                               8);
00933     }
00934     else {
00935         GA_URS_IFLOOP(2)
00936             * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16);
00937         GA_URS_IFLOOP(3)
00938             * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24);
00939         GA_URS_IFLOOP(4)
00940             * --op =
00941             ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24) | ip[i + 3] << (b -
00942                                                                                              32);
00943     }
00944 #undef GA_URS_IFLOOP
00945     return (samples_read);
00946 }
00947 
00948 
00949 
00950 /************************************************************************
00951 *
00952 * read_samples()
00953 *
00954 * PURPOSE:  reads the PCM samples from a file to the buffer
00955 *
00956 *  SEMANTICS:
00957 * Reads #samples_read# number of shorts from #musicin# filepointer
00958 * into #sample_buffer[]#.  Returns the number of samples read.
00959 *
00960 ************************************************************************/
00961 
00962 int
00963 read_samples_pcm(FILE * musicin, int sample_buffer[2304], int frame_size, int samples_to_read)
00964 {
00965     int     samples_read;
00966     int     iswav = (input_format == sf_wave);
00967     int     hi_lo_order;     /* byte order of input stream */
00968 
00969     if ((32 == pcmbitwidth) || (24 == pcmbitwidth) || (16 == pcmbitwidth)) {
00970 #ifndef WORDS_BIGENDIAN
00971         int const machine_byte_order = order_littleEndian;
00972 #else
00973         int const machine_byte_order = order_bigEndian;
00974 #endif
00975         if (in_endian != order_unknown) {
00976             hi_lo_order = in_endian != machine_byte_order;
00977         }
00978         else {
00979             /* assume only recognized wav files are */
00980             /*  in little endian byte order */
00981             hi_lo_order = !iswav;
00982         }
00983         if (pcmswapbytes) {
00984             hi_lo_order = !hi_lo_order;
00985         }
00986         samples_read = unpack_read_samples(samples_to_read, pcmbitwidth / 8,
00987                                            hi_lo_order, sample_buffer, musicin);
00988 
00989     }
00990     else if (8 == pcmbitwidth) {
00991         samples_read = unpack_read_samples(samples_to_read, 1, 0, sample_buffer, musicin);
00992     }
00993     else {
00994         if (silent < 10) {
00995             error_printf("Only 8, 16, 24 and 32 bit input files supported \n");
00996         }
00997         exit(1);
00998     }
00999     if (ferror(musicin)) {
01000         if (silent < 10) {
01001             error_printf("Error reading input file\n");
01002         }
01003         exit(1);
01004     }
01005 
01006     return samples_read;
01007 }
01008 
01009 
01010 
01011 /* AIFF Definitions */
01012 
01013 #define IFF_ID_FORM 0x464f524d /* "FORM" */
01014 #define IFF_ID_AIFF 0x41494646 /* "AIFF" */
01015 #define IFF_ID_AIFC 0x41494643 /* "AIFC" */
01016 #define IFF_ID_COMM 0x434f4d4d /* "COMM" */
01017 #define IFF_ID_SSND 0x53534e44 /* "SSND" */
01018 #define IFF_ID_MPEG 0x4d504547 /* "MPEG" */
01019 
01020 #define IFF_ID_NONE 0x4e4f4e45 /* "NONE" */ /* AIFF-C data format */
01021 #define IFF_ID_2CBE 0x74776f73 /* "twos" */ /* AIFF-C data format */
01022 #define IFF_ID_2CLE 0x736f7774 /* "sowt" */ /* AIFF-C data format */
01023 
01024 #define WAV_ID_RIFF 0x52494646 /* "RIFF" */
01025 #define WAV_ID_WAVE 0x57415645 /* "WAVE" */
01026 #define WAV_ID_FMT  0x666d7420 /* "fmt " */
01027 #define WAV_ID_DATA 0x64617461 /* "data" */
01028 
01029 
01030 
01031 
01032 /*****************************************************************************
01033  *
01034  *      Read Microsoft Wave headers
01035  *
01036  *      By the time we get here the first 32-bits of the file have already been
01037  *      read, and we're pretty sure that we're looking at a WAV file.
01038  *
01039  *****************************************************************************/
01040 
01041 static int
01042 parse_wave_header(lame_global_flags * gfp, FILE * sf)
01043 {
01044     int     format_tag = 0;
01045     int     channels = 0;
01046     int     block_align = 0;
01047     int     bits_per_sample = 0;
01048     int     samples_per_sec = 0;
01049     int     avg_bytes_per_sec = 0;
01050 
01051 
01052     int     is_wav = 0;
01053     long    data_length = 0, file_length, subSize = 0;
01054     int     loop_sanity = 0;
01055 
01056     file_length = Read32BitsHighLow(sf);
01057     if (Read32BitsHighLow(sf) != WAV_ID_WAVE)
01058         return 0;
01059 
01060     for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
01061         int     type = Read32BitsHighLow(sf);
01062 
01063         if (type == WAV_ID_FMT) {
01064             subSize = Read32BitsLowHigh(sf);
01065             if (subSize < 16) {
01066                 /*DEBUGF(
01067                    "'fmt' chunk too short (only %ld bytes)!", subSize);  */
01068                 return 0;
01069             }
01070 
01071             format_tag = Read16BitsLowHigh(sf);
01072             subSize -= 2;
01073             channels = Read16BitsLowHigh(sf);
01074             subSize -= 2;
01075             samples_per_sec = Read32BitsLowHigh(sf);
01076             subSize -= 4;
01077             avg_bytes_per_sec = Read32BitsLowHigh(sf);
01078             subSize -= 4;
01079             block_align = Read16BitsLowHigh(sf);
01080             subSize -= 2;
01081             bits_per_sample = Read16BitsLowHigh(sf);
01082             subSize -= 2;
01083 
01084             /* DEBUGF("   skipping %d bytes\n", subSize); */
01085 
01086             if (subSize > 0) {
01087                 if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
01088                     return 0;
01089             };
01090 
01091         }
01092         else if (type == WAV_ID_DATA) {
01093             subSize = Read32BitsLowHigh(sf);
01094             data_length = subSize;
01095             is_wav = 1;
01096             /* We've found the audio data. Read no further! */
01097             break;
01098 
01099         }
01100         else {
01101             subSize = Read32BitsLowHigh(sf);
01102             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
01103                 return 0;
01104         }
01105     }
01106 
01107     if (format_tag != 1) {
01108         return 0;       /* oh no! non-supported format  */
01109     }
01110 
01111 
01112     if (is_wav) {
01113         /* make sure the header is sane */
01114         if (-1 == lame_set_num_channels(gfp, channels)) {
01115             if (silent < 10) {
01116                 error_printf("Unsupported number of channels: %ud\n", channels);
01117             }
01118             exit(1);
01119         }
01120         (void) lame_set_in_samplerate(gfp, samples_per_sec);
01121         pcmbitwidth = bits_per_sample;
01122         (void) lame_set_num_samples(gfp, data_length / (channels * ((bits_per_sample + 7) / 8)));
01123     }
01124     return is_wav;
01125 }
01126 
01127 
01128 
01129 /************************************************************************
01130 * aiff_check2
01131 *
01132 * PURPOSE:      Checks AIFF header information to make sure it is valid.
01133 *               returns 0 on success, 1 on errors
01134 ************************************************************************/
01135 
01136 int
01137 aiff_check2(IFF_AIFF * const pcm_aiff_data)
01138 {
01139     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
01140         if (silent < 10) {
01141             error_printf("ERROR: input sound data is not PCM\n");
01142         }
01143         return 1;
01144     }
01145     if (pcm_aiff_data->sampleSize != sizeof(short) * CHAR_BIT) {
01146         if (silent < 10) {
01147             error_printf("ERROR: input ound data is not %i bits\n",
01148                          sizeof(short) * CHAR_BIT);
01149         }
01150         return 1;
01151     }
01152     if (pcm_aiff_data->numChannels != 1 && pcm_aiff_data->numChannels != 2) {
01153         if (silent < 10) {
01154             error_printf("ERROR: input sound data is not mono or stereo\n");
01155         }
01156         return 1;
01157     }
01158     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
01159         if (silent < 10) {
01160             error_printf("ERROR: block size of input sound data is not 0 bytes\n");
01161         }
01162         return 1;
01163     }
01164     /* A bug, since we correctly skip the offset earlier in the code.
01165        if (pcm_aiff_data->blkAlgn.offset != 0) {
01166        error_printf("Block offset is not 0 bytes in '%s'\n", file_name);
01167        return 1;
01168        } */
01169 
01170     return 0;
01171 }
01172 
01173 /*****************************************************************************
01174  *
01175  *      Read Audio Interchange File Format (AIFF) headers.
01176  *
01177  *      By the time we get here the first 32 bits of the file have already been
01178  *      read, and we're pretty sure that we're looking at an AIFF file.
01179  *
01180  *****************************************************************************/
01181 
01182 static int
01183 parse_aiff_header(lame_global_flags * gfp, FILE * sf)
01184 {
01185     int     is_aiff = 0;
01186     long    chunkSize = 0, subSize = 0, typeID = 0, dataType = 0;
01187     IFF_AIFF aiff_info;
01188 
01189     memset(&aiff_info, 0, sizeof(aiff_info));
01190     chunkSize = Read32BitsHighLow(sf);
01191 
01192     typeID = Read32BitsHighLow(sf);
01193     if ((typeID != IFF_ID_AIFF) && (typeID != IFF_ID_AIFC))
01194         return 0;
01195 
01196     while (chunkSize > 0) {
01197         int     type = Read32BitsHighLow(sf);
01198         chunkSize -= 4;
01199 
01200         /* DEBUGF(
01201            "found chunk type %08x '%4.4s'\n", type, (char*)&type); */
01202 
01203         /* don't use a switch here to make it easier to use 'break' for SSND */
01204         if (type == IFF_ID_COMM) {
01205             subSize = Read32BitsHighLow(sf);
01206             chunkSize -= subSize;
01207 
01208             aiff_info.numChannels = Read16BitsHighLow(sf);
01209             subSize -= 2;
01210             aiff_info.numSampleFrames = Read32BitsHighLow(sf);
01211             subSize -= 4;
01212             aiff_info.sampleSize = Read16BitsHighLow(sf);
01213             subSize -= 2;
01214             aiff_info.sampleRate = ReadIeeeExtendedHighLow(sf);
01215             subSize -= 10;
01216 
01217             if (typeID == IFF_ID_AIFC) {
01218                 dataType = Read32BitsHighLow(sf);
01219                 subSize -= 4;
01220 
01221                 if ((dataType != IFF_ID_2CLE) &&
01222                     (dataType != IFF_ID_2CBE) && (dataType != IFF_ID_NONE))
01223                     return 0;
01224 
01225                 if (aiff_info.sampleSize == 16)
01226                     pcmswapbytes = (!swapbytes == (dataType == IFF_ID_2CLE));
01227             }
01228 
01229             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
01230                 return 0;
01231         }
01232         else if (type == IFF_ID_SSND) {
01233             subSize = Read32BitsHighLow(sf);
01234             chunkSize -= subSize;
01235 
01236             aiff_info.blkAlgn.offset = Read32BitsHighLow(sf);
01237             subSize -= 4;
01238             aiff_info.blkAlgn.blockSize = Read32BitsHighLow(sf);
01239             subSize -= 4;
01240 
01241             if (fskip(sf, (long) aiff_info.blkAlgn.offset, SEEK_CUR) != 0)
01242                 return 0;
01243 
01244             aiff_info.sampleType = IFF_ID_SSND;
01245             is_aiff = 1;
01246 
01247             /* We've found the audio data. Read no further! */
01248             break;
01249 
01250         }
01251         else {
01252             subSize = Read32BitsHighLow(sf);
01253             chunkSize -= subSize;
01254 
01255             if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
01256                 return 0;
01257         }
01258     }
01259 
01260     /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
01261     if (is_aiff) {
01262         /* make sure the header is sane */
01263         if (0 != aiff_check2(&aiff_info))
01264             return 0;
01265         if (-1 == lame_set_num_channels(gfp, aiff_info.numChannels)) {
01266             if (silent < 10) {
01267                 error_printf("Unsupported number of channels: %ud\n", aiff_info.numChannels);
01268             }
01269             exit(1);
01270         }
01271         (void) lame_set_in_samplerate(gfp, (int) aiff_info.sampleRate);
01272         pcmbitwidth = aiff_info.sampleSize;
01273         (void) lame_set_num_samples(gfp, aiff_info.numSampleFrames);
01274     }
01275     return is_aiff;
01276 }
01277 
01278 
01279 
01280 /************************************************************************
01281 *
01282 * parse_file_header
01283 *
01284 * PURPOSE: Read the header from a bytestream.  Try to determine whether
01285 *                  it's a WAV file or AIFF without rewinding, since rewind
01286 *                  doesn't work on pipes and there's a good chance we're reading
01287 *                  from stdin (otherwise we'd probably be using libsndfile).
01288 *
01289 * When this function returns, the file offset will be positioned at the
01290 * beginning of the sound data.
01291 *
01292 ************************************************************************/
01293 
01294 void
01295 parse_file_header(lame_global_flags * gfp, FILE * sf)
01296 {
01297 
01298     int     type = Read32BitsHighLow(sf);
01299     /*
01300        DEBUGF(
01301        "First word of input stream: %08x '%4.4s'\n", type, (char*) &type); 
01302      */
01303     count_samples_carefully = 0;
01304     /*input_format = sf_raw; commented out, because it is better to fail
01305       here as to encode some hundreds of input files not supported by LAME
01306       If you know you have RAW PCM data, use the -r switch
01307       */
01308 
01309     if (type == WAV_ID_RIFF) {
01310         /* It's probably a WAV file */
01311         if (parse_wave_header(gfp, sf)) {
01312             input_format = sf_wave;
01313             count_samples_carefully = 1;
01314         }
01315         else {
01316             if (silent < 10) {
01317                 error_printf("Warning: corrupt or unsupported WAVE format\n");
01318             }
01319             exit(2);
01320         }
01321     }
01322     else if (type == IFF_ID_FORM) {
01323         /* It's probably an AIFF file */
01324         if (parse_aiff_header(gfp, sf)) {
01325             input_format = sf_aiff;
01326             count_samples_carefully = 1;
01327         }
01328     }
01329     if (input_format == sf_raw) {
01330         /*
01331          ** Assume it's raw PCM.  Since the audio data is assumed to begin
01332          ** at byte zero, this will unfortunately require seeking.
01333          */
01334         if (fseek(sf, 0L, SEEK_SET) != 0) {
01335             /* ignore errors */            
01336         }
01337         input_format = sf_raw;
01338     }
01339 }
01340 
01341 
01342 
01343 void
01344 CloseSndFile(sound_file_format input, FILE * musicin)
01345 {
01346     if (fclose(musicin) != 0) {
01347         if (silent < 10) {
01348             error_printf("Could not close audio input file\n");
01349         }
01350         exit(2);
01351     }
01352 }
01353 
01354 
01355 
01356 
01357 
01358 FILE   *
01359 OpenSndFile(lame_global_flags * gfp, char *inPath, int *enc_delay, int *enc_padding)
01360 {
01361     FILE   *musicin;
01362 
01363     /* set the defaults from info incase we cannot determine them from file */
01364     lame_set_num_samples(gfp, MAX_U_32_NUM);
01365 
01366 
01367     if (!strcmp(inPath, "-")) {
01368         lame_set_stream_binary_mode(musicin = stdin); /* Read from standard input. */
01369     }
01370     else {
01371         if ((musicin = fopen(inPath, "rb")) == NULL) {
01372             if (silent < 10) {
01373                 error_printf("Could not find \"%s\".\n", inPath);
01374             }
01375             exit(1);
01376         }
01377     }
01378 
01379     if (is_mpeg_file_format(input_format)) {
01380 #ifdef AMIGA_MPEGA
01381         if (-1 == lame_decode_initfile(inPath, &mp3input_data)) {
01382             if (silent < 10) {
01383                 error_printf("Error reading headers in mp3 input file %s.\n", inPath);
01384             }
01385             exit(1);
01386         }
01387 #endif
01388 #ifdef HAVE_MPGLIB
01389         if (-1 == lame_decode_initfile(musicin, &mp3input_data, enc_delay, enc_padding)) {
01390             if (silent < 10) {
01391                 error_printf("Error reading headers in mp3 input file %s.\n", inPath);
01392             }
01393             exit(1);
01394         }
01395 #endif
01396         if (-1 == lame_set_num_channels(gfp, mp3input_data.stereo)) {
01397             if (silent < 10) {
01398                 error_printf("Unsupported number of channels: %ud\n", mp3input_data.stereo);
01399             }
01400             exit(1);
01401         }
01402         (void) lame_set_in_samplerate(gfp, mp3input_data.samplerate);
01403         (void) lame_set_num_samples(gfp, mp3input_data.nsamp);
01404     }
01405     else if (input_format == sf_ogg) {
01406         if (silent < 10) {
01407             error_printf("sorry, vorbis support in LAME is deprecated.\n");
01408         }
01409         exit(1);
01410     }
01411     else {
01412         if (input_format != sf_raw) {
01413             parse_file_header(gfp, musicin);
01414         }
01415 
01416         if (input_format == sf_raw) {
01417             /* assume raw PCM */
01418             if (silent < 10) {
01419                 console_printf("Assuming raw pcm input file");
01420                 if (swapbytes)
01421                     console_printf(" : Forcing byte-swapping\n");
01422                 else
01423                     console_printf("\n");
01424             }
01425             pcmswapbytes = swapbytes;
01426         }
01427     }
01428     if (input_format == sf_unknown) {
01429         if (silent < 10) {
01430             error_printf("Unknown input file format.\n");
01431         }
01432         exit(1);
01433     }
01434 
01435 
01436     if (lame_get_num_samples(gfp) == MAX_U_32_NUM && musicin != stdin) {
01437 
01438         double  flen = lame_get_file_size(inPath); /* try to figure out num_samples */
01439         if (flen >= 0) {
01440             /* try file size, assume 2 bytes per sample */
01441             if (is_mpeg_file_format(input_format)) {
01442                 if (mp3input_data.bitrate > 0) {
01443                     double  totalseconds = (flen * 8.0 / (1000.0 * mp3input_data.bitrate));
01444                     unsigned long tmp_num_samples =
01445                         (unsigned long) (totalseconds * lame_get_in_samplerate(gfp));
01446 
01447                     (void) lame_set_num_samples(gfp, tmp_num_samples);
01448                     mp3input_data.nsamp = tmp_num_samples;
01449                 }
01450             }
01451             else {
01452                 (void) lame_set_num_samples(gfp,
01453                                             (unsigned long) (flen /
01454                                                              (2 * lame_get_num_channels(gfp))));
01455             }
01456         }
01457     }
01458     return musicin;
01459 }
01460 #endif /* defined(LIBSNDFILE) */
01461 
01462 
01463 
01464 
01465 
01466 #if defined(HAVE_MPGLIB)
01467 static int
01468 check_aid(const unsigned char *header)
01469 {
01470     return 0 == memcmp(header, "AiD\1", 4);
01471 }
01472 
01473 /*
01474  * Please check this and don't kill me if there's a bug
01475  * This is a (nearly?) complete header analysis for a MPEG-1/2/2.5 Layer I, II or III
01476  * data stream
01477  */
01478 
01479 static int
01480 is_syncword_mp123(const void *const headerptr)
01481 {
01482     const unsigned char *const p = headerptr;
01483     static const char abl2[16] = { 0, 7, 7, 7, 0, 7, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8 };
01484 
01485     if ((p[0] & 0xFF) != 0xFF)
01486         return 0;       /* first 8 bits must be '1' */
01487     if ((p[1] & 0xE0) != 0xE0)
01488         return 0;       /* next 3 bits are also */
01489     if ((p[1] & 0x18) == 0x08)
01490         return 0;       /* no MPEG-1, -2 or -2.5 */
01491     switch (p[1] & 0x06) {
01492     default:
01493     case 0x00: /* illegal Layer */
01494       return 0;
01495 
01496     case 0x02: /* Layer3 */
01497       if (input_format != sf_mp3 && input_format != sf_mp123) {
01498         return 0;
01499       }
01500       input_format = sf_mp3;
01501       break;
01502 
01503     case 0x04: /* Layer2 */
01504       if (input_format != sf_mp2 && input_format != sf_mp123) {
01505         return 0;
01506       }
01507       input_format = sf_mp2;
01508       break;
01509 
01510     case 0x06: /* Layer1 */
01511       if (input_format != sf_mp1 && input_format != sf_mp123) {
01512         return 0;
01513       }
01514       input_format = sf_mp1;
01515       break;
01516     }
01517     if ((p[1] & 0x06) == 0x00)
01518         return 0;       /* no Layer I, II and III */
01519     if ((p[2] & 0xF0) == 0xF0)
01520         return 0;       /* bad bitrate */
01521     if ((p[2] & 0x0C) == 0x0C)
01522         return 0;       /* no sample frequency with (32,44.1,48)/(1,2,4)     */
01523     if ((p[1] & 0x18) == 0x18 && (p[1] & 0x06) == 0x04 && abl2[p[2] >> 4] & (1 << (p[3] >> 6)))
01524         return 0;
01525     if ((p[3] & 3) == 2)
01526         return 0;       /* reserved enphasis mode */
01527     return 1;
01528 }
01529 
01530 int
01531 lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding)
01532 {
01533     /*  VBRTAGDATA pTagData; */
01534     /* int xing_header,len2,num_frames; */
01535     unsigned char buf[100];
01536     int     ret;
01537     int     len, aid_header;
01538     short int pcm_l[1152], pcm_r[1152];
01539     int     freeformat = 0;
01540 
01541     memset(mp3data, 0, sizeof(mp3data_struct));
01542     lame_decode_init();
01543 
01544     len = 4;
01545     if (fread(buf, 1, len, fd) != len)
01546         return -1;      /* failed */
01547     if (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3') {
01548         if (silent < 10) {
01549             console_printf("ID3v2 found. "
01550                            "Be aware that the ID3 tag is currently lost when transcoding.\n");
01551         }
01552         len = 6;
01553         if (fread(&buf, 1, len, fd) != len)
01554             return -1;  /* failed */
01555         buf[2] &= 127;
01556         buf[3] &= 127;
01557         buf[4] &= 127;
01558         buf[5] &= 127;
01559         len = (((((buf[2] << 7) + buf[3]) << 7) + buf[4]) << 7) + buf[5];
01560         fskip(fd, len, SEEK_CUR);
01561         len = 4;
01562         if (fread(&buf, 1, len, fd) != len)
01563             return -1;  /* failed */
01564     }
01565     aid_header = check_aid(buf);
01566     if (aid_header) {
01567         if (fread(&buf, 1, 2, fd) != 2)
01568             return -1;  /* failed */
01569         aid_header = (unsigned char) buf[0] + 256 * (unsigned char) buf[1];
01570         if (silent < 10) {
01571             console_printf("Album ID found.  length=%i \n", aid_header);
01572         }
01573         /* skip rest of AID, except for 6 bytes we have already read */
01574         fskip(fd, aid_header - 6, SEEK_CUR);
01575 
01576         /* read 4 more bytes to set up buffer for MP3 header check */
01577         if (fread(&buf, 1, len, fd) != len)
01578             return -1;  /* failed */
01579     }
01580     len = 4;
01581     while (!is_syncword_mp123(buf)) {
01582         int     i;
01583         for (i = 0; i < len - 1; i++)
01584             buf[i] = buf[i + 1];
01585         if (fread(buf + len - 1, 1, 1, fd) != 1)
01586             return -1;  /* failed */
01587     }
01588 
01589     if ((buf[2] & 0xf0) == 0) {
01590         if (silent < 10) {
01591             console_printf("Input file is freeformat.\n");
01592         }
01593         freeformat = 1;
01594     }
01595     /* now parse the current buffer looking for MP3 headers.    */
01596     /* (as of 11/00: mpglib modified so that for the first frame where  */
01597     /* headers are parsed, no data will be decoded.   */
01598     /* However, for freeformat, we need to decode an entire frame, */
01599     /* so mp3data->bitrate will be 0 until we have decoded the first */
01600     /* frame.  Cannot decode first frame here because we are not */
01601     /* yet prepared to handle the output. */
01602     ret = lame_decode1_headersB(buf, len, pcm_l, pcm_r, mp3data, enc_delay, enc_padding);
01603     if (-1 == ret)
01604         return -1;
01605 
01606     /* repeat until we decode a valid mp3 header.  */
01607     while (!mp3data->header_parsed) {
01608         len = (int)fread(buf, 1, sizeof(buf), fd);
01609         if (len != sizeof(buf))
01610             return -1;
01611         ret = lame_decode1_headersB(buf, len, pcm_l, pcm_r, mp3data, enc_delay, enc_padding);
01612         if (-1 == ret)
01613             return -1;
01614     }
01615 
01616     if (mp3data->bitrate == 0 && !freeformat) {
01617         if (silent < 10) {
01618             error_printf("fail to sync...\n");
01619         }
01620         return lame_decode_initfile(fd, mp3data, enc_delay, enc_padding);
01621     }
01622 
01623     if (mp3data->totalframes > 0) {
01624         /* mpglib found a Xing VBR header and computed nsamp & totalframes */
01625     }
01626     else {
01627         /* set as unknown.  Later, we will take a guess based on file size
01628          * ant bitrate */
01629         mp3data->nsamp = MAX_U_32_NUM;
01630     }
01631 
01632 
01633     /*
01634        report_printf("ret = %i NEED_MORE=%i \n",ret,MP3_NEED_MORE);
01635        report_printf("stereo = %i \n",mp.fr.stereo);
01636        report_printf("samp = %i  \n",freqs[mp.fr.sampling_frequency]);
01637        report_printf("framesize = %i  \n",framesize);
01638        report_printf("bitrate = %i  \n",mp3data->bitrate);
01639        report_printf("num frames = %ui  \n",num_frames);
01640        report_printf("num samp = %ui  \n",mp3data->nsamp);
01641        report_printf("mode     = %i  \n",mp.fr.mode);
01642      */
01643 
01644     return 0;
01645 }
01646 
01647 /*
01648 For lame_decode_fromfile:  return code
01649   -1     error
01650    n     number of samples output.  either 576 or 1152 depending on MP3 file.
01651 
01652 
01653 For lame_decode1_headers():  return code
01654   -1     error
01655    0     ok, but need more data before outputing any samples
01656    n     number of samples output.  either 576 or 1152 depending on MP3 file.
01657 */
01658 int
01659 lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
01660 {
01661     int     ret = 0, len = 0;
01662     unsigned char buf[1024];
01663 
01664     /* first see if we still have data buffered in the decoder: */
01665     ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
01666     if (ret != 0)
01667         return ret;
01668 
01669 
01670     /* read until we get a valid output frame */
01671     while (1) {
01672         len = (int)fread(buf, 1, 1024, fd);
01673         if (len == 0) {
01674             /* we are done reading the file, but check for buffered data */
01675             ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
01676             if (ret <= 0) {
01677                 lame_decode_exit(); /* release mp3decoder memory */
01678                 return -1; /* done with file */
01679             }
01680             break;
01681         }
01682 
01683         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
01684         if (ret == -1) {
01685             lame_decode_exit(); /* release mp3decoder memory */
01686             return -1;
01687         }
01688         if (ret > 0)
01689             break;
01690     }
01691     return ret;
01692 }
01693 #endif /* defined(HAVE_MPGLIB) */
01694 
01695 /* end of get_audio.c */

Generated on Sun Dec 2 11:34:17 2007 for LAME by  doxygen 1.5.2