1 /*
2 Audio File Library
3 Copyright (C) 1998-2000, 2003-2004, 2010-2013, Michael Pruett <michael@68k.org>
4 Copyright (C) 2000-2002, Silicon Graphics, Inc.
5 Copyright (C) 2002-2003, Davy Durham
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
11
12 This library 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 GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with this library; if not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301 USA
21 */
22
23 /*
24 WAVE.cpp
25
26 This file contains code for reading and writing RIFF WAVE format
27 sound files.
28 */
29
30 #include "config.h"
31 #include "WAVE.h"
32
33 #include <assert.h>
34 #include <math.h>
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "File.h"
40 #include "Instrument.h"
41 #include "Marker.h"
42 #include "Setup.h"
43 #include "Tag.h"
44 #include "Track.h"
45 #include "UUID.h"
46 #include "byteorder.h"
47 #include "util.h"
48
49 /* These constants are from RFC 2361. */
50 enum
51 {
52 WAVE_FORMAT_UNKNOWN = 0x0000, /* Microsoft Unknown Wave Format */
53 WAVE_FORMAT_PCM = 0x0001, /* Microsoft PCM Format */
54 WAVE_FORMAT_ADPCM = 0x0002, /* Microsoft ADPCM Format */
55 WAVE_FORMAT_IEEE_FLOAT = 0x0003, /* IEEE Float */
56 WAVE_FORMAT_VSELP = 0x0004, /* Compaq Computer's VSELP */
57 WAVE_FORMAT_IBM_CVSD = 0x0005, /* IBM CVSD */
58 WAVE_FORMAT_ALAW = 0x0006, /* Microsoft ALAW */
59 WAVE_FORMAT_MULAW = 0x0007, /* Microsoft MULAW */
60 WAVE_FORMAT_OKI_ADPCM = 0x0010, /* OKI ADPCM */
61 WAVE_FORMAT_DVI_ADPCM = 0x0011, /* Intel's DVI ADPCM */
62 WAVE_FORMAT_MEDIASPACE_ADPCM = 0x0012, /* Videologic's MediaSpace ADPCM */
63 WAVE_FORMAT_SIERRA_ADPCM = 0x0013, /* Sierra ADPCM */
64 WAVE_FORMAT_G723_ADPCM = 0x0014, /* G.723 ADPCM */
65 WAVE_FORMAT_DIGISTD = 0x0015, /* DSP Solutions' DIGISTD */
66 WAVE_FORMAT_DIGIFIX = 0x0016, /* DSP Solutions' DIGIFIX */
67 WAVE_FORMAT_DIALOGIC_OKI_ADPCM = 0x0017, /* Dialogic OKI ADPCM */
68 WAVE_FORMAT_MEDIAVISION_ADPCM = 0x0018, /* MediaVision ADPCM */
69 WAVE_FORMAT_CU_CODEC = 0x0019, /* HP CU */
70 WAVE_FORMAT_YAMAHA_ADPCM = 0x0020, /* Yamaha ADPCM */
71 WAVE_FORMAT_SONARC = 0x0021, /* Speech Compression's Sonarc */
72 WAVE_FORMAT_DSP_TRUESPEECH = 0x0022, /* DSP Group's True Speech */
73 WAVE_FORMAT_ECHOSC1 = 0x0023, /* Echo Speech's EchoSC1 */
74 WAVE_FORMAT_AUDIOFILE_AF36 = 0x0024, /* Audiofile AF36 */
75 WAVE_FORMAT_APTX = 0x0025, /* APTX */
76 WAVE_FORMAT_DOLBY_AC2 = 0x0030, /* Dolby AC2 */
77 WAVE_FORMAT_GSM610 = 0x0031, /* GSM610 */
78 WAVE_FORMAT_MSNAUDIO = 0x0032, /* MSNAudio */
79 WAVE_FORMAT_ANTEX_ADPCME = 0x0033, /* Antex ADPCME */
80
81 WAVE_FORMAT_MPEG = 0x0050, /* MPEG */
82 WAVE_FORMAT_MPEGLAYER3 = 0x0055, /* MPEG layer 3 */
83 WAVE_FORMAT_LUCENT_G723 = 0x0059, /* Lucent G.723 */
84 WAVE_FORMAT_G726_ADPCM = 0x0064, /* G.726 ADPCM */
85 WAVE_FORMAT_G722_ADPCM = 0x0065, /* G.722 ADPCM */
86
87 IBM_FORMAT_MULAW = 0x0101,
88 IBM_FORMAT_ALAW = 0x0102,
89 IBM_FORMAT_ADPCM = 0x0103,
90
91 WAVE_FORMAT_CREATIVE_ADPCM = 0x0200,
92
93 WAVE_FORMAT_EXTENSIBLE = 0xfffe
94 };
95
96 const int _af_wave_compression_types[_AF_WAVE_NUM_COMPTYPES] =
97 {
98 AF_COMPRESSION_G711_ULAW,
99 AF_COMPRESSION_G711_ALAW,
100 AF_COMPRESSION_IMA,
101 AF_COMPRESSION_MS_ADPCM
102 };
103
104 const InstParamInfo _af_wave_inst_params[_AF_WAVE_NUM_INSTPARAMS] =
105 {
106 { AF_INST_MIDI_BASENOTE, AU_PVTYPE_LONG, "MIDI base note", {60} },
107 { AF_INST_NUMCENTS_DETUNE, AU_PVTYPE_LONG, "Detune in cents", {0} },
108 { AF_INST_MIDI_LOVELOCITY, AU_PVTYPE_LONG, "Low velocity", {1} },
109 { AF_INST_MIDI_HIVELOCITY, AU_PVTYPE_LONG, "High velocity", {127} },
110 { AF_INST_MIDI_LONOTE, AU_PVTYPE_LONG, "Low note", {0} },
111 { AF_INST_MIDI_HINOTE, AU_PVTYPE_LONG, "High note", {127} },
112 { AF_INST_NUMDBS_GAIN, AU_PVTYPE_LONG, "Gain in dB", {0} }
113 };
114
115 static const _AFfilesetup waveDefaultFileSetup =
116 {
117 _AF_VALID_FILESETUP, /* valid */
118 AF_FILE_WAVE, /* fileFormat */
119 true, /* trackSet */
120 true, /* instrumentSet */
121 true, /* miscellaneousSet */
122 1, /* trackCount */
123 NULL, /* tracks */
124 0, /* instrumentCount */
125 NULL, /* instruments */
126 0, /* miscellaneousCount */
127 NULL /* miscellaneous */
128 };
129
130 static const UUID _af_wave_guid_pcm =
131 {{
132 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
133 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
134 }};
135 static const UUID _af_wave_guid_ieee_float =
136 {{
137 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
138 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
139 }};
140 static const UUID _af_wave_guid_ulaw =
141 {{
142 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
143 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
144 }};
145 static const UUID _af_wave_guid_alaw =
146 {{
147 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
148 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
149 }};
150
WAVEFile()151 WAVEFile::WAVEFile()
152 {
153 setFormatByteOrder(AF_BYTEORDER_LITTLEENDIAN);
154
155 m_factOffset = 0;
156 m_miscellaneousOffset = 0;
157 m_markOffset = 0;
158 m_dataSizeOffset = 0;
159
160 m_msadpcmNumCoefficients = 0;
161 }
162
parseFrameCount(const Tag & id,uint32_t size)163 status WAVEFile::parseFrameCount(const Tag &id, uint32_t size)
164 {
165 Track *track = getTrack();
166
167 uint32_t totalFrames;
168 readU32(&totalFrames);
169
170 track->totalfframes = totalFrames;
171
172 return AF_SUCCEED;
173 }
174
parseFormat(const Tag & id,uint32_t size)175 status WAVEFile::parseFormat(const Tag &id, uint32_t size)
176 {
177 Track *track = getTrack();
178
179 uint16_t formatTag;
180 readU16(&formatTag);
181 uint16_t channelCount;
182 readU16(&channelCount);
183 uint32_t sampleRate;
184 readU32(&sampleRate);
185 uint32_t averageBytesPerSecond;
186 readU32(&averageBytesPerSecond);
187 uint16_t blockAlign;
188 readU16(&blockAlign);
189
190 if (!channelCount)
191 {
192 _af_error(AF_BAD_CHANNELS, "invalid file with 0 channels");
193 return AF_FAIL;
194 }
195
196 track->f.channelCount = channelCount;
197 track->f.sampleRate = sampleRate;
198 track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;
199
200 /* Default to uncompressed audio data. */
201 track->f.compressionType = AF_COMPRESSION_NONE;
202 track->f.framesPerPacket = 1;
203
204 switch (formatTag)
205 {
206 case WAVE_FORMAT_PCM:
207 {
208 uint16_t bitsPerSample;
209 readU16(&bitsPerSample);
210
211 track->f.sampleWidth = bitsPerSample;
212
213 if (bitsPerSample == 0 || bitsPerSample > 32)
214 {
215 _af_error(AF_BAD_WIDTH,
216 "bad sample width of %d bits",
217 bitsPerSample);
218 return AF_FAIL;
219 }
220
221 if (bitsPerSample <= 8)
222 track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
223 else
224 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
225 }
226 break;
227
228 case WAVE_FORMAT_MULAW:
229 case IBM_FORMAT_MULAW:
230 track->f.sampleWidth = 16;
231 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
232 track->f.byteOrder = _AF_BYTEORDER_NATIVE;
233 track->f.compressionType = AF_COMPRESSION_G711_ULAW;
234 track->f.bytesPerPacket = track->f.channelCount;
235 break;
236
237 case WAVE_FORMAT_ALAW:
238 case IBM_FORMAT_ALAW:
239 track->f.sampleWidth = 16;
240 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
241 track->f.byteOrder = _AF_BYTEORDER_NATIVE;
242 track->f.compressionType = AF_COMPRESSION_G711_ALAW;
243 track->f.bytesPerPacket = track->f.channelCount;
244 break;
245
246 case WAVE_FORMAT_IEEE_FLOAT:
247 {
248 uint16_t bitsPerSample;
249 readU16(&bitsPerSample);
250
251 if (bitsPerSample == 64)
252 {
253 track->f.sampleWidth = 64;
254 track->f.sampleFormat = AF_SAMPFMT_DOUBLE;
255 }
256 else
257 {
258 track->f.sampleWidth = 32;
259 track->f.sampleFormat = AF_SAMPFMT_FLOAT;
260 }
261 }
262 break;
263
264 case WAVE_FORMAT_ADPCM:
265 {
266 uint16_t bitsPerSample, extraByteCount,
267 samplesPerBlock, numCoefficients;
268
269 if (track->f.channelCount != 1 &&
270 track->f.channelCount != 2)
271 {
272 _af_error(AF_BAD_CHANNELS,
273 "WAVE file with MS ADPCM compression "
274 "must have 1 or 2 channels");
275 }
276
277 readU16(&bitsPerSample);
278 readU16(&extraByteCount);
279 readU16(&samplesPerBlock);
280 readU16(&numCoefficients);
281
282 /* numCoefficients should be at least 7. */
283 assert(numCoefficients >= 7 && numCoefficients <= 255);
284
285 m_msadpcmNumCoefficients = numCoefficients;
286
287 for (int i=0; i<m_msadpcmNumCoefficients; i++)
288 {
289 readS16(&m_msadpcmCoefficients[i][0]);
290 readS16(&m_msadpcmCoefficients[i][1]);
291 }
292
293 track->f.sampleWidth = 16;
294 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
295 track->f.compressionType = AF_COMPRESSION_MS_ADPCM;
296 track->f.byteOrder = _AF_BYTEORDER_NATIVE;
297
298 track->f.framesPerPacket = samplesPerBlock;
299 track->f.bytesPerPacket = blockAlign;
300
301 // Create the parameter list.
302 AUpvlist pv = AUpvnew(2);
303 AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);
304 AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
305 long l = m_msadpcmNumCoefficients;
306 AUpvsetval(pv, 0, &l);
307
308 AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);
309 AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);
310 void *v = m_msadpcmCoefficients;
311 AUpvsetval(pv, 1, &v);
312
313 track->f.compressionParams = pv;
314 }
315 break;
316
317 case WAVE_FORMAT_DVI_ADPCM:
318 {
319 uint16_t bitsPerSample, extraByteCount, samplesPerBlock;
320
321 readU16(&bitsPerSample);
322 readU16(&extraByteCount);
323 readU16(&samplesPerBlock);
324
325 if (bitsPerSample != 4)
326 {
327 _af_error(AF_BAD_NOT_IMPLEMENTED,
328 "IMA ADPCM compression supports only 4 bits per sample");
329 }
330
331 int bytesPerBlock = (samplesPerBlock + 14) / 8 * 4 * channelCount;
332 if (bytesPerBlock > blockAlign || (samplesPerBlock % 8) != 1)
333 {
334 _af_error(AF_BAD_CODEC_CONFIG,
335 "Invalid samples per block for IMA ADPCM compression");
336 }
337
338 track->f.sampleWidth = 16;
339 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
340 track->f.compressionType = AF_COMPRESSION_IMA;
341 track->f.byteOrder = _AF_BYTEORDER_NATIVE;
342
343 initIMACompressionParams();
344
345 track->f.framesPerPacket = samplesPerBlock;
346 track->f.bytesPerPacket = blockAlign;
347 }
348 break;
349
350 case WAVE_FORMAT_EXTENSIBLE:
351 {
352 uint16_t bitsPerSample;
353 readU16(&bitsPerSample);
354 uint16_t extraByteCount;
355 readU16(&extraByteCount);
356 uint16_t reserved;
357 readU16(&reserved);
358 uint32_t channelMask;
359 readU32(&channelMask);
360 UUID subformat;
361 readUUID(&subformat);
362 if (subformat == _af_wave_guid_pcm)
363 {
364 track->f.sampleWidth = bitsPerSample;
365
366 if (bitsPerSample == 0 || bitsPerSample > 32)
367 {
368 _af_error(AF_BAD_WIDTH,
369 "bad sample width of %d bits",
370 bitsPerSample);
371 return AF_FAIL;
372 }
373
374 // Use valid bits per sample if bytes per sample is the same.
375 if (reserved <= bitsPerSample &&
376 (reserved + 7) / 8 == (bitsPerSample + 7) / 8)
377 track->f.sampleWidth = reserved;
378
379 if (bitsPerSample <= 8)
380 track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
381 else
382 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
383 }
384 else if (subformat == _af_wave_guid_ieee_float)
385 {
386 if (bitsPerSample == 64)
387 {
388 track->f.sampleWidth = 64;
389 track->f.sampleFormat = AF_SAMPFMT_DOUBLE;
390 }
391 else
392 {
393 track->f.sampleWidth = 32;
394 track->f.sampleFormat = AF_SAMPFMT_FLOAT;
395 }
396 }
397 else if (subformat == _af_wave_guid_alaw ||
398 subformat == _af_wave_guid_ulaw)
399 {
400 track->f.compressionType = subformat == _af_wave_guid_alaw ?
401 AF_COMPRESSION_G711_ALAW : AF_COMPRESSION_G711_ULAW;
402 track->f.sampleWidth = 16;
403 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
404 track->f.byteOrder = _AF_BYTEORDER_NATIVE;
405 track->f.bytesPerPacket = channelCount;
406 }
407 else
408 {
409 _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE extensible data format %s is not currently supported", subformat.name().c_str());
410 return AF_FAIL;
411 }
412 }
413 break;
414
415 case WAVE_FORMAT_YAMAHA_ADPCM:
416 case WAVE_FORMAT_OKI_ADPCM:
417 case WAVE_FORMAT_CREATIVE_ADPCM:
418 case IBM_FORMAT_ADPCM:
419 _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE ADPCM data format 0x%x is not currently supported", formatTag);
420 return AF_FAIL;
421 break;
422
423 case WAVE_FORMAT_MPEG:
424 _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG data format is not supported");
425 return AF_FAIL;
426 break;
427
428 case WAVE_FORMAT_MPEGLAYER3:
429 _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG layer 3 data format is not supported");
430 return AF_FAIL;
431 break;
432
433 default:
434 _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE file data format 0x%x not currently supported != 0xfffe ? %d, != EXTENSIBLE? %d", formatTag, formatTag != 0xfffe, formatTag != WAVE_FORMAT_EXTENSIBLE);
435 return AF_FAIL;
436 break;
437 }
438
439 if (track->f.isUncompressed())
440 track->f.computeBytesPerPacketPCM();
441
442 _af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);
443
444 return AF_SUCCEED;
445 }
446
parseData(const Tag & id,uint32_t size)447 status WAVEFile::parseData(const Tag &id, uint32_t size)
448 {
449 Track *track = getTrack();
450
451 track->fpos_first_frame = m_fh->tell();
452 track->data_size = size;
453
454 return AF_SUCCEED;
455 }
456
parsePlayList(const Tag & id,uint32_t size)457 status WAVEFile::parsePlayList(const Tag &id, uint32_t size)
458 {
459 uint32_t segmentCount;
460 readU32(&segmentCount);
461
462 if (segmentCount == 0)
463 {
464 m_instrumentCount = 0;
465 m_instruments = NULL;
466 return AF_SUCCEED;
467 }
468
469 for (unsigned segment=0; segment<segmentCount; segment++)
470 {
471 uint32_t startMarkID, loopLength, loopCount;
472
473 readU32(&startMarkID);
474 readU32(&loopLength);
475 readU32(&loopCount);
476 }
477
478 return AF_SUCCEED;
479 }
480
parseCues(const Tag & id,uint32_t size)481 status WAVEFile::parseCues(const Tag &id, uint32_t size)
482 {
483 Track *track = getTrack();
484
485 uint32_t markerCount;
486 readU32(&markerCount);
487 track->markerCount = markerCount;
488
489 if (markerCount == 0)
490 {
491 track->markers = NULL;
492 return AF_SUCCEED;
493 }
494
495 if ((track->markers = _af_marker_new(markerCount)) == NULL)
496 return AF_FAIL;
497
498 for (unsigned i=0; i<markerCount; i++)
499 {
500 uint32_t id, position, chunkid;
501 uint32_t chunkByteOffset, blockByteOffset;
502 uint32_t sampleFrameOffset;
503 Marker *marker = &track->markers[i];
504
505 readU32(&id);
506 readU32(&position);
507 readU32(&chunkid);
508 readU32(&chunkByteOffset);
509 readU32(&blockByteOffset);
510
511 /*
512 sampleFrameOffset represents the position of
513 the mark in units of frames.
514 */
515 readU32(&sampleFrameOffset);
516
517 marker->id = id;
518 marker->position = sampleFrameOffset;
519 marker->name = _af_strdup("");
520 marker->comment = _af_strdup("");
521 }
522
523 return AF_SUCCEED;
524 }
525
526 /* Parse an adtl sub-chunk within a LIST chunk. */
parseADTLSubChunk(const Tag & id,uint32_t size)527 status WAVEFile::parseADTLSubChunk(const Tag &id, uint32_t size)
528 {
529 Track *track = getTrack();
530
531 AFfileoffset endPos = m_fh->tell() + size;
532
533 while (m_fh->tell() < endPos)
534 {
535 Tag chunkID;
536 uint32_t chunkSize;
537
538 readTag(&chunkID);
539 readU32(&chunkSize);
540
541 if (chunkID == "labl" || chunkID == "note")
542 {
543 uint32_t id;
544 long length=chunkSize-4;
545 char *p = (char *) _af_malloc(length);
546
547 readU32(&id);
548 m_fh->read(p, length);
549
550 Marker *marker = track->getMarker(id);
551
552 if (marker)
553 {
554 if (chunkID == "labl")
555 {
556 free(marker->name);
557 marker->name = p;
558 }
559 else if (chunkID == "note")
560 {
561 free(marker->comment);
562 marker->comment = p;
563 }
564 else
565 free(p);
566 }
567 else
568 free(p);
569
570 /*
571 If chunkSize is odd, skip an extra byte
572 at the end of the chunk.
573 */
574 if ((chunkSize % 2) != 0)
575 m_fh->seek(1, File::SeekFromCurrent);
576 }
577 else
578 {
579 /* If chunkSize is odd, skip an extra byte. */
580 m_fh->seek(chunkSize + (chunkSize % 2), File::SeekFromCurrent);
581 }
582 }
583 return AF_SUCCEED;
584 }
585
586 /* Parse an INFO sub-chunk within a LIST chunk. */
parseINFOSubChunk(const Tag & id,uint32_t size)587 status WAVEFile::parseINFOSubChunk(const Tag &id, uint32_t size)
588 {
589 AFfileoffset endPos = m_fh->tell() + size;
590
591 while (m_fh->tell() < endPos)
592 {
593 int misctype = AF_MISC_UNRECOGNIZED;
594 Tag miscid;
595 uint32_t miscsize;
596
597 readTag(&miscid);
598 readU32(&miscsize);
599
600 if (miscid == "IART")
601 misctype = AF_MISC_AUTH;
602 else if (miscid == "INAM")
603 misctype = AF_MISC_NAME;
604 else if (miscid == "ICOP")
605 misctype = AF_MISC_COPY;
606 else if (miscid == "ICMT")
607 misctype = AF_MISC_ICMT;
608 else if (miscid == "ICRD")
609 misctype = AF_MISC_ICRD;
610 else if (miscid == "ISFT")
611 misctype = AF_MISC_ISFT;
612
613 if (misctype != AF_MISC_UNRECOGNIZED)
614 {
615 char *string = (char *) _af_malloc(miscsize);
616
617 m_fh->read(string, miscsize);
618
619 m_miscellaneousCount++;
620 m_miscellaneous = (Miscellaneous *) _af_realloc(m_miscellaneous, sizeof (Miscellaneous) * m_miscellaneousCount);
621
622 m_miscellaneous[m_miscellaneousCount-1].id = m_miscellaneousCount;
623 m_miscellaneous[m_miscellaneousCount-1].type = misctype;
624 m_miscellaneous[m_miscellaneousCount-1].size = miscsize;
625 m_miscellaneous[m_miscellaneousCount-1].position = 0;
626 m_miscellaneous[m_miscellaneousCount-1].buffer = string;
627 }
628 else
629 {
630 m_fh->seek(miscsize, File::SeekFromCurrent);
631 }
632
633 /* Make the current position an even number of bytes. */
634 if (miscsize % 2 != 0)
635 m_fh->seek(1, File::SeekFromCurrent);
636 }
637 return AF_SUCCEED;
638 }
639
parseList(const Tag & id,uint32_t size)640 status WAVEFile::parseList(const Tag &id, uint32_t size)
641 {
642 Tag typeID;
643 readTag(&typeID);
644 size-=4;
645
646 if (typeID == "adtl")
647 {
648 /* Handle adtl sub-chunks. */
649 return parseADTLSubChunk(typeID, size);
650 }
651 else if (typeID == "INFO")
652 {
653 /* Handle INFO sub-chunks. */
654 return parseINFOSubChunk(typeID, size);
655 }
656 else
657 {
658 /* Skip unhandled sub-chunks. */
659 m_fh->seek(size, File::SeekFromCurrent);
660 return AF_SUCCEED;
661 }
662 return AF_SUCCEED;
663 }
664
parseInstrument(const Tag & id,uint32_t size)665 status WAVEFile::parseInstrument(const Tag &id, uint32_t size)
666 {
667 uint8_t baseNote;
668 int8_t detune, gain;
669 uint8_t lowNote, highNote, lowVelocity, highVelocity;
670 uint8_t padByte;
671
672 readU8(&baseNote);
673 readS8(&detune);
674 readS8(&gain);
675 readU8(&lowNote);
676 readU8(&highNote);
677 readU8(&lowVelocity);
678 readU8(&highVelocity);
679 readU8(&padByte);
680
681 return AF_SUCCEED;
682 }
683
recognize(File * fh)684 bool WAVEFile::recognize(File *fh)
685 {
686 uint8_t buffer[8];
687
688 fh->seek(0, File::SeekFromBeginning);
689
690 if (fh->read(buffer, 8) != 8 || memcmp(buffer, "RIFF", 4) != 0)
691 return false;
692 if (fh->read(buffer, 4) != 4 || memcmp(buffer, "WAVE", 4) != 0)
693 return false;
694
695 return true;
696 }
697
readInit(AFfilesetup setup)698 status WAVEFile::readInit(AFfilesetup setup)
699 {
700 Tag type, formtype;
701 uint32_t size;
702 uint32_t index = 0;
703
704 bool hasFormat = false;
705 bool hasData = false;
706 bool hasFrameCount = false;
707
708 Track *track = allocateTrack();
709
710 m_fh->seek(0, File::SeekFromBeginning);
711
712 readTag(&type);
713 readU32(&size);
714 readTag(&formtype);
715
716 assert(type == "RIFF");
717 assert(formtype == "WAVE");
718
719 /* Include the offset of the form type. */
720 index += 4;
721
722 while (index < size)
723 {
724 Tag chunkid;
725 uint32_t chunksize = 0;
726 status result;
727
728 readTag(&chunkid);
729 readU32(&chunksize);
730
731 if (chunkid == "fmt ")
732 {
733 result = parseFormat(chunkid, chunksize);
734 if (result == AF_FAIL)
735 return AF_FAIL;
736
737 hasFormat = true;
738 }
739 else if (chunkid == "data")
740 {
741 /* The format chunk must precede the data chunk. */
742 if (!hasFormat)
743 {
744 _af_error(AF_BAD_HEADER, "missing format chunk in WAVE file");
745 return AF_FAIL;
746 }
747
748 result = parseData(chunkid, chunksize);
749 if (result == AF_FAIL)
750 return AF_FAIL;
751
752 hasData = true;
753 }
754 else if (chunkid == "inst")
755 {
756 result = parseInstrument(chunkid, chunksize);
757 if (result == AF_FAIL)
758 return AF_FAIL;
759 }
760 else if (chunkid == "fact")
761 {
762 hasFrameCount = true;
763 result = parseFrameCount(chunkid, chunksize);
764 if (result == AF_FAIL)
765 return AF_FAIL;
766 }
767 else if (chunkid == "cue ")
768 {
769 result = parseCues(chunkid, chunksize);
770 if (result == AF_FAIL)
771 return AF_FAIL;
772 }
773 else if (chunkid == "LIST" || chunkid == "list")
774 {
775 result = parseList(chunkid, chunksize);
776 if (result == AF_FAIL)
777 return AF_FAIL;
778 }
779 else if (chunkid == "INST")
780 {
781 result = parseInstrument(chunkid, chunksize);
782 if (result == AF_FAIL)
783 return AF_FAIL;
784 }
785 else if (chunkid == "plst")
786 {
787 result = parsePlayList(chunkid, chunksize);
788 if (result == AF_FAIL)
789 return AF_FAIL;
790 }
791
792 index += chunksize + 8;
793
794 /* All chunks must be aligned on an even number of bytes */
795 if ((index % 2) != 0)
796 index++;
797
798 m_fh->seek(index + 8, File::SeekFromBeginning);
799 }
800
801 /* The format chunk and the data chunk are required. */
802 if (!hasFormat || !hasData)
803 {
804 return AF_FAIL;
805 }
806
807 /*
808 At this point we know that the file has a format chunk and a
809 data chunk, so we can assume that track->f and track->data_size
810 have been initialized.
811 */
812 if (!hasFrameCount)
813 {
814 if (track->f.bytesPerPacket && track->f.framesPerPacket)
815 {
816 track->computeTotalFileFrames();
817 }
818 else
819 {
820 _af_error(AF_BAD_HEADER, "Frame count required but not found");
821 return AF_FAIL;
822 }
823 }
824
825 return AF_SUCCEED;
826 }
827
completeSetup(AFfilesetup setup)828 AFfilesetup WAVEFile::completeSetup(AFfilesetup setup)
829 {
830 if (setup->trackSet && setup->trackCount != 1)
831 {
832 _af_error(AF_BAD_NUMTRACKS, "WAVE file must have 1 track");
833 return AF_NULL_FILESETUP;
834 }
835
836 TrackSetup *track = setup->getTrack();
837
838 if (track->f.isCompressed())
839 {
840 if (!track->sampleFormatSet)
841 _af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, 16);
842 else
843 _af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);
844 }
845 else if (track->sampleFormatSet)
846 {
847 switch (track->f.sampleFormat)
848 {
849 case AF_SAMPFMT_FLOAT:
850 if (track->sampleWidthSet &&
851 track->f.sampleWidth != 32)
852 {
853 _af_error(AF_BAD_WIDTH,
854 "Warning: invalid sample width for floating-point WAVE file: %d (must be 32 bits)\n",
855 track->f.sampleWidth);
856 _af_set_sample_format(&track->f, AF_SAMPFMT_FLOAT, 32);
857 }
858 break;
859
860 case AF_SAMPFMT_DOUBLE:
861 if (track->sampleWidthSet &&
862 track->f.sampleWidth != 64)
863 {
864 _af_error(AF_BAD_WIDTH,
865 "Warning: invalid sample width for double-precision floating-point WAVE file: %d (must be 64 bits)\n",
866 track->f.sampleWidth);
867 _af_set_sample_format(&track->f, AF_SAMPFMT_DOUBLE, 64);
868 }
869 break;
870
871 case AF_SAMPFMT_UNSIGNED:
872 if (track->sampleWidthSet)
873 {
874 if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
875 {
876 _af_error(AF_BAD_WIDTH, "invalid sample width for WAVE file: %d (must be 1-32 bits)\n", track->f.sampleWidth);
877 return AF_NULL_FILESETUP;
878 }
879 if (track->f.sampleWidth > 8)
880 {
881 _af_error(AF_BAD_SAMPFMT, "WAVE integer data of more than 8 bits must be two's complement signed");
882 _af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, track->f.sampleWidth);
883 }
884 }
885 else
886 /*
887 If the sample width is not set but the user requests
888 unsigned data, set the width to 8 bits.
889 */
890 _af_set_sample_format(&track->f, track->f.sampleFormat, 8);
891 break;
892
893 case AF_SAMPFMT_TWOSCOMP:
894 if (track->sampleWidthSet)
895 {
896 if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
897 {
898 _af_error(AF_BAD_WIDTH, "invalid sample width %d for WAVE file (must be 1-32)", track->f.sampleWidth);
899 return AF_NULL_FILESETUP;
900 }
901 else if (track->f.sampleWidth <= 8)
902 {
903 _af_error(AF_BAD_SAMPFMT, "Warning: WAVE format integer data of 1-8 bits must be unsigned; setting sample format to unsigned");
904 _af_set_sample_format(&track->f, AF_SAMPFMT_UNSIGNED, track->f.sampleWidth);
905 }
906 }
907 else
908 /*
909 If no sample width was specified, we default to 16 bits
910 for signed integer data.
911 */
912 _af_set_sample_format(&track->f, track->f.sampleFormat, 16);
913 break;
914 }
915 }
916 /*
917 Otherwise set the sample format depending on the sample
918 width or set completely to default.
919 */
920 else
921 {
922 if (!track->sampleWidthSet)
923 {
924 track->f.sampleWidth = 16;
925 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
926 }
927 else
928 {
929 if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
930 {
931 _af_error(AF_BAD_WIDTH, "invalid sample width %d for WAVE file (must be 1-32)", track->f.sampleWidth);
932 return AF_NULL_FILESETUP;
933 }
934 else if (track->f.sampleWidth > 8)
935 /* Here track->f.sampleWidth is in {1..32}. */
936 track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
937 else
938 /* Here track->f.sampleWidth is in {1..8}. */
939 track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
940 }
941 }
942
943 if (track->f.compressionType != AF_COMPRESSION_NONE &&
944 track->f.compressionType != AF_COMPRESSION_G711_ULAW &&
945 track->f.compressionType != AF_COMPRESSION_G711_ALAW &&
946 track->f.compressionType != AF_COMPRESSION_IMA &&
947 track->f.compressionType != AF_COMPRESSION_MS_ADPCM)
948 {
949 _af_error(AF_BAD_NOT_IMPLEMENTED, "compression format not supported in WAVE format");
950 return AF_NULL_FILESETUP;
951 }
952
953 if (track->f.isUncompressed() &&
954 track->byteOrderSet &&
955 track->f.byteOrder != AF_BYTEORDER_LITTLEENDIAN &&
956 track->f.isByteOrderSignificant())
957 {
958 _af_error(AF_BAD_BYTEORDER, "WAVE format only supports little-endian data");
959 return AF_NULL_FILESETUP;
960 }
961
962 if (track->f.isUncompressed())
963 track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;
964
965 if (track->aesDataSet)
966 {
967 _af_error(AF_BAD_FILESETUP, "WAVE files cannot have AES data");
968 return AF_NULL_FILESETUP;
969 }
970
971 if (setup->instrumentSet)
972 {
973 if (setup->instrumentCount > 1)
974 {
975 _af_error(AF_BAD_NUMINSTS, "WAVE files can have 0 or 1 instrument");
976 return AF_NULL_FILESETUP;
977 }
978 else if (setup->instrumentCount == 1)
979 {
980 if (setup->instruments[0].loopSet &&
981 setup->instruments[0].loopCount > 0 &&
982 (!track->markersSet || track->markerCount == 0))
983 {
984 _af_error(AF_BAD_NUMMARKS, "WAVE files with loops must contain at least 1 marker");
985 return AF_NULL_FILESETUP;
986 }
987 }
988 }
989
990 /* Make sure the miscellaneous data is of an acceptable type. */
991 if (setup->miscellaneousSet)
992 {
993 for (int i=0; i<setup->miscellaneousCount; i++)
994 {
995 switch (setup->miscellaneous[i].type)
996 {
997 case AF_MISC_COPY:
998 case AF_MISC_AUTH:
999 case AF_MISC_NAME:
1000 case AF_MISC_ICRD:
1001 case AF_MISC_ISFT:
1002 case AF_MISC_ICMT:
1003 break;
1004 default:
1005 _af_error(AF_BAD_MISCTYPE, "illegal miscellaneous type [%d] for WAVE file", setup->miscellaneous[i].type);
1006 return AF_NULL_FILESETUP;
1007 }
1008 }
1009 }
1010
1011 /*
1012 Allocate an AFfilesetup and make all the unset fields correct.
1013 */
1014 AFfilesetup newsetup = _af_filesetup_copy(setup, &waveDefaultFileSetup, false);
1015
1016 /* Make sure we do not copy loops if they are not specified in setup. */
1017 if (setup->instrumentSet && setup->instrumentCount > 0 &&
1018 setup->instruments[0].loopSet)
1019 {
1020 free(newsetup->instruments[0].loops);
1021 newsetup->instruments[0].loopCount = 0;
1022 }
1023
1024 return newsetup;
1025 }
1026
isInstrumentParameterValid(AUpvlist list,int i)1027 bool WAVEFile::isInstrumentParameterValid(AUpvlist list, int i)
1028 {
1029 int param, type;
1030
1031 AUpvgetparam(list, i, ¶m);
1032 AUpvgetvaltype(list, i, &type);
1033 if (type != AU_PVTYPE_LONG)
1034 return false;
1035
1036 long lval;
1037 AUpvgetval(list, i, &lval);
1038
1039 switch (param)
1040 {
1041 case AF_INST_MIDI_BASENOTE:
1042 return ((lval >= 0) && (lval <= 127));
1043
1044 case AF_INST_NUMCENTS_DETUNE:
1045 return ((lval >= -50) && (lval <= 50));
1046
1047 case AF_INST_MIDI_LOVELOCITY:
1048 return ((lval >= 1) && (lval <= 127));
1049
1050 case AF_INST_MIDI_HIVELOCITY:
1051 return ((lval >= 1) && (lval <= 127));
1052
1053 case AF_INST_MIDI_LONOTE:
1054 return ((lval >= 0) && (lval <= 127));
1055
1056 case AF_INST_MIDI_HINOTE:
1057 return ((lval >= 0) && (lval <= 127));
1058
1059 case AF_INST_NUMDBS_GAIN:
1060 return true;
1061
1062 default:
1063 return false;
1064 }
1065
1066 return true;
1067 }
1068
writeFormat()1069 status WAVEFile::writeFormat()
1070 {
1071 uint16_t formatTag, channelCount;
1072 uint32_t sampleRate, averageBytesPerSecond;
1073 uint16_t blockAlign;
1074 uint32_t chunkSize;
1075 uint16_t bitsPerSample;
1076
1077 Track *track = getTrack();
1078
1079 m_fh->write("fmt ", 4);
1080
1081 switch (track->f.compressionType)
1082 {
1083 case AF_COMPRESSION_NONE:
1084 chunkSize = 16;
1085 if (track->f.sampleFormat == AF_SAMPFMT_FLOAT ||
1086 track->f.sampleFormat == AF_SAMPFMT_DOUBLE)
1087 {
1088 formatTag = WAVE_FORMAT_IEEE_FLOAT;
1089 }
1090 else if (track->f.sampleFormat == AF_SAMPFMT_TWOSCOMP ||
1091 track->f.sampleFormat == AF_SAMPFMT_UNSIGNED)
1092 {
1093 formatTag = WAVE_FORMAT_PCM;
1094 }
1095 else
1096 {
1097 _af_error(AF_BAD_COMPTYPE, "bad sample format");
1098 return AF_FAIL;
1099 }
1100
1101 blockAlign = _af_format_frame_size(&track->f, false);
1102 bitsPerSample = 8 * _af_format_sample_size(&track->f, false);
1103 break;
1104
1105 /*
1106 G.711 compression uses eight bits per sample.
1107 */
1108 case AF_COMPRESSION_G711_ULAW:
1109 chunkSize = 18;
1110 formatTag = IBM_FORMAT_MULAW;
1111 blockAlign = track->f.channelCount;
1112 bitsPerSample = 8;
1113 break;
1114
1115 case AF_COMPRESSION_G711_ALAW:
1116 chunkSize = 18;
1117 formatTag = IBM_FORMAT_ALAW;
1118 blockAlign = track->f.channelCount;
1119 bitsPerSample = 8;
1120 break;
1121
1122 case AF_COMPRESSION_IMA:
1123 chunkSize = 20;
1124 formatTag = WAVE_FORMAT_DVI_ADPCM;
1125 blockAlign = track->f.bytesPerPacket;
1126 bitsPerSample = 4;
1127 break;
1128
1129 case AF_COMPRESSION_MS_ADPCM:
1130 chunkSize = 50;
1131 formatTag = WAVE_FORMAT_ADPCM;
1132 blockAlign = track->f.bytesPerPacket;
1133 bitsPerSample = 4;
1134 break;
1135
1136 default:
1137 _af_error(AF_BAD_COMPTYPE, "bad compression type");
1138 return AF_FAIL;
1139 }
1140
1141 writeU32(&chunkSize);
1142 writeU16(&formatTag);
1143
1144 channelCount = track->f.channelCount;
1145 writeU16(&channelCount);
1146
1147 sampleRate = track->f.sampleRate;
1148 writeU32(&sampleRate);
1149
1150 averageBytesPerSecond =
1151 track->f.sampleRate * _af_format_frame_size(&track->f, false);
1152 if (track->f.compressionType == AF_COMPRESSION_IMA ||
1153 track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
1154 averageBytesPerSecond = track->f.sampleRate * track->f.bytesPerPacket /
1155 track->f.framesPerPacket;
1156 writeU32(&averageBytesPerSecond);
1157
1158 writeU16(&blockAlign);
1159
1160 writeU16(&bitsPerSample);
1161
1162 if (track->f.compressionType == AF_COMPRESSION_G711_ULAW ||
1163 track->f.compressionType == AF_COMPRESSION_G711_ALAW)
1164 {
1165 uint16_t zero = 0;
1166 writeU16(&zero);
1167 }
1168 else if (track->f.compressionType == AF_COMPRESSION_IMA)
1169 {
1170 uint16_t extraByteCount = 2;
1171 writeU16(&extraByteCount);
1172 uint16_t samplesPerBlock = track->f.framesPerPacket;
1173 writeU16(&samplesPerBlock);
1174 }
1175 else if (track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
1176 {
1177 uint16_t extraByteCount = 2 + 2 + m_msadpcmNumCoefficients * 4;
1178 writeU16(&extraByteCount);
1179 uint16_t samplesPerBlock = track->f.framesPerPacket;
1180 writeU16(&samplesPerBlock);
1181
1182 uint16_t numCoefficients = m_msadpcmNumCoefficients;
1183 writeU16(&numCoefficients);
1184
1185 for (int i=0; i<m_msadpcmNumCoefficients; i++)
1186 {
1187 writeS16(&m_msadpcmCoefficients[i][0]);
1188 writeS16(&m_msadpcmCoefficients[i][1]);
1189 }
1190 }
1191
1192 return AF_SUCCEED;
1193 }
1194
writeFrameCount()1195 status WAVEFile::writeFrameCount()
1196 {
1197 uint32_t factSize = 4;
1198 uint32_t totalFrameCount;
1199
1200 Track *track = getTrack();
1201
1202 /* Omit the fact chunk only for uncompressed integer audio formats. */
1203 if (track->f.compressionType == AF_COMPRESSION_NONE &&
1204 (track->f.sampleFormat == AF_SAMPFMT_TWOSCOMP ||
1205 track->f.sampleFormat == AF_SAMPFMT_UNSIGNED))
1206 return AF_SUCCEED;
1207
1208 /*
1209 If the offset for the fact chunk hasn't been set yet,
1210 set it to the file's current position.
1211 */
1212 if (m_factOffset == 0)
1213 m_factOffset = m_fh->tell();
1214 else
1215 m_fh->seek(m_factOffset, File::SeekFromBeginning);
1216
1217 m_fh->write("fact", 4);
1218 writeU32(&factSize);
1219
1220 totalFrameCount = track->totalfframes;
1221 writeU32(&totalFrameCount);
1222
1223 return AF_SUCCEED;
1224 }
1225
writeData()1226 status WAVEFile::writeData()
1227 {
1228 Track *track = getTrack();
1229
1230 m_fh->write("data", 4);
1231 m_dataSizeOffset = m_fh->tell();
1232
1233 uint32_t chunkSize = track->data_size;
1234
1235 writeU32(&chunkSize);
1236 track->fpos_first_frame = m_fh->tell();
1237
1238 return AF_SUCCEED;
1239 }
1240
update()1241 status WAVEFile::update()
1242 {
1243 Track *track = getTrack();
1244
1245 if (track->fpos_first_frame != 0)
1246 {
1247 uint32_t dataLength, fileLength;
1248
1249 // Update the frame count chunk if present.
1250 writeFrameCount();
1251
1252 // Update the length of the data chunk.
1253 m_fh->seek(m_dataSizeOffset, File::SeekFromBeginning);
1254 dataLength = (uint32_t) track->data_size;
1255 writeU32(&dataLength);
1256
1257 // Update the length of the RIFF chunk.
1258 fileLength = (uint32_t) m_fh->length();
1259 fileLength -= 8;
1260
1261 m_fh->seek(4, File::SeekFromBeginning);
1262 writeU32(&fileLength);
1263 }
1264
1265 /*
1266 Write the actual data that was set after initializing
1267 the miscellaneous IDs. The size of the data will be
1268 unchanged.
1269 */
1270 writeMiscellaneous();
1271
1272 // Write the new positions; the size of the data will be unchanged.
1273 writeCues();
1274
1275 return AF_SUCCEED;
1276 }
1277
1278 /* Convert an Audio File Library miscellaneous type to a WAVE type. */
misc_type_to_wave(int misctype,Tag * miscid)1279 static bool misc_type_to_wave (int misctype, Tag *miscid)
1280 {
1281 if (misctype == AF_MISC_AUTH)
1282 *miscid = "IART";
1283 else if (misctype == AF_MISC_NAME)
1284 *miscid = "INAM";
1285 else if (misctype == AF_MISC_COPY)
1286 *miscid = "ICOP";
1287 else if (misctype == AF_MISC_ICMT)
1288 *miscid = "ICMT";
1289 else if (misctype == AF_MISC_ICRD)
1290 *miscid = "ICRD";
1291 else if (misctype == AF_MISC_ISFT)
1292 *miscid = "ISFT";
1293 else
1294 return false;
1295
1296 return true;
1297 }
1298
writeMiscellaneous()1299 status WAVEFile::writeMiscellaneous()
1300 {
1301 if (m_miscellaneousCount != 0)
1302 {
1303 uint32_t miscellaneousBytes;
1304 uint32_t chunkSize;
1305
1306 /* Start at 12 to account for 'LIST', size, and 'INFO'. */
1307 miscellaneousBytes = 12;
1308
1309 /* Then calculate the size of the whole INFO chunk. */
1310 for (int i=0; i<m_miscellaneousCount; i++)
1311 {
1312 Tag miscid;
1313
1314 // Skip miscellaneous data of an unsupported type.
1315 if (!misc_type_to_wave(m_miscellaneous[i].type, &miscid))
1316 continue;
1317
1318 // Account for miscellaneous type and size.
1319 miscellaneousBytes += 8;
1320 miscellaneousBytes += m_miscellaneous[i].size;
1321
1322 // Add a pad byte if necessary.
1323 if (m_miscellaneous[i].size % 2 != 0)
1324 miscellaneousBytes++;
1325
1326 assert(miscellaneousBytes % 2 == 0);
1327 }
1328
1329 if (m_miscellaneousOffset == 0)
1330 m_miscellaneousOffset = m_fh->tell();
1331 else
1332 m_fh->seek(m_miscellaneousOffset, File::SeekFromBeginning);
1333
1334 /*
1335 Write the data. On the first call to this
1336 function (from _af_wave_write_init), the
1337 data won't be available, fh->seek is used to
1338 reserve space until the data has been provided.
1339 On subseuent calls to this function (from
1340 _af_wave_update), the data will really be written.
1341 */
1342
1343 /* Write 'LIST'. */
1344 m_fh->write("LIST", 4);
1345
1346 /* Write the size of the following chunk. */
1347 chunkSize = miscellaneousBytes-8;
1348 writeU32(&chunkSize);
1349
1350 /* Write 'INFO'. */
1351 m_fh->write("INFO", 4);
1352
1353 /* Write each miscellaneous chunk. */
1354 for (int i=0; i<m_miscellaneousCount; i++)
1355 {
1356 uint32_t miscsize = m_miscellaneous[i].size;
1357 Tag miscid;
1358
1359 // Skip miscellaneous data of an unsupported type.
1360 if (!misc_type_to_wave(m_miscellaneous[i].type, &miscid))
1361 continue;
1362
1363 writeTag(&miscid);
1364 writeU32(&miscsize);
1365 if (m_miscellaneous[i].buffer != NULL)
1366 {
1367 uint8_t zero = 0;
1368
1369 m_fh->write(m_miscellaneous[i].buffer, m_miscellaneous[i].size);
1370
1371 // Pad if necessary.
1372 if ((m_miscellaneous[i].size%2) != 0)
1373 writeU8(&zero);
1374 }
1375 else
1376 {
1377 int size;
1378 size = m_miscellaneous[i].size;
1379
1380 // Pad if necessary.
1381 if ((size % 2) != 0)
1382 size++;
1383 m_fh->seek(size, File::SeekFromCurrent);
1384 }
1385 }
1386 }
1387
1388 return AF_SUCCEED;
1389 }
1390
writeCues()1391 status WAVEFile::writeCues()
1392 {
1393 Track *track = getTrack();
1394
1395 if (!track->markerCount)
1396 return AF_SUCCEED;
1397
1398 if (m_markOffset == 0)
1399 m_markOffset = m_fh->tell();
1400 else
1401 m_fh->seek(m_markOffset, File::SeekFromBeginning);
1402
1403 Tag cue("cue ");
1404 writeTag(&cue);
1405
1406 /*
1407 The cue chunk consists of 4 bytes for the number of cue points
1408 followed by 24 bytes for each cue point record.
1409 */
1410 uint32_t cueChunkSize = 4 + track->markerCount * 24;
1411 writeU32(&cueChunkSize);
1412 uint32_t numCues = track->markerCount;
1413 writeU32(&numCues);
1414
1415 // Write each marker to the file.
1416 for (int i=0; i<track->markerCount; i++)
1417 {
1418 uint32_t identifier = track->markers[i].id;
1419 writeU32(&identifier);
1420
1421 uint32_t position = i;
1422 writeU32(&position);
1423
1424 Tag data("data");
1425 writeTag(&data);
1426
1427 /*
1428 For an uncompressed WAVE file which contains only one data chunk,
1429 chunkStart and blockStart are zero.
1430 */
1431 uint32_t chunkStart = 0;
1432 writeU32(&chunkStart);
1433
1434 uint32_t blockStart = 0;
1435 writeU32(&blockStart);
1436
1437 AFframecount markPosition = track->markers[i].position;
1438 uint32_t sampleOffset = markPosition;
1439 writeU32(&sampleOffset);
1440 }
1441
1442 // Now write the cue names and comments within a master list chunk.
1443 uint32_t listChunkSize = 4;
1444 for (int i=0; i<track->markerCount; i++)
1445 {
1446 const char *name = track->markers[i].name;
1447 const char *comment = track->markers[i].comment;
1448
1449 /*
1450 Each 'labl' or 'note' chunk consists of 4 bytes for the chunk ID,
1451 4 bytes for the chunk data size, 4 bytes for the cue point ID,
1452 and then the length of the label as a null-terminated string.
1453
1454 In all, this is 12 bytes plus the length of the string, its null
1455 termination byte, and a trailing pad byte if the length of the
1456 chunk is otherwise odd.
1457 */
1458 listChunkSize += 12 + zStringLength(name);
1459 listChunkSize += 12 + zStringLength(comment);
1460 }
1461
1462 Tag list("LIST");
1463 writeTag(&list);
1464 writeU32(&listChunkSize);
1465 Tag adtl("adtl");
1466 writeTag(&adtl);
1467
1468 for (int i=0; i<track->markerCount; i++)
1469 {
1470 uint32_t cuePointID = track->markers[i].id;
1471
1472 const char *name = track->markers[i].name;
1473 uint32_t labelSize = 4 + zStringLength(name);
1474 Tag lablTag("labl");
1475 writeTag(&lablTag);
1476 writeU32(&labelSize);
1477 writeU32(&cuePointID);
1478 writeZString(name);
1479
1480 const char *comment = track->markers[i].comment;
1481 uint32_t noteSize = 4 + zStringLength(comment);
1482 Tag noteTag("note");
1483 writeTag(¬eTag);
1484 writeU32(¬eSize);
1485 writeU32(&cuePointID);
1486 writeZString(comment);
1487 }
1488
1489 return AF_SUCCEED;
1490 }
1491
writeZString(const char * s)1492 bool WAVEFile::writeZString(const char *s)
1493 {
1494 ssize_t lengthPlusNull = strlen(s) + 1;
1495 if (m_fh->write(s, lengthPlusNull) != lengthPlusNull)
1496 return false;
1497 if (lengthPlusNull & 1)
1498 {
1499 uint8_t zero = 0;
1500 if (!writeU8(&zero))
1501 return false;
1502 }
1503 return true;
1504 }
1505
zStringLength(const char * s)1506 size_t WAVEFile::zStringLength(const char *s)
1507 {
1508 size_t lengthPlusNull = strlen(s) + 1;
1509 return lengthPlusNull + (lengthPlusNull & 1);
1510 }
1511
writeInit(AFfilesetup setup)1512 status WAVEFile::writeInit(AFfilesetup setup)
1513 {
1514 if (initFromSetup(setup) == AF_FAIL)
1515 return AF_FAIL;
1516
1517 initCompressionParams();
1518
1519 uint32_t zero = 0;
1520
1521 m_fh->seek(0, File::SeekFromBeginning);
1522 m_fh->write("RIFF", 4);
1523 m_fh->write(&zero, 4);
1524 m_fh->write("WAVE", 4);
1525
1526 writeMiscellaneous();
1527 writeCues();
1528 writeFormat();
1529 writeFrameCount();
1530 writeData();
1531
1532 return AF_SUCCEED;
1533 }
1534
readUUID(UUID * u)1535 bool WAVEFile::readUUID(UUID *u)
1536 {
1537 return m_fh->read(u->data, 16) == 16;
1538 }
1539
writeUUID(const UUID * u)1540 bool WAVEFile::writeUUID(const UUID *u)
1541 {
1542 return m_fh->write(u->data, 16) == 16;
1543 }
1544
initCompressionParams()1545 void WAVEFile::initCompressionParams()
1546 {
1547 Track *track = getTrack();
1548 if (track->f.compressionType == AF_COMPRESSION_IMA)
1549 initIMACompressionParams();
1550 else if (track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
1551 initMSADPCMCompressionParams();
1552 }
1553
initIMACompressionParams()1554 void WAVEFile::initIMACompressionParams()
1555 {
1556 Track *track = getTrack();
1557
1558 track->f.framesPerPacket = 505;
1559 track->f.bytesPerPacket = 256 * track->f.channelCount;
1560
1561 AUpvlist pv = AUpvnew(1);
1562 AUpvsetparam(pv, 0, _AF_IMA_ADPCM_TYPE);
1563 AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
1564 long l = _AF_IMA_ADPCM_TYPE_WAVE;
1565 AUpvsetval(pv, 0, &l);
1566
1567 track->f.compressionParams = pv;
1568 }
1569
initMSADPCMCompressionParams()1570 void WAVEFile::initMSADPCMCompressionParams()
1571 {
1572 const int16_t coefficients[7][2] =
1573 {
1574 { 256, 0 },
1575 { 512, -256 },
1576 { 0, 0 },
1577 { 192, 64 },
1578 { 240, 0 },
1579 { 460, -208 },
1580 { 392, -232 }
1581 };
1582 memcpy(m_msadpcmCoefficients, coefficients, sizeof (int16_t) * 7 * 2);
1583 m_msadpcmNumCoefficients = 7;
1584
1585 Track *track = getTrack();
1586
1587 track->f.framesPerPacket = 500;
1588 track->f.bytesPerPacket = 256 * track->f.channelCount;
1589
1590 AUpvlist pv = AUpvnew(2);
1591 AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);
1592 AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
1593 long l = m_msadpcmNumCoefficients;
1594 AUpvsetval(pv, 0, &l);
1595
1596 AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);
1597 AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);
1598 void *v = m_msadpcmCoefficients;
1599 AUpvsetval(pv, 1, &v);
1600
1601 track->f.compressionParams = pv;
1602 }
1603