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  **           2010, Monty <monty@xiph.org>
8  **
9  ** AIFF/AIFC support from OggSquish, (c) 1994-1996 Monty <xiphmont@xiph.org>
10  **/
11 
12 #ifdef HAVE_CONFIG_H
13 #include <config.h>
14 #endif
15 
16 #include <limits.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <sys/types.h>
21 #include <math.h>
22 
23 #include "audio.h"
24 #include "platform.h"
25 #include "i18n.h"
26 #include "resample.h"
27 
28 #ifdef HAVE_LIBFLAC
29 #include "flac.h"
30 #endif
31 
32 /* Macros to read header data */
33 #define READ_U32_LE(buf) \
34     (((buf)[3]<<24)|((buf)[2]<<16)|((buf)[1]<<8)|((buf)[0]&0xff))
35 
36 #define READ_U16_LE(buf) \
37     (((buf)[1]<<8)|((buf)[0]&0xff))
38 
39 #define READ_U32_BE(buf) \
40     (((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|((buf)[3]&0xff))
41 
42 #define READ_U16_BE(buf) \
43     (((buf)[0]<<8)|((buf)[1]&0xff))
44 
45 /* Define the supported formats here */
46 input_format formats[] = {
47     {wav_id, 12, wav_open, wav_close, "wav", N_("WAV file reader")},
48     {aiff_id, 12, aiff_open, wav_close, "aiff", N_("AIFF/AIFC file reader")},
49 #ifdef HAVE_LIBFLAC
50     {flac_id,     4, flac_open, flac_close, "flac", N_("FLAC file reader")},
51     {oggflac_id, 32, flac_open, flac_close, "ogg", N_("Ogg FLAC file reader")},
52 #endif
53     {NULL, 0, NULL, NULL, NULL, NULL}
54 };
55 
open_audio_file(FILE * in,oe_enc_opt * opt)56 input_format *open_audio_file(FILE *in, oe_enc_opt *opt)
57 {
58     int j=0;
59     unsigned char *buf=NULL;
60     int buf_size=0, buf_filled=0;
61     int size,ret;
62 
63     while(formats[j].id_func)
64     {
65         size = formats[j].id_data_len;
66         if(size >= buf_size)
67         {
68             buf = realloc(buf, size);
69             buf_size = size;
70         }
71 
72         if(size > buf_filled)
73         {
74             ret = fread(buf+buf_filled, 1, buf_size-buf_filled, in);
75             buf_filled += ret;
76 
77             if(buf_filled < size)
78             { /* File truncated */
79                 j++;
80                 continue;
81             }
82         }
83 
84         if(formats[j].id_func(buf, buf_filled))
85         {
86             /* ok, we now have something that can handle the file */
87             if(formats[j].open_func(in, opt, buf, buf_filled)) {
88                 free(buf);
89                 return &formats[j];
90             }
91         }
92         j++;
93     }
94 
95     free(buf);
96 
97     return NULL;
98 }
99 
seek_forward(FILE * in,unsigned int length)100 static int seek_forward(FILE *in, unsigned int length)
101 {
102     if(fseek(in, length, SEEK_CUR))
103     {
104         /* Failed. Do it the hard way. */
105         unsigned char buf[1024];
106         unsigned int seek_needed = length;
107         int seeked;
108         while(seek_needed > 0)
109         {
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;
115         }
116     }
117     return 1;
118 }
119 
120 
find_wav_chunk(FILE * in,char * type,unsigned int * len)121 static int find_wav_chunk(FILE *in, char *type, unsigned int *len)
122 {
123     unsigned char buf[8];
124 
125     while(1)
126     {
127         if(fread(buf,1,8,in) < 8) /* Suck down a chunk specifier */
128         {
129             fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
130             return 0; /* EOF before reaching the appropriate chunk */
131         }
132 
133         if(memcmp(buf, type, 4))
134         {
135             *len = READ_U32_LE(buf+4);
136             if(!seek_forward(in, *len))
137                 return 0;
138 
139             buf[4] = 0;
140             fprintf(stderr, _("Skipping chunk of type \"%s\", length %d\n"), buf, *len);
141         }
142         else
143         {
144             *len = READ_U32_LE(buf+4);
145             return 1;
146         }
147     }
148 }
149 
find_aiff_chunk(FILE * in,char * type,unsigned int * len)150 static int find_aiff_chunk(FILE *in, char *type, unsigned int *len)
151 {
152     unsigned char buf[8];
153     int restarted = 0;
154 
155     while(1)
156     {
157         if(fread(buf,1,8,in) <8)
158         {
159             if(!restarted) {
160                 /* Handle out of order chunks by seeking back to the start
161                  * to retry */
162                 restarted = 1;
163                 fseek(in, 12, SEEK_SET);
164                 continue;
165             }
166             fprintf(stderr, _("Warning: Unexpected EOF in AIFF chunk\n"));
167             return 0;
168         }
169 
170         *len = READ_U32_BE(buf+4);
171 
172         if(memcmp(buf,type,4))
173         {
174             if((*len) & 0x1)
175                 (*len)++;
176 
177             if(!seek_forward(in, *len))
178                 return 0;
179         }
180         else
181             return 1;
182     }
183 }
184 
185 
186 
read_IEEE80(unsigned char * buf)187 double read_IEEE80(unsigned char *buf)
188 {
189     int s=buf[0]&0xff;
190     int e=((buf[0]&0x7f)<<8)|(buf[1]&0xff);
191     double f=((unsigned long)(buf[2]&0xff)<<24)|
192         ((buf[3]&0xff)<<16)|
193         ((buf[4]&0xff)<<8) |
194          (buf[5]&0xff);
195 
196     if(e==32767)
197     {
198         if(buf[2]&0x80)
199             return HUGE_VAL; /* Really NaN, but this won't happen in reality */
200         else
201         {
202             if(s)
203                 return -HUGE_VAL;
204             else
205                 return HUGE_VAL;
206         }
207     }
208 
209     f=ldexp(f,32);
210     f+= ((buf[6]&0xff)<<24)|
211         ((buf[7]&0xff)<<16)|
212         ((buf[8]&0xff)<<8) |
213          (buf[9]&0xff);
214 
215     return ldexp(f, e-16446);
216 }
217 
218 /* AIFF/AIFC support adapted from the old OggSQUISH application */
aiff_id(unsigned char * buf,int len)219 int aiff_id(unsigned char *buf, int len)
220 {
221     if(len<12) return 0; /* Truncated file, probably */
222 
223     if(memcmp(buf, "FORM", 4))
224         return 0;
225 
226     if(memcmp(buf+8, "AIF",3))
227         return 0;
228 
229     if(buf[11]!='C' && buf[11]!='F')
230         return 0;
231 
232     return 1;
233 }
234 
235 static int aiff_permute_matrix[6][6] =
236 {
237   {0},              /* 1.0 mono   */
238   {0,1},            /* 2.0 stereo */
239   {0,2,1},          /* 3.0 channel ('wide') stereo */
240   {0,1,2,3},        /* 4.0 discrete quadraphonic (WARN) */
241   {0,2,1,3,4},      /* 5.0 surround (WARN) */
242   {0,1,2,3,4,5},    /* 5.1 surround (WARN)*/
243 };
244 
245 
aiff_open(FILE * in,oe_enc_opt * opt,unsigned char * buf,int buflen)246 int aiff_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen)
247 {
248     int aifc; /* AIFC or AIFF? */
249     unsigned int len, readlen;
250     unsigned char buffer[22];
251     unsigned char buf2[8];
252     aiff_fmt format;
253     aifffile *aiff = malloc(sizeof(aifffile));
254     int i;
255     long channels;
256 
257     if(buf[11]=='C')
258         aifc=1;
259     else
260         aifc=0;
261 
262     if(!find_aiff_chunk(in, "COMM", &len))
263     {
264         fprintf(stderr, _("Warning: No common chunk found in AIFF file\n"));
265         return 0; /* EOF before COMM chunk */
266     }
267 
268     if(len < 18)
269     {
270         fprintf(stderr, _("Warning: Truncated common chunk in AIFF header\n"));
271         return 0; /* Weird common chunk */
272     }
273 
274     readlen = len < sizeof(buffer) ? len : sizeof(buffer);
275     if(fread(buffer,1,readlen,in) < readlen ||
276        (len > readlen && !seek_forward(in, len-readlen)))
277     {
278         fprintf(stderr, _("Warning: Unexpected EOF in reading AIFF header\n"));
279         return 0;
280     }
281 
282     format.channels = channels = READ_U16_BE(buffer);
283     format.totalframes = READ_U32_BE(buffer+2);
284     format.samplesize = READ_U16_BE(buffer+6);
285     format.rate = (int)read_IEEE80(buffer+8);
286 
287     if(channels <= 0L || SHRT_MAX < channels)
288     {
289         fprintf(stderr, _("Warning: Unsupported count of channels in AIFF header\n"));
290         return 0;
291     }
292     aiff->bigendian = 1;
293 
294     if(aifc)
295     {
296         if(len < 22)
297         {
298             fprintf(stderr, _("Warning: AIFF-C header truncated.\n"));
299             return 0;
300         }
301 
302         if(!memcmp(buffer+18, "NONE", 4))
303         {
304             aiff->bigendian = 1;
305         }
306         else if(!memcmp(buffer+18, "sowt", 4))
307         {
308             aiff->bigendian = 0;
309         }
310         else
311         {
312             fprintf(stderr, _("Warning: Can't handle compressed AIFF-C (%c%c%c%c)\n"), *(buffer+18), *(buffer+19), *(buffer+20), *(buffer+21));
313             return 0; /* Compressed. Can't handle */
314         }
315     }
316 
317     if(!find_aiff_chunk(in, "SSND", &len))
318     {
319         fprintf(stderr, _("Warning: No SSND chunk found in AIFF file\n"));
320         return 0; /* No SSND chunk -> no actual audio */
321     }
322 
323     if(len < 8)
324     {
325         fprintf(stderr, _("Warning: Corrupted SSND chunk in AIFF header\n"));
326         return 0;
327     }
328 
329     if(fread(buf2,1,8, in) < 8)
330     {
331         fprintf(stderr, _("Warning: Unexpected EOF reading AIFF header\n"));
332         return 0;
333     }
334 
335     format.offset = READ_U32_BE(buf2);
336     format.blocksize = READ_U32_BE(buf2+4);
337 
338     if( format.blocksize == 0 &&
339         (format.samplesize == 16 || format.samplesize == 8))
340     {
341         /* From here on, this is very similar to the wav code. Oh well. */
342         if(opt->ignorelength)
343         {
344             format.totalframes = -1;
345         }
346 
347         opt->rate = format.rate;
348         opt->channels = format.channels;
349         opt->read_samples = wav_read; /* Similar enough, so we use the same */
350         opt->total_samples_per_channel = format.totalframes;
351 
352         aiff->f = in;
353         aiff->samplesread = 0;
354         aiff->channels = format.channels;
355         aiff->samplesize = format.samplesize;
356         aiff->totalsamples = format.totalframes;
357 
358         if(aiff->channels>3)
359           fprintf(stderr,"WARNING: AIFF[-C] files with greater than three channels use\n"
360                   "speaker locations incompatible with Vorbis suppound definitions.\n"
361                   "Not performaing channel location mapping.\n");
362 
363         opt->readdata = (void *)aiff;
364 
365         aiff->channel_permute = malloc(aiff->channels * sizeof(int));
366         if (aiff->channels <= 6)
367             /* Where we know the mappings, use them. */
368             memcpy(aiff->channel_permute, aiff_permute_matrix[aiff->channels-1],
369                     sizeof(int) * aiff->channels);
370         else
371             /* Use a default 1-1 mapping */
372             for (i=0; i < aiff->channels; i++)
373                 aiff->channel_permute[i] = i;
374 
375         seek_forward(in, format.offset); /* Swallow some data */
376         return 1;
377     }
378     else
379     {
380         fprintf(stderr,
381                 _("Warning: OggEnc does not support this type of AIFF/AIFC file\n"
382                 " Must be 8 or 16 bit PCM.\n"));
383         return 0;
384     }
385 }
386 
387 
wav_id(unsigned char * buf,int len)388 int wav_id(unsigned char *buf, int len)
389 {
390     unsigned int flen;
391 
392     if(len<12) return 0; /* Something screwed up */
393 
394     if(memcmp(buf, "RIFF", 4))
395         return 0; /* Not wave */
396 
397     flen = READ_U32_LE(buf+4); /* We don't use this */
398 
399     if(memcmp(buf+8, "WAVE",4))
400         return 0; /* RIFF, but not wave */
401 
402     return 1;
403 }
404 
405 static int wav_permute_matrix[8][8] =
406 {
407   {0},              /* 1.0 mono   */
408   {0,1},            /* 2.0 stereo */
409   {0,2,1},          /* 3.0 channel ('wide') stereo */
410   {0,1,2,3},        /* 4.0 discrete quadraphonic */
411   {0,2,1,3,4},      /* 5.0 surround */
412   {0,2,1,4,5,3},    /* 5.1 surround */
413   {0,2,1,5,6,4,3},  /* 6.1 surround */
414   {0,2,1,6,7,4,5,3} /* 7.1 surround (classic theater 8-track) */
415 };
416 
417 
wav_open(FILE * in,oe_enc_opt * opt,unsigned char * oldbuf,int buflen)418 int wav_open(FILE *in, oe_enc_opt *opt, unsigned char *oldbuf, int buflen)
419 {
420     unsigned char buf[40];
421     unsigned int len;
422     int samplesize;
423     wav_fmt format;
424     wavfile *wav = malloc(sizeof(wavfile));
425     int i;
426     long channels;
427 
428     /* Ok. At this point, we know we have a WAV file. Now we have to detect
429      * whether we support the subtype, and we have to find the actual data
430      * We don't (for the wav reader) need to use the buffer we used to id this
431      * as a wav file (oldbuf)
432      */
433 
434     if(!find_wav_chunk(in, "fmt ", &len))
435         return 0; /* EOF */
436 
437     if(len < 16)
438     {
439         fprintf(stderr, _("Warning: Unrecognised format chunk in WAV header\n"));
440         return 0; /* Weird format chunk */
441     }
442 
443     /* A common error is to have a format chunk that is not 16, 18 or
444      * 40 bytes in size.  This is incorrect, but not fatal, so we only
445      * warn about it instead of refusing to work with the file.
446      * Please, if you have a program that's creating format chunks of
447      * sizes other than 16 or 18 bytes in size, report a bug to the
448      * author.
449      */
450     if(len!=16 && len!=18 && len!=40)
451         fprintf(stderr,
452                 _("Warning: INVALID format chunk in wav header.\n"
453                 " Trying to read anyway (may not work)...\n"));
454 
455     if(len>40)len=40;
456 
457     if(fread(buf,1,len,in) < len)
458     {
459         fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n"));
460         return 0;
461     }
462 
463     format.format =      READ_U16_LE(buf);
464     format.channels = channels = READ_U16_LE(buf+2);
465     format.samplerate =  READ_U32_LE(buf+4);
466     format.bytespersec = READ_U32_LE(buf+8);
467     format.align =       READ_U16_LE(buf+12);
468     format.samplesize =  READ_U16_LE(buf+14);
469 
470     if(channels <= 0L || SHRT_MAX < channels)
471     {
472         fprintf(stderr, _("Warning: Unsupported count of channels in WAV header\n"));
473         return 0;
474     }
475 
476     if(format.format == -2) /* WAVE_FORMAT_EXTENSIBLE */
477     {
478       if(len<40)
479       {
480         fprintf(stderr,"ERROR: Extended WAV format header invalid (too small)\n");
481         return 0;
482       }
483 
484       format.mask = READ_U32_LE(buf+20);
485       /* warn the user if the format mask is not a supported/expected type */
486       switch(format.mask){
487       case 1539: /* 4.0 using side surround instead of back */
488         fprintf(stderr,"WARNING: WAV file uses side surround instead of rear for quadraphonic;\n"
489                 "remapping side speakers to rear in encoding.\n");
490         break;
491       case 1551: /* 5.1 using side instead of rear */
492         fprintf(stderr,"WARNING: WAV file uses side surround instead of rear for 5.1;\n"
493                 "remapping side speakers to rear in encoding.\n");
494         break;
495       case 319:  /* 6.1 using rear instead of side */
496         fprintf(stderr,"WARNING: WAV file uses rear surround instead of side for 6.1;\n"
497                 "remapping rear speakers to side in encoding.\n");
498         break;
499       case 255:  /* 7.1 'Widescreen' */
500         fprintf(stderr,"WARNING: WAV file is a 7.1 'Widescreen' channel mapping;\n"
501                 "remapping speakers to Vorbis 7.1 format.\n");
502         break;
503       case 0:    /* default/undeclared */
504       case 1:    /* mono */
505       case 3:    /* stereo */
506       case 51:   /* quad */
507       case 55:   /* 5.0 */
508       case 63:   /* 5.1 */
509       case 1807: /* 6.1 */
510       case 1599: /* 7.1 */
511         break;
512       default:
513         fprintf(stderr,"WARNING: Unknown WAV surround channel mask: %d\n"
514                 "blindly mapping speakers using default SMPTE/ITU ordering.\n",
515                 format.mask);
516         break;
517       }
518       format.format = READ_U16_LE(buf+24);
519     }
520 
521     if(!find_wav_chunk(in, "data", &len))
522         return 0; /* EOF */
523 
524     if(format.format == 1)
525     {
526         samplesize = format.samplesize/8;
527         opt->read_samples = wav_read;
528     }
529     else if(format.format == 3)
530     {
531         samplesize = 4;
532         opt->read_samples = wav_ieee_read;
533     }
534     else
535     {
536         fprintf(stderr,
537                 _("ERROR: Wav file is unsupported type (must be standard PCM\n"
538                 " or type 3 floating point PCM\n"));
539         return 0;
540     }
541 
542     if(format.align != format.channels * samplesize) {
543         /* This is incorrect according to the spec. Warn loudly, then ignore
544          * this value.
545          */
546         fprintf(stderr, _("Warning: WAV 'block alignment' value is incorrect, "
547                     "ignoring.\n"
548                     "The software that created this file is incorrect.\n"));
549     }
550 
551     if(format.samplesize == samplesize*8 &&
552             (format.samplesize == 24 || format.samplesize == 16 ||
553              format.samplesize == 8 ||
554          (format.samplesize == 32 && format.format == 3)))
555     {
556         /* OK, good - we have the one supported format,
557            now we want to find the size of the file */
558         opt->rate = format.samplerate;
559         opt->channels = format.channels;
560 
561         wav->f = in;
562         wav->samplesread = 0;
563         wav->bigendian = 0;
564         wav->channels = format.channels; /* This is in several places. The price
565                                             of trying to abstract stuff. */
566         wav->samplesize = format.samplesize;
567 
568         if(opt->ignorelength)
569         {
570             opt->total_samples_per_channel = -1;
571         }
572         else
573         {
574             if(len)
575             {
576                 opt->total_samples_per_channel =
577                     len/(format.channels*samplesize);
578             }
579             else
580             {
581                 long pos;
582                 pos = ftell(in);
583                 if(fseek(in, 0, SEEK_END) == -1)
584                 {
585                     opt->total_samples_per_channel = 0; /* Give up */
586                 }
587                 else
588                 {
589                     opt->total_samples_per_channel = (ftell(in) - pos)/
590                         (format.channels*samplesize);
591                     fseek(in,pos, SEEK_SET);
592                 }
593             }
594         }
595 
596         wav->totalsamples = opt->total_samples_per_channel;
597 
598         opt->readdata = (void *)wav;
599 
600         wav->channel_permute = malloc(wav->channels * sizeof(int));
601         if (wav->channels <= 8)
602             /* Where we know the mappings, use them. */
603             memcpy(wav->channel_permute, wav_permute_matrix[wav->channels-1],
604                     sizeof(int) * wav->channels);
605         else
606             /* Use a default 1-1 mapping */
607             for (i=0; i < wav->channels; i++)
608                 wav->channel_permute[i] = i;
609 
610         return 1;
611     }
612     else
613     {
614         fprintf(stderr,
615                 _("ERROR: Wav file is unsupported subformat (must be 8,16, or 24 bit PCM\n"
616                 "or floating point PCM\n"));
617         return 0;
618     }
619 }
620 
wav_read(void * in,float ** buffer,int samples)621 long wav_read(void *in, float **buffer, int samples)
622 {
623     wavfile *f = (wavfile *)in;
624     int sampbyte = f->samplesize / 8;
625     signed char *buf = alloca(samples*sampbyte*f->channels);
626     long bytes_read = fread(buf, 1, samples*sampbyte*f->channels, f->f);
627     int i,j;
628     long realsamples;
629     int *ch_permute = f->channel_permute;
630 
631     if(f->totalsamples > 0 && f->samplesread +
632             bytes_read/(sampbyte*f->channels) > f->totalsamples) {
633         bytes_read = sampbyte*f->channels*(f->totalsamples - f->samplesread);
634     }
635 
636     realsamples = bytes_read/(sampbyte*f->channels);
637     f->samplesread += realsamples;
638 
639     if(f->samplesize==8)
640     {
641         unsigned char *bufu = (unsigned char *)buf;
642         for(i = 0; i < realsamples; i++)
643         {
644             for(j=0; j < f->channels; j++)
645             {
646                 buffer[j][i]=((int)(bufu[i*f->channels + ch_permute[j]])-128)/128.0f;
647             }
648         }
649     }
650     else if(f->samplesize==16)
651     {
652         if(!f->bigendian)
653         {
654             for(i = 0; i < realsamples; i++)
655             {
656                 for(j=0; j < f->channels; j++)
657                 {
658                     buffer[j][i] = ((buf[i*2*f->channels + 2*ch_permute[j] + 1]<<8) |
659                                     (buf[i*2*f->channels + 2*ch_permute[j]] & 0xff))/32768.0f;
660                 }
661             }
662         }
663         else
664         {
665             for(i = 0; i < realsamples; i++)
666             {
667                 for(j=0; j < f->channels; j++)
668                 {
669                     buffer[j][i]=((buf[i*2*f->channels + 2*ch_permute[j]]<<8) |
670                                   (buf[i*2*f->channels + 2*ch_permute[j] + 1] & 0xff))/32768.0f;
671                 }
672             }
673         }
674     }
675     else if(f->samplesize==24)
676     {
677         if(!f->bigendian) {
678             for(i = 0; i < realsamples; i++)
679             {
680                 for(j=0; j < f->channels; j++)
681                 {
682                     buffer[j][i] = ((buf[i*3*f->channels + 3*ch_permute[j] + 2] << 16) |
683                       (((unsigned char *)buf)[i*3*f->channels + 3*ch_permute[j] + 1] << 8) |
684                       (((unsigned char *)buf)[i*3*f->channels + 3*ch_permute[j]] & 0xff))
685                         / 8388608.0f;
686 
687                 }
688             }
689         }
690         else {
691             fprintf(stderr, _("Big endian 24 bit PCM data is not currently "
692                               "supported, aborting.\n"));
693             return 0;
694         }
695     }
696     else {
697         fprintf(stderr, _("Internal error: attempt to read unsupported "
698                           "bitdepth %d\n"), f->samplesize);
699         return 0;
700     }
701 
702     return realsamples;
703 }
704 
wav_ieee_read(void * in,float ** buffer,int samples)705 long wav_ieee_read(void *in, float **buffer, int samples)
706 {
707     wavfile *f = (wavfile *)in;
708     float *buf = alloca(samples*4*f->channels); /* de-interleave buffer */
709     long bytes_read = fread(buf,1,samples*4*f->channels, f->f);
710     int i,j;
711     long realsamples;
712 
713 
714     if(f->totalsamples > 0 && f->samplesread +
715             bytes_read/(4*f->channels) > f->totalsamples)
716         bytes_read = 4*f->channels*(f->totalsamples - f->samplesread);
717     realsamples = bytes_read/(4*f->channels);
718     f->samplesread += realsamples;
719 
720     for(i=0; i < realsamples; i++)
721         for(j=0; j < f->channels; j++)
722             buffer[j][i] = buf[i*f->channels + f->channel_permute[j]];
723 
724     return realsamples;
725 }
726 
727 
wav_close(void * info)728 void wav_close(void *info)
729 {
730     wavfile *f = (wavfile *)info;
731     free(f->channel_permute);
732 
733     free(f);
734 }
735 
raw_open(FILE * in,oe_enc_opt * opt,unsigned char * buf,int buflen)736 int raw_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen)
737 {
738     wav_fmt format; /* fake wave header ;) */
739     wavfile *wav = malloc(sizeof(wavfile));
740     int i;
741 
742     /* construct fake wav header ;) */
743     format.format =      2;
744     format.channels =    opt->channels;
745     format.samplerate =  opt->rate;
746     format.samplesize =  opt->samplesize;
747     format.bytespersec = opt->channels * opt->rate * opt->samplesize / 8;
748     format.align =       format.bytespersec;
749     wav->f =             in;
750     wav->samplesread =   0;
751     wav->bigendian =     opt->endianness;
752     wav->channels =      format.channels;
753     wav->samplesize =    opt->samplesize;
754     wav->totalsamples =  -1;
755     wav->channel_permute = malloc(wav->channels * sizeof(int));
756     for (i=0; i < wav->channels; i++)
757       wav->channel_permute[i] = i;
758 
759     opt->read_samples = wav_read;
760     opt->readdata = (void *)wav;
761     opt->total_samples_per_channel = -1; /* raw mode, don't bother */
762     return 1;
763 }
764 
765 typedef struct {
766     res_state resampler;
767     audio_read_func real_reader;
768     void *real_readdata;
769     float **bufs;
770     int channels;
771     int bufsize;
772     int done;
773 } resampler;
774 
read_resampled(void * d,float ** buffer,int samples)775 static long read_resampled(void *d, float **buffer, int samples)
776 {
777     resampler *rs = d;
778     long in_samples;
779     int out_samples;
780 
781     in_samples = res_push_max_input(&rs->resampler, samples);
782     if(in_samples > rs->bufsize)
783         in_samples = rs->bufsize;
784 
785     in_samples = rs->real_reader(rs->real_readdata, rs->bufs, in_samples);
786 
787     if(in_samples <= 0) {
788         if(!rs->done) {
789             rs->done = 1;
790             out_samples = res_drain(&rs->resampler, buffer);
791             return out_samples;
792         }
793         return 0;
794     }
795 
796     out_samples = res_push(&rs->resampler, buffer, (float const **)rs->bufs, in_samples);
797 
798     if(out_samples <= 0) {
799         fprintf(stderr, _("BUG: Got zero samples from resampler: your file will be truncated. Please report this.\n"));
800     }
801 
802     return out_samples;
803 }
804 
setup_resample(oe_enc_opt * opt)805 int setup_resample(oe_enc_opt *opt) {
806     resampler *rs = calloc(1, sizeof(resampler));
807     int c;
808 
809     rs->bufsize = 4096; /* Shrug */
810     rs->real_reader = opt->read_samples;
811     rs->real_readdata = opt->readdata;
812     rs->bufs = malloc(sizeof(float *) * opt->channels);
813     rs->channels = opt->channels;
814     rs->done = 0;
815     if(res_init(&rs->resampler, rs->channels, opt->resamplefreq, opt->rate, RES_END))
816     {
817         fprintf(stderr, _("Couldn't initialise resampler\n"));
818         return -1;
819     }
820 
821     for(c=0; c < opt->channels; c++)
822         rs->bufs[c] = malloc(sizeof(float) * rs->bufsize);
823 
824     opt->read_samples = read_resampled;
825     opt->readdata = rs;
826     if(opt->total_samples_per_channel > 0)
827         opt->total_samples_per_channel = (int)((float)opt->total_samples_per_channel *
828             ((float)opt->resamplefreq/(float)opt->rate));
829     opt->rate = opt->resamplefreq;
830 
831     return 0;
832 }
833 
clear_resample(oe_enc_opt * opt)834 void clear_resample(oe_enc_opt *opt) {
835     resampler *rs = opt->readdata;
836     int i;
837 
838     opt->read_samples = rs->real_reader;
839     opt->readdata = rs->real_readdata;
840     res_clear(&rs->resampler);
841 
842     for(i = 0; i < rs->channels; i++)
843         free(rs->bufs[i]);
844 
845     free(rs->bufs);
846 
847     free(rs);
848 }
849 
850 typedef struct {
851     audio_read_func real_reader;
852     void *real_readdata;
853     int channels;
854     float scale_factor;
855 } scaler;
856 
read_scaler(void * data,float ** buffer,int samples)857 static long read_scaler(void *data, float **buffer, int samples) {
858     scaler *d = data;
859     long in_samples = d->real_reader(d->real_readdata, buffer, samples);
860     int i,j;
861 
862     for(i=0; i < d->channels; i++) {
863         for(j=0; j < in_samples; j++) {
864             buffer[i][j] *= d->scale_factor;
865         }
866     }
867 
868     return in_samples;
869 }
870 
871 
setup_scaler(oe_enc_opt * opt,float scale)872 void setup_scaler(oe_enc_opt *opt, float scale) {
873     scaler *d = calloc(1, sizeof(scaler));
874 
875     d->real_reader = opt->read_samples;
876     d->real_readdata = opt->readdata;
877 
878     opt->read_samples = read_scaler;
879     opt->readdata = d;
880     d->channels = opt->channels;
881     d->scale_factor = scale;
882 }
883 
clear_scaler(oe_enc_opt * opt)884 void clear_scaler(oe_enc_opt *opt) {
885     scaler *d = opt->readdata;
886 
887     opt->read_samples = d->real_reader;
888     opt->readdata = d->real_readdata;
889 
890     free(d);
891 }
892 
893 typedef struct {
894     audio_read_func real_reader;
895     void *real_readdata;
896     float **bufs;
897 } downmix;
898 
read_downmix(void * data,float ** buffer,int samples)899 static long read_downmix(void *data, float **buffer, int samples)
900 {
901     downmix *d = data;
902     long in_samples = d->real_reader(d->real_readdata, d->bufs, samples);
903     int i;
904 
905     for(i=0; i < in_samples; i++) {
906         buffer[0][i] = (d->bufs[0][i] + d->bufs[1][i])*0.5f;
907     }
908 
909     return in_samples;
910 }
911 
setup_downmix(oe_enc_opt * opt)912 void setup_downmix(oe_enc_opt *opt) {
913     downmix *d = calloc(1, sizeof(downmix));
914 
915     if(opt->channels != 2) {
916         fprintf(stderr, "Internal error! Please report this bug.\n");
917         return;
918     }
919 
920     d->bufs = malloc(2 * sizeof(float *));
921     d->bufs[0] = malloc(4096 * sizeof(float));
922     d->bufs[1] = malloc(4096 * sizeof(float));
923     d->real_reader = opt->read_samples;
924 
925     d->real_readdata = opt->readdata;
926 
927     opt->read_samples = read_downmix;
928     opt->readdata = d;
929 
930     opt->channels = 1;
931 }
clear_downmix(oe_enc_opt * opt)932 void clear_downmix(oe_enc_opt *opt) {
933     downmix *d = opt->readdata;
934 
935     opt->read_samples = d->real_reader;
936     opt->readdata = d->real_readdata;
937     opt->channels = 2; /* other things in cleanup rely on this */
938 
939     free(d->bufs[0]);
940     free(d->bufs[1]);
941     free(d->bufs);
942     free(d);
943 }
944 
945