Add Russian translation provided by Валерий Крувялис <valkru@mail.ru>
[xiph-mirror.git] / squishyball / loader.c
blobc7c0d5c3cb3e64d9a0d65f6b57b28dc0c9fa148d
1 /*
3 * squishyball
5 * Copyright (C) 2010-2014 Xiph.Org
7 * squishyball is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2, or (at your option)
10 * any later version.
12 * squishyball is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with rtrecord; see the file COPYING. If not, write to the
19 * Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24 #define _GNU_SOURCE
25 #define _LARGEFILE_SOURCE
26 #define _LARGEFILE64_SOURCE
27 #define _FILE_OFFSET_BITS 64
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <math.h>
32 #include <errno.h>
33 #include <vorbis/vorbisfile.h>
34 #include <opusfile.h>
35 #include <FLAC/stream_decoder.h>
36 #include <unistd.h>
37 #include "main.h"
39 static inline int host_is_big_endian() {
40 union {
41 int32_t pattern;
42 unsigned char bytewise[4];
43 } m;
44 m.pattern = 0xfeedface; /* deadbeef */
45 if (m.bytewise[0] == 0xfe) return 1;
46 return 0;
49 static char *trim_path(char *in){
50 /* search back to first /, \, or : */
51 if(in){
52 char *a = strrchr(in,'/');
53 char *b = strrchr(in,'\\');
54 char *c = strrchr(in,':');
55 int posa = (a ? a-in+1 : 0);
56 int posb = (b ? b-in+1 : 0);
57 int posc = (c ? c-in+1 : 0);
58 if(posb>posa)posa=posb;
59 if(posc>posa)posa=posc;
60 return in+posa;
62 return NULL;
65 typedef struct{
66 int (*id_func)(char *path,unsigned char *buf);
67 pcm_t *(*load_func)(char *path, FILE *in);
68 char *format;
69 } input_format;
71 /* steal/simplify/expand file ID/load code from oggenc */
73 /* Macros to read header data */
74 #define READ_U32_LE(buf) \
75 (((buf)[3]<<24)|((buf)[2]<<16)|((buf)[1]<<8)|((buf)[0]&0xff))
77 #define READ_U16_LE(buf) \
78 (((buf)[1]<<8)|((buf)[0]&0xff))
80 #define READ_U32_BE(buf) \
81 (((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|((buf)[3]&0xff))
83 #define READ_U16_BE(buf) \
84 (((buf)[0]<<8)|((buf)[1]&0xff))
86 static int wav_id(char *path,unsigned char *buf){
87 if(memcmp(buf, "RIFF", 4))
88 return 0; /* Not wave */
89 if(memcmp(buf+8, "WAVE",4))
90 return 0; /* RIFF, but not wave */
91 return 1;
94 static int aiff_id(char *path,unsigned char *buf){
95 if(memcmp(buf, "FORM", 4))
96 return 0;
97 if(memcmp(buf+8, "AIF",3))
98 return 0;
99 if(buf[11]!='C' && buf[11]!='F')
100 return 0;
101 return 1;
104 static int flac_id(char *path,unsigned char *buf){
105 return memcmp(buf, "fLaC", 4) == 0;
108 static int oggflac_id(char *path,unsigned char *buf){
109 return memcmp(buf, "OggS", 4) == 0 &&
110 (memcmp (buf+28, "\177FLAC", 5) == 0 ||
111 flac_id(path,buf+28));
114 static int vorbis_id(char *path,unsigned char *buf){
115 return memcmp(buf, "OggS", 4) == 0 &&
116 memcmp (buf+28, "\x01vorbis", 7) == 0;
119 static int opus_id(char *path,unsigned char *buf){
120 return memcmp(buf, "OggS", 4) == 0 &&
121 memcmp (buf+28, "OpusHead", 8) == 0;
124 static int sw_id(char *path,unsigned char *buf){
125 /* if all else fails, look for JM's favorite extension */
126 return memcmp(path+strlen(path)-3,".sw",3)==0;
129 /* WAV file support ***********************************************************/
131 static int find_wav_chunk(FILE *in, char *path, char *type, unsigned int *len){
132 unsigned char buf[8];
134 while(1){
135 if(fread(buf,1,8,in) < 8){
136 fprintf(stderr, "%s: Unexpected EOF in reading WAV header\n",path);
137 return 0; /* EOF before reaching the appropriate chunk */
140 if(memcmp(buf, type, 4)){
141 *len = READ_U32_LE(buf+4);
142 if(fseek(in, *len, SEEK_CUR))
143 return 0;
145 buf[4] = 0;
146 }else{
147 *len = READ_U32_LE(buf+4);
148 return 1;
153 static pcm_t *wav_load(char *path, FILE *in){
154 unsigned char buf[40];
155 unsigned int len;
156 pcm_t *pcm = NULL;
157 int i;
159 if(fseek(in,12,SEEK_SET)==-1){
160 fprintf(stderr,"%s: Failed to seek\n",path);
161 goto err;
164 pcm = calloc(1,sizeof(pcm_t));
165 pcm->name=strdup(trim_path(path));
167 if(!find_wav_chunk(in, path, "fmt ", &len)){
168 fprintf(stderr,"%s: Failed to find fmt chunk in WAV file\n",path);
169 goto err;
172 if(len < 16){
173 fprintf(stderr, "%s: Unrecognised format chunk in WAV header\n",path);
174 goto err;
177 if(sb_verbose){
178 /* A common error is to have a format chunk that is not 16, 18 or
179 * 40 bytes in size. This is incorrect, but not fatal, so we only
180 * warn about it instead of refusing to work with the file.
181 * Please, if you have a program that's creating format chunks of
182 * sizes other than 16 or 18 bytes in size, report a bug to the
183 * author.
185 if(len!=16 && len!=18 && len!=40)
186 fprintf(stderr,
187 "%s: INVALID format chunk in WAV header.\n"
188 " Trying to read anyway (may not work)...\n",path);
191 if(len>40)len=40;
193 if(fread(buf,1,len,in) < len){
194 fprintf(stderr,"%s: Unexpected EOF in reading WAV header\n",path);
195 goto err;
198 unsigned int mask = 0;
199 unsigned int format = READ_U16_LE(buf);
200 unsigned int channels = READ_U16_LE(buf+2);
201 unsigned int samplerate = READ_U32_LE(buf+4);
202 //unsigned int bytespersec = READ_U32_LE(buf+8);
203 unsigned int align = READ_U16_LE(buf+12);
204 unsigned int samplesize = READ_U16_LE(buf+14);
205 const char *mask_map[32]={
206 "L","R","C","LFE", "BL","BR","CL","CR",
207 "BC","SL","SR","X", "X","X","X","X",
208 "X","X","X","X", "X","X","X","X",
209 "X","X","X","X", "X","X","X","X"};
211 if(format == 0xfffe){ /* WAVE_FORMAT_EXTENSIBLE */
213 if(len<40){
214 fprintf(stderr,"%s: Extended WAV format header invalid (too small)\n",path);
215 goto err;
218 mask = READ_U32_LE(buf+20);
219 format = READ_U16_LE(buf+24);
222 if(mask==0){
223 switch(channels){
224 case 1:
225 pcm->matrix = strdup("M");
226 pcm->mix = strdup("A");
227 break;
228 case 2:
229 pcm->matrix = strdup("L,R");
230 pcm->mix = strdup("BC");
231 break;
232 case 3:
233 pcm->matrix = strdup("L,R,C");
234 pcm->mix = strdup("BCD");
235 break;
236 case 4:
237 pcm->matrix = strdup("L,R,BL,BR");
238 pcm->mix = strdup("BCFG");
239 break;
240 case 5:
241 pcm->matrix = strdup("L,R,C,BL,BR");
242 pcm->mix = strdup("BCDFG");
243 break;
244 case 6:
245 pcm->matrix = strdup("L,R,C,LFE,BL,BR");
246 pcm->mix = strdup("BCDEFG");
247 break;
248 case 7:
249 pcm->matrix = strdup("L,R,C,LFE,BC,SL,SR");
250 pcm->mix = strdup("BCDEJKL");
251 break;
252 default:
253 pcm->matrix = strdup("L,R,C,LFE,BL,BR,SL,SR");
254 pcm->mix = strdup("BCDEFGKL");
255 break;
257 }else{
258 int count=0;
259 pcm->matrix = calloc(32*4+1,sizeof(char));
260 pcm->mix = calloc(33,sizeof(char));
261 for(i=0;i<32;i++){
262 if(mask&(1<<i)){
263 strcat(pcm->matrix,mask_map[i]);
264 strcat(pcm->matrix,",");
265 pcm->mix[count++]='B'+i;
270 if(!find_wav_chunk(in, path, "data", &len)){
271 fprintf(stderr,"%s: Failed to find fmt chunk in WAV file\n",path);
272 goto err;
275 if(sb_verbose){
276 if(align != channels * ((samplesize+7)/8)) {
277 /* This is incorrect according to the spec. Warn loudly, then ignore
278 * this value.
280 fprintf(stderr, "%s: WAV 'block alignment' value is incorrect, "
281 "ignoring.\n"
282 "The software that created this file is incorrect.\n",path);
286 if((format==1 && (samplesize == 24 || samplesize == 16 || samplesize == 8)) ||
287 (samplesize == 32 && format == 3)){
288 /* OK, good - we have a supported format,
289 now we want to find the size of the file */
290 pcm->rate = samplerate;
291 pcm->ch = channels;
292 pcm->nativebits = (format==3 ? -samplesize : samplesize);
293 pcm->currentbits = -32;
295 if(len){
296 pcm->size = len;
297 }else{
298 long pos;
299 pos = ftell(in);
300 if(fseek(in, 0, SEEK_END) == -1){
301 fprintf(stderr,"%s failed to seek: %s\n",path,strerror(errno));
302 goto err;
303 }else{
304 pcm->size = ftell(in) - pos;
305 fseek(in,pos, SEEK_SET);
309 }else{
310 fprintf(stderr,
311 "%s: Wav file is unsupported subformat (must be 8,16, or 24-bit PCM\n"
312 "or floating point PCM\n",path);
313 goto err;
316 /* read the samples into memory */
317 switch(pcm->nativebits){
318 case 8:
319 pcm->data = calloc(1,pcm->size*sizeof(float));
320 break;
321 case 16:
322 pcm->data = calloc(1,pcm->size/2*sizeof(float));
323 break;
324 case 24:
325 pcm->data = calloc(1,pcm->size/3*sizeof(float));
326 break;
327 case -32:
328 case 32:
329 pcm->data = calloc(1,pcm->size/4*sizeof(float));
330 break;
331 default:
332 /* Won't get here unless the code is modified and the modifier
333 misses expanding here and below */
334 fprintf(stderr,"%s: Unsupported bit depth\n",path);
335 goto err;
338 if(pcm->data == NULL){
339 fprintf(stderr,"Unable to allocate enough memory to load sample into memory\n");
340 goto err;
344 off_t j=0,k;
345 unsigned char *d = pcm->data;
346 float *f = (float *)pcm->data;
348 while(j<pcm->size){
349 off_t bytes = (pcm->size-j > 65536 ? 65536 : pcm->size-j);
350 if(sb_verbose)
351 fprintf(stderr,"\rLoading %s: %ld to go... ",pcm->name,(long)(pcm->size-j));
352 j+=bytes=fread(d+j,1,bytes,in);
353 if(bytes==0)break;
355 if(j<pcm->size){
356 if(sb_verbose)
357 fprintf(stderr,"\r%s: File ended before declared length (%ld < %ld); continuing...\n",path,(long)j,(long)pcm->size);
358 pcm->size=j;
361 /* non float must be expanded to float */
362 if(sb_verbose)
363 fprintf(stderr,"\rLoading %s: parsing... ",pcm->name);
365 switch(pcm->nativebits){
366 case 8:
367 k=pcm->size;
368 for(j=pcm->size-1;j>=0;j--)
369 f[--k] = (int32_t)((d[j]-128)<<24) * (1.f/2147483648.f);
370 pcm->size=pcm->size*sizeof(float);
371 break;
372 case 16:
373 k=pcm->size/2;
374 for(j=pcm->size-2;j>=0;j-=2)
375 f[--k] = (int32_t)((d[j]<<16)|(d[j+1]<<24)) * (1.f/2147483648.f);
376 pcm->size=pcm->size/2*sizeof(float);
377 break;
378 case 24:
379 k=pcm->size/3;
380 for(j=pcm->size-3;j>=0;j-=3)
381 f[--k] = (int32_t)((d[j]<<8)|(d[j+1]<<16)|(d[j+2]<<24)) * (1.f/2147483648.f);
382 pcm->size=pcm->size/3*sizeof(float);
383 break;
384 case 32:
385 k=pcm->size/4;
386 for(j=pcm->size-4;j>=0;j-=4)
387 f[--k] = (int32_t)(d[j]|(d[j+1]<<8)|(d[j+2]<<16)|(d[j+3]<<24)) * (1.f/2147483648.f);
388 pcm->size=pcm->size/4*sizeof(float);
389 break;
390 case -32:
391 k=pcm->size/4;
392 for(j=pcm->size-4;j>=0;j-=4){
393 int val=0;
394 int mantissa = d[j] | (d[j+1]<<8) | ((d[j+2]&0x7f)<<16) | (1<<23);
395 int exponent = 127 - ((d[j+2]>>7) | ((d[j+3]&0x7f)<<1));
396 int sign = d[j+3]>>7;
397 if(exponent <= 0){
398 if(exponent == -128){
399 fprintf(stderr,"%s: Input file contains invalid floating point values.\n",pcm->name);
400 exit(6);
402 if(sign)
403 val = 8388608;
404 else
405 val = 8388607;
406 }else if(exponent <= 24){
407 val = mantissa>>exponent;
408 /* round with tiebreaks toward even */
409 if(((mantissa<<(24-exponent))&0xffffff) + (val&1) > 0x800000) ++val;
411 if(sign) val= -val;
412 f[--k] = val/8388608.;
414 pcm->size=pcm->size/4*sizeof(float);
415 break;
419 if(sb_verbose)
420 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
422 return pcm;
423 err:
424 free_pcm(pcm);
425 return NULL;
428 /* AIFF file support ***********************************************************/
430 static int find_aiff_chunk(FILE *in, char *path, char *type, unsigned int *len){
431 unsigned char buf[8];
432 int restarted = 0;
434 while(1){
435 if(fread(buf,1,8,in)<8){
436 if(!restarted) {
437 /* Handle out of order chunks by seeking back to the start
438 * to retry */
439 restarted = 1;
440 fseek(in, 12, SEEK_SET);
441 continue;
443 fprintf(stderr,"%s: Unexpected EOF in AIFF chunk\n",path);
444 return 0;
447 *len = READ_U32_BE(buf+4);
449 if(memcmp(buf,type,4)){
450 if((*len) & 0x1)
451 (*len)++;
453 if(fseek(in,*len,SEEK_CUR))
454 return 0;
455 }else
456 return 1;
460 static double read_IEEE80(unsigned char *buf){
461 int s=buf[0]&0xff;
462 int e=((buf[0]&0x7f)<<8)|(buf[1]&0xff);
463 double f=((unsigned long)(buf[2]&0xff)<<24)|
464 ((buf[3]&0xff)<<16)|
465 ((buf[4]&0xff)<<8) |
466 (buf[5]&0xff);
468 if(e==32767){
469 if(buf[2]&0x80)
470 return HUGE_VAL; /* Really NaN, but this won't happen in reality */
471 else{
472 if(s)
473 return -HUGE_VAL;
474 else
475 return HUGE_VAL;
479 f=ldexp(f,32);
480 f+= ((buf[6]&0xff)<<24)|
481 ((buf[7]&0xff)<<16)|
482 ((buf[8]&0xff)<<8) |
483 (buf[9]&0xff);
484 return ldexp(f, e-16446);
487 static pcm_t *aiff_load(char *path, FILE *in){
488 pcm_t *pcm = NULL;
489 int aifc; /* AIFC or AIFF? */
490 unsigned int len;
491 unsigned char *buffer;
492 unsigned char buf2[12];
493 int bend = 1;
494 int fp = 0;
496 if(fseek(in,0,SEEK_SET)==-1){
497 fprintf(stderr,"%s: Failed to seek\n",path);
498 goto err;
500 if(fread(buf2,1,12,in)!=12){
501 fprintf(stderr,"%s: Failed to read AIFF header\n",path);
502 goto err;
505 pcm = calloc(1,sizeof(pcm_t));
506 pcm->name=strdup(trim_path(path));
508 if(buf2[11]=='C')
509 aifc=1;
510 else
511 aifc=0;
513 if(!find_aiff_chunk(in, path, "COMM", &len)){
514 fprintf(stderr,"%s: No common chunk found in AIFF file\n",path);
515 goto err;
518 if(len < 18){
519 fprintf(stderr, "%s: Truncated common chunk in AIFF header\n",path);
520 goto err;
523 buffer = alloca(len);
525 if(fread(buffer,1,len,in) < len){
526 fprintf(stderr, "%s: Unexpected EOF in reading AIFF header\n",path);
527 goto err;
530 pcm->ch = READ_U16_BE(buffer);
531 pcm->rate = (int)read_IEEE80(buffer+8);
532 pcm->nativebits = READ_U16_BE(buffer+6);
533 pcm->size = READ_U32_BE(buffer+2)*pcm->ch*((pcm->nativebits+7)/8);
534 pcm->currentbits = -32;
536 switch(pcm->ch){
537 case 1:
538 pcm->matrix = strdup("M");
539 pcm->mix = strdup("A");
540 break;
541 case 2:
542 pcm->matrix = strdup("L,R");
543 pcm->mix = strdup("BC");
544 break;
545 case 3:
546 pcm->matrix = strdup("L,R,C");
547 pcm->mix = strdup("BCD");
548 break;
549 default:
550 pcm->matrix = strdup("L,R,BL,BR");
551 pcm->mix = strdup("BCFG");
552 break;
555 if(aifc){
556 if(len < 22){
557 fprintf(stderr, "%s: AIFF-C header truncated.\n",path);
558 goto err;
561 if(!memcmp(buffer+18, "NONE", 4) || !memcmp(buffer+18, "twos", 4)){
562 bend = 1;
563 }else if(!memcmp(buffer+18, "sowt", 4)){
564 bend = 0;
565 }else if(!memcmp(buffer+18, "fl32", 4)){
566 bend = 1;
567 fp = 1;
568 }else{
569 fprintf(stderr, "%s: Can't handle compressed AIFF-C (%c%c%c%c)\n", path,
570 *(buffer+18), *(buffer+19), *(buffer+20), *(buffer+21));
571 goto err;
575 if(!find_aiff_chunk(in, path, "SSND", &len)){
576 fprintf(stderr, "%s: No SSND chunk found in AIFF file\n",path);
577 goto err;
579 if(len < 8) {
580 fprintf(stderr,"%s: Corrupted SSND chunk in AIFF header\n",path);
581 goto err;
584 if(fread(buf2,1,8, in) < 8){
585 fprintf(stderr, "%s: Unexpected EOF reading AIFF header\n",path);
586 goto err;
589 int offset = READ_U32_BE(buf2);
591 if(!((fp==0 && (pcm->nativebits==32 ||
592 pcm->nativebits==24 ||
593 pcm->nativebits==16 ||
594 pcm->nativebits==8)) ||
595 (fp==1 && pcm->nativebits==32))){
596 fprintf(stderr,
597 "%s: Unsupported type of AIFF/AIFC file\n"
598 " Must be 8-, 16-, 24- or 32-bit integer or 32-bit floating point PCM.\n",
599 path);
600 goto err;
602 if(fp==1)
603 pcm->nativebits = -pcm->nativebits;
605 fseek(in, offset, SEEK_CUR); /* Swallow some data */
607 /* read the samples into memory */
608 switch(pcm->nativebits){
609 case 8:
610 pcm->data = calloc(1,pcm->size*sizeof(float));
611 break;
612 case 16:
613 pcm->data = calloc(1,pcm->size/2*sizeof(float));
614 break;
615 case 24:
616 pcm->data = calloc(1,pcm->size/3*sizeof(float));
617 break;
618 case 32:
619 case -32:
620 pcm->data = calloc(1,pcm->size/4*sizeof(float));
621 break;
624 if(pcm->data == NULL){
625 fprintf(stderr,"Unable to allocate enough memory to load sample into memory\n");
626 goto err;
630 unsigned char *d = pcm->data;
631 float *f = (float *)pcm->data;
632 off_t j=0,k;
633 while(j<pcm->size){
634 off_t bytes = (pcm->size-j > 65536 ? 65536 : pcm->size-j);
635 if(sb_verbose)
636 fprintf(stderr,"\rLoading %s: %ld to go... \r",pcm->name,(long)(pcm->size-j));
637 j+=bytes=fread(d+j,1,bytes,in);
638 if(bytes==0)break;
640 if(j<pcm->size){
641 if(sb_verbose)
642 fprintf(stderr,"\r%s: File ended before declared length (%ld < %ld); continuing...\n",path,(long)j,(long)pcm->size);
643 pcm->size=j;
646 /* expand to float */
647 if(sb_verbose)
648 fprintf(stderr,"\rLoading %s: parsing... ",pcm->name);
650 switch(pcm->nativebits){
651 case 8:
652 k=pcm->size;
653 for(j=pcm->size-1;j>=0;j--)
654 f[--k] = (int32_t)((d[j]-128)<<24) * (1.f/2147483648.f);
655 pcm->size=pcm->size*sizeof(float);
656 break;
657 case 16:
658 k=pcm->size/2;
659 if(bend){
660 for(j=pcm->size-2;j>=0;j-=2)
661 f[--k] = (int32_t)((d[j]<<24)|(d[j+1]<<16)) * (1.f/2147483648.f);
662 }else{
663 for(j=pcm->size-2;j>=0;j-=2)
664 f[--k] = (int32_t)((d[j]<<16)|(d[j+1]<<24)) * (1.f/2147483648.f);
666 pcm->size=pcm->size/2*sizeof(float);
667 break;
668 case 24:
669 k=pcm->size/3;
670 if(bend){
671 for(j=pcm->size-3;j>=0;j-=3)
672 f[--k] = (int32_t)(d[j+2]|(d[j+1]<<8)|(d[j]<<16)) * (1.f/2147483648.f);
673 }else{
674 for(j=pcm->size-3;j>=0;j-=3)
675 f[--k] = (int32_t)(d[j]|(d[j+1]<<8)|(d[j+2]<<16)) * (1.f/2147483648.f);
677 pcm->size=pcm->size/3*sizeof(float);
678 break;
679 case 32:
680 k=pcm->size/4;
681 if(bend){
682 for(j=pcm->size-4;j>=0;j-=4)
683 f[--k] = (int32_t)(d[j+3]|(d[j+2]<<8)|(d[j+1]<<16)|(d[j]<<24)) * (1.f/2147483648.f);
684 }else{
685 for(j=pcm->size-4;j>=0;j-=4)
686 f[--k] = (int32_t)(d[j]|(d[j+1]<<8)|(d[j+2]<<16)|(d[j+3]<<24)) * (1.f/2147483648.f);
688 pcm->size=pcm->size/4*sizeof(float);
689 break;
690 case -32:
691 k=pcm->size/4;
692 for(j=pcm->size-4;j>=0;j-=4){
693 int val=0;
694 int mantissa;
695 int exponent;
696 int sign;
698 if(bend){
699 mantissa = d[j+3] | (d[j+2]<<8) | ((d[j+1]&0x7f)<<16) | (1<<23);
700 exponent = 127 - ((d[j+1]>>7) | ((d[j]&0x7f)<<1));
701 sign = d[j]>>7;
702 }else{
703 mantissa = d[j] | (d[j+1]<<8) | ((d[j+2]&0x7f)<<16) | (1<<23);
704 exponent = 127 - ((d[j+2]>>7) | ((d[j+3]&0x7f)<<1));
705 sign = d[j+3]>>7;
708 if(exponent <= 0){
709 if(exponent == -128){
710 fprintf(stderr,"%s: Input file contains invalid floating point values.\n",pcm->name);
711 exit(6);
713 if(sign)
714 val = 8388608;
715 else
716 val = 8388607;
717 }else if(exponent <= 24){
718 val = mantissa>>exponent;
719 /* round with tiebreaks toward even */
720 if(((mantissa<<(24-exponent))&0xffffff) + (val&1) > 0x800000) ++val;
722 if(sign) val= -val;
723 f[--k] = val/8388608.;
725 pcm->size=pcm->size/4*sizeof(float);
726 break;
730 if(sb_verbose)
731 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
733 return pcm;
734 err:
735 free_pcm(pcm);
736 return NULL;
740 /* SW loading to make JM happy *******************************************************/
742 static pcm_t *sw_load(char *path, FILE *in){
743 pcm_t *pcm = calloc(1,sizeof(pcm_t));
744 pcm->name=strdup(trim_path(path));
745 pcm->nativebits=16;
746 pcm->currentbits=-32;
747 pcm->ch=1;
748 pcm->rate=48000;
749 pcm->matrix=strdup("M");
750 pcm->mix=strdup("A");
752 if(fseek(in,0,SEEK_END)==-1){
753 fprintf(stderr,"%s: Failed to seek\n",path);
754 goto err;
756 pcm->size=ftell(in);
757 if(pcm->size==-1 || fseek(in,0,SEEK_SET)==-1){
758 fprintf(stderr,"%s: Failed to seek\n",path);
759 goto err;
762 pcm->data = calloc(1,pcm->size/2*sizeof(float));
764 if(pcm->data == NULL){
765 fprintf(stderr,"Unable to allocate enough memory to load sample into memory\n");
766 goto err;
770 off_t j=0;
771 int16_t *d = (int16_t *)pcm->data;
772 float *f = (float *)pcm->data;
774 while(j<pcm->size){
775 off_t bytes = (pcm->size-j > 65536 ? 65536 : pcm->size-j);
776 if(sb_verbose)
777 fprintf(stderr,"\rLoading %s: %ld to go... ",pcm->name,(long)(pcm->size-j));
778 j+=bytes=fread(pcm->data+j,1,bytes,in);
779 if(bytes==0)break;
781 if(j<pcm->size){
782 if(sb_verbose)
783 fprintf(stderr,"\r%s: File ended before declared length (%ld < %ld); continuing...\n",path,(long)j,(long)pcm->size);
784 pcm->size=j;
787 if(sb_verbose)
788 fprintf(stderr,"\rLoading %s: parsing... ",pcm->name);
790 for(j=pcm->size/2-1;j>=0;j--)
791 f[j] = d[j]/32768.;
793 pcm->size=pcm->size/2*sizeof(float);
796 if(sb_verbose)
797 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
799 return pcm;
800 err:
801 free_pcm(pcm);
802 return NULL;
805 /* FLAC and OggFLAC load support *****************************************************************/
807 typedef struct {
808 FILE *in;
809 pcm_t *pcm;
810 off_t fill;
811 } flac_callback_arg;
813 /* glorified fread wrapper */
814 static FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder,
815 FLAC__byte buffer[],
816 size_t *bytes,
817 void *client_data){
818 flac_callback_arg *flac = (flac_callback_arg *)client_data;
819 pcm_t *pcm = flac->pcm;
821 if(feof(flac->in)){
822 *bytes = 0;
823 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
824 }else if(ferror(flac->in)){
825 *bytes = 0;
826 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
829 if(sb_verbose)
830 fprintf(stderr,"\rLoading %s: %ld to go... ",flac->pcm->name,(long)(pcm->size-flac->fill));
831 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, flac->in);
833 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
836 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder,
837 const FLAC__Frame *frame,
838 const FLAC__int32 *const buffer[],
839 void *client_data){
840 flac_callback_arg *flac = (flac_callback_arg *)client_data;
841 pcm_t *pcm = flac->pcm;
842 int samples = frame->header.blocksize;
843 int channels = frame->header.channels;
844 int bits_per_sample = frame->header.bits_per_sample;
845 off_t fill = flac->fill;
846 int i, j;
848 if(pcm->data == NULL){
849 /* lazy initialization */
850 pcm->ch = channels;
851 pcm->nativebits = (bits_per_sample+7)/8*8;
852 pcm->size *= channels*sizeof(float);
853 pcm->currentbits = -32;
854 pcm->data = calloc(pcm->size,1);
857 if(channels != pcm->ch){
858 fprintf(stderr,"\r%s: number of channels changes part way through file\n",pcm->name);
859 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
861 if(pcm->nativebits != (bits_per_sample+7)/8*8){
862 fprintf(stderr,"\r%s: bit depth changes part way through file\n",pcm->name);
863 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
866 if(sb_verbose)
867 fprintf(stderr,"\rLoading %s: parsing... ",pcm->name);
870 float *d = (float *)pcm->data;
871 int shift = pcm->nativebits - bits_per_sample;
872 switch(pcm->nativebits){
873 case 16:
874 for (j = 0; j < samples; j++)
875 for (i = 0; i < channels; i++)
876 d[fill++] = (buffer[i][j]<<shift)*(1.f/32768.f);
877 break;
878 case 24:
879 for (j = 0; j < samples; j++)
880 for (i = 0; i < channels; i++)
881 d[fill++] = (buffer[i][j]<<shift)*(1.f/8388608.f);
882 break;
883 default:
884 fprintf(stderr,"\r%s: Only 16- and 24-bit FLACs are supported for decode right now.\n",pcm->name);
885 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
888 flac->fill=fill;
890 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
893 static void metadata_callback(const FLAC__StreamDecoder *decoder,
894 const FLAC__StreamMetadata *metadata,
895 void *client_data){
896 flac_callback_arg *flac = (flac_callback_arg *)client_data;
897 pcm_t *pcm = flac->pcm;
899 switch (metadata->type){
900 case FLAC__METADATA_TYPE_STREAMINFO:
901 pcm->size = metadata->data.stream_info.total_samples; /* temp setting */
902 pcm->rate = metadata->data.stream_info.sample_rate;
903 break;
904 default:
905 break;
909 static void error_callback(const FLAC__StreamDecoder *decoder,
910 FLAC__StreamDecoderErrorStatus status,
911 void *client_data){
913 flac_callback_arg *flac = (flac_callback_arg *)client_data;
914 pcm_t *pcm = flac->pcm;
915 fprintf(stderr,"\r%s: Error decoding file.\n",pcm->name);
918 static FLAC__bool eof_callback(const FLAC__StreamDecoder *decoder,
919 void *client_data){
920 flac_callback_arg *flac = (flac_callback_arg *)client_data;
921 return feof(flac->in)? true : false;
924 static pcm_t *flac_load_i(char *path, FILE *in, int oggp){
925 pcm_t *pcm;
926 flac_callback_arg *flac;
927 FLAC__StreamDecoder *decoder;
928 FLAC__bool ret;
930 if(fseek(in,0,SEEK_SET)==-1){
931 fprintf(stderr,"%s: Failed to seek\n",path);
932 goto err;
935 pcm = calloc(1,sizeof(pcm_t));
936 flac = calloc(1,sizeof(flac_callback_arg));
937 decoder = FLAC__stream_decoder_new();
938 FLAC__stream_decoder_set_md5_checking(decoder, true);
939 FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
941 pcm->name=strdup(trim_path(path));
942 flac->in=in;
943 flac->pcm=pcm;
945 if(oggp)
946 FLAC__stream_decoder_init_ogg_stream(decoder,
947 read_callback,
948 /*seek_callback=*/0,
949 /*tell_callback=*/0,
950 /*length_callback=*/0,
951 eof_callback,
952 write_callback,
953 metadata_callback,
954 error_callback,
955 flac);
956 else
957 FLAC__stream_decoder_init_stream(decoder,
958 read_callback,
959 /*seek_callback=*/0,
960 /*tell_callback=*/0,
961 /*length_callback=*/0,
962 eof_callback,
963 write_callback,
964 metadata_callback,
965 error_callback,
966 flac);
968 /* setup and sample reading handled by configured callbacks */
969 ret=FLAC__stream_decoder_process_until_end_of_stream(decoder);
970 FLAC__stream_decoder_finish(decoder);
971 FLAC__stream_decoder_delete(decoder);
972 free(flac);
973 if(!ret){
974 free_pcm(pcm);
975 return NULL;
978 /* set channel matrix */
979 switch(pcm->ch){
980 case 1:
981 pcm->matrix = strdup("M");
982 pcm->mix = strdup("A");
983 break;
984 case 2:
985 pcm->matrix = strdup("L,R");
986 pcm->mix = strdup("BC");
987 break;
988 case 3:
989 pcm->matrix = strdup("L,R,C");
990 pcm->mix = strdup("BCD");
991 break;
992 case 4:
993 pcm->matrix = strdup("L,R,BL,BR");
994 pcm->mix = strdup("BCFG");
995 break;
996 case 5:
997 pcm->matrix = strdup("L,R,C,BL,BR");
998 pcm->mix = strdup("BCDFG");
999 break;
1000 case 6:
1001 pcm->matrix = strdup("L,R,C,LFE,BL,BR");
1002 pcm->mix = strdup("BCDEFG");
1003 break;
1004 case 7:
1005 pcm->matrix = strdup("L,R,C,LFE,BC,SL,SR");
1006 pcm->mix = strdup("BCDEJKL");
1007 break;
1008 default:
1009 pcm->matrix = strdup("L,R,C,LFE,BL,BR,SL,SR");
1010 pcm->mix = strdup("BCDEFGKL");
1011 break;
1014 if(sb_verbose)
1015 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
1017 return pcm;
1018 err:
1019 return NULL;
1022 static pcm_t *flac_load(char *path, FILE *in){
1023 return flac_load_i(path,in,0);
1026 static pcm_t *oggflac_load(char *path, FILE *in){
1027 return flac_load_i(path,in,1);
1030 /* Vorbis load support **************************************************************************/
1031 static pcm_t *vorbis_load(char *path, FILE *in){
1032 OggVorbis_File vf;
1033 vorbis_info *vi=NULL;
1034 pcm_t *pcm=NULL;
1035 off_t fill=0;
1036 int throttle=0;
1037 int last_section=-1;
1039 memset(&vf,0,sizeof(vf));
1041 if(fseek(in,0,SEEK_SET)==-1){
1042 fprintf(stderr,"%s: Failed to seek\n",path);
1043 goto err;
1046 if(ov_open_callbacks(in, &vf, NULL, 0, OV_CALLBACKS_NOCLOSE) < 0) {
1047 fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n");
1048 goto err;
1051 vi=ov_info(&vf,-1);
1052 pcm = calloc(1,sizeof(pcm_t));
1053 pcm->name=strdup(trim_path(path));
1054 pcm->nativebits=-32;
1055 pcm->currentbits=-32;
1056 pcm->ch=vi->channels;
1057 pcm->rate=vi->rate;
1058 pcm->size=ov_pcm_total(&vf,-1)*vi->channels*sizeof(float);
1059 pcm->data=calloc(pcm->size,1);
1061 switch(pcm->ch){
1062 case 1:
1063 pcm->matrix = strdup("M");
1064 pcm->mix = strdup("A");
1065 break;
1066 case 2:
1067 pcm->matrix = strdup("L,R");
1068 pcm->mix = strdup("BC");
1069 break;
1070 case 3:
1071 pcm->matrix = strdup("L,C,R");
1072 pcm->mix = strdup("BDC");
1073 break;
1074 case 4:
1075 pcm->matrix = strdup("L,R,BL,BR");
1076 pcm->mix = strdup("BCFG");
1077 break;
1078 case 5:
1079 pcm->matrix = strdup("L,C,R,BL,BR");
1080 pcm->mix = strdup("BDCFG");
1081 break;
1082 case 6:
1083 pcm->matrix = strdup("L,C,R,BL,BR,LFE");
1084 pcm->mix = strdup("BDCFGE");
1085 break;
1086 case 7:
1087 pcm->matrix = strdup("L,C,R,SL,SR,BC,LFE");
1088 pcm->mix = strdup("BDCKLJE");
1089 break;
1090 default:
1091 pcm->matrix = strdup("L,C,R,SL,SR,BL,BR,LFE");
1092 pcm->mix = strdup("BDCKLFGE");
1093 break;
1096 while(fill*sizeof(float)<pcm->size){
1097 int current_section;
1098 int i,j;
1099 float **pcmout;
1100 long ret=ov_read_float(&vf,&pcmout,4096,&current_section);
1101 float *d = (float *)pcm->data;
1103 if(current_section!=last_section){
1104 last_section=current_section;
1105 vi=ov_info(&vf,-1);
1106 if(vi->channels != pcm->ch || vi->rate!=pcm->rate){
1107 fprintf(stderr,"%s: Chained file changes channel count/sample rate\n",path);
1108 goto err;
1112 if(ret<0){
1113 fprintf(stderr,"%s: Error while decoding file\n",path);
1114 goto err;
1116 if(ret==0){
1117 fprintf(stderr,"%s: Audio data ended prematurely\n",path);
1118 goto err;
1121 for(i=0;i<ret;i++)
1122 for(j=0;j<pcm->ch;j++)
1123 d[fill++]=pcmout[j][i];
1125 if (sb_verbose && (throttle&0x3f)==0)
1126 fprintf(stderr,"\rLoading %s: %ld to go... ",pcm->name,(long)(pcm->size-fill*sizeof(float)));
1127 throttle++;
1129 ov_clear(&vf);
1131 if(sb_verbose)
1132 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
1134 return pcm;
1135 err:
1136 ov_clear(&vf);
1137 free_pcm(pcm);
1138 return NULL;
1141 /* Opus load support **************************************************************************/
1143 int opc_read(void *_stream,unsigned char *_ptr,int _nbytes){
1144 return fread(_ptr,1,_nbytes,_stream);
1147 int opc_seek(void *_stream,opus_int64 _offset,int _whence){
1148 return fseek(_stream,_offset,_whence);
1151 opus_int64 opc_tell(void *_stream){
1152 return ftell(_stream);
1155 int opc_close(void *_stream){
1156 return 0;
1159 static OpusFileCallbacks opus_callbacks =
1160 { opc_read,opc_seek,opc_tell,opc_close };
1162 static pcm_t *opus_load(char *path, FILE *in){
1163 OggOpusFile *of;
1164 pcm_t *pcm=NULL;
1165 off_t fill=0;
1166 int throttle=0;
1167 int last_section=-1;
1169 if(fseek(in,0,SEEK_SET)==-1){
1170 fprintf(stderr,"%s: Failed to seek\n",path);
1171 goto err;
1174 of = op_open_callbacks(in, &opus_callbacks , NULL, 0, NULL);
1175 if(!of){
1176 fprintf(stderr,"Input does not appear to be an Opus bitstream.\n");
1177 goto err;
1180 pcm = calloc(1,sizeof(pcm_t));
1181 pcm->name=strdup(trim_path(path));
1182 pcm->nativebits=-32;
1183 pcm->currentbits=-32;
1184 pcm->ch=op_channel_count(of,-1);
1185 pcm->rate=48000;
1186 pcm->size=op_pcm_total(of,-1)*pcm->ch*sizeof(float);
1187 pcm->data=calloc(pcm->size,1);
1190 switch(pcm->ch){
1191 case 1:
1192 pcm->matrix = strdup("M");
1193 pcm->mix = strdup("A");
1194 break;
1195 case 2:
1196 pcm->matrix = strdup("L,R");
1197 pcm->mix = strdup("BC");
1198 break;
1199 case 3:
1200 pcm->matrix = strdup("L,C,R");
1201 pcm->mix = strdup("BDC");
1202 break;
1203 case 4:
1204 pcm->matrix = strdup("L,R,BL,BR");
1205 pcm->mix = strdup("BCFG");
1206 break;
1207 case 5:
1208 pcm->matrix = strdup("L,C,R,BL,BR");
1209 pcm->mix = strdup("BDCFG");
1210 break;
1211 case 6:
1212 pcm->matrix = strdup("L,C,R,BL,BR,LFE");
1213 pcm->mix = strdup("BDCFGE");
1214 break;
1215 case 7:
1216 pcm->matrix = strdup("L,C,R,SL,SR,BC,LFE");
1217 pcm->mix = strdup("BDCKLJE");
1218 break;
1219 default:
1220 pcm->matrix = strdup("L,C,R,SL,SR,BL,BR,LFE");
1221 pcm->mix = strdup("BDCKLFGE");
1222 break;
1225 while(fill*sizeof(float)<pcm->size){
1226 int current_section;
1227 int i,j;
1228 float pcmout[4096];
1229 long ret=op_read_float(of,pcmout,4096,&current_section);
1230 float *d = (float *)pcm->data;
1231 float *s = pcmout;
1233 if(current_section!=last_section){
1234 last_section=current_section;
1235 if(op_channel_count(of,-1) != pcm->ch){
1236 fprintf(stderr,"%s: Chained file changes channel count\n",path);
1237 goto err;
1241 if(ret<0){
1242 fprintf(stderr,"%s: Error while decoding file\n",path);
1243 goto err;
1245 if(ret==0){
1246 fprintf(stderr,"%s: Audio data ended prematurely\n",path);
1247 goto err;
1250 for(i=0;i<ret;i++)
1251 for(j=0;j<pcm->ch;j++)
1252 d[fill++]=*s++;
1254 if (sb_verbose && (throttle&0x3f)==0)
1255 fprintf(stderr,"\rLoading %s: %ld to go... ",pcm->name,(long)(pcm->size-fill*sizeof(float)));
1256 throttle++;
1258 op_free(of);
1260 if(sb_verbose)
1261 fprintf(stderr,"\rLoading %s: loaded. ",pcm->name);
1263 return pcm;
1264 err:
1265 op_free(of);
1266 free_pcm(pcm);
1267 return NULL;
1270 #define MAX_ID_LEN 36
1271 unsigned char buf[MAX_ID_LEN];
1273 /* Define the supported formats here */
1274 static input_format formats[] = {
1275 {wav_id, wav_load, "wav"},
1276 {aiff_id, aiff_load, "aiff"},
1277 {flac_id, flac_load, "flac"},
1278 {oggflac_id, oggflac_load,"oggflac"},
1279 {vorbis_id, vorbis_load, "oggvorbis"},
1280 {opus_id, opus_load, "oggopus"},
1281 {sw_id, sw_load, "sw"},
1282 {NULL, NULL, NULL}
1285 pcm_t *load_audio_file(char *path){
1286 FILE *f = fopen(path,"rb");
1287 int j=0;
1288 int fill;
1290 if(!f){
1291 fprintf(stderr,"Unable to open file %s: %s\n",path,strerror(errno));
1292 return NULL;
1295 fill = fread(buf, 1, MAX_ID_LEN, f);
1296 if(fill<MAX_ID_LEN){
1297 fprintf(stderr,"%s: Input file truncated or NULL\n",path);
1298 fclose(f);
1299 return NULL;
1302 while(formats[j].id_func){
1303 if(formats[j].id_func(path,buf)){
1304 pcm_t *ret=formats[j].load_func(path,f);
1305 fclose(f);
1306 return ret;
1308 j++;
1310 fprintf(stderr,"%s: Unrecognized file format\n",path);
1311 return NULL;
1314 void free_pcm(pcm_t *pcm){
1315 if(pcm){
1316 if(pcm->name)free(pcm->name);
1317 if(pcm->matrix)free(pcm->matrix);
1318 if(pcm->mix)free(pcm->mix);
1319 if(pcm->data)free(pcm->data);
1320 memset(pcm,0,sizeof(*pcm));
1321 free(pcm);