audio.c 18.1 KB
Newer Older
Jack Moffitt's avatar
Jack Moffitt committed
1
2
3
4
5
/* OggEnc
 **
 ** This program is distributed under the GNU General Public License, version 2.
 ** A copy of this license is included with this source.
 **
6
 ** Copyright 2000-2002, Michael Smith <msmith@xiph.org>
Jack Moffitt's avatar
Jack Moffitt committed
7
 **
Michael Smith's avatar
   
Michael Smith committed
8
 ** AIFF/AIFC support from OggSquish, (c) 1994-1996 Monty <xiphmont@xiph.org>
Jack Moffitt's avatar
Jack Moffitt committed
9
10
11
12
13
14
15
 **/


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
Michael Smith's avatar
   
Michael Smith committed
16
#include <math.h>
Jack Moffitt's avatar
Jack Moffitt committed
17
#include "audio.h"
Michael Smith's avatar
   
Michael Smith committed
18
#include "platform.h"
19
#include "i18n.h"
20
#include "resample.h"
Jack Moffitt's avatar
Jack Moffitt committed
21

22
23
24
25
#ifdef HAVE_LIBFLAC
#include "flac.h"
#endif

Jack Moffitt's avatar
Jack Moffitt committed
26
27
28
#define WAV_HEADER_SIZE 44

/* Macros to read header data */
Michael Smith's avatar
   
Michael Smith committed
29
#define READ_U32_LE(buf) \
30
	(((buf)[3]<<24)|((buf)[2]<<16)|((buf)[1]<<8)|((buf)[0]&0xff))
Jack Moffitt's avatar
Jack Moffitt committed
31

Michael Smith's avatar
   
Michael Smith committed
32
#define READ_U16_LE(buf) \
33
	(((buf)[1]<<8)|((buf)[0]&0xff))
Jack Moffitt's avatar
Jack Moffitt committed
34

Michael Smith's avatar
   
Michael Smith committed
35
#define READ_U32_BE(buf) \
36
	(((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|((buf)[3]&0xff))
Michael Smith's avatar
   
Michael Smith committed
37
38

#define READ_U16_BE(buf) \
39
	(((buf)[0]<<8)|((buf)[1]&0xff))
Michael Smith's avatar
   
Michael Smith committed
40

Michael Smith's avatar
   
Michael Smith committed
41
42
/* Define the supported formats here */
input_format formats[] = {
43
44
	{wav_id, 12, wav_open, wav_close, "wav", N_("WAV file reader")},
	{aiff_id, 12, aiff_open, wav_close, "aiff", N_("AIFF/AIFC file reader")},
45
46
47
48
#ifdef HAVE_LIBFLAC
	{flac_id,     4, flac_open, flac_close, "flac", N_("FLAC file reader")},
	{oggflac_id, 32, flac_open, flac_close, "ogg", N_("Ogg FLAC file reader")},
#endif
Michael Smith's avatar
   
Michael Smith committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	{NULL, 0, NULL, NULL, NULL, NULL}
};

input_format *open_audio_file(FILE *in, oe_enc_opt *opt)
{
	int j=0;
	unsigned char *buf=NULL;
	int buf_size=0, buf_filled=0;
	int size,ret;

	while(formats[j].id_func)
	{
		size = formats[j].id_data_len;
		if(size >= buf_size)
		{
			buf = realloc(buf, size);
			buf_size = size;
		}

68
		if(size > buf_filled)
Michael Smith's avatar
   
Michael Smith committed
69
70
71
72
		{
			ret = fread(buf+buf_filled, 1, buf_size-buf_filled, in);
			buf_filled += ret;

73
			if(buf_filled < size)
Michael Smith's avatar
   
Michael Smith committed
74
75
76
77
78
79
			{ /* File truncated */
				j++;
				continue;
			}
		}

80
		if(formats[j].id_func(buf, buf_filled))
Michael Smith's avatar
   
Michael Smith committed
81
82
		{
			/* ok, we now have something that can handle the file */
83
			if(formats[j].open_func(in, opt, buf, buf_filled)) {
84
                free(buf);
Michael Smith's avatar
   
Michael Smith committed
85
				return &formats[j];
86
            }
Michael Smith's avatar
   
Michael Smith committed
87
88
89
90
		}
		j++;
	}

91
92
    free(buf);

Michael Smith's avatar
   
Michael Smith committed
93
94
95
	return NULL;
}

Michael Smith's avatar
   
Michael Smith committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
static int seek_forward(FILE *in, int length)
{
	if(fseek(in, length, SEEK_CUR))
	{
		/* Failed. Do it the hard way. */
		unsigned char buf[1024];
		int seek_needed = length, seeked;
		while(seek_needed > 0)
		{
			seeked = fread(buf, 1, seek_needed>1024?1024:seek_needed, in);
			if(!seeked)
				return 0; /* Couldn't read more, can't read file */
			else
				seek_needed -= seeked;
		}
	}
	return 1;
}
Michael Smith's avatar
   
Michael Smith committed
114

Michael Smith's avatar
   
Michael Smith committed
115
116

static int find_wav_chunk(FILE *in, char *type, unsigned int *len)
Jack Moffitt's avatar
Jack Moffitt committed
117
118
119
120
121
122
123
{
	unsigned char buf[8];

	while(1)
	{
		if(fread(buf,1,8,in) < 8) /* Suck down a chunk specifier */
		{
124
			fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
Jack Moffitt's avatar
Jack Moffitt committed
125
126
127
128
129
			return 0; /* EOF before reaching the appropriate chunk */
		}

		if(memcmp(buf, type, 4))
		{
Michael Smith's avatar
   
Michael Smith committed
130
131
132
133
			*len = READ_U32_LE(buf+4);
			if(!seek_forward(in, *len))
				return 0;

Jack Moffitt's avatar
Jack Moffitt committed
134
			buf[4] = 0;
135
			fprintf(stderr, _("Skipping chunk of type \"%s\", length %d\n"), buf, *len);
Jack Moffitt's avatar
Jack Moffitt committed
136
137
138
		}
		else
		{
Michael Smith's avatar
   
Michael Smith committed
139
			*len = READ_U32_LE(buf+4);
Jack Moffitt's avatar
Jack Moffitt committed
140
141
142
143
144
			return 1;
		}
	}
}

Michael Smith's avatar
   
Michael Smith committed
145
146
147
148
149
150
151
152
static int find_aiff_chunk(FILE *in, char *type, unsigned int *len)
{
	unsigned char buf[8];

	while(1)
	{
		if(fread(buf,1,8,in) <8)
		{
153
			fprintf(stderr, _("Warning: Unexpected EOF in AIFF chunk\n"));
Michael Smith's avatar
   
Michael Smith committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
			return 0;
		}

		*len = READ_U32_BE(buf+4);

		if(memcmp(buf,type,4))
		{
			if((*len) & 0x1)
				(*len)++;

			if(!seek_forward(in, *len))
				return 0;
		}
		else
			return 1;
	}
}



double read_IEEE80(unsigned char *buf)
{
	int s=buf[0]&0xff;
	int e=((buf[0]&0x7f)<<8)|(buf[1]&0xff);
	double f=((unsigned long)(buf[2]&0xff)<<24)|
		((buf[3]&0xff)<<16)|
		((buf[4]&0xff)<<8) |
		 (buf[5]&0xff);

	if(e==32767)
	{
		if(buf[2]&0x80)
			return HUGE_VAL; /* Really NaN, but this won't happen in reality */
		else
		{
			if(s)
				return -HUGE_VAL;
			else
				return HUGE_VAL;
		}
	}

	f=ldexp(f,32);
	f+= ((buf[6]&0xff)<<24)|
		((buf[7]&0xff)<<16)|
		((buf[8]&0xff)<<8) |
		 (buf[9]&0xff);

	return ldexp(f, e-16446);
}

/* AIFF/AIFC support adapted from the old OggSQUISH application */
int aiff_id(unsigned char *buf, int len)
{
	if(len<12) return 0; /* Truncated file, probably */

	if(memcmp(buf, "FORM", 4))
		return 0;

	if(memcmp(buf+8, "AIF",3))
		return 0;

	if(buf[11]!='C' && buf[11]!='F')
		return 0;

	return 1;
}

int aiff_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen)
{
	int aifc; /* AIFC or AIFF? */
	unsigned int len;
	unsigned char *buffer;
	unsigned char buf2[8];
	aiff_fmt format;
	aifffile *aiff = malloc(sizeof(aifffile));

	if(buf[11]=='C')
		aifc=1;
	else
		aifc=0;

	if(!find_aiff_chunk(in, "COMM", &len))
	{
238
		fprintf(stderr, _("Warning: No common chunk found in AIFF file\n"));
Michael Smith's avatar
   
Michael Smith committed
239
240
241
242
243
		return 0; /* EOF before COMM chunk */
	}

	if(len < 18) 
	{
244
		fprintf(stderr, _("Warning: Truncated common chunk in AIFF header\n"));
Michael Smith's avatar
   
Michael Smith committed
245
246
247
248
249
250
251
		return 0; /* Weird common chunk */
	}

	buffer = alloca(len);

	if(fread(buffer,1,len,in) < len)
	{
252
		fprintf(stderr, _("Warning: Unexpected EOF in reading AIFF header\n"));
Michael Smith's avatar
   
Michael Smith committed
253
254
255
256
257
258
259
260
		return 0;
	}

	format.channels = READ_U16_BE(buffer);
	format.totalframes = READ_U32_BE(buffer+2);
	format.samplesize = READ_U16_BE(buffer+6);
	format.rate = (int)read_IEEE80(buffer+8);

Michael Smith's avatar
Michael Smith committed
261
262
    aiff->bigendian = 1;

Michael Smith's avatar
   
Michael Smith committed
263
264
265
266
	if(aifc)
	{
		if(len < 22)
		{
267
			fprintf(stderr, _("Warning: AIFF-C header truncated.\n"));
Michael Smith's avatar
   
Michael Smith committed
268
269
			return 0;
		}
270
271
272
273
274
275
276
277
278
279

		if(!memcmp(buffer+18, "NONE", 4)) 
		{
			aiff->bigendian = 1;
		}
		else if(!memcmp(buffer+18, "sowt", 4)) 
		{
			aiff->bigendian = 0;
		}
		else
Michael Smith's avatar
   
Michael Smith committed
280
		{
281
			fprintf(stderr, _("Warning: Can't handle compressed AIFF-C (%c%c%c%c)\n"), *(buffer+18), *(buffer+19), *(buffer+20), *(buffer+21));
Michael Smith's avatar
   
Michael Smith committed
282
283
284
285
286
287
			return 0; /* Compressed. Can't handle */
		}
	}

	if(!find_aiff_chunk(in, "SSND", &len))
	{
288
		fprintf(stderr, _("Warning: No SSND chunk found in AIFF file\n"));
Michael Smith's avatar
   
Michael Smith committed
289
290
291
292
293
		return 0; /* No SSND chunk -> no actual audio */
	}

	if(len < 8) 
	{
294
		fprintf(stderr, _("Warning: Corrupted SSND chunk in AIFF header\n"));
Michael Smith's avatar
   
Michael Smith committed
295
296
297
298
299
		return 0; 
	}

	if(fread(buf2,1,8, in) < 8)
	{
300
		fprintf(stderr, _("Warning: Unexpected EOF reading AIFF header\n"));
Michael Smith's avatar
   
Michael Smith committed
301
302
303
304
305
306
307
		return 0;
	}

	format.offset = READ_U32_BE(buf2);
	format.blocksize = READ_U32_BE(buf2+4);

	if( format.blocksize == 0 &&
308
		(format.samplesize == 16 || format.samplesize == 8))
Michael Smith's avatar
   
Michael Smith committed
309
310
311
312
313
314
315
316
317
318
319
	{
		/* From here on, this is very similar to the wav code. Oh well. */
		
		opt->rate = format.rate;
		opt->channels = format.channels;
		opt->read_samples = wav_read; /* Similar enough, so we use the same */
		opt->total_samples_per_channel = format.totalframes;

		aiff->f = in;
		aiff->samplesread = 0;
		aiff->channels = format.channels;
320
		aiff->samplesize = format.samplesize;
Michael Smith's avatar
   
Michael Smith committed
321
322
323
324
325
326
327
328
329
330
		aiff->totalsamples = format.totalframes;

		opt->readdata = (void *)aiff;

		seek_forward(in, format.offset); /* Swallow some data */
		return 1;
	}
	else
	{
		fprintf(stderr, 
331
				_("Warning: OggEnc does not support this type of AIFF/AIFC file\n"
Michael Smith's avatar
Michael Smith committed
332
				" Must be 8, 16, or 24 bit PCM.\n"));
Michael Smith's avatar
   
Michael Smith committed
333
334
335
336
337
		return 0;
	}
}


Michael Smith's avatar
   
Michael Smith committed
338
339
340
341
342
343
344
345
346
int wav_id(unsigned char *buf, int len)
{
	unsigned int flen;
	
	if(len<12) return 0; /* Something screwed up */

	if(memcmp(buf, "RIFF", 4))
		return 0; /* Not wave */

Michael Smith's avatar
   
Michael Smith committed
347
	flen = READ_U32_LE(buf+4); /* We don't use this */
Michael Smith's avatar
   
Michael Smith committed
348
349
350
351
352
353
354

	if(memcmp(buf+8, "WAVE",4))
		return 0; /* RIFF, but not wave */

	return 1;
}

Michael Smith's avatar
   
Michael Smith committed
355
int wav_open(FILE *in, oe_enc_opt *opt, unsigned char *oldbuf, int buflen)
Jack Moffitt's avatar
Jack Moffitt committed
356
{
357
	unsigned char buf[16];
Jack Moffitt's avatar
Jack Moffitt committed
358
	unsigned int len;
359
	int samplesize;
Jack Moffitt's avatar
Jack Moffitt committed
360
361
362
363
364
	wav_fmt format;
	wavfile *wav = malloc(sizeof(wavfile));

	/* Ok. At this point, we know we have a WAV file. Now we have to detect
	 * whether we support the subtype, and we have to find the actual data
Michael Smith's avatar
   
Michael Smith committed
365
366
	 * We don't (for the wav reader) need to use the buffer we used to id this
	 * as a wav file (oldbuf)
Jack Moffitt's avatar
Jack Moffitt committed
367
368
	 */

Michael Smith's avatar
   
Michael Smith committed
369
	if(!find_wav_chunk(in, "fmt ", &len))
Jack Moffitt's avatar
Jack Moffitt committed
370
371
		return 0; /* EOF */

372
	if(len < 16) 
Jack Moffitt's avatar
Jack Moffitt committed
373
	{
374
		fprintf(stderr, _("Warning: Unrecognised format chunk in WAV header\n"));
Jack Moffitt's avatar
Jack Moffitt committed
375
376
377
		return 0; /* Weird format chunk */
	}

378
379
380
381
382
	/* A common error is to have a format chunk that is not 16 or 18 bytes
	 * in size.  This is incorrect, but not fatal, so we only warn about 
	 * it instead of refusing to work with the file.  Please, if you
	 * have a program that's creating format chunks of sizes other than
	 * 16 or 18 bytes in size, report a bug to the author.
383
	 */
384
	if(len!=16 && len!=18)
385
		fprintf(stderr, 
386
387
				_("Warning: INVALID format chunk in wav header.\n"
				" Trying to read anyway (may not work)...\n"));
388

Jack Moffitt's avatar
Jack Moffitt committed
389
	if(fread(buf,1,16,in) < 16)
Jack Moffitt's avatar
Jack Moffitt committed
390
	{
391
		fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
Jack Moffitt's avatar
Jack Moffitt committed
392
393
394
		return 0;
	}

395
396
397
398
399
	/* Deal with stupid broken apps. Don't use these programs.
	 */
	if(len - 16 > 0 && !seek_forward(in, len-16))
	    return 0;

Michael Smith's avatar
   
Michael Smith committed
400
401
402
403
404
405
	format.format =      READ_U16_LE(buf); 
	format.channels =    READ_U16_LE(buf+2); 
	format.samplerate =  READ_U32_LE(buf+4);
	format.bytespersec = READ_U32_LE(buf+8);
	format.align =       READ_U16_LE(buf+12);
	format.samplesize =  READ_U16_LE(buf+14);
Jack Moffitt's avatar
Jack Moffitt committed
406

Michael Smith's avatar
   
Michael Smith committed
407
	if(!find_wav_chunk(in, "data", &len))
Jack Moffitt's avatar
Jack Moffitt committed
408
409
		return 0; /* EOF */

410
411
	if(format.format == 1)
	{
412
		samplesize = format.samplesize/8;
413
414
415
416
417
418
419
420
421
422
		opt->read_samples = wav_read;
	}
	else if(format.format == 3)
	{
		samplesize = 4;
		opt->read_samples = wav_ieee_read;
	}
	else
	{
		fprintf(stderr, 
423
424
				_("ERROR: Wav file is unsupported type (must be standard PCM\n"
				" or type 3 floating point PCM\n"));
425
426
427
428
429
430
		return 0;
	}



	if( format.align == format.channels*samplesize &&
Michael Smith's avatar
Michael Smith committed
431
432
			format.samplesize == samplesize*8 && 
    		(format.samplesize == 24 || format.samplesize == 16 || 
433
434
             format.samplesize == 8 ||
	     (format.samplesize == 32 && format.format == 3)))
Jack Moffitt's avatar
Jack Moffitt committed
435
436
437
	{
		/* OK, good - we have the one supported format,
		   now we want to find the size of the file */
Michael Smith's avatar
   
Michael Smith committed
438
		opt->rate = format.samplerate;
Jack Moffitt's avatar
Jack Moffitt committed
439
440
441
442
		opt->channels = format.channels;

		wav->f = in;
		wav->samplesread = 0;
Michael Smith's avatar
   
Michael Smith committed
443
		wav->bigendian = 0;
Michael Smith's avatar
   
Michael Smith committed
444
445
		wav->channels = format.channels; /* This is in several places. The price
											of trying to abstract stuff. */
446
		wav->samplesize = format.samplesize;
Jack Moffitt's avatar
Jack Moffitt committed
447
448

		if(len)
449
        {
450
			opt->total_samples_per_channel = len/(format.channels*samplesize);
Jack Moffitt's avatar
Jack Moffitt committed
451
452
453
454
455
456
457
458
459
460
461
		}
		else
		{
			long pos;
			pos = ftell(in);
			if(fseek(in, 0, SEEK_END) == -1)
			{
				opt->total_samples_per_channel = 0; /* Give up */
			}
			else
			{
462
463
				opt->total_samples_per_channel = (ftell(in) - pos)/
                    (format.channels*samplesize);
Jack Moffitt's avatar
Jack Moffitt committed
464
465
466
				fseek(in,pos, SEEK_SET);
			}
		}
467
468
		wav->totalsamples = opt->total_samples_per_channel;

Jack Moffitt's avatar
Jack Moffitt committed
469
470
471
472
473
		opt->readdata = (void *)wav;
		return 1;
	}
	else
	{
474
		fprintf(stderr, 
Michael Smith's avatar
Michael Smith committed
475
				_("ERROR: Wav file is unsupported subformat (must be 8,16, or 24 bit PCM\n"
476
				"or floating point PCM\n"));
Jack Moffitt's avatar
Jack Moffitt committed
477
478
479
480
		return 0;
	}
}

Michael Smith's avatar
   
Michael Smith committed
481
long wav_read(void *in, float **buffer, int samples)
Jack Moffitt's avatar
Jack Moffitt committed
482
483
{
	wavfile *f = (wavfile *)in;
484
485
486
	int sampbyte = f->samplesize / 8;
	signed char *buf = alloca(samples*sampbyte*f->channels);
	long bytes_read = fread(buf, 1, samples*sampbyte*f->channels, f->f);
Michael Smith's avatar
   
Michael Smith committed
487
488
489
490
	int i,j;
	long realsamples;

	if(f->totalsamples && f->samplesread + 
491
			bytes_read/(sampbyte*f->channels) > f->totalsamples) {
492
		bytes_read = sampbyte*f->channels*(f->totalsamples - f->samplesread);
493
    }
494
495

	realsamples = bytes_read/(sampbyte*f->channels);
Michael Smith's avatar
   
Michael Smith committed
496
	f->samplesread += realsamples;
Jack Moffitt's avatar
Jack Moffitt committed
497
		
498
	if(f->samplesize==8)
Michael Smith's avatar
   
Michael Smith committed
499
	{
500
		unsigned char *bufu = (unsigned char *)buf;
Michael Smith's avatar
   
Michael Smith committed
501
502
503
504
		for(i = 0; i < realsamples; i++)
		{
			for(j=0; j < f->channels; j++)
			{
505
				buffer[j][i]=((int)(bufu[i*f->channels + j])-128)/128.0f;
Michael Smith's avatar
   
Michael Smith committed
506
507
508
			}
		}
	}
Michael Smith's avatar
Michael Smith committed
509
	else if(f->samplesize==16)
Jack Moffitt's avatar
Jack Moffitt committed
510
	{
511
		if(!f->bigendian)
Michael Smith's avatar
   
Michael Smith committed
512
		{
513
			for(i = 0; i < realsamples; i++)
Michael Smith's avatar
   
Michael Smith committed
514
			{
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
				for(j=0; j < f->channels; j++)
				{
					buffer[j][i] = ((buf[i*2*f->channels + 2*j + 1]<<8) |
							        (buf[i*2*f->channels + 2*j] & 0xff))/32768.0f;
				}
			}
		}
		else
		{
			for(i = 0; i < realsamples; i++)
			{
				for(j=0; j < f->channels; j++)
				{
					buffer[j][i]=((buf[i*2*f->channels + 2*j]<<8) |
							      (buf[i*2*f->channels + 2*j + 1] & 0xff))/32768.0f;
				}
Michael Smith's avatar
   
Michael Smith committed
531
			}
Michael Smith's avatar
   
Michael Smith committed
532
		}
Jack Moffitt's avatar
Jack Moffitt committed
533
	}
Michael Smith's avatar
Michael Smith committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    else if(f->samplesize==24) 
    {
        if(!f->bigendian) {
            for(i = 0; i < realsamples; i++)
            {
                for(j=0; j < f->channels; j++) 
                {
                    buffer[j][i] = ((buf[i*3*f->channels + 3*j + 2] << 16) |
                      (((unsigned char *)buf)[i*3*f->channels + 3*j + 1] << 8) |
                      (((unsigned char *)buf)[i*3*f->channels + 3*j] & 0xff)) 
                        / 8388608.0f;

                }
            }
        }
        else {
            fprintf(stderr, _("Big endian 24 bit PCM data is not currently "
                              "supported, aborting.\n"));
            return 0;
        }
    }
    else {
        fprintf(stderr, _("Internal error: attempt to read unsupported "
                          "bitdepth %d\n"), f->samplesize);
        return 0;
    }
Jack Moffitt's avatar
Jack Moffitt committed
560

Michael Smith's avatar
   
Michael Smith committed
561
	return realsamples;
Jack Moffitt's avatar
Jack Moffitt committed
562
563
}

564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
long wav_ieee_read(void *in, float **buffer, int samples)
{
	wavfile *f = (wavfile *)in;
	float *buf = alloca(samples*4*f->channels); /* de-interleave buffer */
	long bytes_read = fread(buf,1,samples*4*f->channels, f->f);
	int i,j;
	long realsamples;


	if(f->totalsamples && f->samplesread +
			bytes_read/(4*f->channels) > f->totalsamples)
		bytes_read = 4*f->channels*(f->totalsamples - f->samplesread);
	realsamples = bytes_read/(4*f->channels);
	f->samplesread += realsamples;

	for(i=0; i < realsamples; i++)
		for(j=0; j < f->channels; j++)
			buffer[j][i] = buf[i*f->channels + j];

	return realsamples;
}


Jack Moffitt's avatar
Jack Moffitt committed
587
588
589
590
591
592
593
594
595
void wav_close(void *info)
{
	wavfile *f = (wavfile *)info;

	free(f);
}

int raw_open(FILE *in, oe_enc_opt *opt)
{
596
597
598
599
600
601
602
603
604
605
606
607
	wav_fmt format; /* fake wave header ;) */
	wavfile *wav = malloc(sizeof(wavfile));

	/* construct fake wav header ;) */
	format.format =      2; 
	format.channels =    opt->channels;
	format.samplerate =  opt->rate;
	format.samplesize =  opt->samplesize;
	format.bytespersec = opt->channels * opt->rate * opt->samplesize / 8;
	format.align =       format.bytespersec;
	wav->f =             in;
	wav->samplesread =   0;
Michael Smith's avatar
Michael Smith committed
608
	wav->bigendian =     opt->endianness;
609
610
	wav->channels =      format.channels;
	wav->samplesize =    opt->samplesize;
611
    wav->totalsamples =  0;
612
613
614

	opt->read_samples = wav_read;
	opt->readdata = (void *)wav;
Jack Moffitt's avatar
Jack Moffitt committed
615
616
617
	opt->total_samples_per_channel = 0; /* raw mode, don't bother */
	return 1;
}
618
619
620
621
622
623
624
625
626
627
628

typedef struct {
    res_state resampler;
    audio_read_func real_reader;
    void *real_readdata;
    float **bufs;
    int channels;
    int bufsize;
    int done;
} resampler;

629
static long read_resampled(void *d, float **buffer, int samples)
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
{
    resampler *rs = d;
    long in_samples;
    int out_samples;

    in_samples = res_push_max_input(&rs->resampler, samples);
    if(in_samples > rs->bufsize)
        in_samples = rs->bufsize;

    in_samples = rs->real_reader(rs->real_readdata, rs->bufs, in_samples);

    if(in_samples <= 0) {
        if(!rs->done) {
            rs->done = 1;
            out_samples = res_drain(&rs->resampler, buffer);
            return out_samples;
        }
        return 0;
    }

    out_samples = res_push(&rs->resampler, buffer, (float const **)rs->bufs, in_samples);

    if(out_samples <= 0) {
        fprintf(stderr, _("BUG: Got zero samples from resampler: your file will be truncated. Please report this.\n"));
    }

    return out_samples;
}

int setup_resample(oe_enc_opt *opt) {
    resampler *rs = calloc(1, sizeof(resampler));
    int c;

    rs->bufsize = 4096; /* Shrug */
    rs->real_reader = opt->read_samples;
    rs->real_readdata = opt->readdata;
    rs->bufs = malloc(sizeof(float *) * opt->channels);
    rs->channels = opt->channels;
    rs->done = 0;
    if(res_init(&rs->resampler, rs->channels, opt->resamplefreq, opt->rate, RES_END))
    {
        fprintf(stderr, _("Couldn't initialise resampler\n"));
        return -1;
    }

    for(c=0; c < opt->channels; c++)
        rs->bufs[c] = malloc(sizeof(float) * rs->bufsize);

    opt->read_samples = read_resampled;
    opt->readdata = rs;
    if(opt->total_samples_per_channel)
        opt->total_samples_per_channel = (int)((float)opt->total_samples_per_channel * 
            ((float)opt->resamplefreq/(float)opt->rate));
    opt->rate = opt->resamplefreq;

    return 0;
}

void clear_resample(oe_enc_opt *opt) {
    resampler *rs = opt->readdata;
    int i;

    opt->read_samples = rs->real_reader;
    opt->readdata = rs->real_readdata;
    res_clear(&rs->resampler);

    for(i = 0; i < rs->channels; i++)
        free(rs->bufs[i]);

    free(rs->bufs);

    free(rs);
}

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
typedef struct {
    audio_read_func real_reader;
    void *real_readdata;
    int channels;
    float scale_factor;
} scaler;

static long read_scaler(void *data, float **buffer, int samples) {
    scaler *d = data;
    long in_samples = d->real_reader(d->real_readdata, buffer, samples);
    int i,j;

    for(i=0; i < d->channels; i++) {
        for(j=0; j < in_samples; j++) {
            buffer[i][j] *= d->scale_factor;
        }
    }

    return in_samples;
}


void setup_scaler(oe_enc_opt *opt, float scale) {
    scaler *d = calloc(1, sizeof(scaler));

    d->real_reader = opt->read_samples;
    d->real_readdata = opt->readdata;

    opt->read_samples = read_scaler;
    opt->readdata = d;
    d->channels = opt->channels;
    d->scale_factor = scale;
}

void clear_scaler(oe_enc_opt *opt) {
    scaler *d = opt->readdata;

    opt->read_samples = d->real_reader;
    opt->readdata = d->real_readdata;

    free(d);
}

747
748
749
750
751
752
typedef struct {
    audio_read_func real_reader;
    void *real_readdata;
    float **bufs;
} downmix;

753
static long read_downmix(void *data, float **buffer, int samples)
754
755
756
757
758
759
{
    downmix *d = data;
    long in_samples = d->real_reader(d->real_readdata, d->bufs, samples);
    int i;

    for(i=0; i < in_samples; i++) {
760
        buffer[0][i] = (d->bufs[0][i] + d->bufs[1][i])*0.5f;
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
    }

    return in_samples;
}

void setup_downmix(oe_enc_opt *opt) {
    downmix *d = calloc(1, sizeof(downmix));

    if(opt->channels != 2) {
        fprintf(stderr, "Internal error! Please report this bug.\n");
        return;
    }
    
    d->bufs = malloc(2 * sizeof(float *));
    d->bufs[0] = malloc(4096 * sizeof(float));
    d->bufs[1] = malloc(4096 * sizeof(float));
    d->real_reader = opt->read_samples;

    d->real_readdata = opt->readdata;

    opt->read_samples = read_downmix;
    opt->readdata = d;

    opt->channels = 1;
}
void clear_downmix(oe_enc_opt *opt) {
    downmix *d = opt->readdata;

    opt->read_samples = d->real_reader;
    opt->readdata = d->real_readdata;
    opt->channels = 2; /* other things in cleanup rely on this */

    free(d->bufs[0]);
    free(d->bufs[1]);
    free(d->bufs);
    free(d);
}