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