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