1 // Copyright (C) 1999-2005 Open Source Telecom Corporation.
2 // Copyright (C) 2006-2014 David Sugar, Tycho Softworks.
3 // Copyright (C) 2015 Cherokees of Idaho.
4 //
5 // This file is part of GNU ccAudio2.
6 //
7 // GNU ccAudio2 is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU Lesser General Public License as published
9 // by the Free Software Foundation, either version 3 of the License, or
10 // (at your option) any later version.
11 //
12 // GNU ccAudio2 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 Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with GNU ccAudio2.  If not, see <http://www.gnu.org/licenses/>.
19 
20 #include <ucommon/ucommon.h>
21 #include <ccaudio2-config.h>
22 #ifdef  HAVE_ENDIAN_H
23 #include <sys/endian.h>
24 #ifndef __BYTE_ORDER
25 #define __LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
26 #define __BIG_ENDIAN    (_BYTE_ORDER == _BIG_ENDIAN)
27 #define __BYTE_ORDER _BYTE_ORDER
28 #endif
29 #endif
30 #include <ucommon/export.h>
31 #include <ccaudio2.h>
32 
33 #if defined(__GNUC__)
34 #define _PACKED
35 #elif !defined(__hpux) && !defined(_AIX)
36 #define _PACKED
37 #endif
38 
39 #if !defined(__BIG_ENDIAN)
40 #define __LITTLE_ENDIAN 1234
41 #define __BIG_ENDIAN    4321
42 #define __PDP_ENDIAN    3412
43 #define __BYTE_ORDER    __LITTLE_ENDIAN
44 #endif
45 
46 namespace ucommon {
47 
48 #ifdef  _PACKED
49 #pragma pack(1)
50 #endif
51 
52 typedef struct {
53 #if __BYTE_ORDER == __LITTLE_ENDIAN
54     unsigned char mp_sync1 : 8;
55     unsigned char mp_crc   : 1;
56     unsigned char mp_layer : 2;
57     unsigned char mp_ver   : 2;
58     unsigned char mp_sync2 : 3;
59 
60     unsigned char mp_priv  : 1;
61     unsigned char mp_pad   : 1;
62     unsigned char mp_srate : 2;
63     unsigned char mp_brate : 4;
64 
65     unsigned char mp_emp   : 2;
66     unsigned char mp_original : 1;
67     unsigned char mp_copyright: 1;
68     unsigned char mp_extend   : 2;
69     unsigned char mp_channels : 2;
70 
71 #else
72     unsigned char mp_sync1 : 8;
73 
74     unsigned char mp_sync2 : 3;
75     unsigned char mp_ver   : 2;
76     unsigned char mp_layer : 2;
77     unsigned char mp_crc   : 1;
78 
79     unsigned char mp_brate : 4;
80     unsigned char mp_srate : 2;
81     unsigned char mp_pad   : 1;
82     unsigned char mp_priv  : 1;
83 
84     unsigned char mp_channels : 2;
85     unsigned char mp_extend   : 2;
86     unsigned char mp_copyright : 1;
87     unsigned char mp_original : 1;
88     unsigned char mp_emp : 2;
89 #endif
90 }   mpeg_audio;
91 
92 typedef struct {
93     char tag_id[3];
94     char tag_title[30];
95     char tag_artist[30];
96     char tag_album[30];
97     char tag_year[4];
98     char tag_note[30];
99     unsigned char genre;
100 }   mpeg_tagv1;
101 
102 #ifdef  _PACKED
103 #pragma pack()
104 #endif
105 
106 static const char * const ErrorStrs[] = {
107     "errSuccess",
108     "errReadLast",
109     "errNotOpened",
110     "errEndOfFile",
111     "errStartOfFile",
112     "errRateInvalid",
113     "errEncodingInvalid",
114     "errReadInterrupt",
115     "errWriteInterrupt",
116     "errReadFailure",
117     "errWriteFailure",
118     "errReadIncomplete",
119     "errWriteIncomplete",
120     "errRequestInvalid",
121     "errTOCFailed",
122     "errStatFailed",
123     "errInvalidTrack",
124     "errPlaybackFailed",
125     "errNotPlaying"
126 };
127 
mp3info(Audio::Info & info,mpeg_audio * mp3)128 static void mp3info(Audio::Info& info, mpeg_audio *mp3)
129 {
130     info.headersize = 4;
131     info.padding = 0;
132 
133     if(mp3->mp_pad)
134         info.padding = 1;
135 
136     switch(mp3->mp_layer) {
137     case 0x03:
138         if(mp3->mp_pad)
139             info.padding = 4;
140         info.encoding = Audio::mp1Audio;
141         break;
142     case 0x02:
143         info.encoding = Audio::mp2Audio;
144         break;
145     case 0x01:
146         info.encoding = Audio::mp3Audio;
147         break;
148     }
149 
150     switch(mp3->mp_ver) {
151     case 0x03:
152         info.bitrate = 32000;
153         switch(mp3->mp_srate) {
154         case 00:
155             info.rate = 44100;
156             break;
157         case 01:
158             info.rate = 48000;
159             break;
160         case 02:
161             info.rate = 32000;
162         }
163         switch(mp3->mp_layer) {
164         case 0x03:
165             info.bitrate = 32000 * mp3->mp_brate;
166             break;
167         case 0x02:
168             if(mp3->mp_brate < 8)
169                 info.bitrate = 16000 * (mp3->mp_brate + 1);
170             else
171                 info.bitrate = 32000 * (mp3->mp_brate - 4);
172             break;
173         case 0x01:
174             switch(mp3->mp_brate) {
175             case 0x02:
176                 info.bitrate = 40000;
177                 break;
178             case 0x03:
179                 info.bitrate = 48000;
180                 break;
181             case 0x04:
182                 info.bitrate = 56000;
183                 break;
184             case 0x05:
185                 info.bitrate = 64000;
186                 break;
187             case 0x06:
188                 info.bitrate = 80000;
189                 break;
190             case 0x07:
191                 info.bitrate = 96000;
192                 break;
193             case 0x08:
194                 info.bitrate = 112000;
195                 break;
196             case 0x09:
197                 info.bitrate = 128000;
198                 break;
199             case 0x0a:
200                 info.bitrate = 160000;
201                 break;
202             case 0x0b:
203                 info.bitrate = 192000;
204                 break;
205             case 0x0c:
206                 info.bitrate = 224000;
207                 break;
208             case 0x0d:
209                 info.bitrate = 256000;
210                 break;
211             case 0x0e:
212                 info.bitrate = 320000;
213                 break;
214             }
215             break;
216         }
217         break;
218     case 0x00:
219         switch(mp3->mp_srate) {
220         case 00:
221             info.rate = 11025;
222             break;
223         case 01:
224             info.rate = 12000;
225             break;
226         case 02:
227             info.rate = 8000;
228             break;
229         }
230     case 0x02:
231         if(mp3->mp_ver == 0x02) {
232             switch(mp3->mp_srate) {
233             case 00:
234                 info.rate = 22050;
235                 break;
236             case 01:
237                 info.rate = 24000;
238                 break;
239             case 02:
240                 info.rate = 16000;
241                 break;
242             }
243         }
244         switch(mp3->mp_layer) {
245         case 0x03:
246             if(mp3->mp_brate < 0x0d)
247                 info.bitrate = 16000 * (mp3->mp_brate + 1);
248             else if(mp3->mp_brate == 0x0d)
249                 info.bitrate = 224000;
250             else
251                 info.bitrate = 256000;
252             break;
253         case 0x02:
254         case 0x01:
255             if(mp3->mp_brate < 9)
256                 info.bitrate = 8000 * mp3->mp_brate;
257             else
258                 info.bitrate = 16000 * (mp3->mp_brate - 4);
259         }
260     }
261 
262     if(mp3->mp_crc)
263         info.headersize = 6;
264 
265     info.set();
266 }
267 
268 
269 
getCodec(void)270 AudioCodec *AudioFile::getCodec(void)
271 {
272     Encoding e = getEncoding();
273     switch(e) {
274     case alawAudio:
275         return AudioCodec::get(e, "g.711");
276     case mulawAudio:
277         return AudioCodec::get(e, "g.711");
278     case g721ADPCM:
279     case okiADPCM:
280     case voxADPCM:
281         return AudioCodec::get(e, "g.721");
282     case g722_7bit:
283     case g722_6bit:
284         return AudioCodec::get(e, "g.722");
285     case g723_3bit:
286     case g723_5bit:
287         return AudioCodec::get(e, "g.723");
288     default:
289         return NULL;
290     }
291 }
292 
setShort(unsigned char * data,unsigned short val)293 void AudioFile::setShort(unsigned char *data, unsigned short val)
294 {
295     if(info.order == __BIG_ENDIAN) {
296         data[0] = val / 256;
297         data[1] = val % 256;
298     }
299     else {
300         data[1] = val / 256;
301         data[0] = val % 256;
302     }
303 }
304 
getShort(unsigned char * data) const305 unsigned short AudioFile::getShort(unsigned char *data) const
306 {
307     if(info.order == __BIG_ENDIAN)
308         return data[0] * 256 + data[1];
309     else
310         return data[1] * 256 + data[0];
311 }
312 
setLong(unsigned char * data,unsigned long val)313 void AudioFile::setLong(unsigned char *data, unsigned long val)
314 {
315     int i = 4;
316 
317     while(i-- > 0) {
318         if(info.order == __BIG_ENDIAN)
319             data[i] = (unsigned char)(val & 0xff);
320         else
321             data[3 - i] = (unsigned char)(val & 0xff);
322         val /= 256;
323     }
324 }
325 
getLong(unsigned char * data) const326 unsigned long AudioFile::getLong(unsigned char * data) const
327 {
328     int i = 4;
329     unsigned long val =0;
330 
331     while(i-- > 0) {
332         if(info.order == __BIG_ENDIAN)
333             val = (val << 8) | data[3 - i];
334         else
335             val = (val << 8) | data[i];
336     }
337     return val;
338 }
339 
AudioFile(const char * name,unsigned long sample)340 AudioFile::AudioFile(const char *name, unsigned long sample) :
341 AudioBase()
342 {
343     pathname = NULL;
344     initialize();
345     AudioFile::open(name);
346     if(!is_open())
347         return;
348     setPosition(sample);
349 }
350 
AudioFile(const char * name,Info * inf,unsigned long samples)351 AudioFile::AudioFile(const char *name, Info *inf, unsigned long samples) :
352 AudioBase(inf)
353 {
354     pathname = NULL;
355     initialize();
356     AudioFile::create(name, inf);
357     if(!is_open())
358         return;
359     setMinimum(samples);
360 }
361 
~AudioFile()362 AudioFile::~AudioFile()
363 {
364     AudioFile::close();
365     AudioFile::clear();
366 }
367 
create(const char * name,Info * myinfo,bool exclusive,timeout_t framing)368 void AudioFile::create(const char *name, Info *myinfo, bool exclusive, timeout_t framing)
369 {
370     int pcm = 0;
371     unsigned char aufile[24];
372     unsigned char riffhdr[40];
373     const char *ext = strrchr(name, '/');
374 
375     if(!ext)
376         ext = strrchr(name, '\\');
377 
378     if(!ext)
379         ext = strrchr(name, ':');
380 
381     if(!ext)
382         ext = strrchr(name, '.');
383     else
384         ext = strrchr(ext, '.');
385 
386     if(!ext)
387         ext = ".none";
388 
389     mode = modeWrite;
390 
391     if(!afCreate(name, exclusive))
392         return;
393 
394     memset(riffhdr, 0, sizeof(riffhdr));
395     memcpy(&info, myinfo, sizeof(info));
396     info.annotation = NULL;
397     pathname = new char[strlen(name) + 1];
398     strcpy(pathname, name);
399     if(myinfo->annotation) {
400         info.annotation = new char[strlen(myinfo->annotation) + 1];
401         strcpy(info.annotation, myinfo->annotation);
402     }
403 
404     if(!stricmp(ext, ".raw") || !stricmp(ext, ".bin")) {
405         info.format = raw;
406         if(info.encoding == unknownEncoding)
407             info.encoding = pcm16Mono;
408     }
409     else if(!stricmp(ext, ".au") || !stricmp(ext, ".snd"))
410     {
411         info.order = 0;
412         info.format = snd;
413     }
414     else if(!stricmp(ext, ".wav") || !stricmp(ext, ".wave"))
415     {
416         info.order = 0;
417         info.format = wave;
418     }
419     else if(!stricmp(ext, ".ul") || !stricmp(ext, ".ulaw") || !stricmp(ext, ".mulaw"))
420     {
421         info.encoding = mulawAudio;
422         info.format = raw;
423         info.order = 0;
424         info.rate = 8000;
425     }
426     else if(!stricmp(ext, ".al") || !stricmp(ext, ".alaw"))
427     {
428         info.encoding = alawAudio;
429         info.format = raw;
430         info.order = 0;
431         info.rate = 8000;
432     }
433     else if(!stricmp(ext, ".sw") || !stricmp(ext, ".pcm"))
434     {
435         info.encoding = pcm16Mono;
436         info.format = raw;
437         info.order = 0;
438     }
439     else if(!stricmp(ext, ".vox"))
440     {
441         info.encoding = voxADPCM;
442         info.format = raw;
443         info.order = 0;
444         info.rate = 6000;
445     }
446     else if(!stricmp(ext, ".gsm"))
447     {
448         info.encoding = gsmVoice;
449         info.format = raw;
450         info.order = 0;
451         info.rate = 8000;
452         info.framecount = 160;
453         info.framesize = 33;
454         info.bitrate = 13200;
455     }
456     else if(!stricmp(ext, ".adpcm") || !stricmp(ext, ".a32"))
457     {
458         info.encoding = g721ADPCM;
459         info.format = raw;
460         info.order = 0;
461         info.rate = 8000;
462     }
463     else if(!stricmp(ext, ".a24"))
464     {
465         info.encoding = g723_3bit;
466         info.format = raw;
467         info.order = 0;
468         info.rate = 8000;
469     }
470     else if(!stricmp(ext, ".a16"))
471     {
472         info.encoding = g723_2bit;
473         info.format = raw;
474         info.order = 0;
475         info.order = 8000;
476     }
477     else if(!stricmp(ext, ".sx"))
478     {
479         info.encoding = sx96Voice;
480         info.format = raw;
481         info.order = 0;
482         info.rate = 8000;
483     }
484     else if(!stricmp(ext, ".a40"))
485     {
486         info.encoding = g723_5bit;
487         info.format = raw;
488         info.order = 0;
489         info.rate = 8000;
490     }
491     else if(!stricmp(ext, ".cda"))
492     {
493         info.encoding = cdaStereo;
494         info.format = raw;
495         info.order = __LITTLE_ENDIAN;
496         info.rate = 44100;
497     }
498 
499     switch(info.format) {
500     case wave:
501     case riff:
502         /*
503          * RIFF header
504          *
505          * 12 bytes
506          *
507          * 0-3: RIFF magic "RIFF" (0x52 49 46 46)
508          *
509          * 4-7: RIFF header chunk size
510          *      (4 + (8 + subchunk 1 size) + (8 + subchunk 2 size))
511          *
512          * 8-11: WAVE RIFF type magic "WAVE" (0x57 41 56 45)
513          */
514         if(!info.order)
515             info.order = __LITTLE_ENDIAN;
516         if(info.order == __LITTLE_ENDIAN)
517             strncpy((char *)riffhdr, "RIFF", 4);
518         else
519             strncpy((char *)riffhdr, "RIFX", 4);
520         if(!info.rate)
521             info.rate = Audio::getRate(info.encoding);
522         if(!info.rate)
523             info.rate = rate8khz;
524 
525         header = 0;
526 
527         memset(riffhdr + 4, 0xff, 4);
528         strncpy((char *)riffhdr + 8, "WAVE", 4);
529         if(afWrite(riffhdr, 12) != 12) {
530             AudioFile::close();
531             return;
532         }
533 
534         /*
535          * Subchunk 1: WAVE metadata
536          *
537          * Length: 24+
538          *
539          * (offset from start of subchunk 1) startoffset-endoffset
540          *
541          * (0) 12-15: WAVE metadata magic "fmt " (0x 66 6d 74 20)
542          *
543          * (4) 16-19: subchunk 1 size minus 8.  0x10 for PCM.
544          *
545          * (8) 20-21: Audio format code.  0x01 for linear PCM.
546          * More codes here:
547          * http://www.goice.co.jp/member/mo/formats/wav.html
548          *
549          * (10) 22-23: Number of channels.  Mono = 0x01,
550          * Stereo = 0x02.
551          *
552          * (12) 24-27: Sample rate in samples per second. (8000,
553          * 44100, etc)
554          *
555          * (16) 28-31: Bytes per second = SampleRate *
556          * NumChannels * (BitsPerSample / 8)
557          *
558          * (20) 32-33: Block align (the number of bytes for
559          * one multi-channel sample) = Numchannels *
560          * (BitsPerSample / 8)
561          *
562          * (22) 34-35: Bits per single-channel sample.  8 bits
563          * per channel sample = 0x8, 16 bits per channel
564          * sample = 0x10
565          *
566          * (24) 36-37: Size of extra PCM parameters for
567          * non-PCM formats.  If a PCM format code is
568          * specified, this doesn't exist.
569          *
570          * Subchunk 3: Optional 'fact' subchunk for non-PCM formats
571          * (26) 38-41: WAVE metadata magic 'fact' (0x 66 61 63 74)
572          *
573          * (30) 42-45: Length of 'fact' subchunk, not
574          * including this field and the fact
575          * identification field (usually 4)
576          *
577          * (34) 46-49: ??? sndrec32.exe outputs 0x 00 00 00 00
578          * here.  See
579          * http://www.health.uottawa.ca/biomech/csb/ARCHIVES/riff-for.txt
580          *
581          */
582 
583         memset(riffhdr, 0, sizeof(riffhdr));
584         strncpy((char *)riffhdr, "fmt ", 4);
585         // FIXME A bunch of the following only works for PCM
586         // and mulaw/alaw, so you'll probably have to fix it
587         // if you want to use one of the other formats.
588         if(info.encoding < cdaStereo)
589             setLong(riffhdr + 4, 18);
590         else
591             setLong(riffhdr + 4, 16);
592 
593         setShort(riffhdr + 8, 0x01); // default in case invalid encoding specified
594         if(is_mono(info.encoding))
595             setShort(riffhdr + 10, 1);
596         else
597             setShort(riffhdr + 10, 2);
598         setLong(riffhdr + 12, info.rate);
599         setLong(riffhdr + 16, (unsigned long)toBytes(info, info.rate));
600         setShort(riffhdr + 20, (snd16_t)toBytes(info, 1));
601         setShort(riffhdr + 22, 0);
602 
603         switch(info.encoding) {
604         case pcm8Mono:
605         case pcm8Stereo:
606             setShort(riffhdr + 22, 8);
607             pcm = 1;
608             break;
609         case pcm16Mono:
610         case pcm16Stereo:
611         case cdaMono:
612         case cdaStereo:
613             setShort(riffhdr + 22, 16);
614             pcm = 1;
615             break;
616         case pcm32Mono:
617         case pcm32Stereo:
618             setShort(riffhdr + 22, 32);
619             pcm = 1;
620             break;
621         case alawAudio:
622             setShort(riffhdr + 8, 6);
623             setShort(riffhdr + 22, 8);
624             break;
625         case mulawAudio:
626             setShort(riffhdr + 8, 7);
627             setShort(riffhdr + 22, 8);
628             break;
629 
630             // FIXME I'm pretty sure these are supposed to
631             // be writing to offset 22 instead of 24...
632         case okiADPCM:
633             setShort(riffhdr + 8, 0x10);
634             setShort(riffhdr + 24, 4);
635             break;
636         case voxADPCM:
637             setShort(riffhdr + 8, 0x17);
638             setShort(riffhdr + 24, 4);
639             break;
640         case g721ADPCM:
641             setShort(riffhdr + 8, 0x40);
642             setShort(riffhdr + 24, 4);
643             break;
644         case g722Audio:
645             setShort(riffhdr + 8, 0x64);
646             setShort(riffhdr + 24, 8);
647             break;
648         case gsmVoice:
649         case msgsmVoice:
650             setShort(riffhdr + 8, 0x31);
651             setShort(riffhdr + 24, 260);
652             break;
653         case g723_3bit:
654             setShort(riffhdr + 8, 0x14);
655             setShort(riffhdr + 24, 3);
656             break;
657         case g723_5bit:
658             setShort(riffhdr + 8, 0x14);
659             setShort(riffhdr + 24, 5);
660         case unknownEncoding:
661         default:
662             break;
663         }
664 
665         if(pcm == 0) {
666             setShort(riffhdr + 24, 0);
667             strncpy((char *)(riffhdr + 26), "fact", 4);
668             setLong(riffhdr + 30, 4);
669             setLong(riffhdr + 34, 0);
670             if(afWrite(riffhdr, 38) != 38) {
671                 AudioFile::close();
672                 return;
673             }
674         }
675         else {
676             if(afWrite(riffhdr, 24) != 24) {
677                 AudioFile::close();
678                 return;
679             }
680         }
681 
682         /*
683          * Subchunk 2: data subchunk
684          *
685          * Length: 8+
686          *
687          * (0) 36-39: data subchunk magic "data" (0x 64 61 74 61)
688          *
689          * (4) 40-43: subchunk 2 size =
690          * NumSamples * NumChannels * (BitsPerSample / 8)
691          * Note that this does not include the size of this
692          * field and the previous one.
693          *
694          * (8) 44+: Samples
695          */
696 
697         memset(riffhdr, 0, sizeof(riffhdr));
698         strncpy((char *)riffhdr, "data", 4);
699         memset(riffhdr + 4, 0xff, 4);
700         if(afWrite(riffhdr, 8) != 8) {
701             AudioFile::close();
702             return;
703         }
704 
705         header = getAbsolutePosition();
706         length = getAbsolutePosition();
707         break;
708 
709     case snd:
710 //      if(!info.order)
711             info.order = __BIG_ENDIAN;
712 
713         if(!info.rate)
714             info.rate = Audio::getRate(info.encoding);
715         if(!info.rate)
716             info.rate = rate8khz;
717 
718         strncpy((char *)aufile, ".snd", 4);
719         if(info.annotation)
720             setLong(aufile + 4, 24 + (unsigned long)strlen(info.annotation) + 1);
721         else
722             setLong(aufile + 4, 24);
723         header = getLong(aufile + 4);
724         setLong(aufile + 8, ~0l);
725         switch(info.encoding) {
726         case pcm8Stereo:
727         case pcm8Mono:
728             setLong(aufile + 12, 2);
729             break;
730         case pcm16Stereo:
731         case pcm16Mono:
732         case cdaStereo:
733         case cdaMono:
734             setLong(aufile + 12, 3);
735             break;
736         case pcm32Stereo:
737         case pcm32Mono:
738             setLong(aufile + 12, 5);
739             break;
740         case g721ADPCM:
741             setLong(aufile + 12, 23);
742             break;
743         case g722Audio:
744         case g722_7bit:
745         case g722_6bit:
746             setLong(aufile + 12, 24);
747             break;
748         case g723_3bit:
749             setLong(aufile + 12, 25);
750             break;
751         case g723_5bit:
752             setLong(aufile + 12, 26);
753             break;
754         case gsmVoice:
755             setLong(aufile + 12, 28);
756             break;
757         case alawAudio:
758             setLong(aufile + 12, 27);
759             break;
760         default:
761             setLong(aufile + 12, 1);
762         }
763         setLong(aufile + 16, info.rate);
764         if(is_mono(info.encoding))
765             setLong(aufile + 20, 1);
766         else
767             setLong(aufile + 20, 2);
768         if(afWrite(aufile, 24) != 24) {
769             AudioFile::close();
770             return;
771         }
772         if(info.annotation)
773             afWrite((unsigned char *)info.annotation, (unsigned long)strlen(info.annotation) + 1);
774         header = getAbsolutePosition();
775         length = getAbsolutePosition();
776         break;
777     case mpeg:
778         framing = 0;
779         info.headersize = 4;    // no crc...
780     case raw:
781         break;
782     }
783     if(framing)
784         info.setFraming(framing);
785     else
786         info.set();
787 }
788 
getWaveFormat(int request)789 void AudioFile::getWaveFormat(int request)
790 {
791     unsigned char filehdr[24];
792     int bitsize;
793     int channels;
794 
795     if(request > 24)
796         request = 24;
797 
798     if(!afPeek(filehdr, request)) {
799         AudioFile::close();
800         return;
801     }
802     channels = getShort(filehdr + 2);
803     info.rate = getLong(filehdr + 4);
804 
805     switch(getShort(filehdr)) {
806     case 1:
807         bitsize = getShort(filehdr + 14);
808         switch(bitsize) {
809         case 8:
810             if(channels > 1)
811                 info.encoding = pcm8Stereo;
812             else
813                 info.encoding = pcm8Mono;
814             break;
815         case 16:
816             if(info.rate == 44100) {
817                 if(channels > 1)
818                     info.encoding = cdaStereo;
819                 else
820                     info.encoding = cdaMono;
821                 break;
822             }
823             if(channels > 1)
824                     info.encoding = pcm16Stereo;
825             else
826                 info.encoding = pcm16Mono;
827             break;
828         case 32:
829             if(channels > 1)
830                 info.encoding = pcm32Stereo;
831             else
832                 info.encoding = pcm32Mono;
833             break;
834         default:
835             info.encoding = unknownEncoding;
836         }
837         break;
838     case 6:
839         info.encoding = alawAudio;
840         break;
841     case 7:
842         info.encoding = mulawAudio;
843         break;
844     case 0x10:
845         info.encoding = okiADPCM;
846         break;
847     case 0x17:
848         info.encoding = voxADPCM;
849         break;
850     case 0x40:
851         info.encoding = g721ADPCM;
852         break;
853     case 0x65:
854         info.encoding = g722Audio;
855         break;
856     case 0x31:
857         info.encoding = msgsmVoice;
858         break;
859     case 0x14:
860         bitsize = getLong(filehdr + 8) * 8 / info.rate;
861         if(bitsize == 3)
862             info.encoding = g723_3bit;
863         else
864             info.encoding = g723_5bit;
865         break;
866     default:
867         info.encoding = unknownEncoding;
868     }
869 }
870 
open(const char * name,Mode m,timeout_t framing)871 void AudioFile::open(const char *name, Mode m, timeout_t framing)
872 {
873     unsigned char filehdr[24];
874     unsigned int count;
875     char *ext;
876     unsigned channels;
877     mpeg_audio *mp3 = (mpeg_audio *)&filehdr;
878     mode = m;
879 
880 
881     while(!afOpen(name, m)) {
882         if(mode == modeReadAny || mode == modeReadOne)
883             name = getContinuation();
884         else
885             name = NULL;
886 
887         if(!name)
888             return;
889     }
890 
891     pathname = new char[strlen(name) + 1];
892     strcpy(pathname, name);
893     header = 0l;
894 
895     info.framesize = 0;
896     info.framecount = 0;
897     info.encoding = mulawAudio;
898     info.format = raw;
899     info.order = 0;
900     ext = strrchr(pathname, '.');
901     if(!ext)
902         goto done;
903 
904     info.encoding = Audio::getEncoding(ext);
905     switch(info.encoding) {
906     case cdaStereo:
907         info.order = __LITTLE_ENDIAN;
908         break;
909     case unknownEncoding:
910         info.encoding = mulawAudio;
911     default:
912         break;
913     }
914 
915     strcpy((char *)filehdr, ".xxx");
916 
917     if(!afPeek(filehdr, 24)) {
918         AudioFile::close();
919         return;
920     }
921 
922     if(!strncmp((char *)filehdr, "RIFF", 4)) {
923         info.format = riff;
924         info.order = __LITTLE_ENDIAN;
925     }
926 
927     if(!strncmp((char *)filehdr, "RIFX", 4)) {
928         info.order = __BIG_ENDIAN;
929         info.format = riff;
930     }
931 
932     if(!strncmp((char *)filehdr + 8, "WAVE", 4) && info.format == riff) {
933         header = 12;
934         for(;;)
935         {
936             if(!afSeek(header)) {
937                 AudioFile::close();
938                 return;
939             }
940             if(!afPeek(filehdr, 8)) {
941                 AudioFile::close();
942                 return;
943             }
944             header += 8;
945             if(!strncmp((char *)filehdr, "data", 4))
946                 break;
947 
948             count = getLong(filehdr + 4);
949             header += count;
950             if(!strncmp((char *)filehdr, "fmt ", 4))
951                 getWaveFormat(count);
952 
953         }
954         afSeek(header);
955         goto done;
956     }
957     if(!strncmp((char *)filehdr, ".snd", 4)) {
958         info.format = snd;
959         info.order = __BIG_ENDIAN;
960         header = getLong(filehdr + 4);
961         info.rate = getLong(filehdr + 16);
962         channels = getLong(filehdr + 20);
963 
964         switch(getLong(filehdr + 12)) {
965         case 2:
966             if(channels > 1)
967                 info.encoding = pcm8Stereo;
968             else
969                 info.encoding = pcm8Mono;
970             break;
971         case 3:
972             if(info.rate == 44100) {
973                 if(channels > 1)
974                     info.encoding = cdaStereo;
975                 else
976                     info.encoding = cdaMono;
977                 break;
978             }
979             if(channels > 1)
980                 info.encoding = pcm16Stereo;
981             else
982                 info.encoding = pcm16Mono;
983             break;
984         case 5:
985             if(channels > 1)
986                 info.encoding = pcm32Stereo;
987             else
988                 info.encoding = pcm32Mono;
989             break;
990         case 23:
991             info.encoding = g721ADPCM;
992             break;
993         case 24:
994             info.encoding = g722Audio;
995             break;
996         case 25:
997             info.encoding = g723_3bit;
998             break;
999         case 26:
1000             info.encoding = g723_5bit;
1001             break;
1002         case 27:
1003             info.encoding = alawAudio;
1004             break;
1005         case 28:
1006             info.encoding = gsmVoice;
1007             break;
1008         case 1:
1009             info.encoding = mulawAudio;
1010             break;
1011         default:
1012             info.encoding = unknownEncoding;
1013         }
1014         if(header > 24) {
1015             info.annotation = new char[header - 24];
1016             afSeek(24);
1017             afRead((unsigned char *)info.annotation, header - 24);
1018         }
1019         goto done;
1020     }
1021 
1022     if(!strnicmp((char *)filehdr, "ID3", 3)) {
1023         afSeek(10);
1024         info.order = __BIG_ENDIAN;
1025         header = 10;
1026         if(filehdr[5] & 0x10)
1027             header += 10;   // footer
1028 
1029         header += (filehdr[9] & 0x7f);
1030         header += (filehdr[8] & 0x7f) * 128;
1031         header += (filehdr[7] & 0x7f) * 128 * 128;
1032         header += (filehdr[6] & 0x7f) * 128 * 128 * 128;
1033         afSeek(header);
1034         afRead(filehdr, 4);
1035         goto mp3;
1036     }
1037 
1038     if(mp3->mp_sync1 == 0xff && mp3->mp_sync2 == 0x07)
1039         goto mp3;
1040     else
1041         afSeek(0);
1042 
1043     goto done;
1044 
1045 mp3:
1046     //framing = 0;
1047     afSeek(header);
1048 
1049     info.order = __BIG_ENDIAN;
1050     info.format = mpeg;
1051     mp3info(info, mp3);
1052     return;
1053 
1054 done:
1055     info.headersize = 0;
1056     if(framing)
1057         info.setFraming(framing);
1058     else
1059         info.set();
1060 
1061     if(mode == modeFeed) {
1062         setPosition();
1063         iolimit = (unsigned long)toBytes(info, getPosition());
1064         setPosition(0);
1065     }
1066 }
1067 
Info()1068 Audio::Info::Info()
1069 {
1070     clear();
1071 }
1072 
Info(const Info & copy)1073 Audio::Info::Info(const Info& copy)
1074 {
1075     format = copy.format;
1076     encoding = copy.encoding;
1077     rate = copy.rate;
1078     bitrate = copy.bitrate;
1079     order = copy.order;
1080     framesize = copy.framesize;
1081     framecount = copy.framecount;
1082     headersize = copy.headersize;
1083     padding = copy.padding;
1084     framing = copy.framing;
1085     annotation = copy.annotation;
1086 }
1087 
clear(void)1088 void Audio::Info::clear(void)
1089 {
1090     memset(this, 0, sizeof(Info));
1091 }
1092 
setRate(Rate r)1093 void Audio::Info::setRate(Rate r)
1094 {
1095     rate = getRate(encoding, r);
1096     set();
1097 }
1098 
setFraming(timeout_t timeout)1099 void Audio::Info::setFraming(timeout_t timeout)
1100 {
1101     set();
1102 
1103     framing = getFraming(encoding);
1104 
1105     if(!timeout)
1106         return;
1107 
1108     if(framing) {
1109         timeout = (timeout / framing);
1110         if(!timeout)
1111             timeout = framing;
1112         else
1113             timeout = timeout * framing;
1114     }
1115 
1116     switch(timeout) {
1117     case 10:
1118     case 15:
1119     case 20:
1120     case 30:
1121     case 40:
1122         break;
1123     default:
1124         timeout = 20;
1125     }
1126 
1127     framing = timeout;
1128     framecount = (rate * framing) / 1000l;
1129     framesize = (unsigned)toBytes(encoding, framecount);
1130 }
1131 
set(void)1132 void Audio::Info::set(void)
1133 {
1134 
1135     switch(encoding) {
1136     case mp1Audio:
1137         framecount = 384;
1138         framesize = (12 * bitrate / rate) * 4 + headersize + padding;
1139         return;
1140     case mp2Audio:
1141     case mp3Audio:
1142         framecount = 1152;
1143         framesize = (144 * bitrate / rate) + headersize + padding;
1144         return;
1145     default:
1146         break;
1147     }
1148     if(!framesize)
1149         framesize = getFrame(encoding);
1150 
1151     if(!framecount)
1152         framecount = getCount(encoding);
1153 
1154     if(!rate)
1155         rate = getRate(encoding);
1156 
1157     if(!bitrate && rate && framesize && framecount)
1158         bitrate = ((long)framesize * 8l * rate) / (long)framecount;
1159 }
1160 
1161 
close(void)1162 void AudioFile::close(void)
1163 {
1164 #ifndef _MSWINDOWS_
1165     struct stat ino;
1166 #endif
1167 
1168     unsigned char buf[58];
1169     if(! is_open())
1170         return;
1171 
1172     if(mode != modeWrite) {
1173         afClose();
1174         clear();
1175         return;
1176     }
1177 
1178     if(! afSeek(0)) {
1179         afClose();
1180         clear();
1181         return;
1182     }
1183 
1184     if(-1 == afRead(buf, 58)) {
1185         afClose();
1186         clear();
1187         return;
1188     }
1189 
1190     afSeek(0);
1191 
1192     switch(info.format) {
1193     case riff:
1194     case wave:
1195 #ifndef _MSWINDOWS_
1196         fstat(file.fd, &ino);
1197         length = ino.st_size;
1198 #endif
1199         // RIFF header
1200         setLong(buf + 4, length - 8);
1201 
1202         // If it's a non-PCM datatype, the offsets are a bit
1203         // different for subchunk 2.
1204         switch(info.encoding) {
1205         case cdaStereo:
1206         case cdaMono:
1207         case pcm8Stereo:
1208         case pcm8Mono:
1209         case pcm16Stereo:
1210         case pcm16Mono:
1211         case pcm32Stereo:
1212         case pcm32Mono:
1213             setLong(buf + 40, length - header);
1214             break;
1215         default:
1216             setLong(buf + 54, length - header);
1217         }
1218 
1219         afWrite(buf, 58);
1220         break;
1221     case snd:
1222 #ifndef _MSWINDOWS_
1223         fstat(file.fd, &ino);
1224         length = ino.st_size;
1225 #endif
1226         setLong(buf + 8, length - header);
1227         afWrite(buf, 12);
1228         break;
1229     default:
1230         break;
1231     }
1232     afClose();
1233     clear();
1234 }
1235 
clear(void)1236 void AudioFile::clear(void)
1237 {
1238     if(pathname) {
1239         if(pathname)
1240             delete[] pathname;
1241         pathname = NULL;
1242     }
1243     if(info.annotation) {
1244         if(info.annotation)
1245             delete[] info.annotation;
1246         info.annotation = NULL;
1247     }
1248     minimum = 0;
1249     iolimit = 0;
1250 }
1251 
getInfo(Info * infobuf)1252 Audio::Error AudioFile::getInfo(Info *infobuf)
1253 {
1254     if(!is_open())
1255         return setError(errNotOpened);
1256 
1257     if(!infobuf)
1258         return setError(errRequestInvalid);
1259 
1260     memcpy(infobuf, &info, sizeof(info));
1261     return errSuccess;
1262 }
1263 
setError(Error err)1264 Audio::Error AudioFile::setError(Error err)
1265 {
1266     if(err)
1267         error = err;
1268     return err;
1269 }
1270 
getErrorStr(Error err) const1271 const char * AudioFile::getErrorStr(Error err) const
1272 {
1273     return ErrorStrs[err];
1274 }
1275 
setMinimum(unsigned long samples)1276 Audio::Error AudioFile::setMinimum(unsigned long samples)
1277 {
1278     if(!is_open())
1279         return setError(errNotOpened);
1280     minimum = samples;
1281     return errSuccess;
1282 }
1283 
getLinear(Linear addr,unsigned samples)1284 unsigned AudioFile::getLinear(Linear addr, unsigned samples)
1285 {
1286     unsigned rts = 0;
1287     int count;
1288     AudioCodec *codec;
1289 
1290     if(!samples)
1291         samples = info.framecount;
1292 
1293     if(getEncoding() == pcm16Mono) {
1294         count = getNative((Encoded)addr, samples * 2);
1295         if(count < 0)
1296             return 0;
1297         return count / 2;
1298     }
1299 
1300     codec = getCodec();
1301     if(!codec)
1302         return 0;
1303 
1304     count = getCount(info.encoding);
1305     samples = (samples / count) * count;
1306     count = (int)toBytes(info, samples);
1307 
1308     Encoded buffer = new unsigned char[count];
1309     count = getBuffer(buffer, count);
1310     if(count < 1) {
1311         delete[] buffer;
1312         return 0;
1313     }
1314 
1315     samples = toSamples(info, count);
1316     rts = codec->decode(addr, buffer, samples);
1317     delete[] buffer;
1318     return rts;
1319 }
1320 
putLinear(Linear addr,unsigned samples)1321 unsigned AudioFile::putLinear(Linear addr, unsigned samples)
1322 {
1323     int count;
1324     AudioCodec *codec;
1325 
1326     if(!samples)
1327         samples = info.framecount;
1328 
1329     if(getEncoding() == pcm16Mono) {
1330         count = putNative((Encoded)addr, samples * 2);
1331         if(count < 0)
1332             return 0;
1333         return count / 2;
1334     }
1335     codec = getCodec();
1336     if(!codec)
1337         return 0;
1338 
1339     count = getCount(info.encoding);
1340     samples = samples / count * count;
1341     count = (int)toBytes(info, samples);
1342 
1343     Encoded buffer = new unsigned char[count];
1344 
1345     samples = codec->encode(addr, buffer, samples);
1346     if(samples < 1) {
1347         delete[] buffer;
1348         return 0;
1349     }
1350     count = (int)toBytes(info, samples);
1351     count = putBuffer(buffer, count);
1352     delete[] buffer;
1353     if(count < 0)
1354         return 0;
1355     return toSamples(info, count);
1356 }
1357 
getBuffer(Encoded addr,size_t bytes)1358 ssize_t AudioFile::getBuffer(Encoded addr, size_t bytes)
1359 {
1360     Info prior;
1361     char *fname;
1362     int count;
1363     unsigned long curpos, xfer = 0;
1364     mpeg_audio *mp3 = (mpeg_audio *)addr;
1365 
1366     if(!bytes && info.format == mpeg) {
1367 rescan:
1368         count = afRead(addr, 4);
1369         if(count < 0)
1370             return count;
1371         if(count < 4)
1372             return 0;
1373         if(mp3->mp_sync1 != 0xff || mp3->mp_sync2 != 0x07) {
1374             afSeek(getAbsolutePosition() - 3);
1375             goto rescan;
1376         }
1377         mp3info(info, mp3);
1378         count = afRead(addr + 4, info.framesize - 4);
1379         if(count > 0)
1380             count += 4;
1381         return count;
1382     }
1383 
1384     if(!bytes)
1385         bytes = info.framesize;
1386 
1387     curpos = (unsigned long)toBytes(info, getPosition());
1388     if(curpos >= iolimit && mode == modeFeed) {
1389         curpos = 0;
1390         setPosition(0);
1391     }
1392     if (iolimit && ((curpos + bytes) > iolimit))
1393         bytes = iolimit - curpos;
1394 
1395     getInfo(&prior);
1396 
1397     for(;;)
1398     {
1399         count = afRead(addr, (unsigned)bytes);
1400         if(count < 0) {
1401             if(!xfer)
1402                 return count;
1403             return xfer;
1404         }
1405         xfer += count;
1406         if(count == (int)bytes)
1407             return xfer;
1408         if(mode == modeFeed) {
1409             setPosition(0l);
1410             goto cont;
1411         }
1412 
1413 retry:
1414         if(mode == modeReadOne)
1415             fname = NULL;
1416         else
1417             fname = getContinuation();
1418 
1419         if(!fname)
1420             return xfer;
1421         AudioFile::close();
1422         AudioFile::open(fname, modeRead, info.framing);
1423         if(!is_open()) {
1424             if(mode == modeReadAny)
1425                 goto retry;
1426             return xfer;
1427         }
1428 
1429         if(prior.encoding != info.encoding) {
1430             AudioFile::close();
1431             return xfer;
1432         }
1433 cont:
1434         bytes -= count;
1435         addr += count;
1436     }
1437 }
1438 
getSamples(void * addr,unsigned request)1439 Audio::Error AudioFile::getSamples(void *addr, unsigned request)
1440 {
1441     char *fname;
1442     unsigned char *caddr = (unsigned char *)addr;
1443     int count, bytes;
1444 
1445     if(!request)
1446         request = info.framecount;
1447 
1448     for(;;)
1449     {
1450         bytes = (int)toBytes(info, request);
1451         if(bytes < 1)
1452             return setError(errRequestInvalid);
1453         count = afRead(caddr, bytes);
1454         if(count == bytes)
1455             return errSuccess;
1456 
1457         if(count < 0)
1458             return errReadFailure;
1459 
1460         if(count > 0) {
1461             caddr += count;
1462             count = request - toSamples(info.encoding, count);
1463         }
1464         else
1465             count = request;
1466 
1467         if(mode == modeFeed) {
1468             setPosition(0);
1469             request = count;
1470             continue;
1471         }
1472 
1473 retry:
1474         if(mode == modeReadOne)
1475             fname = NULL;
1476         else
1477             fname = getContinuation();
1478 
1479         if(!fname)
1480             break;
1481 
1482         AudioFile::close();
1483         AudioFile::open(fname, modeRead);
1484         if(!is_open()) {
1485             if(mode == modeReadAny)
1486                 goto retry;
1487             break;
1488         }
1489 
1490         request = count;
1491     }
1492     if(count)
1493         Audio::fill(caddr, count, info.encoding);
1494     return errReadIncomplete;
1495 }
1496 
putBuffer(Encoded addr,size_t len)1497 ssize_t AudioFile::putBuffer(Encoded addr, size_t len)
1498 {
1499     int count;
1500     unsigned long curpos;
1501     mpeg_audio *mp3 = (mpeg_audio *)addr;
1502 
1503     if(!len && info.format == mpeg) {
1504         mp3info(info, mp3);
1505         len = info.framesize;
1506     }
1507 
1508     if(!len)
1509         len = info.framesize;
1510 
1511     curpos = (unsigned long)toBytes(info, getPosition());
1512     if(curpos >= iolimit && mode == modeFeed) {
1513         curpos = 0;
1514         setPosition(0);
1515     }
1516 
1517     if (iolimit && ((curpos + len) > iolimit))
1518         len = iolimit - curpos;
1519 
1520     if (len <= 0)
1521         return 0;
1522 
1523     count = afWrite((unsigned char *)addr, (unsigned)len);
1524     if(count == (int)len) {
1525         length += count;
1526         return count;
1527     }
1528     if(count < 1)
1529         return count;
1530     else {
1531         length += count;
1532         return count;
1533     }
1534 }
1535 
putSamples(void * addr,unsigned samples)1536 Audio::Error AudioFile::putSamples(void *addr, unsigned samples)
1537 {
1538     int count;
1539     int bytes;
1540 
1541     if(!samples)
1542         samples = info.framecount;
1543 
1544     bytes = (int)toBytes(info, samples);
1545     if(bytes < 1)
1546         return setError(errRequestInvalid);
1547 
1548     count = afWrite((unsigned char *)addr, bytes);
1549     if(count == bytes) {
1550         length += count;
1551         return errSuccess;
1552     }
1553     if(count < 1)
1554         return errWriteFailure;
1555     else {
1556         length += count;
1557         return errWriteIncomplete;
1558     }
1559 }
1560 
skip(long samples)1561 Audio::Error AudioFile::skip(long samples)
1562 {
1563     unsigned long orig = getPosition();
1564     unsigned long pos = orig + samples;
1565 
1566     setPosition(pos);
1567     if(orig < getPosition())
1568         length += (getPosition() - orig);
1569 
1570     return errSuccess;
1571 }
1572 
setLimit(unsigned long samples)1573 Audio::Error AudioFile::setLimit(unsigned long samples)
1574 {
1575     if(!is_open())
1576         return setError(errNotOpened);
1577 
1578     if(!samples) {
1579         iolimit = 0;
1580         return errSuccess;
1581     }
1582 
1583     samples += getPosition();
1584     iolimit = (unsigned long)toBytes(info, samples);
1585     return errSuccess;
1586 }
1587 
is_signed(void) const1588 bool AudioFile::is_signed(void) const
1589 {
1590     switch(info.format) {
1591     case snd:
1592         return false;
1593     default:
1594         break;
1595     }
1596 
1597     switch(info.encoding) {
1598     case pcm8Mono:
1599     case pcm8Stereo:
1600     case pcm16Mono:
1601     case pcm16Stereo:
1602     case pcm32Mono:
1603     case pcm32Stereo:
1604         return true;
1605     default:
1606         return false;
1607     }
1608 }
1609 
position(const char * timestamp)1610 Audio::Error AudioFile::position(const char *timestamp)
1611 {
1612     timeout_t pos = toTimeout(timestamp);
1613 
1614     pos /= info.framing;
1615     return setPosition(pos * info.framecount);
1616 }
1617 
getPosition(char * timestamp,size_t size)1618 void AudioFile::getPosition(char *timestamp, size_t size)
1619 {
1620     timeout_t pos = getAbsolutePosition();
1621 
1622     pos /= info.framecount;
1623     toTimestamp(pos * info.framing, timestamp, size);
1624 }
1625 
1626 } // namespace ucommon
1627