Subversion Repositories planix.SVN

Rev

Rev 2 | Details | Compare with Previous | Last modification | View Log | RSS feed

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