Fix memleak in raw mode
[xiph/unicode.git] / vorbis-tools / oggenc / audio.c
blob0c11667ab9f2efbae0228ee867fc585a0a14d3e7
1 /* OggEnc
2 **
3 ** This program is distributed under the GNU General Public License, version 2.
4 ** A copy of this license is included with this source.
5 **
6 ** Copyright 2000-2002, Michael Smith <msmith@xiph.org>
7 **
8 ** AIFF/AIFC support from OggSquish, (c) 1994-1996 Monty <xiphmont@xiph.org>
9 **/
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <math.h>
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
22 #include "audio.h"
23 #include "platform.h"
24 #include "i18n.h"
25 #include "resample.h"
27 #ifdef HAVE_LIBFLAC
28 #include "flac.h"
29 #endif
31 #define WAV_HEADER_SIZE 44
33 /* Macros to read header data */
34 #define READ_U32_LE(buf) \
35 (((buf)[3]<<24)|((buf)[2]<<16)|((buf)[1]<<8)|((buf)[0]&0xff))
37 #define READ_U16_LE(buf) \
38 (((buf)[1]<<8)|((buf)[0]&0xff))
40 #define READ_U32_BE(buf) \
41 (((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|((buf)[3]&0xff))
43 #define READ_U16_BE(buf) \
44 (((buf)[0]<<8)|((buf)[1]&0xff))
46 /* Define the supported formats here */
47 input_format formats[] = {
48 {wav_id, 12, wav_open, wav_close, "wav", N_("WAV file reader")},
49 {aiff_id, 12, aiff_open, wav_close, "aiff", N_("AIFF/AIFC file reader")},
50 #ifdef HAVE_LIBFLAC
51 {flac_id, 4, flac_open, flac_close, "flac", N_("FLAC file reader")},
52 {oggflac_id, 32, flac_open, flac_close, "ogg", N_("Ogg FLAC file reader")},
53 #endif
54 {NULL, 0, NULL, NULL, NULL, NULL}
57 input_format *open_audio_file(FILE *in, oe_enc_opt *opt)
59 int j=0;
60 unsigned char *buf=NULL;
61 int buf_size=0, buf_filled=0;
62 int size,ret;
64 while(formats[j].id_func)
66 size = formats[j].id_data_len;
67 if(size >= buf_size)
69 buf = realloc(buf, size);
70 buf_size = size;
73 if(size > buf_filled)
75 ret = fread(buf+buf_filled, 1, buf_size-buf_filled, in);
76 buf_filled += ret;
78 if(buf_filled < size)
79 { /* File truncated */
80 j++;
81 continue;
85 if(formats[j].id_func(buf, buf_filled))
87 /* ok, we now have something that can handle the file */
88 if(formats[j].open_func(in, opt, buf, buf_filled)) {
89 free(buf);
90 return &formats[j];
93 j++;
96 free(buf);
98 return NULL;
101 static int seek_forward(FILE *in, int length)
103 if(fseek(in, length, SEEK_CUR))
105 /* Failed. Do it the hard way. */
106 unsigned char buf[1024];
107 int seek_needed = length, seeked;
108 while(seek_needed > 0)
110 seeked = fread(buf, 1, seek_needed>1024?1024:seek_needed, in);
111 if(!seeked)
112 return 0; /* Couldn't read more, can't read file */
113 else
114 seek_needed -= seeked;
117 return 1;
121 static int find_wav_chunk(FILE *in, char *type, unsigned int *len)
123 unsigned char buf[8];
125 while(1)
127 if(fread(buf,1,8,in) < 8) /* Suck down a chunk specifier */
129 fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
130 return 0; /* EOF before reaching the appropriate chunk */
133 if(memcmp(buf, type, 4))
135 *len = READ_U32_LE(buf+4);
136 if(!seek_forward(in, *len))
137 return 0;
139 buf[4] = 0;
140 fprintf(stderr, _("Skipping chunk of type \"%s\", length %d\n"), buf, *len);
142 else
144 *len = READ_U32_LE(buf+4);
145 return 1;
150 static int find_aiff_chunk(FILE *in, char *type, unsigned int *len)
152 unsigned char buf[8];
154 while(1)
156 if(fread(buf,1,8,in) <8)
158 fprintf(stderr, _("Warning: Unexpected EOF in AIFF chunk\n"));
159 return 0;
162 *len = READ_U32_BE(buf+4);
164 if(memcmp(buf,type,4))
166 if((*len) & 0x1)
167 (*len)++;
169 if(!seek_forward(in, *len))
170 return 0;
172 else
173 return 1;
179 double read_IEEE80(unsigned char *buf)
181 int s=buf[0]&0xff;
182 int e=((buf[0]&0x7f)<<8)|(buf[1]&0xff);
183 double f=((unsigned long)(buf[2]&0xff)<<24)|
184 ((buf[3]&0xff)<<16)|
185 ((buf[4]&0xff)<<8) |
186 (buf[5]&0xff);
188 if(e==32767)
190 if(buf[2]&0x80)
191 return HUGE_VAL; /* Really NaN, but this won't happen in reality */
192 else
194 if(s)
195 return -HUGE_VAL;
196 else
197 return HUGE_VAL;
201 f=ldexp(f,32);
202 f+= ((buf[6]&0xff)<<24)|
203 ((buf[7]&0xff)<<16)|
204 ((buf[8]&0xff)<<8) |
205 (buf[9]&0xff);
207 return ldexp(f, e-16446);
210 /* AIFF/AIFC support adapted from the old OggSQUISH application */
211 int aiff_id(unsigned char *buf, int len)
213 if(len<12) return 0; /* Truncated file, probably */
215 if(memcmp(buf, "FORM", 4))
216 return 0;
218 if(memcmp(buf+8, "AIF",3))
219 return 0;
221 if(buf[11]!='C' && buf[11]!='F')
222 return 0;
224 return 1;
227 int aiff_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen)
229 int aifc; /* AIFC or AIFF? */
230 unsigned int len;
231 unsigned char *buffer;
232 unsigned char buf2[8];
233 aiff_fmt format;
234 aifffile *aiff = malloc(sizeof(aifffile));
236 if(buf[11]=='C')
237 aifc=1;
238 else
239 aifc=0;
241 if(!find_aiff_chunk(in, "COMM", &len))
243 fprintf(stderr, _("Warning: No common chunk found in AIFF file\n"));
244 return 0; /* EOF before COMM chunk */
247 if(len < 18)
249 fprintf(stderr, _("Warning: Truncated common chunk in AIFF header\n"));
250 return 0; /* Weird common chunk */
253 buffer = alloca(len);
255 if(fread(buffer,1,len,in) < len)
257 fprintf(stderr, _("Warning: Unexpected EOF in reading AIFF header\n"));
258 return 0;
261 format.channels = READ_U16_BE(buffer);
262 format.totalframes = READ_U32_BE(buffer+2);
263 format.samplesize = READ_U16_BE(buffer+6);
264 format.rate = (int)read_IEEE80(buffer+8);
266 aiff->bigendian = 1;
268 if(aifc)
270 if(len < 22)
272 fprintf(stderr, _("Warning: AIFF-C header truncated.\n"));
273 return 0;
276 if(!memcmp(buffer+18, "NONE", 4))
278 aiff->bigendian = 1;
280 else if(!memcmp(buffer+18, "sowt", 4))
282 aiff->bigendian = 0;
284 else
286 fprintf(stderr, _("Warning: Can't handle compressed AIFF-C (%c%c%c%c)\n"), *(buffer+18), *(buffer+19), *(buffer+20), *(buffer+21));
287 return 0; /* Compressed. Can't handle */
291 if(!find_aiff_chunk(in, "SSND", &len))
293 fprintf(stderr, _("Warning: No SSND chunk found in AIFF file\n"));
294 return 0; /* No SSND chunk -> no actual audio */
297 if(len < 8)
299 fprintf(stderr, _("Warning: Corrupted SSND chunk in AIFF header\n"));
300 return 0;
303 if(fread(buf2,1,8, in) < 8)
305 fprintf(stderr, _("Warning: Unexpected EOF reading AIFF header\n"));
306 return 0;
309 format.offset = READ_U32_BE(buf2);
310 format.blocksize = READ_U32_BE(buf2+4);
312 if( format.blocksize == 0 &&
313 (format.samplesize == 16 || format.samplesize == 8))
315 /* From here on, this is very similar to the wav code. Oh well. */
317 opt->rate = format.rate;
318 opt->channels = format.channels;
319 opt->read_samples = wav_read; /* Similar enough, so we use the same */
320 opt->total_samples_per_channel = format.totalframes;
322 aiff->f = in;
323 aiff->samplesread = 0;
324 aiff->channels = format.channels;
325 aiff->samplesize = format.samplesize;
326 aiff->totalsamples = format.totalframes;
328 opt->readdata = (void *)aiff;
330 seek_forward(in, format.offset); /* Swallow some data */
331 return 1;
333 else
335 fprintf(stderr,
336 _("Warning: OggEnc does not support this type of AIFF/AIFC file\n"
337 " Must be 8 or 16 bit PCM.\n"));
338 return 0;
343 int wav_id(unsigned char *buf, int len)
345 unsigned int flen;
347 if(len<12) return 0; /* Something screwed up */
349 if(memcmp(buf, "RIFF", 4))
350 return 0; /* Not wave */
352 flen = READ_U32_LE(buf+4); /* We don't use this */
354 if(memcmp(buf+8, "WAVE",4))
355 return 0; /* RIFF, but not wave */
357 return 1;
360 int wav_open(FILE *in, oe_enc_opt *opt, unsigned char *oldbuf, int buflen)
362 unsigned char buf[16];
363 unsigned int len;
364 int samplesize;
365 wav_fmt format;
366 wavfile *wav = malloc(sizeof(wavfile));
368 /* Ok. At this point, we know we have a WAV file. Now we have to detect
369 * whether we support the subtype, and we have to find the actual data
370 * We don't (for the wav reader) need to use the buffer we used to id this
371 * as a wav file (oldbuf)
374 if(!find_wav_chunk(in, "fmt ", &len))
375 return 0; /* EOF */
377 if(len < 16)
379 fprintf(stderr, _("Warning: Unrecognised format chunk in WAV header\n"));
380 return 0; /* Weird format chunk */
383 /* A common error is to have a format chunk that is not 16 or 18 bytes
384 * in size. This is incorrect, but not fatal, so we only warn about
385 * it instead of refusing to work with the file. Please, if you
386 * have a program that's creating format chunks of sizes other than
387 * 16 or 18 bytes in size, report a bug to the author.
389 if(len!=16 && len!=18)
390 fprintf(stderr,
391 _("Warning: INVALID format chunk in wav header.\n"
392 " Trying to read anyway (may not work)...\n"));
394 if(fread(buf,1,16,in) < 16)
396 fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
397 return 0;
400 /* Deal with stupid broken apps. Don't use these programs.
402 if(len - 16 > 0 && !seek_forward(in, len-16))
403 return 0;
405 format.format = READ_U16_LE(buf);
406 format.channels = READ_U16_LE(buf+2);
407 format.samplerate = READ_U32_LE(buf+4);
408 format.bytespersec = READ_U32_LE(buf+8);
409 format.align = READ_U16_LE(buf+12);
410 format.samplesize = READ_U16_LE(buf+14);
412 if(!find_wav_chunk(in, "data", &len))
413 return 0; /* EOF */
415 if(format.format == 1)
417 samplesize = format.samplesize/8;
418 opt->read_samples = wav_read;
420 else if(format.format == 3)
422 samplesize = 4;
423 opt->read_samples = wav_ieee_read;
425 else
427 fprintf(stderr,
428 _("ERROR: Wav file is unsupported type (must be standard PCM\n"
429 " or type 3 floating point PCM\n"));
430 return 0;
435 if( format.align == format.channels*samplesize &&
436 format.samplesize == samplesize*8 &&
437 (format.samplesize == 24 || format.samplesize == 16 ||
438 format.samplesize == 8 ||
439 (format.samplesize == 32 && format.format == 3)))
441 /* OK, good - we have the one supported format,
442 now we want to find the size of the file */
443 opt->rate = format.samplerate;
444 opt->channels = format.channels;
446 wav->f = in;
447 wav->samplesread = 0;
448 wav->bigendian = 0;
449 wav->channels = format.channels; /* This is in several places. The price
450 of trying to abstract stuff. */
451 wav->samplesize = format.samplesize;
453 if(len)
455 opt->total_samples_per_channel = len/(format.channels*samplesize);
457 else
459 long pos;
460 pos = ftell(in);
461 if(fseek(in, 0, SEEK_END) == -1)
463 opt->total_samples_per_channel = 0; /* Give up */
465 else
467 opt->total_samples_per_channel = (ftell(in) - pos)/
468 (format.channels*samplesize);
469 fseek(in,pos, SEEK_SET);
472 wav->totalsamples = opt->total_samples_per_channel;
474 opt->readdata = (void *)wav;
475 return 1;
477 else
479 fprintf(stderr,
480 _("ERROR: Wav file is unsupported subformat (must be 8,16, or 24 bit PCM\n"
481 "or floating point PCM\n"));
482 return 0;
486 long wav_read(void *in, float **buffer, int samples)
488 wavfile *f = (wavfile *)in;
489 int sampbyte = f->samplesize / 8;
490 signed char *buf = alloca(samples*sampbyte*f->channels);
491 long bytes_read = fread(buf, 1, samples*sampbyte*f->channels, f->f);
492 int i,j;
493 long realsamples;
495 if(f->totalsamples && f->samplesread +
496 bytes_read/(sampbyte*f->channels) > f->totalsamples) {
497 bytes_read = sampbyte*f->channels*(f->totalsamples - f->samplesread);
500 realsamples = bytes_read/(sampbyte*f->channels);
501 f->samplesread += realsamples;
503 if(f->samplesize==8)
505 unsigned char *bufu = (unsigned char *)buf;
506 for(i = 0; i < realsamples; i++)
508 for(j=0; j < f->channels; j++)
510 buffer[j][i]=((int)(bufu[i*f->channels + j])-128)/128.0f;
514 else if(f->samplesize==16)
516 if(!f->bigendian)
518 for(i = 0; i < realsamples; i++)
520 for(j=0; j < f->channels; j++)
522 buffer[j][i] = ((buf[i*2*f->channels + 2*j + 1]<<8) |
523 (buf[i*2*f->channels + 2*j] & 0xff))/32768.0f;
527 else
529 for(i = 0; i < realsamples; i++)
531 for(j=0; j < f->channels; j++)
533 buffer[j][i]=((buf[i*2*f->channels + 2*j]<<8) |
534 (buf[i*2*f->channels + 2*j + 1] & 0xff))/32768.0f;
539 else if(f->samplesize==24)
541 if(!f->bigendian) {
542 for(i = 0; i < realsamples; i++)
544 for(j=0; j < f->channels; j++)
546 buffer[j][i] = ((buf[i*3*f->channels + 3*j + 2] << 16) |
547 (((unsigned char *)buf)[i*3*f->channels + 3*j + 1] << 8) |
548 (((unsigned char *)buf)[i*3*f->channels + 3*j] & 0xff))
549 / 8388608.0f;
554 else {
555 fprintf(stderr, _("Big endian 24 bit PCM data is not currently "
556 "supported, aborting.\n"));
557 return 0;
560 else {
561 fprintf(stderr, _("Internal error: attempt to read unsupported "
562 "bitdepth %d\n"), f->samplesize);
563 return 0;
566 return realsamples;
569 long wav_ieee_read(void *in, float **buffer, int samples)
571 wavfile *f = (wavfile *)in;
572 float *buf = alloca(samples*4*f->channels); /* de-interleave buffer */
573 long bytes_read = fread(buf,1,samples*4*f->channels, f->f);
574 int i,j;
575 long realsamples;
578 if(f->totalsamples && f->samplesread +
579 bytes_read/(4*f->channels) > f->totalsamples)
580 bytes_read = 4*f->channels*(f->totalsamples - f->samplesread);
581 realsamples = bytes_read/(4*f->channels);
582 f->samplesread += realsamples;
584 for(i=0; i < realsamples; i++)
585 for(j=0; j < f->channels; j++)
586 buffer[j][i] = buf[i*f->channels + j];
588 return realsamples;
592 void wav_close(void *info)
594 wavfile *f = (wavfile *)info;
596 free(f);
599 int raw_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen)
601 wav_fmt format; /* fake wave header ;) */
602 wavfile *wav = malloc(sizeof(wavfile));
604 /* construct fake wav header ;) */
605 format.format = 2;
606 format.channels = opt->channels;
607 format.samplerate = opt->rate;
608 format.samplesize = opt->samplesize;
609 format.bytespersec = opt->channels * opt->rate * opt->samplesize / 8;
610 format.align = format.bytespersec;
611 wav->f = in;
612 wav->samplesread = 0;
613 wav->bigendian = opt->endianness;
614 wav->channels = format.channels;
615 wav->samplesize = opt->samplesize;
616 wav->totalsamples = 0;
618 opt->read_samples = wav_read;
619 opt->readdata = (void *)wav;
620 opt->total_samples_per_channel = 0; /* raw mode, don't bother */
621 return 1;
624 typedef struct {
625 res_state resampler;
626 audio_read_func real_reader;
627 void *real_readdata;
628 float **bufs;
629 int channels;
630 int bufsize;
631 int done;
632 } resampler;
634 static long read_resampled(void *d, float **buffer, int samples)
636 resampler *rs = d;
637 long in_samples;
638 int out_samples;
640 in_samples = res_push_max_input(&rs->resampler, samples);
641 if(in_samples > rs->bufsize)
642 in_samples = rs->bufsize;
644 in_samples = rs->real_reader(rs->real_readdata, rs->bufs, in_samples);
646 if(in_samples <= 0) {
647 if(!rs->done) {
648 rs->done = 1;
649 out_samples = res_drain(&rs->resampler, buffer);
650 return out_samples;
652 return 0;
655 out_samples = res_push(&rs->resampler, buffer, (float const **)rs->bufs, in_samples);
657 if(out_samples <= 0) {
658 fprintf(stderr, _("BUG: Got zero samples from resampler: your file will be truncated. Please report this.\n"));
661 return out_samples;
664 int setup_resample(oe_enc_opt *opt) {
665 resampler *rs = calloc(1, sizeof(resampler));
666 int c;
668 rs->bufsize = 4096; /* Shrug */
669 rs->real_reader = opt->read_samples;
670 rs->real_readdata = opt->readdata;
671 rs->bufs = malloc(sizeof(float *) * opt->channels);
672 rs->channels = opt->channels;
673 rs->done = 0;
674 if(res_init(&rs->resampler, rs->channels, opt->resamplefreq, opt->rate, RES_END))
676 fprintf(stderr, _("Couldn't initialise resampler\n"));
677 return -1;
680 for(c=0; c < opt->channels; c++)
681 rs->bufs[c] = malloc(sizeof(float) * rs->bufsize);
683 opt->read_samples = read_resampled;
684 opt->readdata = rs;
685 if(opt->total_samples_per_channel)
686 opt->total_samples_per_channel = (int)((float)opt->total_samples_per_channel *
687 ((float)opt->resamplefreq/(float)opt->rate));
688 opt->rate = opt->resamplefreq;
690 return 0;
693 void clear_resample(oe_enc_opt *opt) {
694 resampler *rs = opt->readdata;
695 int i;
697 opt->read_samples = rs->real_reader;
698 opt->readdata = rs->real_readdata;
699 res_clear(&rs->resampler);
701 for(i = 0; i < rs->channels; i++)
702 free(rs->bufs[i]);
704 free(rs->bufs);
706 free(rs);
709 typedef struct {
710 audio_read_func real_reader;
711 void *real_readdata;
712 int channels;
713 float scale_factor;
714 } scaler;
716 static long read_scaler(void *data, float **buffer, int samples) {
717 scaler *d = data;
718 long in_samples = d->real_reader(d->real_readdata, buffer, samples);
719 int i,j;
721 for(i=0; i < d->channels; i++) {
722 for(j=0; j < in_samples; j++) {
723 buffer[i][j] *= d->scale_factor;
727 return in_samples;
731 void setup_scaler(oe_enc_opt *opt, float scale) {
732 scaler *d = calloc(1, sizeof(scaler));
734 d->real_reader = opt->read_samples;
735 d->real_readdata = opt->readdata;
737 opt->read_samples = read_scaler;
738 opt->readdata = d;
739 d->channels = opt->channels;
740 d->scale_factor = scale;
743 void clear_scaler(oe_enc_opt *opt) {
744 scaler *d = opt->readdata;
746 opt->read_samples = d->real_reader;
747 opt->readdata = d->real_readdata;
749 free(d);
752 typedef struct {
753 audio_read_func real_reader;
754 void *real_readdata;
755 float **bufs;
756 } downmix;
758 static long read_downmix(void *data, float **buffer, int samples)
760 downmix *d = data;
761 long in_samples = d->real_reader(d->real_readdata, d->bufs, samples);
762 int i;
764 for(i=0; i < in_samples; i++) {
765 buffer[0][i] = (d->bufs[0][i] + d->bufs[1][i])*0.5f;
766 fprintf(stderr, "%f %f -> %f\n", d->bufs[0][i] , d->bufs[1][i], buffer[0][i]);
769 return in_samples;
772 void setup_downmix(oe_enc_opt *opt) {
773 downmix *d = calloc(1, sizeof(downmix));
775 if(opt->channels != 2) {
776 fprintf(stderr, "Internal error! Please report this bug.\n");
777 return;
780 d->bufs = malloc(2 * sizeof(float *));
781 d->bufs[0] = malloc(4096 * sizeof(float));
782 d->bufs[1] = malloc(4096 * sizeof(float));
783 d->real_reader = opt->read_samples;
785 d->real_readdata = opt->readdata;
787 opt->read_samples = read_downmix;
788 opt->readdata = d;
790 opt->channels = 1;
792 void clear_downmix(oe_enc_opt *opt) {
793 downmix *d = opt->readdata;
795 opt->read_samples = d->real_reader;
796 opt->readdata = d->real_readdata;
797 opt->channels = 2; /* other things in cleanup rely on this */
799 free(d->bufs[0]);
800 free(d->bufs[1]);
801 free(d->bufs);
802 free(d);