1 /*
2  *      Get Audio routines source file
3  *
4  *      Copyright (c) 1999 Albert L Faber
5  *                    2008-2017 Robert Hegemann
6  *
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.
11  *
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.
16  *
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.
21  */
22 
23 /* $Id$ */
24 
25 
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29 
30 #include <assert.h>
31 
32 #ifdef HAVE_LIMITS_H
33 # include <limits.h>
34 #endif
35 
36 #include <stdio.h>
37 
38 #ifdef STDC_HEADERS
39 # include <stdlib.h>
40 # include <string.h>
41 #else
42 # ifndef HAVE_STRCHR
43 #  define strchr index
44 #  define strrchr rindex
45 # endif
46 char   *strchr(), *strrchr();
47 # ifndef HAVE_MEMCPY
48 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
49 #  define memmove(d, s, n) bcopy ((s), (d), (n))
50 # endif
51 #endif
52 
53 #ifdef HAVE_INTTYPES_H
54 # include <inttypes.h>
55 #else
56 # ifdef HAVE_STDINT_H
57 #  include <stdint.h>
58 # endif
59 #endif
60 
61 #if defined(HAVE_MPGLIB) || defined(HAVE_MPG123)
62 #define hip_global_struct mpstr_tag
63 #endif
64 #ifdef HAVE_MPG123
65 #include <mpg123.h>
66 /* for mpstr_tag */
67 #include "mpglib/mpglib.h"
68 
69 #endif
70 
71 #define         MAX_U_32_NUM            0xFFFFFFFF
72 
73 
74 #include <math.h>
75 
76 #if defined(__riscos__)
77 # include <kernel.h>
78 # include <sys/swis.h>
79 #elif defined(_WIN32)
80 # include <sys/types.h>
81 # include <sys/stat.h>
82 #else
83 # include <sys/stat.h>
84 #endif
85 
86 #ifdef __sun__
87 /* woraround for SunOS 4.x, it has SEEK_* defined here */
88 #include <unistd.h>
89 #endif
90 
91 #include "lame.h"
92 #include "main.h"
93 #include "get_audio.h"
94 #include "lametime.h"
95 #include "console.h"
96 
97 #ifdef WITH_DMALLOC
98 #include <dmalloc.h>
99 #endif
100 
101 #ifndef STR
102 # define __STR(x)  #x
103 # define STR(x)    __STR(x)
104 #define __LOC__ __FILE__ "("STR(__LINE__)") : "
105 #endif
106 
107 
108 #define FLOAT_TO_UNSIGNED(f) ((unsigned long)(((long)((f) - 2147483648.0)) + 2147483647L + 1))
109 #define UNSIGNED_TO_FLOAT(u) (((double)((long)((u) - 2147483647L - 1))) + 2147483648.0)
110 
uint32_high_low(unsigned char const *bytes)111 static uint32_t uint32_high_low(unsigned char const *bytes)
112 {
113     uint32_t const hh = bytes[0];
114     uint32_t const hl = bytes[1];
115     uint32_t const lh = bytes[2];
116     uint32_t const ll = bytes[3];
117     return (hh << 24) | (hl << 16) | (lh << 8) | ll;
118 }
119 
120 static double
read_ieee_extended_high_low(FILE * fp)121 read_ieee_extended_high_low(FILE * fp)
122 {
123     unsigned char bytes[10];
124     memset(bytes, 0, 10);
125     fread(bytes, 1, 10, fp);
126     {
127         int32_t const s = (bytes[0] & 0x80);
128         int32_t const e_h = (bytes[0] & 0x7F);
129         int32_t const e_l = bytes[1];
130         int32_t e = (e_h << 8) | e_l;
131         uint32_t const hm = uint32_high_low(bytes + 2);
132         uint32_t const lm = uint32_high_low(bytes + 6);
133         double  result = 0;
134         if (e != 0 || hm != 0 || lm != 0) {
135             if (e == 0x7fff) {
136                 result = HUGE_VAL;
137             }
138             else {
139                 double  mantissa_h = UNSIGNED_TO_FLOAT(hm);
140                 double  mantissa_l = UNSIGNED_TO_FLOAT(lm);
141                 e -= 0x3fff;
142                 e -= 31;
143                 result = ldexp(mantissa_h, e);
144                 e -= 32;
145                 result += ldexp(mantissa_l, e);
146             }
147         }
148         return s ? -result : result;
149     }
150 }
151 
152 
153 static uint16_t
read_16_bits_low_high(FILE * fp)154 read_16_bits_low_high(FILE * fp)
155 {
156     unsigned char bytes[2] = { 0, 0 };
157     fread(bytes, 1, 2, fp);
158     {
159         uint16_t const l = bytes[0];
160         uint16_t const h = bytes[1];
161         return (h << 8) | l;
162     }
163 }
164 
165 
166 static uint32_t
read_32_bits_low_high(FILE * fp)167 read_32_bits_low_high(FILE * fp)
168 {
169     unsigned char bytes[4] = { 0, 0, 0, 0 };
170     fread(bytes, 1, 4, fp);
171     {
172         uint32_t const ll = bytes[0];
173         uint32_t const lh = bytes[1];
174         uint32_t const hl = bytes[2];
175         uint32_t const hh = bytes[3];
176         return (hh << 24) | (hl << 16) | (lh << 8) | ll;
177     }
178 }
179 
180 static uint16_t
read_16_bits_high_low(FILE * fp)181 read_16_bits_high_low(FILE * fp)
182 {
183     unsigned char bytes[2] = { 0, 0 };
184     fread(bytes, 1, 2, fp);
185     {
186         uint16_t const h = bytes[0];
187         uint16_t const l = bytes[1];
188         return (h << 8) | l;
189     }
190 }
191 
192 static uint32_t
read_32_bits_high_low(FILE * fp)193 read_32_bits_high_low(FILE * fp)
194 {
195     unsigned char bytes[4] = { 0, 0, 0, 0 };
196     fread(bytes, 1, 4, fp);
197     return uint32_high_low(bytes);
198 }
199 
200 static void
write_16_bits_low_high(FILE * fp, int val)201 write_16_bits_low_high(FILE * fp, int val)
202 {
203     unsigned char bytes[2];
204     bytes[0] = (val & 0xff);
205     bytes[1] = ((val >> 8) & 0xff);
206     fwrite(bytes, 1, 2, fp);
207 }
208 
209 static void
write_32_bits_low_high(FILE * fp, int val)210 write_32_bits_low_high(FILE * fp, int val)
211 {
212     unsigned char bytes[4];
213     bytes[0] = (val & 0xff);
214     bytes[1] = ((val >> 8) & 0xff);
215     bytes[2] = ((val >> 16) & 0xff);
216     bytes[3] = ((val >> 24) & 0xff);
217     fwrite(bytes, 1, 4, fp);
218 }
219 
220 #ifdef LIBSNDFILE
221 
222 #include <sndfile.h>
223 
224 
225 #else
226 
227 typedef void SNDFILE;
228 
229 #endif /* ifdef LIBSNDFILE */
230 
231 
232 
233 typedef struct blockAlign_struct {
234     uint32_t offset;
235     uint32_t blockSize;
236 } blockAlign;
237 
238 typedef struct IFF_AIFF_struct {
239     short   numChannels;
240     unsigned long numSampleFrames;
241     short   sampleSize;
242     double  sampleRate;
243     uint32_t sampleType;
244     uint32_t sampleFormat;
245     blockAlign blkAlgn;
246 } IFF_AIFF;
247 
248 
249 
250 struct PcmBuffer {
251     void   *ch[2];           /* buffer for each channel */
252     int     w;               /* sample width */
253     int     n;               /* number samples allocated */
254     int     u;               /* number samples used */
255     int     skip_start;      /* number samples to ignore at the beginning */
256     int     skip_end;        /* number samples to ignore at the end */
257 };
258 
259 typedef struct PcmBuffer PcmBuffer;
260 
261 static void
initPcmBuffer(PcmBuffer * b, int w)262 initPcmBuffer(PcmBuffer * b, int w)
263 {
264     b->ch[0] = 0;
265     b->ch[1] = 0;
266     b->w = w;
267     b->n = 0;
268     b->u = 0;
269     b->skip_start = 0;
270     b->skip_end = 0;
271 }
272 
273 static void
freePcmBuffer(PcmBuffer * b)274 freePcmBuffer(PcmBuffer * b)
275 {
276     if (b != 0) {
277         free(b->ch[0]);
278         free(b->ch[1]);
279         b->ch[0] = 0;
280         b->ch[1] = 0;
281         b->n = 0;
282         b->u = 0;
283     }
284 }
285 
286 static int
addPcmBuffer(PcmBuffer * b, void *a0, void *a1, int read)287 addPcmBuffer(PcmBuffer * b, void *a0, void *a1, int read)
288 {
289     int     a_n;
290 
291     if (b == 0) {
292         return 0;
293     }
294     if (read < 0) {
295         return b->u - b->skip_end;
296     }
297     if (b->skip_start >= read) {
298         b->skip_start -= read;
299         return b->u - b->skip_end;
300     }
301     a_n = read - b->skip_start;
302 
303     if (a_n > 0) {
304         int const a_skip = b->w * b->skip_start;
305         int const a_want = b->w * a_n;
306         int const b_used = b->w * b->u;
307         int const b_have = b->w * b->n;
308         int const b_need = b->w * (b->u + a_n);
309         if (b_have < b_need) {
310             b->n = b->u + a_n;
311             b->ch[0] = realloc(b->ch[0], b_need);
312             b->ch[1] = realloc(b->ch[1], b_need);
313         }
314         b->u += a_n;
315         if (b->ch[0] != 0 && a0 != 0) {
316             char   *src = a0;
317             char   *dst = b->ch[0];
318             memcpy(dst + b_used, src + a_skip, a_want);
319         }
320         if (b->ch[1] != 0 && a1 != 0) {
321             char   *src = a1;
322             char   *dst = b->ch[1];
323             memcpy(dst + b_used, src + a_skip, a_want);
324         }
325     }
326     b->skip_start = 0;
327     return b->u - b->skip_end;
328 }
329 
330 static int
takePcmBuffer(PcmBuffer * b, void *a0, void *a1, int a_n, int mm)331 takePcmBuffer(PcmBuffer * b, void *a0, void *a1, int a_n, int mm)
332 {
333     if (a_n > mm) {
334         a_n = mm;
335     }
336     if (b != 0 && a_n > 0) {
337         int const a_take = b->w * a_n;
338         if (a0 != 0 && b->ch[0] != 0) {
339             memcpy(a0, b->ch[0], a_take);
340         }
341         if (a1 != 0 && b->ch[1] != 0) {
342             memcpy(a1, b->ch[1], a_take);
343         }
344         b->u -= a_n;
345         if (b->u < 0) {
346             b->u = 0;
347             return a_n;
348         }
349         if (b->ch[0] != 0) {
350             memmove(b->ch[0], (char *) b->ch[0] + a_take, b->w * b->u);
351         }
352         if (b->ch[1] != 0) {
353             memmove(b->ch[1], (char *) b->ch[1] + a_take, b->w * b->u);
354         }
355     }
356     return a_n;
357 }
358 
359 /* global data for get_audio.c. */
360 typedef struct get_audio_global_data_struct {
361     int     count_samples_carefully;
362     int     pcmbitwidth;
363     int     pcmswapbytes;
364     int     pcm_is_unsigned_8bit;
365     int     pcm_is_ieee_float;
366     unsigned int num_samples_read;
367     FILE   *music_in;
368     SNDFILE *snd_file;
369 #ifdef HAVE_MPG123
370     mpg123_handle* mh;
371 #endif
372     hip_t     hip;
373     PcmBuffer pcm32;
374     PcmBuffer pcm16;
375     size_t  in_id3v2_size;
376     unsigned char* in_id3v2_tag;
377 } get_audio_global_data;
378 
379 static get_audio_global_data global;
380 
381 
382 
383 #ifdef AMIGA_MPEGA
384 int     lame_decode_initfile_amiga(const char *fullname, mp3data_struct * const mp3data);
385 #else
386 int     lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding);
387 #endif
388 #ifdef HAVE_MPG123
389 int     lame123_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding);
390 #endif
391 
392 /* read mp3 file until mpglib returns one frame of PCM data */
393 static int lame_decode_fromfile(FILE * fd, short int pcm_l[], short int pcm_r[],
394                                 mp3data_struct * mp3data);
395 
396 
397 static int read_samples_pcm(FILE * musicin, int sample_buffer[2304], int samples_to_read);
398 static int read_samples_mp3(lame_t gfp, FILE * musicin, short int mpg123pcm[2][1152]);
399 #ifdef LIBSNDFILE
400 static SNDFILE *open_snd_file(lame_t gfp, char const *inPath);
401 #endif
402 static FILE *open_mpeg_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding);
403 static FILE *open_wave_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding);
404 static int close_input_file(FILE * musicin);
405 
406 
407 static  size_t
min_size_t(size_t a, size_t b)408 min_size_t(size_t a, size_t b)
409 {
410     if (a < b) {
411         return a;
412     }
413     return b;
414 }
415 
416 enum ByteOrder machine_byte_order(void);
417 
418 enum ByteOrder
machine_byte_order(void)419 machine_byte_order(void)
420 {
421     long    one = 1;
422     return !(*((char *) (&one))) ? ByteOrderBigEndian : ByteOrderLittleEndian;
423 }
424 
425 
426 
427 /* Replacement for forward fseek(,,SEEK_CUR), because fseek() fails on pipes */
428 
429 
430 static int
fskip_long(FILE * fp, long offset, int whence)431 fskip_long(FILE * fp, long offset, int whence)
432 {
433 #ifndef PIPE_BUF
434     char    buffer[4096];
435 #else
436     char    buffer[PIPE_BUF];
437 #endif
438 
439 /* S_ISFIFO macro is defined on newer Linuxes */
440 #ifndef S_ISFIFO
441 # ifdef _S_IFIFO
442     /* _S_IFIFO is defined on Win32 and Cygwin */
443 #  define S_ISFIFO(m) (((m)&_S_IFIFO) == _S_IFIFO)
444 # endif
445 #endif
446 
447 #ifdef S_ISFIFO
448     /* fseek is known to fail on pipes with several C-Library implementations
449        workaround: 1) test for pipe
450        2) for pipes, only relatvie seeking is possible
451        3)            and only in forward direction!
452        else fallback to old code
453      */
454     {
455         int const fd = fileno(fp);
456         struct stat file_stat;
457 
458         if (fstat(fd, &file_stat) == 0) {
459             if (S_ISFIFO(file_stat.st_mode)) {
460                 if (whence != SEEK_CUR || offset < 0) {
461                     return -1;
462                 }
463                 while (offset > 0) {
464                     size_t const bytes_to_skip = min_size_t(sizeof(buffer), offset);
465                     size_t const read = fread(buffer, 1, bytes_to_skip, fp);
466                     if (read < 1) {
467                         return -1;
468                     }
469                     assert( read <= LONG_MAX );
470                     offset -= (long) read;
471                 }
472                 return 0;
473             }
474         }
475     }
476 #endif
477     if (0 == fseek(fp, offset, whence)) {
478         return 0;
479     }
480 
481     if (whence != SEEK_CUR || offset < 0) {
482         if (global_ui_config.silent < 10) {
483             error_printf
484                 ("fskip problem: Mostly the return status of functions is not evaluated, so it is more secure to pollute <stderr>.\n");
485         }
486         return -1;
487     }
488 
489     while (offset > 0) {
490         size_t const bytes_to_skip = min_size_t(sizeof(buffer), offset);
491         size_t const read = fread(buffer, 1, bytes_to_skip, fp);
492         if (read < 1) {
493             return -1;
494         }
495         assert( read <= LONG_MAX );
496         offset -= (long) read;
497     }
498 
499     return 0;
500 }
501 
502 static int
fskip_uint32(FILE * fp, uint32_t offset)503 fskip_uint32(FILE * fp, uint32_t offset)
504 {
505     int   ret = 0;
506     while (offset > INT_MAX && ret == 0) {
507         offset -= INT_MAX;
508         ret = fskip_long(fp, INT_MAX, SEEK_CUR);
509     }
510     if (offset > 0 && ret == 0) {
511         ret = fskip_long(fp, offset, SEEK_CUR);
512     }
513     return ret;
514 }
515 
516 static  off_t
lame_get_file_size(FILE * fp)517 lame_get_file_size(FILE * fp)
518 {
519     struct stat sb;
520     int     fd = fileno(fp);
521 
522     if (0 == fstat(fd, &sb))
523         return sb.st_size;
524     return (off_t) - 1;
525 }
526 
527 
528 FILE   *
init_outfile(char const *outPath, int decode)529 init_outfile(char const *outPath, int decode)
530 {
531     FILE   *outf;
532 
533     /* open the output file */
534     if (0 == strcmp(outPath, "-")) {
535         outf = stdout;
536         lame_set_stream_binary_mode(outf);
537     }
538     else {
539         outf = lame_fopen(outPath, "w+b");
540 #ifdef __riscos__
541         /* Assign correct file type */
542         if (outf != NULL) {
543             char   *p, *out_path = strdup(outPath);
544             for (p = out_path; *p; p++) { /* ugly, ugly to modify a string */
545                 switch (*p) {
546                 case '.':
547                     *p = '/';
548                     break;
549                 case '/':
550                     *p = '.';
551                     break;
552                 }
553             }
554             SetFiletype(out_path, decode ? 0xFB1 /*WAV*/ : 0x1AD /*AMPEG*/);
555             free(out_path);
556         }
557 #else
558         (void) decode;
559 #endif
560     }
561     return outf;
562 }
563 
564 
565 static void
setSkipStartAndEnd(lame_t gfp, int enc_delay, int enc_padding)566 setSkipStartAndEnd(lame_t gfp, int enc_delay, int enc_padding)
567 {
568     int     skip_start = 0, skip_end = 0;
569     long dec_delay = -1;
570 
571     if (global_decoder.mp3_delay_set)
572         skip_start = global_decoder.mp3_delay;
573 
574 #if 0
575     /* We should ask mpg123 for the delay, but we know it is 529 samples and
576        will not change unless we enable gapless mode. Also, global.hip is not
577        always the correct handle, so avoid this for now. */
578     /* Will use it for layer III only, mpg123 does not deal with layer I and II
579        gapless stuff (yet?) */
580     mpg123_getstate(global.hip->mh, MPG123_DEC_DELAY, &dec_delay, NULL);
581 #else
582     if(dec_delay < 0)
583         dec_delay = 528 + 1; /* Same value as above, actually. */
584 #endif
585 
586     switch (global_reader.input_format) {
587     case sf_mp123:
588         break;
589 
590     case sf_mp3:
591         if (skip_start == 0) {
592             if (enc_delay > -1 || enc_padding > -1) {
593                 if (enc_delay > -1)
594                     skip_start = enc_delay + dec_delay;
595                 if (enc_padding > -1)
596                     skip_end = enc_padding - dec_delay;
597             }
598             else
599                 skip_start = lame_get_encoder_delay(gfp) + dec_delay;
600         }
601         else {
602             /* user specified a value of skip. just add for decoder */
603             skip_start += dec_delay; /* mp3 decoder has a 528 sample delay, plus user supplied "skip" */
604         }
605         break;
606     case sf_mp2:
607         skip_start += 240 + 1;
608         break;
609     case sf_mp1:
610         skip_start += 240 + 1;
611         break;
612     case sf_raw:
613         skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
614         break;
615     case sf_wave:
616         skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
617         break;
618     case sf_aiff:
619         skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
620         break;
621     default:
622         skip_start += 0; /* other formats have no delay *//* is += 0 not better ??? */
623         break;
624     }
625     skip_start = skip_start < 0 ? 0 : skip_start;
626     skip_end = skip_end < 0 ? 0 : skip_end;
627     global. pcm16.skip_start = global.pcm32.skip_start = skip_start;
628     global. pcm16.skip_end = global.pcm32.skip_end = skip_end;
629 }
630 
631 
632 
633 int
init_infile(lame_t gfp, char const *inPath)634 init_infile(lame_t gfp, char const *inPath)
635 {
636     int     enc_delay = 0, enc_padding = 0;
637     /* open the input file */
638     global. count_samples_carefully = 0;
639     global. num_samples_read = 0;
640     global. pcmbitwidth = global_raw_pcm.in_bitwidth;
641     global. pcmswapbytes = global_reader.swapbytes;
642     global. pcm_is_unsigned_8bit = global_raw_pcm.in_signed == 1 ? 0 : 1;
643     global. pcm_is_ieee_float = 0;
644     global. hip = 0;
645     global. music_in = 0;
646     global. snd_file = 0;
647     global. in_id3v2_size = 0;
648     global. in_id3v2_tag = 0;
649     if (is_mpeg_file_format(global_reader.input_format)) {
650         global. music_in = open_mpeg_file(gfp, inPath, &enc_delay, &enc_padding);
651     }
652     else {
653 #ifdef LIBSNDFILE
654         if (strcmp(inPath, "-") != 0) { /* not for stdin */
655             global. snd_file = open_snd_file(gfp, inPath);
656         }
657 #endif
658         if (global.snd_file == 0) {
659             global. music_in = open_wave_file(gfp, inPath, &enc_delay, &enc_padding);
660         }
661     }
662     initPcmBuffer(&global.pcm32, sizeof(int));
663     initPcmBuffer(&global.pcm16, sizeof(short));
664     setSkipStartAndEnd(gfp, enc_delay, enc_padding);
665     {
666         unsigned long n = lame_get_num_samples(gfp);
667         if (n != MAX_U_32_NUM) {
668             unsigned long const discard = global.pcm32.skip_start + global.pcm32.skip_end;
669             lame_set_num_samples(gfp, n > discard ? n - discard : 0);
670         }
671     }
672     return (global.snd_file != NULL || global.music_in != NULL) ? 1 : -1;
673 }
674 
675 int
samples_to_skip_at_start(void)676 samples_to_skip_at_start(void)
677 {
678     return global.pcm32.skip_start;
679 }
680 
681 int
samples_to_skip_at_end(void)682 samples_to_skip_at_end(void)
683 {
684     return global.pcm32.skip_end;
685 }
686 
687 void
close_infile(void)688 close_infile(void)
689 {
690 #if defined(HAVE_MPGLIB) || defined(HAVE_MPG123)
691     if (global.hip != 0) {
692         hip_decode_exit(global.hip); /* release mp3decoder memory */
693         global. hip = 0;
694     }
695 #endif
696     close_input_file(global.music_in);
697 #ifdef LIBSNDFILE
698     if (global.snd_file) {
699         if (sf_close(global.snd_file) != 0) {
700             if (global_ui_config.silent < 10) {
701                 error_printf("Could not close sound file \n");
702             }
703         }
704         global. snd_file = 0;
705     }
706 #endif
707     freePcmBuffer(&global.pcm32);
708     freePcmBuffer(&global.pcm16);
709     global. music_in = 0;
710     free(global.in_id3v2_tag);
711     global.in_id3v2_tag = 0;
712     global.in_id3v2_size = 0;
713 }
714 
715 
716 static int
717         get_audio_common(lame_t gfp, int buffer[2][1152], short buffer16[2][1152]);
718 
719 /************************************************************************
720 *
721 * get_audio()
722 *
723 * PURPOSE:  reads a frame of audio data from a file to the buffer,
724 *   aligns the data for future processing, and separates the
725 *   left and right channels
726 *
727 ************************************************************************/
728 int
get_audio(lame_t gfp, int buffer[2][1152])729 get_audio(lame_t gfp, int buffer[2][1152])
730 {
731     int     used = 0, read = 0;
732     do {
733         read = get_audio_common(gfp, buffer, NULL);
734         used = addPcmBuffer(&global.pcm32, buffer[0], buffer[1], read);
735     } while (used <= 0 && read > 0);
736     if (read < 0) {
737         return read;
738     }
739     if (global_reader.swap_channel == 0)
740         return takePcmBuffer(&global.pcm32, buffer[0], buffer[1], used, 1152);
741     else
742         return takePcmBuffer(&global.pcm32, buffer[1], buffer[0], used, 1152);
743 }
744 
745 /*
746   get_audio16 - behave as the original get_audio function, with a limited
747                 16 bit per sample output
748 */
749 int
get_audio16(lame_t gfp, short buffer[2][1152])750 get_audio16(lame_t gfp, short buffer[2][1152])
751 {
752     int     used = 0, read = 0;
753     do {
754         read = get_audio_common(gfp, NULL, buffer);
755         used = addPcmBuffer(&global.pcm16, buffer[0], buffer[1], read);
756     } while (used <= 0 && read > 0);
757     if (read < 0) {
758         return read;
759     }
760     if (global_reader.swap_channel == 0)
761         return takePcmBuffer(&global.pcm16, buffer[0], buffer[1], used, 1152);
762     else
763         return takePcmBuffer(&global.pcm16, buffer[1], buffer[0], used, 1152);
764 }
765 
766 /************************************************************************
767   get_audio_common - central functionality of get_audio*
768     in: gfp
769         buffer    output to the int buffer or 16-bit buffer
770    out: buffer    int output    (if buffer != NULL)
771         buffer16  16-bit output (if buffer == NULL)
772 returns: samples read
773 note: either buffer or buffer16 must be allocated upon call
774 */
775 static int
get_audio_common(lame_t gfp, int buffer[2][1152], short buffer16[2][1152])776 get_audio_common(lame_t gfp, int buffer[2][1152], short buffer16[2][1152])
777 {
778     const int num_channels = lame_get_num_channels(gfp);
779     const int framesize = lame_get_framesize(gfp);
780     int     insamp[2 * 1152];
781     short   buf_tmp16[2][1152];
782     int     samples_read;
783     int     samples_to_read;
784     int     i;
785 
786     /* sanity checks, that's what we expect to be true */
787     if ((num_channels < 1 || 2 < num_channels)
788       ||(framesize < 1 || 1152 < framesize)) {
789         if (global_ui_config.silent < 10) {
790             error_printf("Error: internal problem!\n");
791         }
792         return -1;
793     }
794 
795     /*
796      * NOTE: LAME can now handle arbritray size input data packets,
797      * so there is no reason to read the input data in chuncks of
798      * size "framesize".  EXCEPT:  the LAME graphical frame analyzer
799      * will get out of sync if we read more than framesize worth of data.
800      */
801 
802     samples_to_read = framesize;
803 
804     /* if this flag has been set, then we are carefull to read
805      * exactly num_samples and no more.  This is useful for .wav and .aiff
806      * files which have id3 or other tags at the end.  Note that if you
807      * are using LIBSNDFILE, this is not necessary
808      */
809     if (global.count_samples_carefully) {
810         unsigned int tmp_num_samples, remaining;
811         /* get num_samples */
812         if (is_mpeg_file_format(global_reader.input_format)) {
813             tmp_num_samples = global_decoder.mp3input_data.nsamp;
814         }
815         else {
816             tmp_num_samples = lame_get_num_samples(gfp);
817         }
818         if (global.num_samples_read < tmp_num_samples) {
819             remaining = tmp_num_samples - global.num_samples_read;
820         }
821         else {
822             remaining = 0;
823         }
824         if (remaining < (unsigned int) framesize && 0 != tmp_num_samples)
825             /* in case the input is a FIFO (at least it's reproducible with
826                a FIFO) tmp_num_samples may be 0 and therefore remaining
827                would be 0, but we need to read some samples, so don't
828                change samples_to_read to the wrong value in this case */
829             samples_to_read = remaining;
830     }
831 
832     if (is_mpeg_file_format(global_reader.input_format)) {
833         if (buffer != NULL)
834             samples_read = read_samples_mp3(gfp, global.music_in, buf_tmp16);
835         else
836             samples_read = read_samples_mp3(gfp, global.music_in, buffer16);
837         if (samples_read < 0) {
838             return samples_read;
839         }
840     }
841     else {
842         int    *p;
843         if (global.snd_file) {
844 #ifdef LIBSNDFILE
845             samples_read = sf_read_int(global.snd_file, insamp, num_channels * samples_to_read);
846 #else
847             samples_read = 0;
848 #endif
849         }
850         else {
851             samples_read =
852                 read_samples_pcm(global.music_in, insamp, num_channels * samples_to_read);
853         }
854         if (samples_read < 0) {
855             return samples_read;
856         }
857         p = insamp + samples_read;
858         samples_read /= num_channels;
859         if (buffer != NULL) { /* output to int buffer */
860             if (num_channels == 2) {
861                 for (i = samples_read; --i >= 0;) {
862                     buffer[1][i] = *--p;
863                     buffer[0][i] = *--p;
864                 }
865             }
866             else if (num_channels == 1) {
867                 memset(buffer[1], 0, samples_read * sizeof(int));
868                 for (i = samples_read; --i >= 0;) {
869                     buffer[0][i] = *--p;
870                 }
871             }
872             else
873                 assert(0);
874         }
875         else {          /* convert from int; output to 16-bit buffer */
876             if (num_channels == 2) {
877                 for (i = samples_read; --i >= 0;) {
878                     buffer16[1][i] = *--p >> (8 * sizeof(int) - 16);
879                     buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
880                 }
881             }
882             else if (num_channels == 1) {
883                 memset(buffer16[1], 0, samples_read * sizeof(short));
884                 for (i = samples_read; --i >= 0;) {
885                     buffer16[0][i] = *--p >> (8 * sizeof(int) - 16);
886                 }
887             }
888             else
889                 assert(0);
890         }
891     }
892 
893     /* LAME mp3 output 16bit -  convert to int, if necessary */
894     if (is_mpeg_file_format(global_reader.input_format)) {
895         if (buffer != NULL) {
896             for (i = samples_read; --i >= 0;)
897                 buffer[0][i] = buf_tmp16[0][i] << (8 * sizeof(int) - 16);
898             if (num_channels == 2) {
899                 for (i = samples_read; --i >= 0;)
900                     buffer[1][i] = buf_tmp16[1][i] << (8 * sizeof(int) - 16);
901             }
902             else if (num_channels == 1) {
903                 memset(buffer[1], 0, samples_read * sizeof(int));
904             }
905             else
906                 assert(0);
907         }
908     }
909 
910 
911     /* if ... then it is considered infinitely long.
912        Don't count the samples */
913     if (global.count_samples_carefully)
914         global. num_samples_read += samples_read;
915 
916     return samples_read;
917 }
918 
919 
920 
921 static int
read_samples_mp3(lame_t gfp, FILE * musicin, short int mpg123pcm[2][1152])922 read_samples_mp3(lame_t gfp, FILE * musicin, short int mpg123pcm[2][1152])
923 {
924     int     out;
925 #ifdef HAVE_MPG123
926     short int *outbuf;
927     size_t outbytes;
928 #endif
929 #if defined(AMIGA_MPEGA)  ||  defined(HAVE_MPGLIB) || defined(HAVE_MPG123)
930     int     samplerate;
931     static const char type_name[] = "MP3 file";
932 
933 #ifdef HAVE_MPG123
934     /* Need to deinterleave so rather use mpg123_decode_frame() to decode the
935        current frame and deinterleave from the internal buffer. */
936     out = mpg123_decode_frame(global.hip->mh, NULL, (unsigned char**)&outbuf, &outbytes);
937     if (out != MPG123_OK && out != MPG123_DONE)
938     {
939         if (out == MPG123_NEW_FORMAT)
940         {
941             if (global_ui_config.silent < 10) {
942                 error_printf("Error: format changed in %s - not supported\n",
943                     type_name);
944             }
945         }
946         return -1;
947     }
948     out = outbytes/(sizeof(short)*global_decoder.mp3input_data.stereo);
949     if (global_decoder.mp3input_data.stereo == 2) {
950         int i;
951         for (i=0; i<out; ++i) {
952             mpg123pcm[0][i] = *outbuf++;
953             mpg123pcm[1][i] = *outbuf++;
954         }
955     }
956     else
957         memcpy(mpg123pcm[0], outbuf, sizeof(short)*out);
958     if(global.hip->pinfo)
959         hip_finish_pinfo(global.hip);
960 #else
961     out = lame_decode_fromfile(musicin, mpg123pcm[0], mpg123pcm[1], &global_decoder.mp3input_data);
962     /*
963      * out < 0:  error, probably EOF
964      * out = 0:  not possible with lame_decode_fromfile() ???
965      * out > 0:  number of output samples
966      */
967     if (out < 0) {
968         memset(mpg123pcm, 0, sizeof(**mpg123pcm) * 2 * 1152);
969         return 0;
970     }
971 
972     if (lame_get_num_channels(gfp) != global_decoder.mp3input_data.stereo) {
973         if (global_ui_config.silent < 10) {
974             error_printf("Error: number of channels has changed in %s - not supported\n",
975                          type_name);
976         }
977         out = -1;
978     }
979     samplerate = global_reader.input_samplerate;
980     if (samplerate == 0) {
981         samplerate = global_decoder.mp3input_data.samplerate;
982     }
983     if (lame_get_in_samplerate(gfp) != samplerate) {
984         if (global_ui_config.silent < 10) {
985             error_printf("Error: sample frequency has changed in %s - not supported\n", type_name);
986         }
987         out = -1;
988     }
989 #endif
990 #else
991     out = -1;
992 #endif
993     return out;
994 }
995 
996 static
set_input_num_channels(lame_t gfp, int num_channels)997 int set_input_num_channels(lame_t gfp, int num_channels)
998 {
999     if (gfp) {
1000         if (-1 == lame_set_num_channels(gfp, num_channels)) {
1001             if (global_ui_config.silent < 10) {
1002                 error_printf("Unsupported number of channels: %d\n", num_channels);
1003             }
1004             return 0;
1005         }
1006     }
1007     return 1;
1008 }
1009 
1010 static
set_input_samplerate(lame_t gfp, int input_samplerate)1011 int set_input_samplerate(lame_t gfp, int input_samplerate)
1012 {
1013     if (gfp) {
1014         int sr = global_reader.input_samplerate;
1015         if (sr == 0) sr = input_samplerate;
1016         if (-1 == lame_set_in_samplerate(gfp, sr)) {
1017             if (global_ui_config.silent < 10) {
1018                 error_printf("Unsupported sample rate: %d\n", sr);
1019             }
1020             return 0;
1021         }
1022     }
1023     return 1;
1024 }
1025 
1026 int
WriteWaveHeader(FILE * const fp, int pcmbytes, int freq, int channels, int bits)1027 WriteWaveHeader(FILE * const fp, int pcmbytes, int freq, int channels, int bits)
1028 {
1029     int     bytes = (bits + 7) / 8;
1030 
1031     /* quick and dirty, but documented */
1032     fwrite("RIFF", 1, 4, fp); /* label */
1033     write_32_bits_low_high(fp, pcmbytes + 44 - 8); /* length in bytes without header */
1034     fwrite("WAVEfmt ", 2, 4, fp); /* 2 labels */
1035     write_32_bits_low_high(fp, 2 + 2 + 4 + 4 + 2 + 2); /* length of PCM format declaration area */
1036     write_16_bits_low_high(fp, 1); /* is PCM? */
1037     write_16_bits_low_high(fp, channels); /* number of channels */
1038     write_32_bits_low_high(fp, freq); /* sample frequency in [Hz] */
1039     write_32_bits_low_high(fp, freq * channels * bytes); /* bytes per second */
1040     write_16_bits_low_high(fp, channels * bytes); /* bytes per sample time */
1041     write_16_bits_low_high(fp, bits); /* bits per sample */
1042     fwrite("data", 1, 4, fp); /* label */
1043     write_32_bits_low_high(fp, pcmbytes); /* length in bytes of raw PCM data */
1044 
1045     return ferror(fp) ? -1 : 0;
1046 }
1047 
1048 
1049 
1050 
1051 #if defined(LIBSNDFILE)
1052 
1053 extern SNDFILE *sf_wchar_open(wchar_t const *wpath, int mode, SF_INFO * sfinfo);
1054 
1055 static SNDFILE *
open_snd_file(lame_t gfp, char const *inPath)1056 open_snd_file(lame_t gfp, char const *inPath)
1057 {
1058     char const *lpszFileName = inPath;
1059     SNDFILE *gs_pSndFileIn = NULL;
1060     SF_INFO gs_wfInfo;
1061 
1062     {
1063 #if defined( _WIN32 ) && !defined(__MINGW32__)
1064         wchar_t *file_name = utf8ToUnicode(lpszFileName);
1065 #endif
1066         /* Try to open the sound file */
1067         memset(&gs_wfInfo, 0, sizeof(gs_wfInfo));
1068 #if defined( _WIN32 ) && !defined(__MINGW32__)
1069         gs_pSndFileIn = sf_wchar_open(file_name, SFM_READ, &gs_wfInfo);
1070 #else
1071         gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
1072 #endif
1073 
1074         if (gs_pSndFileIn == NULL) {
1075             if (global_raw_pcm.in_signed == 0 && global_raw_pcm.in_bitwidth != 8) {
1076                 error_printf("Unsigned input only supported with bitwidth 8\n");
1077 #if defined( _WIN32 ) && !defined(__MINGW32__)
1078                 free(file_name);
1079 #endif
1080                 return 0;
1081             }
1082             /* set some defaults incase input is raw PCM */
1083             gs_wfInfo.seekable = (global_reader.input_format != sf_raw); /* if user specified -r, set to not seekable */
1084             gs_wfInfo.samplerate = lame_get_in_samplerate(gfp);
1085             gs_wfInfo.channels = lame_get_num_channels(gfp);
1086             gs_wfInfo.format = SF_FORMAT_RAW;
1087             if ((global_raw_pcm.in_endian == ByteOrderLittleEndian) ^ (global_reader.swapbytes !=
1088                                                                        0)) {
1089                 gs_wfInfo.format |= SF_ENDIAN_LITTLE;
1090             }
1091             else {
1092                 gs_wfInfo.format |= SF_ENDIAN_BIG;
1093             }
1094             switch (global_raw_pcm.in_bitwidth) {
1095             case 8:
1096                 gs_wfInfo.format |=
1097                     global_raw_pcm.in_signed == 0 ? SF_FORMAT_PCM_U8 : SF_FORMAT_PCM_S8;
1098                 break;
1099             case 16:
1100                 gs_wfInfo.format |= SF_FORMAT_PCM_16;
1101                 break;
1102             case 24:
1103                 gs_wfInfo.format |= SF_FORMAT_PCM_24;
1104                 break;
1105             case 32:
1106                 gs_wfInfo.format |= SF_FORMAT_PCM_32;
1107                 break;
1108             default:
1109                 break;
1110             }
1111 #if defined( _WIN32 ) && !defined(__MINGW32__)
1112             gs_pSndFileIn = sf_wchar_open(file_name, SFM_READ, &gs_wfInfo);
1113 #else
1114             gs_pSndFileIn = sf_open(lpszFileName, SFM_READ, &gs_wfInfo);
1115 #endif
1116         }
1117 #if defined( _WIN32 ) && !defined(__MINGW32__)
1118         free(file_name);
1119 #endif
1120 
1121         /* Check result */
1122         if (gs_pSndFileIn == NULL) {
1123             sf_perror(gs_pSndFileIn);
1124             if (global_ui_config.silent < 10) {
1125                 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
1126             }
1127             return 0;
1128         }
1129         sf_command(gs_pSndFileIn, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE);
1130 
1131         if ((gs_wfInfo.format & SF_FORMAT_RAW) == SF_FORMAT_RAW) {
1132             global_reader.input_format = sf_raw;
1133         }
1134 
1135 #ifdef _DEBUG_SND_FILE
1136         printf("\n\nSF_INFO structure\n");
1137         printf("samplerate        :%d\n", gs_wfInfo.samplerate);
1138         printf("samples           :%d\n", gs_wfInfo.frames);
1139         printf("channels          :%d\n", gs_wfInfo.channels);
1140         printf("format            :");
1141 
1142         /* new formats from sbellon@sbellon.de  1/2000 */
1143 
1144         switch (gs_wfInfo.format & SF_FORMAT_TYPEMASK) {
1145         case SF_FORMAT_WAV:
1146             printf("Microsoft WAV format (big endian). ");
1147             break;
1148         case SF_FORMAT_AIFF:
1149             printf("Apple/SGI AIFF format (little endian). ");
1150             break;
1151         case SF_FORMAT_AU:
1152             printf("Sun/NeXT AU format (big endian). ");
1153             break;
1154             /*
1155                case SF_FORMAT_AULE:
1156                DEBUGF("DEC AU format (little endian). ");
1157                break;
1158              */
1159         case SF_FORMAT_RAW:
1160             printf("RAW PCM data. ");
1161             break;
1162         case SF_FORMAT_PAF:
1163             printf("Ensoniq PARIS file format. ");
1164             break;
1165         case SF_FORMAT_SVX:
1166             printf("Amiga IFF / SVX8 / SV16 format. ");
1167             break;
1168         case SF_FORMAT_NIST:
1169             printf("Sphere NIST format. ");
1170             break;
1171         default:
1172             assert(0);
1173             break;
1174         }
1175 
1176         switch (gs_wfInfo.format & SF_FORMAT_SUBMASK) {
1177             /*
1178                case SF_FORMAT_PCM:
1179                DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
1180                break;
1181              */
1182         case SF_FORMAT_FLOAT:
1183             printf("32 bit Intel x86 floats.");
1184             break;
1185         case SF_FORMAT_ULAW:
1186             printf("U-Law encoded.");
1187             break;
1188         case SF_FORMAT_ALAW:
1189             printf("A-Law encoded.");
1190             break;
1191         case SF_FORMAT_IMA_ADPCM:
1192             printf("IMA ADPCM.");
1193             break;
1194         case SF_FORMAT_MS_ADPCM:
1195             printf("Microsoft ADPCM.");
1196             break;
1197             /*
1198                case SF_FORMAT_PCM_BE:
1199                DEBUGF("Big endian PCM data.");
1200                break;
1201                case SF_FORMAT_PCM_LE:
1202                DEBUGF("Little endian PCM data.");
1203                break;
1204              */
1205         case SF_FORMAT_PCM_S8:
1206             printf("Signed 8 bit PCM.");
1207             break;
1208         case SF_FORMAT_PCM_U8:
1209             printf("Unsigned 8 bit PCM.");
1210             break;
1211         case SF_FORMAT_PCM_16:
1212             printf("Signed 16 bit PCM.");
1213             break;
1214         case SF_FORMAT_PCM_24:
1215             printf("Signed 24 bit PCM.");
1216             break;
1217         case SF_FORMAT_PCM_32:
1218             printf("Signed 32 bit PCM.");
1219             break;
1220             /*
1221                case SF_FORMAT_SVX_FIB:
1222                DEBUGF("SVX Fibonacci Delta encoding.");
1223                break;
1224                case SF_FORMAT_SVX_EXP:
1225                DEBUGF("SVX Exponential Delta encoding.");
1226                break;
1227              */
1228         default:
1229             assert(0);
1230             break;
1231         }
1232 
1233         printf("\n");
1234         printf("sections          :%d\n", gs_wfInfo.sections);
1235         printf("seekable          :%d\n", gs_wfInfo.seekable);
1236 #endif
1237         /* Check result */
1238         if (gs_pSndFileIn == NULL) {
1239             sf_perror(gs_pSndFileIn);
1240             if (global_ui_config.silent < 10) {
1241                 error_printf("Could not open sound file \"%s\".\n", lpszFileName);
1242             }
1243             return 0;
1244         }
1245 
1246 
1247         if(gs_wfInfo.frames >= 0 && gs_wfInfo.frames < (sf_count_t)(unsigned)MAX_U_32_NUM)
1248             (void) lame_set_num_samples(gfp, gs_wfInfo.frames);
1249         else
1250             (void) lame_set_num_samples(gfp, MAX_U_32_NUM);
1251         if (!set_input_num_channels(gfp, gs_wfInfo.channels)) {
1252             sf_close(gs_pSndFileIn);
1253             return 0;
1254         }
1255         if (!set_input_samplerate(gfp, gs_wfInfo.samplerate)) {
1256             sf_close(gs_pSndFileIn);
1257             return 0;
1258         }
1259         global. pcmbitwidth = 32;
1260     }
1261 #if 0
1262     if (lame_get_num_samples(gfp) == MAX_U_32_NUM) {
1263         /* try to figure out num_samples */
1264         double const flen = lame_get_file_size(lpszFileName);
1265         if (flen >= 0) {
1266             /* try file size, assume 2 bytes per sample */
1267             lame_set_num_samples(gfp, flen / (2 * lame_get_num_channels(gfp)));
1268         }
1269     }
1270 #endif
1271     return gs_pSndFileIn;
1272 }
1273 
1274 #endif /* defined(LIBSNDFILE) */
1275 
1276 
1277 
1278 /************************************************************************
1279 unpack_read_samples - read and unpack signed low-to-high byte or unsigned
1280                       single byte input. (used for read_samples function)
1281                       Output integers are stored in the native byte order
1282                       (little or big endian).  -jd
1283   in: samples_to_read
1284       bytes_per_sample
1285       swap_order    - set for high-to-low byte order input stream
1286  i/o: pcm_in
1287  out: sample_buffer  (must be allocated up to samples_to_read upon call)
1288 returns: number of samples read
1289 */
1290 static int
unpack_read_samples(const int samples_to_read, const int bytes_per_sample, const int swap_order, int *sample_buffer, FILE * pcm_in)1291 unpack_read_samples(const int samples_to_read, const int bytes_per_sample,
1292                     const int swap_order, int *sample_buffer, FILE * pcm_in)
1293 {
1294     int     samples_read;
1295     int     i;
1296     int    *op;              /* output pointer */
1297     unsigned char *ip = (unsigned char *) sample_buffer; /* input pointer */
1298     const int b = sizeof(int) * 8;
1299 
1300     {
1301         size_t  samples_read_ = fread(sample_buffer, bytes_per_sample, samples_to_read, pcm_in);
1302         assert( samples_read_ <= INT_MAX );
1303         samples_read = (int) samples_read_;
1304     }
1305     op = sample_buffer + samples_read;
1306 
1307 #define GA_URS_IFLOOP( ga_urs_bps ) \
1308     if( bytes_per_sample == ga_urs_bps ) \
1309       for( i = samples_read * bytes_per_sample; (i -= bytes_per_sample) >=0;)
1310 
1311     if (swap_order == 0) {
1312         GA_URS_IFLOOP(1)
1313             * --op = ip[i] << (b - 8);
1314         GA_URS_IFLOOP(2)
1315             * --op = ip[i] << (b - 16) | ip[i + 1] << (b - 8);
1316         GA_URS_IFLOOP(3)
1317             * --op = ip[i] << (b - 24) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 8);
1318         GA_URS_IFLOOP(4)
1319             * --op =
1320             ip[i] << (b - 32) | ip[i + 1] << (b - 24) | ip[i + 2] << (b - 16) | ip[i + 3] << (b -
1321                                                                                               8);
1322     }
1323     else {
1324         GA_URS_IFLOOP(1)
1325             * --op = (ip[i] ^ 0x80) << (b - 8) | 0x7f << (b - 16); /* convert from unsigned */
1326         GA_URS_IFLOOP(2)
1327             * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16);
1328         GA_URS_IFLOOP(3)
1329             * --op = ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24);
1330         GA_URS_IFLOOP(4)
1331             * --op =
1332             ip[i] << (b - 8) | ip[i + 1] << (b - 16) | ip[i + 2] << (b - 24) | ip[i + 3] << (b -
1333                                                                                              32);
1334     }
1335 #undef GA_URS_IFLOOP
1336     if (global.pcm_is_ieee_float) {
1337         ieee754_float32_t const m_max = INT_MAX;
1338         ieee754_float32_t const m_min = -(ieee754_float32_t) INT_MIN;
1339         ieee754_float32_t *x = (ieee754_float32_t *) sample_buffer;
1340         assert(sizeof(ieee754_float32_t) == sizeof(int));
1341         for (i = 0; i < samples_to_read; ++i) {
1342             ieee754_float32_t const u = x[i];
1343             int     v;
1344             if (u >= 1) {
1345                 v = INT_MAX;
1346             }
1347             else if (u <= -1) {
1348                 v = INT_MIN;
1349             }
1350             else if (u >= 0) {
1351                 v = (int) (u * m_max + 0.5f);
1352             }
1353             else {
1354                 v = (int) (u * m_min - 0.5f);
1355             }
1356             sample_buffer[i] = v;
1357         }
1358     }
1359     return (samples_read);
1360 }
1361 
1362 
1363 
1364 /************************************************************************
1365 *
1366 * read_samples()
1367 *
1368 * PURPOSE:  reads the PCM samples from a file to the buffer
1369 *
1370 *  SEMANTICS:
1371 * Reads #samples_read# number of shorts from #musicin# filepointer
1372 * into #sample_buffer[]#.  Returns the number of samples read.
1373 *
1374 ************************************************************************/
1375 
1376 static int
read_samples_pcm(FILE * musicin, int sample_buffer[2304], int samples_to_read)1377 read_samples_pcm(FILE * musicin, int sample_buffer[2304], int samples_to_read)
1378 {
1379     int     samples_read;
1380     int     bytes_per_sample = global.pcmbitwidth / 8;
1381     int     swap_byte_order; /* byte order of input stream */
1382 
1383     switch (global.pcmbitwidth) {
1384     case 32:
1385     case 24:
1386     case 16:
1387         if (global_raw_pcm.in_signed == 0) {
1388             if (global_ui_config.silent < 10) {
1389                 error_printf("Unsigned input only supported with bitwidth 8\n");
1390             }
1391             return -1;
1392         }
1393         swap_byte_order = (global_raw_pcm.in_endian != ByteOrderLittleEndian) ? 1 : 0;
1394         if (global.pcmswapbytes) {
1395             swap_byte_order = !swap_byte_order;
1396         }
1397         break;
1398 
1399     case 8:
1400         swap_byte_order = global.pcm_is_unsigned_8bit;
1401         break;
1402 
1403     default:
1404         if (global_ui_config.silent < 10) {
1405             error_printf("Only 8, 16, 24 and 32 bit input files supported \n");
1406         }
1407         return -1;
1408     }
1409     if (samples_to_read < 0 || samples_to_read > 2304) {
1410         if (global_ui_config.silent < 10) {
1411             error_printf("Error: unexpected number of samples to read: %d\n", samples_to_read);
1412         }
1413         return -1;
1414     }
1415     samples_read = unpack_read_samples(samples_to_read, bytes_per_sample, swap_byte_order,
1416                                        sample_buffer, musicin);
1417     if (ferror(musicin)) {
1418         if (global_ui_config.silent < 10) {
1419             error_printf("Error reading input file\n");
1420         }
1421         return -1;
1422     }
1423 
1424     return samples_read;
1425 }
1426 
1427 
1428 
1429 /* AIFF Definitions */
1430 
1431 static uint32_t const IFF_ID_FORM = 0x464f524d; /* "FORM" */
1432 static uint32_t const IFF_ID_AIFF = 0x41494646; /* "AIFF" */
1433 static uint32_t const IFF_ID_AIFC = 0x41494643; /* "AIFC" */
1434 static uint32_t const IFF_ID_COMM = 0x434f4d4d; /* "COMM" */
1435 static uint32_t const IFF_ID_SSND = 0x53534e44; /* "SSND" */
1436 static uint32_t const IFF_ID_MPEG = 0x4d504547; /* "MPEG" */
1437 
1438 static uint32_t const IFF_ID_NONE = 0x4e4f4e45; /* "NONE" *//* AIFF-C data format */
1439 static uint32_t const IFF_ID_2CBE = 0x74776f73; /* "twos" *//* AIFF-C data format */
1440 static uint32_t const IFF_ID_2CLE = 0x736f7774; /* "sowt" *//* AIFF-C data format */
1441 static uint32_t const IFF_ID_FL32 = 0x666C3332; /* "fl32" *//* AIFF-C data format */
1442 static uint32_t const IFF_ID_FL64 = 0x666C3634; /* "fl64" *//* AIFF-C data format */
1443 
1444 static uint32_t const WAV_ID_RIFF = 0x52494646; /* "RIFF" */
1445 static uint32_t const WAV_ID_WAVE = 0x57415645; /* "WAVE" */
1446 static uint32_t const WAV_ID_FMT = 0x666d7420; /* "fmt " */
1447 static uint32_t const WAV_ID_DATA = 0x64617461; /* "data" */
1448 
1449 #ifndef WAVE_FORMAT_PCM
1450 static uint16_t const WAVE_FORMAT_PCM = 0x0001;
1451 #endif
1452 #ifndef WAVE_FORMAT_IEEE_FLOAT
1453 static uint16_t const WAVE_FORMAT_IEEE_FLOAT = 0x0003;
1454 #endif
1455 #ifndef WAVE_FORMAT_EXTENSIBLE
1456 static uint16_t const WAVE_FORMAT_EXTENSIBLE = 0xFFFE;
1457 #endif
1458 
1459 
1460 static uint32_t
make_even_number_of_bytes_in_length(uint32_t x)1461 make_even_number_of_bytes_in_length(uint32_t x)
1462 {
1463     return x + (x & 0x01);
1464 }
1465 
1466 
1467 /*****************************************************************************
1468  *
1469  *	Read Microsoft Wave headers
1470  *
1471  *	By the time we get here the first 32-bits of the file have already been
1472  *	read, and we're pretty sure that we're looking at a WAV file.
1473  *
1474  *****************************************************************************/
1475 
1476 static int
parse_wave_header(lame_global_flags * gfp, FILE * sf)1477 parse_wave_header(lame_global_flags * gfp, FILE * sf)
1478 {
1479     uint32_t ui32_nSamplesPerSec = 0;
1480     uint32_t ui32_DataChunkSize = 0;
1481     uint16_t ui16_wFormatTag = 0;
1482     uint16_t ui16_nChannels = 0;
1483     uint16_t ui16_wBitsPerSample = 0;
1484 
1485     int     is_wav = 0;
1486     int     loop_sanity = 0;
1487 
1488     uint32_t ui32_chunkSize = read_32_bits_high_low(sf); /* file_length */
1489     uint32_t ui32_WAVEID    = read_32_bits_high_low(sf);
1490     if (ui32_WAVEID != WAV_ID_WAVE || ui32_chunkSize < 1)
1491         return -1;
1492 
1493     for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
1494         uint32_t ui32_ckID = read_32_bits_high_low(sf);
1495         if (ui32_ckID == WAV_ID_FMT) {
1496             uint32_t ui32_nAvgBytesPerSec = 0;
1497             uint32_t ui32_cksize = 0;
1498             uint16_t ui16_nBlockAlign = 0;
1499 
1500             ui32_cksize = read_32_bits_low_high(sf);
1501             ui32_cksize = make_even_number_of_bytes_in_length(ui32_cksize);
1502             if (ui32_cksize < 16u) {
1503                 /*DEBUGF("'fmt' chunk too short (only %ld bytes)!", ui32_cksize);*/
1504                 return -1;
1505             }
1506             ui16_wFormatTag      = read_16_bits_low_high(sf);
1507             ui16_nChannels       = read_16_bits_low_high(sf);
1508             ui32_nSamplesPerSec  = read_32_bits_low_high(sf);
1509             ui32_nAvgBytesPerSec = read_32_bits_low_high(sf);
1510             ui16_nBlockAlign     = read_16_bits_low_high(sf);
1511             ui16_wBitsPerSample  = read_16_bits_low_high(sf);
1512             ui32_cksize -= 16u;
1513             /* WAVE_FORMAT_EXTENSIBLE support */
1514             if ((ui32_cksize > 9u) && (ui16_wFormatTag == WAVE_FORMAT_EXTENSIBLE)) {
1515                 uint16_t ui16_cbSize              = read_16_bits_low_high(sf);
1516                 uint16_t ui16_wValidBitsPerSample = read_16_bits_low_high(sf);
1517                 uint32_t ui32_dwChannelMask       = read_32_bits_low_high(sf);
1518                 uint16_t ui16_SubFormat           = read_16_bits_low_high(sf);
1519                 ui32_cksize -= 10u;
1520                 ui16_wFormatTag = ui16_SubFormat; /* SubType coincident with format_tag for PCM int or float */
1521                 (void) (ui16_cbSize, ui16_wValidBitsPerSample, ui32_dwChannelMask); /* unused */
1522             }
1523             /* DEBUGF("   skipping %d bytes\n", ui32_cksize); */
1524             if (ui32_cksize > 0) {
1525                 if (fskip_uint32(sf, ui32_cksize) != 0)
1526                     return -1;
1527             };
1528         }
1529         else if (ui32_ckID == WAV_ID_DATA) {
1530             ui32_DataChunkSize = read_32_bits_low_high(sf);
1531             is_wav = 1;
1532             /* We've found the audio data. Read no further! */
1533             break;
1534         }
1535         else {
1536             uint32_t ui32_cksize = read_32_bits_low_high(sf);
1537             ui32_cksize = make_even_number_of_bytes_in_length(ui32_cksize);
1538             if (fskip_uint32(sf, ui32_cksize) != 0) {
1539                 return -1;
1540             }
1541         }
1542     }
1543     if (is_wav) {
1544         if (ui16_wFormatTag == 0x0050 || ui16_wFormatTag == 0x0055) {
1545             return sf_mp123;
1546         }
1547         if (ui16_wFormatTag != WAVE_FORMAT_PCM && ui16_wFormatTag != WAVE_FORMAT_IEEE_FLOAT) {
1548             if (global_ui_config.silent < 10) {
1549                 error_printf("Unsupported data format: 0x%04X\n", ui16_wFormatTag);
1550             }
1551             return 0;   /* oh no! non-supported format  */
1552         }
1553 
1554         /* make sure the header is sane */
1555         if (!set_input_num_channels(gfp, ui16_nChannels))
1556             return 0;
1557         if (!set_input_samplerate(gfp, ui32_nSamplesPerSec))
1558             return 0;
1559         /* avoid division by zero */
1560         if (ui16_wBitsPerSample < 1) {
1561             if (global_ui_config.silent < 10)
1562                 error_printf("Unsupported bits per sample: %d\n", ui16_wBitsPerSample);
1563             return -1;
1564         }
1565         global. pcmbitwidth = ui16_wBitsPerSample;
1566         global. pcm_is_unsigned_8bit = 1;
1567         global. pcm_is_ieee_float = (ui16_wFormatTag == WAVE_FORMAT_IEEE_FLOAT ? 1 : 0);
1568         if (ui32_DataChunkSize == MAX_U_32_NUM)
1569             (void) lame_set_num_samples(gfp, MAX_U_32_NUM);
1570         else
1571             (void) lame_set_num_samples(gfp, ui32_DataChunkSize / (ui16_nChannels * ((ui16_wBitsPerSample + 7u) / 8u)));
1572         return 1;
1573     }
1574     return -1;
1575 }
1576 
1577 
1578 
1579 /************************************************************************
1580 * aiff_check2
1581 *
1582 * PURPOSE:	Checks AIFF header information to make sure it is valid.
1583 *	        returns 0 on success, 1 on errors
1584 ************************************************************************/
1585 
1586 static int
aiff_check2(IFF_AIFF * const pcm_aiff_data)1587 aiff_check2(IFF_AIFF * const pcm_aiff_data)
1588 {
1589     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
1590         if (global_ui_config.silent < 10) {
1591             error_printf("ERROR: input sound data is not PCM\n");
1592         }
1593         return 1;
1594     }
1595     switch (pcm_aiff_data->sampleSize) {
1596     case 32:
1597     case 24:
1598     case 16:
1599     case 8:
1600         break;
1601     default:
1602         if (global_ui_config.silent < 10) {
1603             error_printf("ERROR: input sound data is not 8, 16, 24 or 32 bits\n");
1604         }
1605         return 1;
1606     }
1607     if (pcm_aiff_data->numChannels != 1 && pcm_aiff_data->numChannels != 2) {
1608         if (global_ui_config.silent < 10) {
1609             error_printf("ERROR: input sound data is not mono or stereo\n");
1610         }
1611         return 1;
1612     }
1613     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
1614         if (global_ui_config.silent < 10) {
1615             error_printf("ERROR: block size of input sound data is not 0 bytes\n");
1616         }
1617         return 1;
1618     }
1619     /* A bug, since we correctly skip the offset earlier in the code.
1620        if (pcm_aiff_data->blkAlgn.offset != 0) {
1621        error_printf("Block offset is not 0 bytes in '%s'\n", file_name);
1622        return 1;
1623        } */
1624 
1625     return 0;
1626 }
1627 
1628 
1629 /*****************************************************************************
1630  *
1631  *	Read Audio Interchange File Format (AIFF) headers.
1632  *
1633  *	By the time we get here the first 32 bits of the file have already been
1634  *	read, and we're pretty sure that we're looking at an AIFF file.
1635  *
1636  *****************************************************************************/
1637 
1638 static int
parse_aiff_header(lame_global_flags * gfp, FILE * sf)1639 parse_aiff_header(lame_global_flags * gfp, FILE * sf)
1640 {
1641     uint32_t  ui32_ChunkSize = 0;
1642     uint32_t  ui32_TypeID = 0;
1643     IFF_AIFF aiff_info;
1644     int     seen_comm_chunk = 0, seen_ssnd_chunk = 0;
1645     long    pcm_data_pos = -1;
1646 
1647     memset(&aiff_info, 0, sizeof(aiff_info));
1648     aiff_info.sampleFormat = IFF_ID_NONE;
1649     ui32_ChunkSize = read_32_bits_high_low(sf);
1650 
1651     ui32_TypeID = read_32_bits_high_low(sf);
1652     ui32_ChunkSize -= 4;
1653     if ((ui32_TypeID != IFF_ID_AIFF) && (ui32_TypeID != IFF_ID_AIFC))
1654         return -1;
1655 
1656     while (ui32_ChunkSize >= 8) {
1657         uint32_t ui32_type = read_32_bits_high_low(sf);
1658         ui32_ChunkSize -= 4;
1659 
1660         /* DEBUGF(
1661            "found chunk type %08x '%4.4s'\n", ui32_type, (char*)&ui32_type); */
1662 
1663         /* don't use a switch here to make it easier to use 'break' for SSND */
1664         if (ui32_type == IFF_ID_COMM) {
1665             uint32_t ui32_cksize = read_32_bits_high_low(sf);
1666             ui32_ChunkSize -= 4;
1667             ui32_cksize = make_even_number_of_bytes_in_length(ui32_cksize);
1668             if (ui32_cksize < 18 || ui32_ChunkSize < ui32_cksize)
1669                 return -1;
1670             ui32_ChunkSize -= ui32_cksize;
1671             seen_comm_chunk = seen_ssnd_chunk + 1;
1672 
1673             aiff_info.numChannels = read_16_bits_high_low(sf);
1674             aiff_info.numSampleFrames = read_32_bits_high_low(sf);
1675             aiff_info.sampleSize = read_16_bits_high_low(sf);
1676             aiff_info.sampleRate = read_ieee_extended_high_low(sf);
1677             ui32_cksize -= 18;
1678             if (ui32_TypeID == IFF_ID_AIFC) {
1679                 if (ui32_cksize < 4)
1680                     return -1;
1681                 aiff_info.sampleFormat = read_32_bits_high_low(sf);
1682                 ui32_cksize -= 4;
1683             }
1684             if (fskip_uint32(sf, ui32_cksize) != 0)
1685                 return -1;
1686         }
1687         else if (ui32_type == IFF_ID_SSND) {
1688             uint32_t ui32_cksize = read_32_bits_high_low(sf);
1689             ui32_ChunkSize -= 4;
1690             ui32_cksize = make_even_number_of_bytes_in_length(ui32_cksize);
1691             if (ui32_cksize < 8 || ui32_ChunkSize < ui32_cksize)
1692                 return -1;
1693             ui32_ChunkSize -= ui32_cksize;
1694             seen_ssnd_chunk = 1;
1695 
1696             aiff_info.sampleType = IFF_ID_SSND;
1697             aiff_info.blkAlgn.offset = read_32_bits_high_low(sf);
1698             aiff_info.blkAlgn.blockSize = read_32_bits_high_low(sf);
1699             ui32_cksize -= 8;
1700             if (seen_comm_chunk > 0) {
1701                 if (fskip_uint32(sf, aiff_info.blkAlgn.offset) != 0)
1702                     return -1;
1703                 /* We've found the audio data. Read no further! */
1704                 break;
1705             }
1706             pcm_data_pos = ftell(sf);
1707             if (pcm_data_pos >= 0) {
1708                 pcm_data_pos += aiff_info.blkAlgn.offset;
1709             }
1710             if (fskip_uint32(sf, ui32_cksize) != 0)
1711                 return -1;
1712         }
1713         else {
1714             uint32_t ui32_cksize;
1715             ui32_cksize = read_32_bits_high_low(sf);
1716             ui32_ChunkSize -= 4;
1717             ui32_cksize = make_even_number_of_bytes_in_length(ui32_cksize);
1718             if (ui32_ChunkSize < ui32_cksize)
1719                 return -1;
1720             ui32_ChunkSize -= ui32_cksize;
1721             if (fskip_uint32(sf, ui32_cksize) != 0)
1722                 return -1;
1723         }
1724     }
1725     if (aiff_info.sampleFormat == IFF_ID_2CLE) {
1726         global. pcm_is_ieee_float = 0;
1727         global. pcmswapbytes = global_reader.swapbytes;
1728     }
1729     else if (aiff_info.sampleFormat == IFF_ID_2CBE) {
1730         global. pcm_is_ieee_float = 0;
1731         global. pcmswapbytes = !global_reader.swapbytes;
1732     }
1733     else if (aiff_info.sampleFormat == IFF_ID_NONE) {
1734         global. pcm_is_ieee_float = 0;
1735         global. pcmswapbytes = !global_reader.swapbytes;
1736     }
1737     else if (aiff_info.sampleFormat == IFF_ID_FL32) {
1738         global. pcm_is_ieee_float = 1;
1739         global. pcmswapbytes = !global_reader.swapbytes;
1740     }
1741     /*  64 bit floating point reading is still missing
1742     else if (aiff_info.sampleFormat == IFF_ID_FL64) {
1743         global. pcm_is_ieee_float = 1;
1744         global. pcmswapbytes = !global_reader.swapbytes;
1745     }
1746     */
1747     else {
1748         return -1;
1749     }
1750 
1751     /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
1752     if (seen_comm_chunk && (seen_ssnd_chunk > 0 || aiff_info.numSampleFrames == 0)) {
1753         /* make sure the header is sane */
1754         if (0 != aiff_check2(&aiff_info))
1755             return 0;
1756         if (!set_input_num_channels(gfp, aiff_info.numChannels))
1757             return 0;
1758         if (!set_input_samplerate(gfp, (int) aiff_info.sampleRate))
1759             return 0;
1760         (void) lame_set_num_samples(gfp, aiff_info.numSampleFrames);
1761         global. pcmbitwidth = aiff_info.sampleSize;
1762         global. pcm_is_unsigned_8bit = 0;
1763         if (pcm_data_pos >= 0) {
1764             if (fseek(sf, pcm_data_pos, SEEK_SET) != 0) {
1765                 if (global_ui_config.silent < 10) {
1766                     error_printf("Can't rewind stream to audio data position\n");
1767                 }
1768                 return 0;
1769             }
1770         }
1771 
1772         return 1;
1773     }
1774     return -1;
1775 }
1776 
1777 
1778 
1779 /************************************************************************
1780 *
1781 * parse_file_header
1782 *
1783 * PURPOSE: Read the header from a bytestream.  Try to determine whether
1784 *          it's a WAV file or AIFF without rewinding, since rewind
1785 *          doesn't work on pipes and there's a good chance we're reading
1786 *          from stdin (otherwise we'd probably be using libsndfile).
1787 *
1788 * When this function returns, the file offset will be positioned at the
1789 * beginning of the sound data.
1790 *
1791 ************************************************************************/
1792 
1793 static int
parse_file_header(lame_global_flags * gfp, FILE * sf)1794 parse_file_header(lame_global_flags * gfp, FILE * sf)
1795 {
1796     uint32_t ui32_type = read_32_bits_high_low(sf);
1797     /*
1798        DEBUGF(
1799        "First word of input stream: %08x '%4.4s'\n", ui32_type, (char*) &type);
1800      */
1801     global. count_samples_carefully = 0;
1802     global. pcm_is_unsigned_8bit = global_raw_pcm.in_signed == 1 ? 0 : 1;
1803     /*global_reader.input_format = sf_raw; commented out, because it is better to fail
1804        here as to encode some hundreds of input files not supported by LAME
1805        If you know you have RAW PCM data, use the -r switch
1806      */
1807 
1808     if (ui32_type == WAV_ID_RIFF) {
1809         /* It's probably a WAV file */
1810         int const ret = parse_wave_header(gfp, sf);
1811         if (ret == sf_mp123) {
1812             global. count_samples_carefully = 1;
1813             return sf_mp123;
1814         }
1815         if (ret > 0) {
1816             if (lame_get_num_samples(gfp) == MAX_U_32_NUM || global_reader.ignorewavlength == 1)
1817             {
1818                 global. count_samples_carefully = 0;
1819                 lame_set_num_samples(gfp, MAX_U_32_NUM);
1820             }
1821             else
1822                 global. count_samples_carefully = 1;
1823             return sf_wave;
1824         }
1825         if (ret < 0) {
1826             if (global_ui_config.silent < 10) {
1827                 error_printf("Warning: corrupt or unsupported WAVE format\n");
1828             }
1829         }
1830     }
1831     else if (ui32_type == IFF_ID_FORM) {
1832         /* It's probably an AIFF file */
1833         int const ret = parse_aiff_header(gfp, sf);
1834         if (ret > 0) {
1835             global. count_samples_carefully = 1;
1836             return sf_aiff;
1837         }
1838         if (ret < 0) {
1839             if (global_ui_config.silent < 10) {
1840                 error_printf("Warning: corrupt or unsupported AIFF format\n");
1841             }
1842         }
1843     }
1844     else {
1845         if (global_ui_config.silent < 10) {
1846             error_printf("Warning: unsupported audio format\n");
1847         }
1848     }
1849     return sf_unknown;
1850 }
1851 
1852 
1853 static int
open_mpeg_file_part2(lame_t gfp, FILE* musicin, char const *inPath, int *enc_delay, int *enc_padding)1854 open_mpeg_file_part2(lame_t gfp, FILE* musicin, char const *inPath, int *enc_delay, int *enc_padding)
1855 {
1856 #ifdef HAVE_MPG123
1857     if (-1 == lame123_decode_initfile(musicin, &global_decoder.mp3input_data, enc_delay, enc_padding)) {
1858         if (global_ui_config.silent < 10) {
1859             error_printf("Error opening MPEG input file %s.\n", inPath);
1860         }
1861         return 0;
1862     }
1863 #else
1864 #ifdef HAVE_MPGLIB
1865     if (-1 == lame_decode_initfile(musicin, &global_decoder.mp3input_data, enc_delay, enc_padding)) {
1866         if (global_ui_config.silent < 10) {
1867             error_printf("Error reading headers in mp3 input file %s.\n", inPath);
1868         }
1869         return 0;
1870     }
1871 #endif
1872 #endif
1873     if (!set_input_num_channels(gfp, global_decoder.mp3input_data.stereo)) {
1874         return 0;
1875     }
1876     if (!set_input_samplerate(gfp, global_decoder.mp3input_data.samplerate)) {
1877         return 0;
1878     }
1879     (void) lame_set_num_samples(gfp, global_decoder.mp3input_data.nsamp);
1880     return 1;
1881 }
1882 
1883 
1884 static FILE *
open_wave_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding)1885 open_wave_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding)
1886 {
1887     FILE   *musicin;
1888 
1889     /* set the defaults from info incase we cannot determine them from file */
1890     lame_set_num_samples(gfp, MAX_U_32_NUM);
1891 
1892     if (!strcmp(inPath, "-")) {
1893         lame_set_stream_binary_mode(musicin = stdin); /* Read from standard input. */
1894     }
1895     else {
1896         if ((musicin = lame_fopen(inPath, "rb")) == NULL) {
1897             if (global_ui_config.silent < 10) {
1898                 error_printf("Could not find \"%s\".\n", inPath);
1899             }
1900             return 0;
1901         }
1902     }
1903 
1904     if (global_reader.input_format == sf_ogg) {
1905         if (global_ui_config.silent < 10) {
1906             error_printf("sorry, vorbis support in LAME is deprecated.\n");
1907         }
1908         close_input_file(musicin);
1909         return 0;
1910     }
1911     else if (global_reader.input_format == sf_raw) {
1912         /* assume raw PCM */
1913         if (global_ui_config.silent < 9) {
1914             console_printf("Assuming raw pcm input file");
1915             if (global_reader.swapbytes)
1916                 console_printf(" : Forcing byte-swapping\n");
1917             else
1918                 console_printf("\n");
1919         }
1920         global. pcmswapbytes = global_reader.swapbytes;
1921     }
1922     else {
1923         global_reader.input_format = parse_file_header(gfp, musicin);
1924     }
1925     if (global_reader.input_format == sf_mp123) {
1926         if (open_mpeg_file_part2(gfp, musicin, inPath, enc_delay, enc_padding))
1927             return musicin;
1928         close_input_file(musicin);
1929         return 0;
1930     }
1931     if (global_reader.input_format == sf_unknown) {
1932         close_input_file(musicin);
1933         return 0;
1934     }
1935 
1936     if (lame_get_num_samples(gfp) == MAX_U_32_NUM && musicin != stdin) {
1937         int const tmp_num_channels = lame_get_num_channels(gfp);
1938         double const flen = lame_get_file_size(musicin); /* try to figure out num_samples */
1939         if (flen >= 0 && tmp_num_channels > 0 ) {
1940             /* try file size, assume 2 bytes per sample */
1941             unsigned long fsize = (unsigned long) (flen / (2 * tmp_num_channels));
1942             (void) lame_set_num_samples(gfp, fsize);
1943             global. count_samples_carefully = 0;
1944         }
1945     }
1946     return musicin;
1947 }
1948 
1949 
1950 
1951 static FILE *
open_mpeg_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding)1952 open_mpeg_file(lame_t gfp, char const *inPath, int *enc_delay, int *enc_padding)
1953 {
1954     FILE   *musicin;
1955 
1956     /* set the defaults from info incase we cannot determine them from file */
1957     lame_set_num_samples(gfp, MAX_U_32_NUM);
1958 
1959     if (strcmp(inPath, "-") == 0) {
1960         musicin = stdin;
1961         lame_set_stream_binary_mode(musicin); /* Read from standard input. */
1962     }
1963     else {
1964         musicin = lame_fopen(inPath, "rb");
1965         if (musicin == NULL) {
1966             if (global_ui_config.silent < 10) {
1967                 error_printf("Could not find \"%s\".\n", inPath);
1968             }
1969             return 0;
1970         }
1971     }
1972 #ifdef AMIGA_MPEGA
1973     if (-1 == lame_decode_initfile_amiga(inPath, &global_decoder.mp3input_data)) {
1974         if (global_ui_config.silent < 10) {
1975             error_printf("Error reading headers in mp3 input file %s.\n", inPath);
1976         }
1977         close_input_file(musicin);
1978         return 0;
1979     }
1980 #endif
1981     if ( 0 == open_mpeg_file_part2(gfp, musicin, inPath, enc_delay, enc_padding) ) {
1982         close_input_file(musicin);
1983         return 0;
1984     }
1985     if (lame_get_num_samples(gfp) == MAX_U_32_NUM && musicin != stdin) {
1986         double  flen = lame_get_file_size(musicin); /* try to figure out num_samples */
1987         if (flen >= 0) {
1988             /* try file size, assume 2 bytes per sample */
1989             if (global_decoder.mp3input_data.bitrate > 0) {
1990                 double  totalseconds =
1991                     (flen * 8.0 / (1000.0 * global_decoder.mp3input_data.bitrate));
1992                 unsigned long tmp_num_samples =
1993                     (unsigned long) (totalseconds * lame_get_in_samplerate(gfp));
1994 
1995                 (void) lame_set_num_samples(gfp, tmp_num_samples);
1996                 global_decoder.mp3input_data.nsamp = tmp_num_samples;
1997                 global. count_samples_carefully = 0;
1998             }
1999         }
2000     }
2001     return musicin;
2002 }
2003 
2004 
2005 static int
close_input_file(FILE * musicin)2006 close_input_file(FILE * musicin)
2007 {
2008     int     ret = 0;
2009 
2010     if (musicin != stdin && musicin != 0) {
2011         ret = fclose(musicin);
2012     }
2013     if (ret != 0) {
2014         if (global_ui_config.silent < 10) {
2015             error_printf("Could not close audio input file\n");
2016         }
2017     }
2018     return ret;
2019 }
2020 
2021 
2022 
2023 #if defined(HAVE_MPGLIB)
2024 static int
check_aid(const unsigned char *header)2025 check_aid(const unsigned char *header)
2026 {
2027     return 0 == memcmp(header, "AiD\1", 4);
2028 }
2029 
2030 /*
2031  * Please check this and don't kill me if there's a bug
2032  * This is a (nearly?) complete header analysis for a MPEG-1/2/2.5 Layer I, II or III
2033  * data stream
2034  */
2035 
2036 static int
is_syncword_mp123(const void *const headerptr)2037 is_syncword_mp123(const void *const headerptr)
2038 {
2039     const unsigned char *const p = headerptr;
2040     static const char abl2[16] = { 0, 7, 7, 7, 0, 7, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8 };
2041 
2042     if ((p[0] & 0xFF) != 0xFF)
2043         return 0;       /* first 8 bits must be '1' */
2044     if ((p[1] & 0xE0) != 0xE0)
2045         return 0;       /* next 3 bits are also */
2046     if ((p[1] & 0x18) == 0x08)
2047         return 0;       /* no MPEG-1, -2 or -2.5 */
2048     switch (p[1] & 0x06) {
2049     default:
2050     case 0x00:         /* illegal Layer */
2051         return 0;
2052 
2053     case 0x02:         /* Layer3 */
2054         if (global_reader.input_format != sf_mp3 && global_reader.input_format != sf_mp123) {
2055             return 0;
2056         }
2057         global_reader.input_format = sf_mp3;
2058         break;
2059 
2060     case 0x04:         /* Layer2 */
2061         if (global_reader.input_format != sf_mp2 && global_reader.input_format != sf_mp123) {
2062             return 0;
2063         }
2064         global_reader.input_format = sf_mp2;
2065         break;
2066 
2067     case 0x06:         /* Layer1 */
2068         if (global_reader.input_format != sf_mp1 && global_reader.input_format != sf_mp123) {
2069             return 0;
2070         }
2071         global_reader.input_format = sf_mp1;
2072         break;
2073     }
2074     if ((p[1] & 0x06) == 0x00)
2075         return 0;       /* no Layer I, II and III */
2076     if ((p[2] & 0xF0) == 0xF0)
2077         return 0;       /* bad bitrate */
2078     if ((p[2] & 0x0C) == 0x0C)
2079         return 0;       /* no sample frequency with (32,44.1,48)/(1,2,4)     */
2080     if ((p[1] & 0x18) == 0x18 && (p[1] & 0x06) == 0x04 && abl2[p[2] >> 4] & (1 << (p[3] >> 6)))
2081         return 0;
2082     if ((p[3] & 3) == 2)
2083         return 0;       /* reserved enphasis mode */
2084     return 1;
2085 }
2086 
2087 static size_t
lenOfId3v2Tag(unsigned char const* buf)2088 lenOfId3v2Tag(unsigned char const* buf)
2089 {
2090     unsigned int b0 = buf[0] & 127;
2091     unsigned int b1 = buf[1] & 127;
2092     unsigned int b2 = buf[2] & 127;
2093     unsigned int b3 = buf[3] & 127;
2094     return (((((b0 << 7) + b1) << 7) + b2) << 7) + b3;
2095 }
2096 #endif
2097 
2098 #ifdef HAVE_MPG123
2099 #define CHECK123(code) if(MPG123_OK != (code)) return -1
2100 
2101 #ifdef _WIN32
lame123_read_from_file(void* handle, void* buffer, size_t size)2102 static ssize_t lame123_read_from_file(void* handle, void* buffer, size_t size)
2103 {
2104    return fread(buffer, 1, size, (FILE*)handle);
2105 }
2106 
lame123_seek_in_file(void* handle, off_t offset, int direction)2107 static off_t lame123_seek_in_file(void* handle, off_t offset, int direction)
2108 {
2109    if (fseek((FILE*)handle, offset, direction) != 0)
2110       return (off_t)-1;
2111    return ftell((FILE*)handle);
2112 }
2113 
lame123_cleanup_file(void* handle)2114 static void lame123_cleanup_file(void* handle)
2115 {
2116    /* don't call fclose(); close_input_file() will do that */
2117 }
2118 #endif
2119 
lame123_decode_initfile(FILE *fd, mp3data_struct *mp3data, int *enc_delay, int *enc_padding)2120 int lame123_decode_initfile(FILE *fd, mp3data_struct *mp3data, int *enc_delay, int *enc_padding)
2121 {
2122     off_t len;
2123     unsigned char *id3buf;
2124     size_t id3size;
2125     struct mpg123_frameinfo fi;
2126     long rate, val;
2127     int channels;
2128 
2129     mpg123_init();
2130     memset(mp3data, 0, sizeof(mp3data_struct));
2131     if (global.hip) {
2132         hip_decode_exit(global.hip);
2133     }
2134     global. hip = hip_decode_init();
2135     if(!global.hip->mh)
2136         return -1;
2137     /* TODO: enforce float format ... optionally be careful for builds
2138        that only know 16 bit output. */
2139     mpg123_param(global.hip->mh, MPG123_ADD_FLAGS, MPG123_STORE_RAW_ID3, 0.);
2140     mpg123_param(global.hip->mh, MPG123_ADD_FLAGS, MPG123_QUIET, 0.);
2141     mpg123_format_none(global.hip->mh);
2142     /* TODO: switch to MPG123_ENC_FLOAT_32, always! */
2143     CHECK123(mpg123_format2(global.hip->mh,
2144         0, MPG123_MONO|MPG123_STEREO, MPG123_ENC_SIGNED_16));
2145     /* TODO: verboseness / silence set up */
2146 #ifdef _WIN32
2147     /* On Win32 compiles it can happen that lame.exe and libmp3lame.dll use
2148        different C++ runtimes, which maintail different FILE* lists, and
2149        fileno() would produce invalid file numbers for those msvcrt instances.
2150        So use mpg123_replace_reader_handle() / mpg123_open_handle() here
2151        instead of mpg123_open_fd(). */
2152     CHECK123(mpg123_replace_reader_handle(global.hip->mh, lame123_read_from_file, lame123_seek_in_file, lame123_cleanup_file));
2153     CHECK123(mpg123_open_handle(global.hip->mh, fd));
2154 #else
2155     CHECK123(mpg123_open_fd(global.hip->mh, fileno(fd)));
2156 #endif
2157     /* Seek to get past Info frame and ID3v2. */
2158     CHECK123(mpg123_seek(global.hip->mh, SEEK_SET, 0));
2159     /* TODO: Figure out if MPG123_GAPLESS is desired or not. */
2160     /* Guessing seems to be OK, so we do not have to insist on knowing
2161        if libmpg123 got that info from Info tag or not. */
2162     /* I am paranoid about off_t being larger than long or int. */
2163     len = mpg123_framelength(global.hip->mh);
2164     if(len <= (unsigned long)-1)
2165         mp3data->totalframes = len;
2166     else
2167         return -1;
2168     len = mpg123_length(global.hip->mh);
2169     if(len <= ((unsigned int)-1)/2)
2170         mp3data->nsamp = len;
2171     else
2172         return -1;
2173     /* Encoder delay and padding are not needed when libmpg123 handles gapless
2174        decoding itself. So let's see if we get away with that. */
2175     mpg123_getstate(global.hip->mh, MPG123_ENC_DELAY, &val, NULL);
2176     *enc_delay = val;
2177     mpg123_getstate(global.hip->mh, MPG123_ENC_PADDING, &val, NULL);
2178     *enc_padding = val;
2179     if(global.in_id3v2_tag)
2180         free(global.in_id3v2_tag);
2181     global.in_id3v2_size = 0;
2182     if( MPG123_OK == mpg123_id3_raw(global.hip->mh, NULL, NULL,
2183         &id3buf, &id3size) && id3buf && id3size ) {
2184         global.in_id3v2_tag = malloc(id3size);
2185         if(global.in_id3v2_tag) {
2186             memcpy(global.in_id3v2_tag, id3buf, id3size);
2187             global.in_id3v2_size = id3size;
2188         }
2189     }
2190     CHECK123(mpg123_info(global.hip->mh, &fi));
2191     CHECK123(mpg123_getformat(global.hip->mh, &rate, &channels, NULL));
2192     /* How much of this is actually needed for the frontend? */
2193     mp3data->header_parsed = 1;
2194     mp3data->stereo = channels; /* Channel count correct? Or is dual mono different? */
2195     mp3data->samplerate = rate;
2196     mp3data->mode = fi.mode;
2197     mp3data->mode_ext = fi.mode_ext;
2198     mp3data->framesize = mpg123_spf(global.hip->mh);
2199     mp3data->bitrate = fi.bitrate;
2200     if(global_reader.input_format == sf_mp123) switch(fi.layer) {
2201         case 1:
2202             global_reader.input_format = sf_mp1;
2203         break;
2204         case 2:
2205             global_reader.input_format = sf_mp2;
2206         break;
2207         case 3:
2208             global_reader.input_format = sf_mp3;
2209         break;
2210     }
2211 
2212     return 0;
2213 }
2214 #endif
2215 
2216 #ifdef HAVE_MPGLIB
2217 int
lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding)2218 lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int *enc_delay, int *enc_padding)
2219 {
2220     /*  VBRTAGDATA pTagData; */
2221     /* int xing_header,len2,num_frames; */
2222     unsigned char buf[100];
2223     int     ret;
2224     size_t  len;
2225     int     aid_header;
2226     short int pcm_l[1152], pcm_r[1152];
2227     int     freeformat = 0;
2228 
2229     memset(mp3data, 0, sizeof(mp3data_struct));
2230     if (global.hip) {
2231         hip_decode_exit(global.hip);
2232     }
2233     global. hip = hip_decode_init();
2234     hip_set_msgf(global.hip, global_ui_config.silent < 10 ? &frontend_msgf : 0);
2235     hip_set_errorf(global.hip, global_ui_config.silent < 10 ? &frontend_errorf : 0);
2236     hip_set_debugf(global.hip, &frontend_debugf);
2237 
2238     len = 4;
2239     if (fread(buf, 1, len, fd) != len)
2240         return -1;      /* failed */
2241     while (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3') {
2242         len = 6;
2243         if (fread(&buf[4], 1, len, fd) != len)
2244             return -1;  /* failed */
2245         len = lenOfId3v2Tag(&buf[6]);
2246         if (global.in_id3v2_size < 1) {
2247             global.in_id3v2_size = 10 + len;
2248             global.in_id3v2_tag = malloc(global.in_id3v2_size);
2249             if (global.in_id3v2_tag) {
2250                 memcpy(global.in_id3v2_tag, buf, 10);
2251                 if (fread(&global.in_id3v2_tag[10], 1, len, fd) != len)
2252                     return -1;  /* failed */
2253                 len = 0; /* copied, nothing to skip */
2254             }
2255             else {
2256                 global.in_id3v2_size = 0;
2257             }
2258         }
2259         if (len > LONG_MAX)
2260             return -1;
2261         if (fskip_long(fd, (long) len, SEEK_CUR) != 0)
2262             return -1;
2263         len = 4;
2264         if (fread(&buf, 1, len, fd) != len)
2265             return -1;  /* failed */
2266     }
2267     aid_header = check_aid(buf);
2268     if (aid_header) {
2269         if (fread(&buf, 1, 2, fd) != 2)
2270             return -1;  /* failed */
2271         aid_header = (unsigned char) buf[0] + 256 * (unsigned char) buf[1];
2272         if (global_ui_config.silent < 9) {
2273             console_printf("Album ID found.  length=%i \n", aid_header);
2274         }
2275         /* skip rest of AID, except for 6 bytes we have already read */
2276         fskip_long(fd, aid_header - 6, SEEK_CUR);
2277 
2278         /* read 4 more bytes to set up buffer for MP3 header check */
2279         if (fread(&buf, 1, len, fd) != len)
2280             return -1;  /* failed */
2281     }
2282     len = 4;
2283     while (!is_syncword_mp123(buf)) {
2284         unsigned int i;
2285         for (i = 0; i < len - 1; i++)
2286             buf[i] = buf[i + 1];
2287         if (fread(buf + len - 1, 1, 1, fd) != 1)
2288             return -1;  /* failed */
2289     }
2290 
2291     if ((buf[2] & 0xf0) == 0) {
2292         if (global_ui_config.silent < 9) {
2293             console_printf("Input file is freeformat.\n");
2294         }
2295         freeformat = 1;
2296     }
2297     /* now parse the current buffer looking for MP3 headers.    */
2298     /* (as of 11/00: mpglib modified so that for the first frame where  */
2299     /* headers are parsed, no data will be decoded.   */
2300     /* However, for freeformat, we need to decode an entire frame, */
2301     /* so mp3data->bitrate will be 0 until we have decoded the first */
2302     /* frame.  Cannot decode first frame here because we are not */
2303     /* yet prepared to handle the output. */
2304     ret = hip_decode1_headersB(global.hip, buf, len, pcm_l, pcm_r, mp3data, enc_delay, enc_padding);
2305     if (-1 == ret)
2306         return -1;
2307 
2308     /* repeat until we decode a valid mp3 header.  */
2309     while (!mp3data->header_parsed) {
2310         len = fread(buf, 1, sizeof(buf), fd);
2311         if (len != sizeof(buf))
2312             return -1;
2313         ret =
2314             hip_decode1_headersB(global.hip, buf, len, pcm_l, pcm_r, mp3data, enc_delay,
2315                                  enc_padding);
2316         if (-1 == ret)
2317             return -1;
2318     }
2319 
2320     if (mp3data->bitrate == 0 && !freeformat) {
2321         if (global_ui_config.silent < 10) {
2322             error_printf("fail to sync...\n");
2323         }
2324         return lame_decode_initfile(fd, mp3data, enc_delay, enc_padding);
2325     }
2326 
2327     if (mp3data->totalframes > 0) {
2328         /* mpglib found a Xing VBR header and computed nsamp & totalframes */
2329     }
2330     else {
2331         /* set as unknown.  Later, we will take a guess based on file size
2332          * ant bitrate */
2333         mp3data->nsamp = MAX_U_32_NUM;
2334     }
2335 
2336 
2337     /*
2338        report_printf("ret = %i NEED_MORE=%i \n",ret,MP3_NEED_MORE);
2339        report_printf("stereo = %i \n",mp.fr.stereo);
2340        report_printf("samp = %i  \n",freqs[mp.fr.sampling_frequency]);
2341        report_printf("framesize = %i  \n",framesize);
2342        report_printf("bitrate = %i  \n",mp3data->bitrate);
2343        report_printf("num frames = %ui  \n",num_frames);
2344        report_printf("num samp = %ui  \n",mp3data->nsamp);
2345        report_printf("mode     = %i  \n",mp.fr.mode);
2346      */
2347 
2348     return 0;
2349 }
2350 
2351 /*
2352 For lame_decode_fromfile:  return code
2353   -1     error
2354    n     number of samples output.  either 576 or 1152 depending on MP3 file.
2355 
2356 
2357 For lame_decode1_headers():  return code
2358   -1     error
2359    0     ok, but need more data before outputing any samples
2360    n     number of samples output.  either 576 or 1152 depending on MP3 file.
2361 */
2362 static int
lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)2363 lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
2364 {
2365     int     ret = 0;
2366     size_t  len = 0;
2367     unsigned char buf[1024];
2368 
2369     /* first see if we still have data buffered in the decoder: */
2370     ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2371     if (ret != 0)
2372         return ret;
2373 
2374 
2375     /* read until we get a valid output frame */
2376     for (;;) {
2377         len = fread(buf, 1, 1024, fd);
2378         if (len == 0) {
2379             /* we are done reading the file, but check for buffered data */
2380             ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2381             if (ret <= 0) {
2382                 return -1; /* done with file */
2383             }
2384             break;
2385         }
2386 
2387         ret = hip_decode1_headers(global.hip, buf, len, pcm_l, pcm_r, mp3data);
2388         if (ret == -1) {
2389             return -1;
2390         }
2391         if (ret > 0)
2392             break;
2393     }
2394     return ret;
2395 }
2396 #endif /* defined(HAVE_MPGLIB) */
2397 
2398 
2399 int
is_mpeg_file_format(int input_file_format)2400 is_mpeg_file_format(int input_file_format)
2401 {
2402     switch (input_file_format) {
2403     case sf_mp1:
2404         return 1;
2405     case sf_mp2:
2406         return 2;
2407     case sf_mp3:
2408         return 3;
2409     case sf_mp123:
2410         return -1;
2411     default:
2412         break;
2413     }
2414     return 0;
2415 }
2416 
2417 
2418 #define LOW__BYTE(x) (x & 0x00ff)
2419 #define HIGH_BYTE(x) ((x >> 8) & 0x00ff)
2420 
2421 void
put_audio16(FILE * outf, short Buffer[2][1152], int iread, int nch)2422 put_audio16(FILE * outf, short Buffer[2][1152], int iread, int nch)
2423 {
2424     char    data[2 * 1152 * 2];
2425     int     i, m = 0;
2426 
2427     if (global_decoder.disable_wav_header && global_reader.swapbytes) {
2428         if (nch == 1) {
2429             for (i = 0; i < iread; i++) {
2430                 short   x = Buffer[0][i];
2431                 /* write 16 Bits High Low */
2432                 data[m++] = HIGH_BYTE(x);
2433                 data[m++] = LOW__BYTE(x);
2434             }
2435         }
2436         else {
2437             for (i = 0; i < iread; i++) {
2438                 short   x = Buffer[0][i], y = Buffer[1][i];
2439                 /* write 16 Bits High Low */
2440                 data[m++] = HIGH_BYTE(x);
2441                 data[m++] = LOW__BYTE(x);
2442                 /* write 16 Bits High Low */
2443                 data[m++] = HIGH_BYTE(y);
2444                 data[m++] = LOW__BYTE(y);
2445             }
2446         }
2447     }
2448     else {
2449         if (nch == 1) {
2450             for (i = 0; i < iread; i++) {
2451                 short   x = Buffer[0][i];
2452                 /* write 16 Bits Low High */
2453                 data[m++] = LOW__BYTE(x);
2454                 data[m++] = HIGH_BYTE(x);
2455             }
2456         }
2457         else {
2458             for (i = 0; i < iread; i++) {
2459                 short   x = Buffer[0][i], y = Buffer[1][i];
2460                 /* write 16 Bits Low High */
2461                 data[m++] = LOW__BYTE(x);
2462                 data[m++] = HIGH_BYTE(x);
2463                 /* write 16 Bits Low High */
2464                 data[m++] = LOW__BYTE(y);
2465                 data[m++] = HIGH_BYTE(y);
2466             }
2467         }
2468     }
2469     if (m > 0) {
2470         fwrite(data, 1, m, outf);
2471     }
2472     if (global_writer.flush_write == 1) {
2473         fflush(outf);
2474     }
2475 }
2476 
2477 hip_t
get_hip(void)2478 get_hip(void)
2479 {
2480     return global.hip;
2481 }
2482 
2483 size_t
sizeOfOldTag(lame_t gf)2484 sizeOfOldTag(lame_t gf)
2485 {
2486     (void) gf;
2487     return global.in_id3v2_size;
2488 }
2489 
2490 unsigned char*
getOldTag(lame_t gf)2491 getOldTag(lame_t gf)
2492 {
2493     (void) gf;
2494     return global.in_id3v2_tag;
2495 }
2496 
2497 /* end of get_audio.c */
2498