get_audio.c 48 KB

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