The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1136 lines
48KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. static const char* const wavFormatName = "WAV file";
  19. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  20. //==============================================================================
  21. const char* const WavAudioFormat::bwavDescription = "bwav description";
  22. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  23. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  24. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  25. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  26. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  27. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  28. StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  29. const String& originator,
  30. const String& originatorRef,
  31. const Time& date,
  32. const int64 timeReferenceSamples,
  33. const String& codingHistory)
  34. {
  35. StringPairArray m;
  36. m.set (bwavDescription, description);
  37. m.set (bwavOriginator, originator);
  38. m.set (bwavOriginatorRef, originatorRef);
  39. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  40. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  41. m.set (bwavTimeReference, String (timeReferenceSamples));
  42. m.set (bwavCodingHistory, codingHistory);
  43. return m;
  44. }
  45. //==============================================================================
  46. namespace WavFileHelpers
  47. {
  48. inline int chunkName (const char* const name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
  49. #if JUCE_MSVC
  50. #pragma pack (push, 1)
  51. #endif
  52. struct BWAVChunk
  53. {
  54. char description [256];
  55. char originator [32];
  56. char originatorRef [32];
  57. char originationDate [10];
  58. char originationTime [8];
  59. uint32 timeRefLow;
  60. uint32 timeRefHigh;
  61. uint16 version;
  62. uint8 umid[64];
  63. uint8 reserved[190];
  64. char codingHistory[1];
  65. void copyTo (StringPairArray& values, const int totalSize) const
  66. {
  67. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description)));
  68. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator)));
  69. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef)));
  70. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate)));
  71. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime)));
  72. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  73. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  74. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  75. values.set (WavAudioFormat::bwavTimeReference, String (time));
  76. values.set (WavAudioFormat::bwavCodingHistory,
  77. String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory)));
  78. }
  79. static MemoryBlock createFrom (const StringPairArray& values)
  80. {
  81. const size_t sizeNeeded = sizeof (BWAVChunk) + (size_t) values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  82. MemoryBlock data ((sizeNeeded + 3) & ~3);
  83. data.fillWith (0);
  84. BWAVChunk* b = (BWAVChunk*) data.getData();
  85. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  86. // as they get called in the right order..
  87. values [WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257);
  88. values [WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33);
  89. values [WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33);
  90. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  91. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  92. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  93. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  94. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  95. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  96. if (b->description[0] != 0
  97. || b->originator[0] != 0
  98. || b->originationDate[0] != 0
  99. || b->originationTime[0] != 0
  100. || b->codingHistory[0] != 0
  101. || time != 0)
  102. {
  103. return data;
  104. }
  105. return MemoryBlock();
  106. }
  107. } JUCE_PACKED;
  108. //==============================================================================
  109. struct SMPLChunk
  110. {
  111. struct SampleLoop
  112. {
  113. uint32 identifier;
  114. uint32 type; // these are different in AIFF and WAV
  115. uint32 start;
  116. uint32 end;
  117. uint32 fraction;
  118. uint32 playCount;
  119. } JUCE_PACKED;
  120. uint32 manufacturer;
  121. uint32 product;
  122. uint32 samplePeriod;
  123. uint32 midiUnityNote;
  124. uint32 midiPitchFraction;
  125. uint32 smpteFormat;
  126. uint32 smpteOffset;
  127. uint32 numSampleLoops;
  128. uint32 samplerData;
  129. SampleLoop loops[1];
  130. template <typename NameType>
  131. static void setValue (StringPairArray& values, NameType name, uint32 val)
  132. {
  133. values.set (name, String (ByteOrder::swapIfBigEndian (val)));
  134. }
  135. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  136. {
  137. setValue (values, "Loop" + String (prefix) + name, val);
  138. }
  139. void copyTo (StringPairArray& values, const int totalSize) const
  140. {
  141. setValue (values, "Manufacturer", manufacturer);
  142. setValue (values, "Product", product);
  143. setValue (values, "SamplePeriod", samplePeriod);
  144. setValue (values, "MidiUnityNote", midiUnityNote);
  145. setValue (values, "MidiPitchFraction", midiPitchFraction);
  146. setValue (values, "SmpteFormat", smpteFormat);
  147. setValue (values, "SmpteOffset", smpteOffset);
  148. setValue (values, "NumSampleLoops", numSampleLoops);
  149. setValue (values, "SamplerData", samplerData);
  150. for (int i = 0; i < (int) numSampleLoops; ++i)
  151. {
  152. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  153. break;
  154. setValue (values, i, "Identifier", loops[i].identifier);
  155. setValue (values, i, "Type", loops[i].type);
  156. setValue (values, i, "Start", loops[i].start);
  157. setValue (values, i, "End", loops[i].end);
  158. setValue (values, i, "Fraction", loops[i].fraction);
  159. setValue (values, i, "PlayCount", loops[i].playCount);
  160. }
  161. }
  162. template <typename NameType>
  163. static uint32 getValue (const StringPairArray& values, NameType name, const char* def)
  164. {
  165. return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue());
  166. }
  167. static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def)
  168. {
  169. return getValue (values, "Loop" + String (prefix) + name, def);
  170. }
  171. static MemoryBlock createFrom (const StringPairArray& values)
  172. {
  173. MemoryBlock data;
  174. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  175. if (numLoops > 0)
  176. {
  177. const size_t sizeNeeded = sizeof (SMPLChunk) + (size_t) (numLoops - 1) * sizeof (SampleLoop);
  178. data.setSize ((sizeNeeded + 3) & ~3, true);
  179. SMPLChunk* const s = static_cast <SMPLChunk*> (data.getData());
  180. s->manufacturer = getValue (values, "Manufacturer", "0");
  181. s->product = getValue (values, "Product", "0");
  182. s->samplePeriod = getValue (values, "SamplePeriod", "0");
  183. s->midiUnityNote = getValue (values, "MidiUnityNote", "60");
  184. s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0");
  185. s->smpteFormat = getValue (values, "SmpteFormat", "0");
  186. s->smpteOffset = getValue (values, "SmpteOffset", "0");
  187. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  188. s->samplerData = getValue (values, "SamplerData", "0");
  189. for (int i = 0; i < numLoops; ++i)
  190. {
  191. s->loops[i].identifier = getValue (values, i, "Identifier", "0");
  192. s->loops[i].type = getValue (values, i, "Type", "0");
  193. s->loops[i].start = getValue (values, i, "Start", "0");
  194. s->loops[i].end = getValue (values, i, "End", "0");
  195. s->loops[i].fraction = getValue (values, i, "Fraction", "0");
  196. s->loops[i].playCount = getValue (values, i, "PlayCount", "0");
  197. }
  198. }
  199. return data;
  200. }
  201. } JUCE_PACKED;
  202. //==============================================================================
  203. struct InstChunk
  204. {
  205. int8 baseNote;
  206. int8 detune;
  207. int8 gain;
  208. int8 lowNote;
  209. int8 highNote;
  210. int8 lowVelocity;
  211. int8 highVelocity;
  212. static void setValue (StringPairArray& values, const char* name, int val)
  213. {
  214. values.set (name, String (val));
  215. }
  216. void copyTo (StringPairArray& values) const
  217. {
  218. setValue (values, "MidiUnityNote", baseNote);
  219. setValue (values, "Detune", detune);
  220. setValue (values, "Gain", gain);
  221. setValue (values, "LowNote", lowNote);
  222. setValue (values, "HighNote", highNote);
  223. setValue (values, "LowVelocity", lowVelocity);
  224. setValue (values, "HighVelocity", highVelocity);
  225. }
  226. static int8 getValue (const StringPairArray& values, const char* name, const char* def)
  227. {
  228. return (int8) values.getValue (name, def).getIntValue();
  229. }
  230. static MemoryBlock createFrom (const StringPairArray& values)
  231. {
  232. MemoryBlock data;
  233. const StringArray& keys = values.getAllKeys();
  234. if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true))
  235. {
  236. data.setSize (8, true);
  237. InstChunk* const inst = static_cast <InstChunk*> (data.getData());
  238. inst->baseNote = getValue (values, "MidiUnityNote", "60");
  239. inst->detune = getValue (values, "Detune", "0");
  240. inst->gain = getValue (values, "Gain", "0");
  241. inst->lowNote = getValue (values, "LowNote", "0");
  242. inst->highNote = getValue (values, "HighNote", "127");
  243. inst->lowVelocity = getValue (values, "LowVelocity", "1");
  244. inst->highVelocity = getValue (values, "HighVelocity", "127");
  245. }
  246. return data;
  247. }
  248. } JUCE_PACKED;
  249. //==============================================================================
  250. struct CueChunk
  251. {
  252. struct Cue
  253. {
  254. uint32 identifier;
  255. uint32 order;
  256. uint32 chunkID;
  257. uint32 chunkStart;
  258. uint32 blockStart;
  259. uint32 offset;
  260. } JUCE_PACKED;
  261. uint32 numCues;
  262. Cue cues[1];
  263. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  264. {
  265. values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val)));
  266. }
  267. void copyTo (StringPairArray& values, const int totalSize) const
  268. {
  269. values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues)));
  270. for (int i = 0; i < (int) numCues; ++i)
  271. {
  272. if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize)
  273. break;
  274. setValue (values, i, "Identifier", cues[i].identifier);
  275. setValue (values, i, "Order", cues[i].order);
  276. setValue (values, i, "ChunkID", cues[i].chunkID);
  277. setValue (values, i, "ChunkStart", cues[i].chunkStart);
  278. setValue (values, i, "BlockStart", cues[i].blockStart);
  279. setValue (values, i, "Offset", cues[i].offset);
  280. }
  281. }
  282. static void create (MemoryBlock& data, const StringPairArray& values)
  283. {
  284. const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  285. if (numCues > 0)
  286. {
  287. const size_t sizeNeeded = sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue);
  288. data.setSize ((sizeNeeded + 3) & ~3, true);
  289. CueChunk* const c = static_cast <CueChunk*> (data.getData());
  290. c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues);
  291. const String dataChunkID (chunkName ("data"));
  292. int nextOrder = 0;
  293. #if JUCE_DEBUG
  294. Array<uint32> identifiers;
  295. #endif
  296. for (int i = 0; i < numCues; ++i)
  297. {
  298. const String prefix ("Cue" + String (i));
  299. uint32 identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue();
  300. #if JUCE_DEBUG
  301. jassert (! identifiers.contains (identifier));
  302. identifiers.add (identifier);
  303. #endif
  304. c->cues[i].identifier = ByteOrder::swapIfBigEndian ((uint32) identifier);
  305. const int order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue();
  306. nextOrder = jmax (nextOrder, order) + 1;
  307. c->cues[i].order = ByteOrder::swapIfBigEndian ((uint32) order);
  308. c->cues[i].chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue());
  309. c->cues[i].chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue());
  310. c->cues[i].blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue());
  311. c->cues[i].offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue());
  312. }
  313. }
  314. }
  315. } JUCE_PACKED;
  316. //==============================================================================
  317. namespace ListChunk
  318. {
  319. static int getValue (const StringPairArray& values, const String& name)
  320. {
  321. return values.getValue (name, "0").getIntValue();
  322. }
  323. static int getValue (const StringPairArray& values, const String& prefix, const char* name)
  324. {
  325. return getValue (values, prefix + name);
  326. }
  327. static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix,
  328. const int chunkType, MemoryOutputStream& out)
  329. {
  330. const String label (values.getValue (prefix + "Text", prefix));
  331. const int labelLength = label.getNumBytesAsUTF8() + 1;
  332. const int chunkLength = 4 + labelLength + (labelLength & 1);
  333. out.writeInt (chunkType);
  334. out.writeInt (chunkLength);
  335. out.writeInt (getValue (values, prefix, "Identifier"));
  336. out.write (label.toUTF8(), labelLength);
  337. if ((out.getDataSize() & 1) != 0)
  338. out.writeByte (0);
  339. }
  340. static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out)
  341. {
  342. const String text (values.getValue (prefix + "Text", prefix));
  343. const int textLength = text.getNumBytesAsUTF8() + 1; // include null terminator
  344. int chunkLength = textLength + 20 + (textLength & 1);
  345. out.writeInt (chunkName ("ltxt"));
  346. out.writeInt (chunkLength);
  347. out.writeInt (getValue (values, prefix, "Identifier"));
  348. out.writeInt (getValue (values, prefix, "SampleLength"));
  349. out.writeInt (getValue (values, prefix, "Purpose"));
  350. out.writeShort ((short) getValue (values, prefix, "Country"));
  351. out.writeShort ((short) getValue (values, prefix, "Language"));
  352. out.writeShort ((short) getValue (values, prefix, "Dialect"));
  353. out.writeShort ((short) getValue (values, prefix, "CodePage"));
  354. out.write (text.toUTF8(), textLength);
  355. if ((out.getDataSize() & 1) != 0)
  356. out.writeByte (0);
  357. }
  358. static void create (MemoryBlock& block, const StringPairArray& values)
  359. {
  360. const int numCueLabels = getValue (values, "NumCueLabels");
  361. const int numCueNotes = getValue (values, "NumCueNotes");
  362. const int numCueRegions = getValue (values, "NumCueRegions");
  363. if (numCueLabels > 0 || numCueNotes > 0 || numCueRegions > 0)
  364. {
  365. MemoryOutputStream out (block, false);
  366. for (int i = 0; i < numCueLabels; ++i)
  367. appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out);
  368. for (int i = 0; i < numCueNotes; ++i)
  369. appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out);
  370. for (int i = 0; i < numCueRegions; ++i)
  371. appendExtraChunk (values, "CueRegion" + String (i), out);
  372. }
  373. }
  374. }
  375. //==============================================================================
  376. struct ExtensibleWavSubFormat
  377. {
  378. uint32 data1;
  379. uint16 data2;
  380. uint16 data3;
  381. uint8 data4[8];
  382. } JUCE_PACKED;
  383. static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  384. static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  385. static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  386. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  387. {
  388. uint32 riffSizeLow; // low 4 byte size of RF64 block
  389. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  390. uint32 dataSizeLow; // low 4 byte size of data chunk
  391. uint32 dataSizeHigh; // high 4 byte size of data chunk
  392. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  393. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  394. uint32 tableLength; // number of valid entries in array 'table'
  395. } JUCE_PACKED;
  396. #if JUCE_MSVC
  397. #pragma pack (pop)
  398. #endif
  399. }
  400. //==============================================================================
  401. class WavAudioFormatReader : public AudioFormatReader
  402. {
  403. public:
  404. WavAudioFormatReader (InputStream* const in)
  405. : AudioFormatReader (in, TRANS (wavFormatName)),
  406. bwavChunkStart (0),
  407. bwavSize (0),
  408. dataLength (0),
  409. isRF64 (false)
  410. {
  411. using namespace WavFileHelpers;
  412. uint64 len = 0;
  413. uint64 end = 0;
  414. bool hasGotType = false;
  415. bool hasGotData = false;
  416. int cueNoteIndex = 0;
  417. int cueLabelIndex = 0;
  418. int cueRegionIndex = 0;
  419. const int firstChunkType = input->readInt();
  420. if (firstChunkType == chunkName ("RF64"))
  421. {
  422. input->skipNextBytes (4); // size is -1 for RF64
  423. isRF64 = true;
  424. }
  425. else if (firstChunkType == chunkName ("RIFF"))
  426. {
  427. len = (uint64) (uint32) input->readInt();
  428. end = len + (uint64) input->getPosition();
  429. }
  430. else
  431. {
  432. return;
  433. }
  434. const int64 startOfRIFFChunk = input->getPosition();
  435. if (input->readInt() == chunkName ("WAVE"))
  436. {
  437. if (isRF64 && input->readInt() == chunkName ("ds64"))
  438. {
  439. const uint32 length = (uint32) input->readInt();
  440. if (length < 28)
  441. return;
  442. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  443. len = (uint64) input->readInt64();
  444. end = len + (uint64) startOfRIFFChunk;
  445. dataLength = input->readInt64();
  446. input->setPosition (chunkEnd);
  447. }
  448. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  449. {
  450. const int chunkType = input->readInt();
  451. uint32 length = (uint32) input->readInt();
  452. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  453. if (chunkType == chunkName ("fmt "))
  454. {
  455. // read the format chunk
  456. const unsigned short format = (unsigned short) input->readShort();
  457. numChannels = (unsigned int) input->readShort();
  458. sampleRate = input->readInt();
  459. const int bytesPerSec = input->readInt();
  460. input->skipNextBytes (2);
  461. bitsPerSample = (unsigned int) (int) input->readShort();
  462. if (bitsPerSample > 64)
  463. {
  464. bytesPerFrame = bytesPerSec / (int) sampleRate;
  465. bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels;
  466. }
  467. else
  468. {
  469. bytesPerFrame = numChannels * bitsPerSample / 8;
  470. }
  471. if (format == 3)
  472. {
  473. usesFloatingPointData = true;
  474. }
  475. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  476. {
  477. if (length < 40) // too short
  478. {
  479. bytesPerFrame = 0;
  480. }
  481. else
  482. {
  483. input->skipNextBytes (4); // skip over size and bitsPerSample
  484. metadataValues.set ("ChannelMask", String (input->readInt()));
  485. ExtensibleWavSubFormat subFormat;
  486. subFormat.data1 = (uint32) input->readInt();
  487. subFormat.data2 = (uint16) input->readShort();
  488. subFormat.data3 = (uint16) input->readShort();
  489. input->read (subFormat.data4, sizeof (subFormat.data4));
  490. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0
  491. && memcmp (&subFormat, &IEEEFloatFormat, sizeof (subFormat)) != 0
  492. && memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  493. bytesPerFrame = 0;
  494. }
  495. }
  496. else if (format != 1)
  497. {
  498. bytesPerFrame = 0;
  499. }
  500. hasGotType = true;
  501. }
  502. else if (chunkType == chunkName ("data"))
  503. {
  504. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  505. dataLength = length;
  506. dataChunkStart = input->getPosition();
  507. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  508. hasGotData = true;
  509. }
  510. else if (chunkType == chunkName ("bext"))
  511. {
  512. bwavChunkStart = input->getPosition();
  513. bwavSize = length;
  514. HeapBlock <BWAVChunk> bwav;
  515. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  516. input->read (bwav, (int) length);
  517. bwav->copyTo (metadataValues, (int) length);
  518. }
  519. else if (chunkType == chunkName ("smpl"))
  520. {
  521. HeapBlock <SMPLChunk> smpl;
  522. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  523. input->read (smpl, (int) length);
  524. smpl->copyTo (metadataValues, (int) length);
  525. }
  526. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  527. {
  528. HeapBlock <InstChunk> inst;
  529. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  530. input->read (inst, (int) length);
  531. inst->copyTo (metadataValues);
  532. }
  533. else if (chunkType == chunkName ("cue "))
  534. {
  535. HeapBlock <CueChunk> cue;
  536. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  537. input->read (cue, (int) length);
  538. cue->copyTo (metadataValues, (int) length);
  539. }
  540. else if (chunkType == chunkName ("LIST"))
  541. {
  542. if (input->readInt() == chunkName ("adtl"))
  543. {
  544. while (input->getPosition() < chunkEnd)
  545. {
  546. const int adtlChunkType = input->readInt();
  547. const uint32 adtlLength = (uint32) input->readInt();
  548. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  549. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  550. {
  551. String prefix;
  552. if (adtlChunkType == chunkName ("labl"))
  553. prefix << "CueLabel" << cueLabelIndex++;
  554. else if (adtlChunkType == chunkName ("note"))
  555. prefix << "CueNote" << cueNoteIndex++;
  556. const uint32 identifier = (uint32) input->readInt();
  557. const int stringLength = (int) adtlLength - 4;
  558. MemoryBlock textBlock;
  559. input->readIntoMemoryBlock (textBlock, stringLength);
  560. metadataValues.set (prefix + "Identifier", String (identifier));
  561. metadataValues.set (prefix + "Text", textBlock.toString());
  562. }
  563. else if (adtlChunkType == chunkName ("ltxt"))
  564. {
  565. const String prefix ("CueRegion" + String (cueRegionIndex++));
  566. const uint32 identifier = (uint32) input->readInt();
  567. const uint32 sampleLength = (uint32) input->readInt();
  568. const uint32 purpose = (uint32) input->readInt();
  569. const uint16 country = (uint16) input->readInt();
  570. const uint16 language = (uint16) input->readInt();
  571. const uint16 dialect = (uint16) input->readInt();
  572. const uint16 codePage = (uint16) input->readInt();
  573. const uint32 stringLength = adtlLength - 20;
  574. MemoryBlock textBlock;
  575. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  576. metadataValues.set (prefix + "Identifier", String (identifier));
  577. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  578. metadataValues.set (prefix + "Purpose", String (purpose));
  579. metadataValues.set (prefix + "Country", String (country));
  580. metadataValues.set (prefix + "Language", String (language));
  581. metadataValues.set (prefix + "Dialect", String (dialect));
  582. metadataValues.set (prefix + "CodePage", String (codePage));
  583. metadataValues.set (prefix + "Text", textBlock.toString());
  584. }
  585. input->setPosition (adtlChunkEnd);
  586. }
  587. }
  588. }
  589. else if (chunkEnd <= input->getPosition())
  590. {
  591. break;
  592. }
  593. input->setPosition (chunkEnd);
  594. }
  595. }
  596. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  597. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  598. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  599. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  600. }
  601. //==============================================================================
  602. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  603. int64 startSampleInFile, int numSamples)
  604. {
  605. jassert (destSamples != nullptr);
  606. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  607. if (samplesAvailable < numSamples)
  608. {
  609. for (int i = numDestChannels; --i >= 0;)
  610. if (destSamples[i] != nullptr)
  611. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * (size_t) numSamples);
  612. numSamples = (int) samplesAvailable;
  613. }
  614. if (numSamples <= 0)
  615. return true;
  616. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  617. while (numSamples > 0)
  618. {
  619. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  620. char tempBuffer [tempBufSize];
  621. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  622. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  623. if (bytesRead < numThisTime * bytesPerFrame)
  624. {
  625. jassert (bytesRead >= 0);
  626. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  627. }
  628. switch (bitsPerSample)
  629. {
  630. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  631. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  632. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  633. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime);
  634. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  635. default: jassertfalse; break;
  636. }
  637. startOffsetInDestBuffer += numThisTime;
  638. numSamples -= numThisTime;
  639. }
  640. return true;
  641. }
  642. int64 bwavChunkStart, bwavSize;
  643. private:
  644. ScopedPointer<AudioData::Converter> converter;
  645. int bytesPerFrame;
  646. int64 dataChunkStart, dataLength;
  647. bool isRF64;
  648. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  649. };
  650. //==============================================================================
  651. class WavAudioFormatWriter : public AudioFormatWriter
  652. {
  653. public:
  654. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  655. const unsigned int numChannels_, const unsigned int bits,
  656. const StringPairArray& metadataValues)
  657. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  658. lengthInSamples (0),
  659. bytesWritten (0),
  660. writeFailed (false)
  661. {
  662. using namespace WavFileHelpers;
  663. if (metadataValues.size() > 0)
  664. {
  665. // The meta data should have been santised for the WAV format.
  666. // If it was originally sourced from an AIFF file the MetaDataSource
  667. // key should be removed (or set to "WAV") once this has been done
  668. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  669. bwavChunk = BWAVChunk::createFrom (metadataValues);
  670. smplChunk = SMPLChunk::createFrom (metadataValues);
  671. instChunk = InstChunk::createFrom (metadataValues);
  672. CueChunk ::create (cueChunk, metadataValues);
  673. ListChunk::create (listChunk, metadataValues);
  674. }
  675. headerPosition = out->getPosition();
  676. writeHeader();
  677. }
  678. ~WavAudioFormatWriter()
  679. {
  680. if ((bytesWritten & 1) != 0) // pad to an even length
  681. {
  682. ++bytesWritten;
  683. output->writeByte (0);
  684. }
  685. writeHeader();
  686. }
  687. //==============================================================================
  688. bool write (const int** data, int numSamples)
  689. {
  690. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  691. if (writeFailed)
  692. return false;
  693. const size_t bytes = numChannels * (unsigned int) numSamples * bitsPerSample / 8;
  694. tempBlock.ensureSize (bytes, false);
  695. switch (bitsPerSample)
  696. {
  697. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  698. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  699. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  700. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  701. default: jassertfalse; break;
  702. }
  703. if (! output->write (tempBlock.getData(), (int) bytes))
  704. {
  705. // failed to write to disk, so let's try writing the header.
  706. // If it's just run out of disk space, then if it does manage
  707. // to write the header, we'll still have a useable file..
  708. writeHeader();
  709. writeFailed = true;
  710. return false;
  711. }
  712. else
  713. {
  714. bytesWritten += bytes;
  715. lengthInSamples += numSamples;
  716. return true;
  717. }
  718. }
  719. private:
  720. ScopedPointer<AudioData::Converter> converter;
  721. MemoryBlock tempBlock, bwavChunk, smplChunk, instChunk, cueChunk, listChunk;
  722. uint64 lengthInSamples, bytesWritten;
  723. int64 headerPosition;
  724. bool writeFailed;
  725. static int getChannelMask (const int numChannels) noexcept
  726. {
  727. switch (numChannels)
  728. {
  729. case 1: return 0;
  730. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  731. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  732. case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  733. case 7: return 1 + 2 + 4 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT
  734. case 8: return 1 + 2 + 4 + 8 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT
  735. default: break;
  736. }
  737. return 0;
  738. }
  739. void writeHeader()
  740. {
  741. using namespace WavFileHelpers;
  742. const bool seekedOk = output->setPosition (headerPosition);
  743. (void) seekedOk;
  744. // if this fails, you've given it an output stream that can't seek! It needs
  745. // to be able to seek back to write the header
  746. jassert (seekedOk);
  747. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  748. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  749. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  750. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  751. int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  752. + 8 + audioDataSize + (audioDataSize & 1)
  753. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  754. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  755. + (instChunk.getSize() > 0 ? (8 + instChunk.getSize()) : 0)
  756. + (cueChunk .getSize() > 0 ? (8 + cueChunk .getSize()) : 0)
  757. + (listChunk.getSize() > 0 ? (12 + listChunk.getSize()) : 0)
  758. + (8 + 28)); // (ds64 chunk)
  759. riffChunkSize += (riffChunkSize & 1);
  760. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  761. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  762. output->writeInt (chunkName ("WAVE"));
  763. if (! isRF64)
  764. {
  765. output->writeInt (chunkName ("JUNK"));
  766. output->writeInt (28 + (isWaveFmtEx? 0 : 24));
  767. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  768. }
  769. else
  770. {
  771. // write ds64 chunk
  772. output->writeInt (chunkName ("ds64"));
  773. output->writeInt (28); // chunk size for uncompressed data (no table)
  774. output->writeInt64 (riffChunkSize);
  775. output->writeInt64 ((int64) audioDataSize);
  776. output->writeRepeatedByte (0, 12);
  777. }
  778. output->writeInt (chunkName ("fmt "));
  779. if (isWaveFmtEx)
  780. {
  781. output->writeInt (40); // chunk size
  782. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  783. }
  784. else
  785. {
  786. output->writeInt (16); // chunk size
  787. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  788. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  789. }
  790. output->writeShort ((short) numChannels);
  791. output->writeInt ((int) sampleRate);
  792. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  793. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  794. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  795. if (isWaveFmtEx)
  796. {
  797. output->writeShort (22); // cbSize (size of the extension)
  798. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  799. output->writeInt (getChannelMask ((int) numChannels));
  800. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  801. output->writeInt ((int) subFormat.data1);
  802. output->writeShort ((short) subFormat.data2);
  803. output->writeShort ((short) subFormat.data3);
  804. output->write (subFormat.data4, sizeof (subFormat.data4));
  805. }
  806. if (bwavChunk.getSize() > 0)
  807. {
  808. output->writeInt (chunkName ("bext"));
  809. output->writeInt ((int) bwavChunk.getSize());
  810. *output << bwavChunk;
  811. }
  812. if (smplChunk.getSize() > 0)
  813. {
  814. output->writeInt (chunkName ("smpl"));
  815. output->writeInt ((int) smplChunk.getSize());
  816. *output << smplChunk;
  817. }
  818. if (instChunk.getSize() > 0)
  819. {
  820. output->writeInt (chunkName ("inst"));
  821. output->writeInt (7);
  822. *output << instChunk;
  823. }
  824. if (cueChunk.getSize() > 0)
  825. {
  826. output->writeInt (chunkName ("cue "));
  827. output->writeInt ((int) cueChunk.getSize());
  828. *output << cueChunk;
  829. }
  830. if (listChunk.getSize() > 0)
  831. {
  832. output->writeInt (chunkName ("LIST"));
  833. output->writeInt ((int) listChunk.getSize() + 4);
  834. output->writeInt (chunkName ("adtl"));
  835. *output << listChunk;
  836. }
  837. output->writeInt (chunkName ("data"));
  838. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  839. usesFloatingPointData = (bitsPerSample == 32);
  840. }
  841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  842. };
  843. //==============================================================================
  844. WavAudioFormat::WavAudioFormat()
  845. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  846. {
  847. }
  848. WavAudioFormat::~WavAudioFormat()
  849. {
  850. }
  851. Array<int> WavAudioFormat::getPossibleSampleRates()
  852. {
  853. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  854. return Array <int> (rates);
  855. }
  856. Array<int> WavAudioFormat::getPossibleBitDepths()
  857. {
  858. const int depths[] = { 8, 16, 24, 32, 0 };
  859. return Array <int> (depths);
  860. }
  861. bool WavAudioFormat::canDoStereo() { return true; }
  862. bool WavAudioFormat::canDoMono() { return true; }
  863. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  864. const bool deleteStreamIfOpeningFails)
  865. {
  866. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  867. if (r->sampleRate > 0 && r->numChannels > 0)
  868. return r.release();
  869. if (! deleteStreamIfOpeningFails)
  870. r->input = nullptr;
  871. return nullptr;
  872. }
  873. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  874. unsigned int numChannels, int bitsPerSample,
  875. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  876. {
  877. if (getPossibleBitDepths().contains (bitsPerSample))
  878. return new WavAudioFormatWriter (out, sampleRate, (unsigned int) numChannels,
  879. (unsigned int) bitsPerSample, metadataValues);
  880. return nullptr;
  881. }
  882. namespace WavFileHelpers
  883. {
  884. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  885. {
  886. TemporaryFile tempFile (file);
  887. WavAudioFormat wav;
  888. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  889. if (reader != nullptr)
  890. {
  891. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  892. if (outStream != nullptr)
  893. {
  894. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  895. reader->numChannels, (int) reader->bitsPerSample,
  896. metadata, 0));
  897. if (writer != nullptr)
  898. {
  899. outStream.release();
  900. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  901. writer = nullptr;
  902. reader = nullptr;
  903. return ok && tempFile.overwriteTargetFileWithTemporary();
  904. }
  905. }
  906. }
  907. return false;
  908. }
  909. }
  910. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  911. {
  912. using namespace WavFileHelpers;
  913. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  914. if (reader != nullptr)
  915. {
  916. const int64 bwavPos = reader->bwavChunkStart;
  917. const int64 bwavSize = reader->bwavSize;
  918. reader = nullptr;
  919. if (bwavSize > 0)
  920. {
  921. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  922. if (chunk.getSize() <= (size_t) bwavSize)
  923. {
  924. // the new one will fit in the space available, so write it directly..
  925. const int64 oldSize = wavFile.getSize();
  926. {
  927. FileOutputStream out (wavFile);
  928. if (! out.failedToOpen())
  929. {
  930. out.setPosition (bwavPos);
  931. out << chunk;
  932. out.setPosition (oldSize);
  933. }
  934. }
  935. jassert (wavFile.getSize() == oldSize);
  936. return true;
  937. }
  938. }
  939. }
  940. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  941. }