2 * Get Audio routines source file
4 * Copyright (c) 1999 Albert L Faber
5 * 2008-2011 Robert Hegemann
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
23 /* $Id: get_audio.c,v 1.152.2.1 2011/11/18 08:38:04 robert Exp $ */
44 # define strrchr rindex
46 char *strchr(), *strrchr();
48 # define memcpy(d, s, n) bcopy ((s), (d), (n))
49 # define memmove(d, s, n) bcopy ((s), (d), (n))
53 #ifdef HAVE_INTTYPES_H
54 # include <inttypes.h>
61 #define MAX_U_32_NUM 0xFFFFFFFF
66 #if defined(__riscos__)
68 # include <sys/swis.h>
70 # include <sys/types.h>
71 # include <sys/stat.h>
73 # include <sys/stat.h>
77 /* woraround for SunOS 4.x, it has SEEK_* defined here */
83 #include "get_audio.h"
93 # define STR(x) __STR(x)
94 #define __LOC__ __FILE__ "("STR(__LINE__)") : "
98 #define FLOAT_TO_UNSIGNED(f) ((unsigned long)(((long)((f) - 2147483648.0)) + 2147483647L + 1))
99 #define UNSIGNED_TO_FLOAT(u) (((double)((long)((u) - 2147483647L - 1))) + 2147483648.0)
101 static unsigned int uint32_high_low(unsigned char *bytes)
103 uint32_t const hh = bytes[0];
104 uint32_t const hl = bytes[1];
105 uint32_t const lh = bytes[2];
106 uint32_t const ll = bytes[3];
107 return (hh << 24) | (hl << 16) | (lh << 8) | ll;
111 read_ieee_extended_high_low(FILE * fp)
113 unsigned char bytes[10];
114 memset(bytes, 0, 10);
115 fread(bytes, 1, 10, fp);
117 int32_t const s = (bytes[0] & 0x80);
118 int32_t const e_h = (bytes[0] & 0x7F);
119 int32_t const e_l = bytes[1];
120 int32_t e = (e_h << 8) | e_l;
121 uint32_t const hm = uint32_high_low(bytes + 2);
122 uint32_t const lm = uint32_high_low(bytes + 6);
124 if (e != 0 || hm != 0 || lm != 0) {
129 double mantissa_h = UNSIGNED_TO_FLOAT(hm);
130 double mantissa_l = UNSIGNED_TO_FLOAT(lm);
133 result = ldexp(mantissa_h, e);
135 result += ldexp(mantissa_l, e);
138 return s ? -result : result;
144 read_16_bits_low_high(FILE * fp)
146 unsigned char bytes[2] = { 0, 0 };
147 fread(bytes, 1, 2, fp);
149 int32_t const low = bytes[0];
150 int32_t const high = (signed char) (bytes[1]);
151 return (high << 8) | low;
157 read_32_bits_low_high(FILE * fp)
159 unsigned char bytes[4] = { 0, 0, 0, 0 };
160 fread(bytes, 1, 4, fp);
162 int32_t const low = bytes[0];
163 int32_t const medl = bytes[1];
164 int32_t const medh = bytes[2];
165 int32_t const high = (signed char) (bytes[3]);
166 return (high << 24) | (medh << 16) | (medl << 8) | low;
171 read_16_bits_high_low(FILE * fp)
173 unsigned char bytes[2] = { 0, 0 };
174 fread(bytes, 1, 2, fp);
176 int32_t const low = bytes[1];
177 int32_t const high = (signed char) (bytes[0]);
178 return (high << 8) | low;
183 read_32_bits_high_low(FILE * fp)
185 unsigned char bytes[4] = { 0, 0, 0, 0 };
186 fread(bytes, 1, 4, fp);
188 int32_t const low = bytes[3];
189 int32_t const medl = bytes[2];
190 int32_t const medh = bytes[1];
191 int32_t const high = (signed char) (bytes[0]);
192 return (high << 24) | (medh << 16) | (medl << 8) | low;
197 write_16_bits_low_high(FILE * fp, int val)
199 unsigned char bytes[2];
200 bytes[0] = (val & 0xff);
201 bytes[1] = ((val >> 8) & 0xff);
202 fwrite(bytes, 1, 2, fp);
206 write_32_bits_low_high(FILE * fp, int val)
208 unsigned char bytes[4];
209 bytes[0] = (val & 0xff);
210 bytes[1] = ((val >> 8) & 0xff);
211 bytes[2] = ((val >> 16) & 0xff);
212 bytes[3] = ((val >> 24) & 0xff);
213 fwrite(bytes, 1, 4, fp);
223 typedef void SNDFILE;
225 #endif /* ifdef LIBSNDFILE */
229 typedef struct blockAlign_struct {
230 unsigned long offset;
231 unsigned long blockSize;
234 typedef struct IFF_AIFF_struct {
236 unsigned long numSampleFrames;
239 unsigned long sampleType;
246 void *ch[2]; /* buffer for each channel */
247 int w; /* sample width */
248 int n; /* number samples allocated */
249 int u; /* number samples used */
250 int skip_start; /* number samples to ignore at the beginning */
251 int skip_end; /* number samples to ignore at the end */
254 typedef struct PcmBuffer PcmBuffer;
257 initPcmBuffer(PcmBuffer * b, int w)
269 freePcmBuffer(PcmBuffer * b)
282 addPcmBuffer(PcmBuffer * b, void *a0, void *a1, int read)
290 return b->u - b->skip_end;
292 if (b->skip_start >= read) {
293 b->skip_start -= read;
294 return b->u - b->skip_end;
296 a_n = read - b->skip_start;
298 if (b != 0 && a_n > 0) {
299 int const b_free = b->n - b->u;
300 int const a_need = b->w * a_n;
301 int const b_used = b->w * b->u;
302 if (b_free < a_need) {
304 b->ch[0] = realloc(b->ch[0], b->w * b->n);
305 b->ch[1] = realloc(b->ch[1], b->w * b->n);
308 if (b->ch[0] != 0 && a0 != 0) {
310 memcpy((char *) b->ch[0] + b_used, src + b->skip_start, a_need);
312 if (b->ch[1] != 0 && a1 != 0) {
314 memcpy((char *) b->ch[1] + b_used, src + b->skip_start, a_need);
318 return b->u - b->skip_end;
322 takePcmBuffer(PcmBuffer * b, void *a0, void *a1, int a_n, int mm)
327 if (b != 0 && a_n > 0) {
328 int const a_take = b->w * a_n;
329 if (a0 != 0 && b->ch[0] != 0) {
330 memcpy(a0, b->ch[0], a_take);
332 if (a1 != 0 && b->ch[1] != 0) {
333 memcpy(a1, b->ch[1], a_take);
341 memmove(b->ch[0], (char *) b->ch[0] + a_take, b->w * b->u);
344 memmove(b->ch[1], (char *) b->ch[1] + a_take, b->w * b->u);
350 /* global data for get_audio.c. */
351 typedef struct get_audio_global_data_struct {
352 int count_samples_carefully;
355 int pcm_is_unsigned_8bit;
356 int pcm_is_ieee_float;
357 unsigned int num_samples_read;
363 size_t in_id3v2_size;
364 unsigned char* in_id3v2_tag;
365 } get_audio_global_data;
367 static get_audio_global_data global;
372 int lame_decode_initfile(const char *fullname, mp3data_struct * const mp3data);
374 int lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding);
377 /* read mp3 file until mpglib returns one frame of PCM data */
378 static int lame_decode_fromfile(FILE * fd, short int pcm_l[], short int pcm_r[],
379 mp3data_struct * mp3data);
382 static int read_samples_pcm(FILE * musicin, int sample_buffer[2304], int samples_to_read);
383 static int read_samples_mp3(lame_t gfp, FILE * musicin, short int mpg123pcm[2][1152]);
385 static SNDFILE *open_snd_file(lame_t gfp, char const *inPath);
387 static FILE *open_mpeg_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding);
388 static FILE *open_wave_file(lame_t gfp, char const *inPath);
389 static int close_input_file(FILE * musicin);
393 min_size_t(size_t a, size_t b)
401 enum ByteOrder machine_byte_order(void);
404 machine_byte_order(void)
407 return !(*((char *) (&one))) ? ByteOrderBigEndian : ByteOrderLittleEndian;
412 /* Replacement for forward fseek(,,SEEK_CUR), because fseek() fails on pipes */
416 fskip(FILE * fp, long offset, int whence)
421 char buffer[PIPE_BUF];
424 /* S_ISFIFO macro is defined on newer Linuxes */
427 /* _S_IFIFO is defined on Win32 and Cygwin */
428 # define S_ISFIFO(m) (((m)&_S_IFIFO) == _S_IFIFO)
433 /* fseek is known to fail on pipes with several C-Library implementations
434 workaround: 1) test for pipe
435 2) for pipes, only relatvie seeking is possible
436 3) and only in forward direction!
437 else fallback to old code
440 int const fd = fileno(fp);
441 struct stat file_stat;
443 if (fstat(fd, &file_stat) == 0) {
444 if (S_ISFIFO(file_stat.st_mode)) {
445 if (whence != SEEK_CUR || offset < 0) {
449 size_t const bytes_to_skip = min_size_t(sizeof(buffer), offset);
450 size_t const read = fread(buffer, 1, bytes_to_skip, fp);
461 if (0 == fseek(fp, offset, whence)) {
465 if (whence != SEEK_CUR || offset < 0) {
466 if (global_ui_config.silent < 10) {
468 ("fskip problem: Mostly the return status of functions is not evaluate so it is more secure to polute <stderr>.\n");
474 size_t const bytes_to_skip = min_size_t(sizeof(buffer), offset);
475 size_t const read = fread(buffer, 1, bytes_to_skip, fp);
487 lame_get_file_size(FILE * fp)
492 if (0 == fstat(fd, &sb))
499 init_outfile(char const *outPath, int decode)
503 /* open the output file */
504 if (0 == strcmp(outPath, "-")) {
506 lame_set_stream_binary_mode(outf);
509 outf = lame_fopen(outPath, "w+b");
511 /* Assign correct file type */
513 char *p, *out_path = strdup(outPath);
514 for (p = out_path; *p; p++) { /* ugly, ugly to modify a string */
524 SetFiletype(out_path, decode ? 0xFB1 /*WAV*/ : 0x1AD /*AMPEG*/);
536 setSkipStartAndEnd(lame_t gfp, int enc_delay, int enc_padding)
538 int skip_start = 0, skip_end = 0;
540 if (global_decoder.mp3_delay_set)
541 skip_start = global_decoder.mp3_delay;
543 switch (global_reader.input_format) {
548 if (skip_start == 0) {
549 if (enc_delay > -1 || enc_padding > -1) {
551 skip_start = enc_delay + 528 + 1;
552 if (enc_padding > -1)
553 skip_end = enc_padding - (528 + 1);
556 skip_start = lame_get_encoder_delay(gfp) + 528 + 1;
559 /* user specified a value of skip. just add for decoder */
560 skip_start += 528 + 1; /* mp3 decoder has a 528 sample delay, plus user supplied "skip" */
564 skip_start += 240 + 1;
567 skip_start += 240 + 1;
570 skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
573 skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
576 skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
579 skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
582 skip_start = skip_start < 0 ? 0 : skip_start;
583 skip_end = skip_end < 0 ? 0 : skip_end;
584 global. pcm16.skip_start = global.pcm32.skip_start = skip_start;
585 global. pcm16.skip_end = global.pcm32.skip_end = skip_end;
591 init_infile(lame_t gfp, char const *inPath)
593 int enc_delay = 0, enc_padding = 0;
594 /* open the input file */
595 global. count_samples_carefully = 0;
596 global. num_samples_read = 0;
597 global. pcmbitwidth = global_raw_pcm.in_bitwidth;
598 global. pcmswapbytes = global_reader.swapbytes;
599 global. pcm_is_unsigned_8bit = global_raw_pcm.in_signed == 1 ? 0 : 1;
600 global. pcm_is_ieee_float = 0;
602 global. music_in = 0;
603 global. snd_file = 0;
604 global. in_id3v2_size = 0;
605 global. in_id3v2_tag = 0;
606 if (is_mpeg_file_format(global_reader.input_format)) {
607 global. music_in = open_mpeg_file(gfp, inPath, &enc_delay, &enc_padding);
611 if (strcmp(inPath, "-") != 0) { /* not for stdin */
612 global. snd_file = open_snd_file(gfp, inPath);
615 if (global.snd_file == 0) {
616 global. music_in = open_wave_file(gfp, inPath);
619 initPcmBuffer(&global.pcm32, sizeof(int));
620 initPcmBuffer(&global.pcm16, sizeof(short));
621 setSkipStartAndEnd(gfp, enc_delay, enc_padding);
623 unsigned long n = lame_get_num_samples(gfp);
624 if (n != MAX_U_32_NUM) {
625 unsigned long const discard = global.pcm32.skip_start + global.pcm32.skip_end;
626 lame_set_num_samples(gfp, n > discard ? n - discard : 0);
629 return (global.snd_file != NULL || global.music_in != NULL) ? 1 : -1;
633 samples_to_skip_at_start(void)
635 return global.pcm32.skip_start;
639 samples_to_skip_at_end(void)
641 return global.pcm32.skip_end;
647 close_input_file(global.music_in);
649 if (global.snd_file) {
650 if (sf_close(global.snd_file) != 0) {
651 if (global_ui_config.silent < 10) {
652 error_printf("Could not close sound file \n");
655 global. snd_file = 0;
658 freePcmBuffer(&global.pcm32);
659 freePcmBuffer(&global.pcm16);
660 global. music_in = 0;
661 free(global.in_id3v2_tag);
662 global.in_id3v2_tag = 0;
663 global.in_id3v2_size = 0;
668 get_audio_common(lame_t gfp, int buffer[2][1152], short buffer16[2][1152]);
670 /************************************************************************
674 * PURPOSE: reads a frame of audio data from a file to the buffer,
675 * aligns the data for future processing, and separates the
676 * left and right channels
678 ************************************************************************/
680 get_audio(lame_t gfp, int buffer[2][1152])
682 int used = 0, read = 0;
684 read = get_audio_common(gfp, buffer, NULL);
685 used = addPcmBuffer(&global.pcm32, buffer[0], buffer[1], read);
686 } while (used <= 0 && read > 0);
690 if (global_reader.swap_channel == 0)
691 return takePcmBuffer(&global.pcm32, buffer[0], buffer[1], used, 1152);
693 return takePcmBuffer(&global.pcm32, buffer[1], buffer[0], used, 1152);
697 get_audio16 - behave as the original get_audio function, with a limited
698 16 bit per sample output
701 get_audio16(lame_t gfp, short buffer[2][1152])
703 int used = 0, read = 0;
705 read = get_audio_common(gfp, NULL, buffer);
706 used = addPcmBuffer(&global.pcm16, buffer[0], buffer[1], read);
707 } while (used <= 0 && read > 0);
711 if (global_reader.swap_channel == 0)
712 return takePcmBuffer(&global.pcm16, buffer[0], buffer[1], used, 1152);
714 return takePcmBuffer(&global.pcm16, buffer[1], buffer[0], used, 1152);
717 /************************************************************************
718 get_audio_common - central functionality of get_audio*
720 buffer output to the int buffer or 16-bit buffer
721 out: buffer int output (if buffer != NULL)
722 buffer16 16-bit output (if buffer == NULL)
723 returns: samples read
724 note: either buffer or buffer16 must be allocated upon call
727 get_audio_common(lame_t gfp, int buffer[2][1152], short buffer16[2][1152])
729 /* NTS: Do *NOT* allocate these on the stack. This causes crashes with Open Watcom's default small stack size. */
730 static short buf_tmp16[2][1152];
731 static int insamp[2 * 1152];
733 int num_channels = lame_get_num_channels(gfp);
737 unsigned int remaining, tmp_num_samples;
742 * NOTE: LAME can now handle arbritray size input data packets,
743 * so there is no reason to read the input data in chuncks of
744 * size "framesize". EXCEPT: the LAME graphical frame analyzer
745 * will get out of sync if we read more than framesize worth of data.
748 samples_to_read = framesize = lame_get_framesize(gfp);
749 assert(framesize <= 1152);
751 /* get num_samples */
752 if (is_mpeg_file_format(global_reader.input_format)) {
753 tmp_num_samples = global_decoder.mp3input_data.nsamp;
756 tmp_num_samples = lame_get_num_samples(gfp);
759 /* if this flag has been set, then we are carefull to read
760 * exactly num_samples and no more. This is useful for .wav and .aiff
761 * files which have id3 or other tags at the end. Note that if you
762 * are using LIBSNDFILE, this is not necessary
764 if (global.count_samples_carefully) {
765 if (global.num_samples_read < tmp_num_samples) {
766 remaining = tmp_num_samples - global.num_samples_read;
771 if (remaining < (unsigned int) framesize && 0 != tmp_num_samples)
772 /* in case the input is a FIFO (at least it's reproducible with
773 a FIFO) tmp_num_samples may be 0 and therefore remaining
774 would be 0, but we need to read some samples, so don't
775 change samples_to_read to the wrong value in this case */
776 samples_to_read = remaining;
779 if (is_mpeg_file_format(global_reader.input_format)) {
781 samples_read = read_samples_mp3(gfp, global.music_in, buf_tmp16);
783 samples_read = read_samples_mp3(gfp, global.music_in, buffer16);
784 if (samples_read < 0) {
789 if (global.snd_file) {
791 samples_read = sf_read_int(global.snd_file, insamp, num_channels * samples_to_read);
798 read_samples_pcm(global.music_in, insamp, num_channels * samples_to_read);
800 if (samples_read < 0) {
803 p = insamp + samples_read;
804 samples_read /= num_channels;
805 if (buffer != NULL) { /* output to int buffer */
806 if (num_channels == 2) {
807 for (i = samples_read; --i >= 0;) {
812 else if (num_channels == 1) {
813 memset(buffer[1], 0, samples_read * sizeof(int));
814 for (i = samples_read; --i >= 0;) {
821 else { /* convert from int; output to 16-bit buffer */
822 if (num_channels == 2) {
823 for (i = samples_read; --i >= 0;) {
824 buffer16[1][i] = *--p >> (8 * sizeof(int) - 16);
825 buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
828 else if (num_channels == 1) {
829 memset(buffer16[1], 0, samples_read * sizeof(short));
830 for (i = samples_read; --i >= 0;) {
831 buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
839 /* LAME mp3 output 16bit - convert to int, if necessary */
840 if (is_mpeg_file_format(global_reader.input_format)) {
841 if (buffer != NULL) {
842 for (i = samples_read; --i >= 0;)
843 buffer[0][i] = buf_tmp16[0][i] << (8 * sizeof(int) - 16);
844 if (num_channels == 2) {
845 for (i = samples_read; --i >= 0;)
846 buffer[1][i] = buf_tmp16[1][i] << (8 * sizeof(int) - 16);
848 else if (num_channels == 1) {
849 memset(buffer[1], 0, samples_read * sizeof(int));
857 /* if num_samples = MAX_U_32_NUM, then it is considered infinitely long.
858 Don't count the samples */
859 if (tmp_num_samples != MAX_U_32_NUM)
860 global. num_samples_read += samples_read;
868 read_samples_mp3(lame_t gfp, FILE * musicin, short int mpg123pcm[2][1152])
871 #if defined(AMIGA_MPEGA) || defined(HAVE_MPGLIB)
873 static const char type_name[] = "MP3 file";
875 out = lame_decode_fromfile(musicin, mpg123pcm[0], mpg123pcm[1], &global_decoder.mp3input_data);
877 * out < 0: error, probably EOF
878 * out = 0: not possible with lame_decode_fromfile() ???
879 * out > 0: number of output samples
882 memset(mpg123pcm, 0, sizeof(**mpg123pcm) * 2 * 1152);
886 if (lame_get_num_channels(gfp) != global_decoder.mp3input_data.stereo) {
887 if (global_ui_config.silent < 10) {
888 error_printf("Error: number of channels has changed in %s - not supported\n",
893 samplerate = global_reader.input_samplerate;
894 if (samplerate == 0) {
895 samplerate = global_decoder.mp3input_data.samplerate;
897 if (lame_get_in_samplerate(gfp) != samplerate) {
898 if (global_ui_config.silent < 10) {
899 error_printf("Error: sample frequency has changed in %s - not supported\n", type_name);
911 WriteWaveHeader(FILE * const fp, int pcmbytes, int freq, int channels, int bits)
913 int bytes = (bits + 7) / 8;
915 /* quick and dirty, but documented */
916 fwrite("RIFF", 1, 4, fp); /* label */
917 write_32_bits_low_high(fp, pcmbytes + 44 - 8); /* length in bytes without header */
918 fwrite("WAVEfmt ", 2, 4, fp); /* 2 labels */
919 write_32_bits_low_high(fp, 2 + 2 + 4 + 4 + 2 + 2); /* length of PCM format declaration area */
920 write_16_bits_low_high(fp, 1); /* is PCM? */
921 write_16_bits_low_high(fp, channels); /* number of channels */
922 write_32_bits_low_high(fp, freq); /* sample frequency in [Hz] */
923 write_32_bits_low_high(fp, freq * channels * bytes); /* bytes per second */
924 write_16_bits_low_high(fp, channels * bytes); /* bytes per sample time */
925 write_16_bits_low_high(fp, bits); /* bits per sample */
926 fwrite("data", 1, 4, fp); /* label */
927 write_32_bits_low_high(fp, pcmbytes); /* length in bytes of raw PCM data */
929 return ferror(fp) ? -1 : 0;
935 #if defined(LIBSNDFILE)
937 extern SNDFILE *sf_wchar_open(wchar_t const *wpath, int mode, SF_INFO * sfinfo);
940 open_snd_file(lame_t gfp, char const *inPath)
942 char const *lpszFileName = inPath;
943 SNDFILE *gs_pSndFileIn = NULL;
948 wchar_t *file_name = utf8ToUnicode(lpszFileName);
950 /* Try to open the sound file */
951 memset(&gs_wfInfo, 0, sizeof(gs_wfInfo));
953 gs_pSndFileIn = sf_wchar_open(file_name, SFM_READ, &gs_wfInfo);
955 gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
958 if (gs_pSndFileIn == NULL) {
959 if (global_raw_pcm.in_signed == 0 && global_raw_pcm.in_bitwidth != 8) {
960 error_printf("Unsigned input only supported with bitwidth 8\n");
963 /* set some defaults incase input is raw PCM */
964 gs_wfInfo.seekable = (global_reader.input_format != sf_raw); /* if user specified -r, set to not seekable */
965 gs_wfInfo.samplerate = lame_get_in_samplerate(gfp);
966 gs_wfInfo.channels = lame_get_num_channels(gfp);
967 gs_wfInfo.format = SF_FORMAT_RAW;
968 if ((global_raw_pcm.in_endian == ByteOrderLittleEndian) ^ (global_reader.swapbytes !=
970 gs_wfInfo.format |= SF_ENDIAN_LITTLE;
973 gs_wfInfo.format |= SF_ENDIAN_BIG;
975 switch (global_raw_pcm.in_bitwidth) {
978 global_raw_pcm.in_signed == 0 ? SF_FORMAT_PCM_U8 : SF_FORMAT_PCM_S8;
981 gs_wfInfo.format |= SF_FORMAT_PCM_16;
984 gs_wfInfo.format |= SF_FORMAT_PCM_24;
987 gs_wfInfo.format |= SF_FORMAT_PCM_32;
993 gs_pSndFileIn = sf_wchar_open(file_name, SFM_READ, &gs_wfInfo);
995 gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
1003 if (gs_pSndFileIn == NULL) {
1004 sf_perror(gs_pSndFileIn);
1005 if (global_ui_config.silent < 10) {
1006 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
1010 sf_command(gs_pSndFileIn, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE);
1012 if ((gs_wfInfo.format & SF_FORMAT_RAW) == SF_FORMAT_RAW) {
1013 global_reader.input_format = sf_raw;
1016 #ifdef _DEBUG_SND_FILE
1017 printf("\n\nSF_INFO structure\n");
1018 printf("samplerate :%d\n", gs_wfInfo.samplerate);
1019 printf("samples :%d\n", gs_wfInfo.frames);
1020 printf("channels :%d\n", gs_wfInfo.channels);
1023 /* new formats from sbellon@sbellon.de 1/2000 */
1025 switch (gs_wfInfo.format & SF_FORMAT_TYPEMASK) {
1027 printf("Microsoft WAV format (big endian). ");
1029 case SF_FORMAT_AIFF:
1030 printf("Apple/SGI AIFF format (little endian). ");
1033 printf("Sun/NeXT AU format (big endian). ");
1036 case SF_FORMAT_AULE:
1037 DEBUGF("DEC AU format (little endian). ");
1041 printf("RAW PCM data. ");
1044 printf("Ensoniq PARIS file format. ");
1047 printf("Amiga IFF / SVX8 / SV16 format. ");
1049 case SF_FORMAT_NIST:
1050 printf("Sphere NIST format. ");
1057 switch (gs_wfInfo.format & SF_FORMAT_SUBMASK) {
1060 DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
1063 case SF_FORMAT_FLOAT:
1064 printf("32 bit Intel x86 floats.");
1066 case SF_FORMAT_ULAW:
1067 printf("U-Law encoded.");
1069 case SF_FORMAT_ALAW:
1070 printf("A-Law encoded.");
1072 case SF_FORMAT_IMA_ADPCM:
1073 printf("IMA ADPCM.");
1075 case SF_FORMAT_MS_ADPCM:
1076 printf("Microsoft ADPCM.");
1079 case SF_FORMAT_PCM_BE:
1080 DEBUGF("Big endian PCM data.");
1082 case SF_FORMAT_PCM_LE:
1083 DEBUGF("Little endian PCM data.");
1086 case SF_FORMAT_PCM_S8:
1087 printf("Signed 8 bit PCM.");
1089 case SF_FORMAT_PCM_U8:
1090 printf("Unsigned 8 bit PCM.");
1092 case SF_FORMAT_PCM_16:
1093 printf("Signed 16 bit PCM.");
1095 case SF_FORMAT_PCM_24:
1096 printf("Signed 24 bit PCM.");
1098 case SF_FORMAT_PCM_32:
1099 printf("Signed 32 bit PCM.");
1102 case SF_FORMAT_SVX_FIB:
1103 DEBUGF("SVX Fibonacci Delta encoding.");
1105 case SF_FORMAT_SVX_EXP:
1106 DEBUGF("SVX Exponential Delta encoding.");
1115 printf("sections :%d\n", gs_wfInfo.sections);
1116 printf("seekable :\n", gs_wfInfo.seekable);
1119 if (gs_pSndFileIn == NULL) {
1120 sf_perror(gs_pSndFileIn);
1121 if (global_ui_config.silent < 10) {
1122 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
1128 (void) lame_set_num_samples(gfp, gs_wfInfo.frames);
1129 if (-1 == lame_set_num_channels(gfp, gs_wfInfo.channels)) {
1130 if (global_ui_config.silent < 10) {
1131 error_printf("Unsupported number of channels: %ud\n", gs_wfInfo.channels);
1135 if (global_reader.input_samplerate == 0) {
1136 (void) lame_set_in_samplerate(gfp, gs_wfInfo.samplerate);
1139 (void) lame_set_in_samplerate(gfp, global_reader.input_samplerate);
1141 global. pcmbitwidth = 32;
1144 if (lame_get_num_samples(gfp) == MAX_U_32_NUM) {
1145 /* try to figure out num_samples */
1146 double const flen = lame_get_file_size(lpszFileName);
1148 /* try file size, assume 2 bytes per sample */
1149 lame_set_num_samples(gfp, flen / (2 * lame_get_num_channels(gfp)));
1153 return gs_pSndFileIn;
1156 #endif /* defined(LIBSNDFILE) */
1160 /************************************************************************
1161 unpack_read_samples - read and unpack signed low-to-high byte or unsigned
1162 single byte input. (used for read_samples function)
1163 Output integers are stored in the native byte order
1164 (little or big endian). -jd
1167 swap_order - set for high-to-low byte order input stream
1169 out: sample_buffer (must be allocated up to samples_to_read upon call)
1170 returns: number of samples read
1173 unpack_read_samples(const int samples_to_read, const int bytes_per_sample,
1174 const int swap_order, int *sample_buffer, FILE * pcm_in)
1176 size_t samples_read;
1178 int *op; /* output pointer */
1179 unsigned char *ip = (unsigned char *) sample_buffer; /* input pointer */
1180 const int b = sizeof(int) * 8;
1182 #define GA_URS_IFLOOP( ga_urs_bps ) \
1183 if( bytes_per_sample == ga_urs_bps ) \
1184 for( i = samples_read * bytes_per_sample; (i -= bytes_per_sample) >=0;)
1186 samples_read = fread(sample_buffer, bytes_per_sample, samples_to_read, pcm_in);
1187 op = sample_buffer + samples_read;
1189 if (swap_order == 0) {
1191 * --op = ip[i] << (b - 8);
1193 * --op = ip[i] << (b - 16) | ip[i + 1] << (b - 8);
1195 * --op = ip[i] << (b - 24) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 8);
1198 ip[i] << (b - 32) | ip[i + 1] << (b - 24) | ip[i + 2] << (b - 16) | ip[i + 3] << (b -
1203 * --op = (ip[i] ^ 0x80) << (b - 8) | 0x7f << (b - 16); /* convert from unsigned */
1205 * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16);
1207 * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24);
1210 ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24) | ip[i + 3] << (b -
1213 #undef GA_URS_IFLOOP
1214 if (global.pcm_is_ieee_float) {
1215 ieee754_float32_t const m_max = INT_MAX;
1216 ieee754_float32_t const m_min = -(ieee754_float32_t) INT_MIN;
1217 ieee754_float32_t *x = (ieee754_float32_t *) sample_buffer;
1218 assert(sizeof(ieee754_float32_t) == sizeof(int));
1219 for (i = 0; i < samples_to_read; ++i) {
1220 ieee754_float32_t const u = x[i];
1229 v = (int) (u * m_max + 0.5f);
1232 v = (int) (u * m_min - 0.5f);
1234 sample_buffer[i] = v;
1237 return (samples_read);
1242 /************************************************************************
1246 * PURPOSE: reads the PCM samples from a file to the buffer
1249 * Reads #samples_read# number of shorts from #musicin# filepointer
1250 * into #sample_buffer[]#. Returns the number of samples read.
1252 ************************************************************************/
1255 read_samples_pcm(FILE * musicin, int sample_buffer[2304], int samples_to_read)
1258 int bytes_per_sample = global.pcmbitwidth / 8;
1259 int swap_byte_order; /* byte order of input stream */
1261 switch (global.pcmbitwidth) {
1265 if (global_raw_pcm.in_signed == 0) {
1266 if (global_ui_config.silent < 10) {
1267 error_printf("Unsigned input only supported with bitwidth 8\n");
1271 swap_byte_order = (global_raw_pcm.in_endian != ByteOrderLittleEndian) ? 1 : 0;
1272 if (global.pcmswapbytes) {
1273 swap_byte_order = !swap_byte_order;
1278 swap_byte_order = global.pcm_is_unsigned_8bit;
1282 if (global_ui_config.silent < 10) {
1283 error_printf("Only 8, 16, 24 and 32 bit input files supported \n");
1287 samples_read = unpack_read_samples(samples_to_read, bytes_per_sample, swap_byte_order,
1288 sample_buffer, musicin);
1289 if (ferror(musicin)) {
1290 if (global_ui_config.silent < 10) {
1291 error_printf("Error reading input file\n");
1296 return samples_read;
1301 /* AIFF Definitions */
1303 static int const IFF_ID_FORM = 0x464f524d; /* "FORM" */
1304 static int const IFF_ID_AIFF = 0x41494646; /* "AIFF" */
1305 static int const IFF_ID_AIFC = 0x41494643; /* "AIFC" */
1306 static int const IFF_ID_COMM = 0x434f4d4d; /* "COMM" */
1307 static int const IFF_ID_SSND = 0x53534e44; /* "SSND" */
1308 static int const IFF_ID_MPEG = 0x4d504547; /* "MPEG" */
1310 static int const IFF_ID_NONE = 0x4e4f4e45; /* "NONE" *//* AIFF-C data format */
1311 static int const IFF_ID_2CBE = 0x74776f73; /* "twos" *//* AIFF-C data format */
1312 static int const IFF_ID_2CLE = 0x736f7774; /* "sowt" *//* AIFF-C data format */
1314 static int const WAV_ID_RIFF = 0x52494646; /* "RIFF" */
1315 static int const WAV_ID_WAVE = 0x57415645; /* "WAVE" */
1316 static int const WAV_ID_FMT = 0x666d7420; /* "fmt " */
1317 static int const WAV_ID_DATA = 0x64617461; /* "data" */
1319 #ifndef WAVE_FORMAT_PCM
1320 static short const WAVE_FORMAT_PCM = (short)0x0001U;
1322 #ifndef WAVE_FORMAT_IEEE_FLOAT
1323 static short const WAVE_FORMAT_IEEE_FLOAT = (short)0x0003U;
1325 #ifndef WAVE_FORMAT_EXTENSIBLE
1326 static short const WAVE_FORMAT_EXTENSIBLE = (short)0xFFFEU;
1331 make_even_number_of_bytes_in_length(long x)
1333 if ((x & 0x01) != 0) {
1340 /*****************************************************************************
1342 * Read Microsoft Wave headers
1344 * By the time we get here the first 32-bits of the file have already been
1345 * read, and we're pretty sure that we're looking at a WAV file.
1347 *****************************************************************************/
1350 parse_wave_header(lame_global_flags * gfp, FILE * sf)
1354 int block_align = 0;
1355 int bits_per_sample = 0;
1356 int samples_per_sec = 0;
1357 int avg_bytes_per_sec = 0;
1361 long data_length = 0, file_length, subSize = 0;
1362 int loop_sanity = 0;
1364 file_length = read_32_bits_high_low(sf);
1365 if (read_32_bits_high_low(sf) != WAV_ID_WAVE)
1368 for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
1369 int type = read_32_bits_high_low(sf);
1371 if (type == WAV_ID_FMT) {
1372 subSize = read_32_bits_low_high(sf);
1373 subSize = make_even_number_of_bytes_in_length(subSize);
1376 "'fmt' chunk too short (only %ld bytes)!", subSize); */
1380 format_tag = read_16_bits_low_high(sf);
1382 channels = read_16_bits_low_high(sf);
1384 samples_per_sec = read_32_bits_low_high(sf);
1386 avg_bytes_per_sec = read_32_bits_low_high(sf);
1388 block_align = read_16_bits_low_high(sf);
1390 bits_per_sample = read_16_bits_low_high(sf);
1393 /* WAVE_FORMAT_EXTENSIBLE support */
1394 if ((subSize > 9) && (format_tag == WAVE_FORMAT_EXTENSIBLE)) {
1395 read_16_bits_low_high(sf); /* cbSize */
1396 read_16_bits_low_high(sf); /* ValidBitsPerSample */
1397 read_32_bits_low_high(sf); /* ChannelMask */
1398 /* SubType coincident with format_tag for PCM int or float */
1399 format_tag = read_16_bits_low_high(sf);
1403 /* DEBUGF(" skipping %d bytes\n", subSize); */
1406 if (fskip(sf, (long) subSize, SEEK_CUR) != 0)
1411 else if (type == WAV_ID_DATA) {
1412 subSize = read_32_bits_low_high(sf);
1413 data_length = subSize;
1415 /* We've found the audio data. Read no further! */
1420 subSize = read_32_bits_low_high(sf);
1421 subSize = make_even_number_of_bytes_in_length(subSize);
1422 if (fskip(sf, (long) subSize, SEEK_CUR) != 0) {
1428 if (format_tag != WAVE_FORMAT_PCM && format_tag != WAVE_FORMAT_IEEE_FLOAT) {
1429 if (global_ui_config.silent < 10) {
1430 error_printf("Unsupported data format: 0x%04X\n", format_tag);
1432 return 0; /* oh no! non-supported format */
1436 /* make sure the header is sane */
1437 if (-1 == lame_set_num_channels(gfp, channels)) {
1438 if (global_ui_config.silent < 10) {
1439 error_printf("Unsupported number of channels: %u\n", channels);
1443 if (global_reader.input_samplerate == 0) {
1444 (void) lame_set_in_samplerate(gfp, samples_per_sec);
1447 (void) lame_set_in_samplerate(gfp, global_reader.input_samplerate);
1449 global. pcmbitwidth = bits_per_sample;
1450 global. pcm_is_unsigned_8bit = 1;
1451 global. pcm_is_ieee_float = (format_tag == WAVE_FORMAT_IEEE_FLOAT ? 1 : 0);
1452 (void) lame_set_num_samples(gfp, data_length / (channels * ((bits_per_sample + 7) / 8)));
1460 /************************************************************************
1463 * PURPOSE: Checks AIFF header information to make sure it is valid.
1464 * returns 0 on success, 1 on errors
1465 ************************************************************************/
1468 aiff_check2(IFF_AIFF * const pcm_aiff_data)
1470 if (pcm_aiff_data->sampleType != (unsigned long) IFF_ID_SSND) {
1471 if (global_ui_config.silent < 10) {
1472 error_printf("ERROR: input sound data is not PCM\n");
1476 switch (pcm_aiff_data->sampleSize) {
1483 if (global_ui_config.silent < 10) {
1484 error_printf("ERROR: input sound data is not 8, 16, 24 or 32 bits\n");
1488 if (pcm_aiff_data->numChannels != 1 && pcm_aiff_data->numChannels != 2) {
1489 if (global_ui_config.silent < 10) {
1490 error_printf("ERROR: input sound data is not mono or stereo\n");
1494 if (pcm_aiff_data->blkAlgn.blockSize != 0) {
1495 if (global_ui_config.silent < 10) {
1496 error_printf("ERROR: block size of input sound data is not 0 bytes\n");
1500 /* A bug, since we correctly skip the offset earlier in the code.
1501 if (pcm_aiff_data->blkAlgn.offset != 0) {
1502 error_printf("Block offset is not 0 bytes in '%s'\n", file_name);
1510 /*****************************************************************************
1512 * Read Audio Interchange File Format (AIFF) headers.
1514 * By the time we get here the first 32 bits of the file have already been
1515 * read, and we're pretty sure that we're looking at an AIFF file.
1517 *****************************************************************************/
1520 parse_aiff_header(lame_global_flags * gfp, FILE * sf)
1522 long chunkSize = 0, subSize = 0, typeID = 0, dataType = IFF_ID_NONE;
1524 int seen_comm_chunk = 0, seen_ssnd_chunk = 0;
1525 long pcm_data_pos = -1;
1527 memset(&aiff_info, 0, sizeof(aiff_info));
1528 chunkSize = read_32_bits_high_low(sf);
1530 typeID = read_32_bits_high_low(sf);
1531 if ((typeID != IFF_ID_AIFF) && (typeID != IFF_ID_AIFC))
1534 while (chunkSize > 0) {
1536 int type = read_32_bits_high_low(sf);
1540 "found chunk type %08x '%4.4s'\n", type, (char*)&type); */
1542 /* don't use a switch here to make it easier to use 'break' for SSND */
1543 if (type == IFF_ID_COMM) {
1544 seen_comm_chunk = seen_ssnd_chunk + 1;
1545 subSize = read_32_bits_high_low(sf);
1546 ckSize = make_even_number_of_bytes_in_length(subSize);
1547 chunkSize -= ckSize;
1549 aiff_info.numChannels = (short) read_16_bits_high_low(sf);
1551 aiff_info.numSampleFrames = read_32_bits_high_low(sf);
1553 aiff_info.sampleSize = (short) read_16_bits_high_low(sf);
1555 aiff_info.sampleRate = read_ieee_extended_high_low(sf);
1557 if (typeID == IFF_ID_AIFC) {
1558 dataType = read_32_bits_high_low(sf);
1561 if (fskip(sf, ckSize, SEEK_CUR) != 0)
1564 else if (type == IFF_ID_SSND) {
1565 seen_ssnd_chunk = 1;
1566 subSize = read_32_bits_high_low(sf);
1567 ckSize = make_even_number_of_bytes_in_length(subSize);
1568 chunkSize -= ckSize;
1570 aiff_info.blkAlgn.offset = read_32_bits_high_low(sf);
1572 aiff_info.blkAlgn.blockSize = read_32_bits_high_low(sf);
1575 aiff_info.sampleType = IFF_ID_SSND;
1577 if (seen_comm_chunk > 0) {
1578 if (fskip(sf, (long) aiff_info.blkAlgn.offset, SEEK_CUR) != 0)
1580 /* We've found the audio data. Read no further! */
1583 pcm_data_pos = ftell(sf);
1584 if (pcm_data_pos >= 0) {
1585 pcm_data_pos += aiff_info.blkAlgn.offset;
1587 if (fskip(sf, ckSize, SEEK_CUR) != 0)
1591 subSize = read_32_bits_high_low(sf);
1592 ckSize = make_even_number_of_bytes_in_length(subSize);
1593 chunkSize -= ckSize;
1595 if (fskip(sf, ckSize, SEEK_CUR) != 0)
1599 if (dataType == IFF_ID_2CLE) {
1600 global. pcmswapbytes = global_reader.swapbytes;
1602 else if (dataType == IFF_ID_2CBE) {
1603 global. pcmswapbytes = !global_reader.swapbytes;
1605 else if (dataType == IFF_ID_NONE) {
1606 global. pcmswapbytes = !global_reader.swapbytes;
1612 /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
1613 if (seen_comm_chunk && (seen_ssnd_chunk > 0 || aiff_info.numSampleFrames == 0)) {
1614 /* make sure the header is sane */
1615 if (0 != aiff_check2(&aiff_info))
1617 if (-1 == lame_set_num_channels(gfp, aiff_info.numChannels)) {
1618 if (global_ui_config.silent < 10) {
1619 error_printf("Unsupported number of channels: %u\n", aiff_info.numChannels);
1623 if (global_reader.input_samplerate == 0) {
1624 (void) lame_set_in_samplerate(gfp, (int) aiff_info.sampleRate);
1627 (void) lame_set_in_samplerate(gfp, global_reader.input_samplerate);
1629 (void) lame_set_num_samples(gfp, aiff_info.numSampleFrames);
1630 global. pcmbitwidth = aiff_info.sampleSize;
1631 global. pcm_is_unsigned_8bit = 0;
1632 global. pcm_is_ieee_float = 0; /* FIXME: possible ??? */
1633 if (pcm_data_pos >= 0) {
1634 if (fseek(sf, pcm_data_pos, SEEK_SET) != 0) {
1635 if (global_ui_config.silent < 10) {
1636 error_printf("Can't rewind stream to audio data position\n");
1649 /************************************************************************
1653 * PURPOSE: Read the header from a bytestream. Try to determine whether
1654 * it's a WAV file or AIFF without rewinding, since rewind
1655 * doesn't work on pipes and there's a good chance we're reading
1656 * from stdin (otherwise we'd probably be using libsndfile).
1658 * When this function returns, the file offset will be positioned at the
1659 * beginning of the sound data.
1661 ************************************************************************/
1664 parse_file_header(lame_global_flags * gfp, FILE * sf)
1667 int type = read_32_bits_high_low(sf);
1670 "First word of input stream: %08x '%4.4s'\n", type, (char*) &type);
1672 global. count_samples_carefully = 0;
1673 global. pcm_is_unsigned_8bit = global_raw_pcm.in_signed == 1 ? 0 : 1;
1674 /*global_reader.input_format = sf_raw; commented out, because it is better to fail
1675 here as to encode some hundreds of input files not supported by LAME
1676 If you know you have RAW PCM data, use the -r switch
1679 if (type == WAV_ID_RIFF) {
1680 /* It's probably a WAV file */
1681 int const ret = parse_wave_header(gfp, sf);
1683 global. count_samples_carefully = 1;
1687 if (global_ui_config.silent < 10) {
1688 error_printf("Warning: corrupt or unsupported WAVE format\n");
1692 else if (type == IFF_ID_FORM) {
1693 /* It's probably an AIFF file */
1694 int const ret = parse_aiff_header(gfp, sf);
1696 global. count_samples_carefully = 1;
1700 if (global_ui_config.silent < 10) {
1701 error_printf("Warning: corrupt or unsupported AIFF format\n");
1706 if (global_ui_config.silent < 10) {
1707 error_printf("Warning: unsupported audio format\n");
1715 open_wave_file(lame_t gfp, char const *inPath)
1719 /* set the defaults from info incase we cannot determine them from file */
1720 lame_set_num_samples(gfp, MAX_U_32_NUM);
1722 if (!strcmp(inPath, "-")) {
1723 lame_set_stream_binary_mode(musicin = stdin); /* Read from standard input. */
1726 if ((musicin = lame_fopen(inPath, "rb")) == NULL) {
1727 if (global_ui_config.silent < 10) {
1728 error_printf("Could not find \"%s\".\n", inPath);
1734 if (global_reader.input_format == sf_ogg) {
1735 if (global_ui_config.silent < 10) {
1736 error_printf("sorry, vorbis support in LAME is deprecated.\n");
1740 else if (global_reader.input_format == sf_raw) {
1741 /* assume raw PCM */
1742 if (global_ui_config.silent < 9) {
1743 console_printf("Assuming raw pcm input file");
1744 if (global_reader.swapbytes)
1745 console_printf(" : Forcing byte-swapping\n");
1747 console_printf("\n");
1749 global. pcmswapbytes = global_reader.swapbytes;
1752 global_reader.input_format = parse_file_header(gfp, musicin);
1754 if (global_reader.input_format == sf_unknown) {
1758 if (lame_get_num_samples(gfp) == MAX_U_32_NUM && musicin != stdin) {
1759 double const flen = lame_get_file_size(musicin); /* try to figure out num_samples */
1761 /* try file size, assume 2 bytes per sample */
1762 unsigned long fsize = (unsigned long) (flen / (2 * lame_get_num_channels(gfp)));
1763 (void) lame_set_num_samples(gfp, fsize);
1772 open_mpeg_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding)
1776 /* set the defaults from info incase we cannot determine them from file */
1777 lame_set_num_samples(gfp, MAX_U_32_NUM);
1779 if (strcmp(inPath, "-") == 0) {
1781 lame_set_stream_binary_mode(musicin); /* Read from standard input. */
1784 musicin = lame_fopen(inPath, "rb");
1785 if (musicin == NULL) {
1786 if (global_ui_config.silent < 10) {
1787 error_printf("Could not find \"%s\".\n", inPath);
1793 if (-1 == lame_decode_initfile(inPath, &global_decoder.mp3input_data)) {
1794 if (global_ui_config.silent < 10) {
1795 error_printf("Error reading headers in mp3 input file %s.\n", inPath);
1797 close_input_file(musicin);
1802 if (-1 == lame_decode_initfile(musicin, &global_decoder.mp3input_data, enc_delay, enc_padding)) {
1803 if (global_ui_config.silent < 10) {
1804 error_printf("Error reading headers in mp3 input file %s.\n", inPath);
1806 close_input_file(musicin);
1810 if (-1 == lame_set_num_channels(gfp, global_decoder.mp3input_data.stereo)) {
1811 if (global_ui_config.silent < 10) {
1812 error_printf("Unsupported number of channels: %ud\n",
1813 global_decoder.mp3input_data.stereo);
1815 close_input_file(musicin);
1818 if (global_reader.input_samplerate == 0) {
1819 (void) lame_set_in_samplerate(gfp, global_decoder.mp3input_data.samplerate);
1822 (void) lame_set_in_samplerate(gfp, global_reader.input_samplerate);
1824 (void) lame_set_num_samples(gfp, global_decoder.mp3input_data.nsamp);
1826 if (lame_get_num_samples(gfp) == MAX_U_32_NUM && musicin != stdin) {
1827 double flen = lame_get_file_size(musicin); /* try to figure out num_samples */
1829 /* try file size, assume 2 bytes per sample */
1830 if (global_decoder.mp3input_data.bitrate > 0) {
1831 double totalseconds =
1832 (flen * 8.0 / (1000.0 * global_decoder.mp3input_data.bitrate));
1833 unsigned long tmp_num_samples =
1834 (unsigned long) (totalseconds * lame_get_in_samplerate(gfp));
1836 (void) lame_set_num_samples(gfp, tmp_num_samples);
1837 global_decoder.mp3input_data.nsamp = tmp_num_samples;
1846 close_input_file(FILE * musicin)
1850 if (musicin != stdin && musicin != 0) {
1851 ret = fclose(musicin);
1854 if (global_ui_config.silent < 10) {
1855 error_printf("Could not close audio input file\n");
1863 #if defined(HAVE_MPGLIB)
1865 check_aid(const unsigned char *header)
1867 return 0 == memcmp(header, "AiD\1", 4);
1871 * Please check this and don't kill me if there's a bug
1872 * This is a (nearly?) complete header analysis for a MPEG-1/2/2.5 Layer I, II or III
1877 is_syncword_mp123(const void *const headerptr)
1879 const unsigned char *const p = headerptr;
1880 static const char abl2[16] = { 0, 7, 7, 7, 0, 7, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8 };
1882 if ((p[0] & 0xFF) != 0xFF)
1883 return 0; /* first 8 bits must be '1' */
1884 if ((p[1] & 0xE0) != 0xE0)
1885 return 0; /* next 3 bits are also */
1886 if ((p[1] & 0x18) == 0x08)
1887 return 0; /* no MPEG-1, -2 or -2.5 */
1888 switch (p[1] & 0x06) {
1890 case 0x00: /* illegal Layer */
1893 case 0x02: /* Layer3 */
1894 if (global_reader.input_format != sf_mp3 && global_reader.input_format != sf_mp123) {
1897 global_reader.input_format = sf_mp3;
1900 case 0x04: /* Layer2 */
1901 if (global_reader.input_format != sf_mp2 && global_reader.input_format != sf_mp123) {
1904 global_reader.input_format = sf_mp2;
1907 case 0x06: /* Layer1 */
1908 if (global_reader.input_format != sf_mp1 && global_reader.input_format != sf_mp123) {
1911 global_reader.input_format = sf_mp1;
1914 if ((p[1] & 0x06) == 0x00)
1915 return 0; /* no Layer I, II and III */
1916 if ((p[2] & 0xF0) == 0xF0)
1917 return 0; /* bad bitrate */
1918 if ((p[2] & 0x0C) == 0x0C)
1919 return 0; /* no sample frequency with (32,44.1,48)/(1,2,4) */
1920 if ((p[1] & 0x18) == 0x18 && (p[1] & 0x06) == 0x04 && abl2[p[2] >> 4] & (1 << (p[3] >> 6)))
1922 if ((p[3] & 3) == 2)
1923 return 0; /* reserved enphasis mode */
1928 lenOfId3v2Tag(unsigned char const* buf)
1930 unsigned int b0 = buf[0] & 127;
1931 unsigned int b1 = buf[1] & 127;
1932 unsigned int b2 = buf[2] & 127;
1933 unsigned int b3 = buf[3] & 127;
1934 return (((((b0 << 7) + b1) << 7) + b2) << 7) + b3;
1938 lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding)
1940 /* VBRTAGDATA pTagData; */
1941 /* int xing_header,len2,num_frames; */
1942 unsigned char buf[100];
1946 short int pcm_l[1152], pcm_r[1152];
1949 memset(mp3data, 0, sizeof(mp3data_struct));
1951 hip_decode_exit(global.hip);
1953 global. hip = hip_decode_init();
1954 hip_set_msgf(global.hip, global_ui_config.silent < 10 ? &frontend_msgf : 0);
1955 hip_set_errorf(global.hip, global_ui_config.silent < 10 ? &frontend_errorf : 0);
1956 hip_set_debugf(global.hip, &frontend_debugf);
1959 if (fread(buf, 1, len, fd) != len)
1960 return -1; /* failed */
1961 while (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3') {
1963 if (fread(&buf[4], 1, len, fd) != len)
1964 return -1; /* failed */
1965 len = lenOfId3v2Tag(&buf[6]);
1966 if (global.in_id3v2_size < 1) {
1967 global.in_id3v2_size = 10 + len;
1968 global.in_id3v2_tag = malloc(global.in_id3v2_size);
1969 if (global.in_id3v2_tag) {
1970 memcpy(global.in_id3v2_tag, buf, 10);
1971 if (fread(&global.in_id3v2_tag[10], 1, len, fd) != len)
1972 return -1; /* failed */
1973 len = 0; /* copied, nothing to skip */
1976 global.in_id3v2_size = 0;
1979 fskip(fd, len, SEEK_CUR);
1981 if (fread(&buf, 1, len, fd) != len)
1982 return -1; /* failed */
1984 aid_header = check_aid(buf);
1986 if (fread(&buf, 1, 2, fd) != 2)
1987 return -1; /* failed */
1988 aid_header = (unsigned char) buf[0] + 256 * (unsigned char) buf[1];
1989 if (global_ui_config.silent < 9) {
1990 console_printf("Album ID found. length=%i \n", aid_header);
1992 /* skip rest of AID, except for 6 bytes we have already read */
1993 fskip(fd, aid_header - 6, SEEK_CUR);
1995 /* read 4 more bytes to set up buffer for MP3 header check */
1996 if (fread(&buf, 1, len, fd) != len)
1997 return -1; /* failed */
2000 while (!is_syncword_mp123(buf)) {
2002 for (i = 0; i < len - 1; i++)
2003 buf[i] = buf[i + 1];
2004 if (fread(buf + len - 1, 1, 1, fd) != 1)
2005 return -1; /* failed */
2008 if ((buf[2] & 0xf0) == 0) {
2009 if (global_ui_config.silent < 9) {
2010 console_printf("Input file is freeformat.\n");
2014 /* now parse the current buffer looking for MP3 headers. */
2015 /* (as of 11/00: mpglib modified so that for the first frame where */
2016 /* headers are parsed, no data will be decoded. */
2017 /* However, for freeformat, we need to decode an entire frame, */
2018 /* so mp3data->bitrate will be 0 until we have decoded the first */
2019 /* frame. Cannot decode first frame here because we are not */
2020 /* yet prepared to handle the output. */
2021 ret = hip_decode1_headersB(global.hip, buf, len, pcm_l, pcm_r, mp3data, enc_delay, enc_padding);
2025 /* repeat until we decode a valid mp3 header. */
2026 while (!mp3data->header_parsed) {
2027 len = fread(buf, 1, sizeof(buf), fd);
2028 if (len != sizeof(buf))
2031 hip_decode1_headersB(global.hip, buf, len, pcm_l, pcm_r, mp3data, enc_delay,
2037 if (mp3data->bitrate == 0 && !freeformat) {
2038 if (global_ui_config.silent < 10) {
2039 error_printf("fail to sync...\n");
2041 return lame_decode_initfile(fd, mp3data, enc_delay, enc_padding);
2044 if (mp3data->totalframes > 0) {
2045 /* mpglib found a Xing VBR header and computed nsamp & totalframes */
2048 /* set as unknown. Later, we will take a guess based on file size
2050 mp3data->nsamp = MAX_U_32_NUM;
2055 report_printf("ret = %i NEED_MORE=%i \n",ret,MP3_NEED_MORE);
2056 report_printf("stereo = %i \n",mp.fr.stereo);
2057 report_printf("samp = %i \n",freqs[mp.fr.sampling_frequency]);
2058 report_printf("framesize = %i \n",framesize);
2059 report_printf("bitrate = %i \n",mp3data->bitrate);
2060 report_printf("num frames = %ui \n",num_frames);
2061 report_printf("num samp = %ui \n",mp3data->nsamp);
2062 report_printf("mode = %i \n",mp.fr.mode);
2069 For lame_decode_fromfile: return code
2071 n number of samples output. either 576 or 1152 depending on MP3 file.
2074 For lame_decode1_headers(): return code
2076 0 ok, but need more data before outputing any samples
2077 n number of samples output. either 576 or 1152 depending on MP3 file.
2080 lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
2084 unsigned char buf[1024];
2086 /* first see if we still have data buffered in the decoder: */
2087 ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2092 /* read until we get a valid output frame */
2094 len = fread(buf, 1, 1024, fd);
2096 /* we are done reading the file, but check for buffered data */
2097 ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2099 hip_decode_exit(global.hip); /* release mp3decoder memory */
2101 return -1; /* done with file */
2106 ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2108 hip_decode_exit(global.hip); /* release mp3decoder memory */
2117 #endif /* defined(HAVE_MPGLIB) */
2121 is_mpeg_file_format(int input_file_format)
2123 switch (input_file_format) {
2139 #define LOW__BYTE(x) (x & 0x00ff)
2140 #define HIGH_BYTE(x) ((x >> 8) & 0x00ff)
2143 put_audio16(FILE * outf, short Buffer[2][1152], int iread, int nch)
2145 char data[2 * 1152 * 2];
2148 if (global_decoder.disable_wav_header && global_reader.swapbytes) {
2150 for (i = 0; i < iread; i++) {
2151 short x = Buffer[0][i];
2152 /* write 16 Bits High Low */
2153 data[m++] = HIGH_BYTE(x);
2154 data[m++] = LOW__BYTE(x);
2158 for (i = 0; i < iread; i++) {
2159 short x = Buffer[0][i], y = Buffer[1][i];
2160 /* write 16 Bits High Low */
2161 data[m++] = HIGH_BYTE(x);
2162 data[m++] = LOW__BYTE(x);
2163 /* write 16 Bits High Low */
2164 data[m++] = HIGH_BYTE(y);
2165 data[m++] = LOW__BYTE(y);
2171 for (i = 0; i < iread; i++) {
2172 short x = Buffer[0][i];
2173 /* write 16 Bits Low High */
2174 data[m++] = LOW__BYTE(x);
2175 data[m++] = HIGH_BYTE(x);
2179 for (i = 0; i < iread; i++) {
2180 short x = Buffer[0][i], y = Buffer[1][i];
2181 /* write 16 Bits Low High */
2182 data[m++] = LOW__BYTE(x);
2183 data[m++] = HIGH_BYTE(x);
2184 /* write 16 Bits Low High */
2185 data[m++] = LOW__BYTE(y);
2186 data[m++] = HIGH_BYTE(y);
2191 fwrite(data, 1, m, outf);
2193 if (global_writer.flush_write == 1) {
2205 sizeOfOldTag(lame_t gf)
2208 return global.in_id3v2_size;
2212 getOldTag(lame_t gf)
2215 return global.in_id3v2_tag;
2218 /* end of get_audio.c */