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.

1145 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. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  385. {
  386. uint32 riffSizeLow; // low 4 byte size of RF64 block
  387. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  388. uint32 dataSizeLow; // low 4 byte size of data chunk
  389. uint32 dataSizeHigh; // high 4 byte size of data chunk
  390. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  391. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  392. uint32 tableLength; // number of valid entries in array 'table'
  393. } JUCE_PACKED;
  394. #if JUCE_MSVC
  395. #pragma pack (pop)
  396. #endif
  397. }
  398. //==============================================================================
  399. class WavAudioFormatReader : public AudioFormatReader
  400. {
  401. public:
  402. WavAudioFormatReader (InputStream* const in)
  403. : AudioFormatReader (in, TRANS (wavFormatName)),
  404. bwavChunkStart (0),
  405. bwavSize (0),
  406. dataLength (0),
  407. isRF64 (false)
  408. {
  409. using namespace WavFileHelpers;
  410. uint64 len = 0;
  411. uint64 end = 0;
  412. bool hasGotType = false;
  413. bool hasGotData = false;
  414. int cueNoteIndex = 0;
  415. int cueLabelIndex = 0;
  416. int cueRegionIndex = 0;
  417. const int firstChunkType = input->readInt();
  418. if (firstChunkType == chunkName ("RF64"))
  419. {
  420. input->skipNextBytes (4); // size is -1 for RF64
  421. isRF64 = true;
  422. }
  423. else if (firstChunkType == chunkName ("RIFF"))
  424. {
  425. len = (uint64) (uint32) input->readInt();
  426. end = input->getPosition() + len;
  427. }
  428. else
  429. {
  430. return;
  431. }
  432. const int64 startOfRIFFChunk = input->getPosition();
  433. if (input->readInt() == chunkName ("WAVE"))
  434. {
  435. if (isRF64 && input->readInt() == chunkName ("ds64"))
  436. {
  437. const uint32 length = (uint32) input->readInt();
  438. if (length < 28)
  439. return;
  440. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  441. len = (uint64) input->readInt64();
  442. end = startOfRIFFChunk + len;
  443. dataLength = input->readInt64();
  444. input->setPosition (chunkEnd);
  445. }
  446. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  447. {
  448. const int chunkType = input->readInt();
  449. uint32 length = (uint32) input->readInt();
  450. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  451. if (chunkType == chunkName ("fmt "))
  452. {
  453. // read the format chunk
  454. const unsigned short format = (unsigned short) input->readShort();
  455. numChannels = (unsigned int) input->readShort();
  456. sampleRate = input->readInt();
  457. const int bytesPerSec = input->readInt();
  458. input->skipNextBytes (2);
  459. bitsPerSample = (unsigned int) (int) input->readShort();
  460. if (bitsPerSample > 64)
  461. {
  462. bytesPerFrame = bytesPerSec / (int) sampleRate;
  463. bitsPerSample = 8 * bytesPerFrame / numChannels;
  464. }
  465. else
  466. {
  467. bytesPerFrame = numChannels * bitsPerSample / 8;
  468. }
  469. if (format == 3)
  470. {
  471. usesFloatingPointData = true;
  472. }
  473. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  474. {
  475. if (length < 40) // too short
  476. {
  477. bytesPerFrame = 0;
  478. }
  479. else
  480. {
  481. input->skipNextBytes (6); // skip over bitsPerSample
  482. metadataValues.set ("ChannelMask", String (input->readInt()));
  483. ExtensibleWavSubFormat subFormat;
  484. subFormat.data1 = (uint32) input->readInt();
  485. subFormat.data2 = (uint16) input->readShort();
  486. subFormat.data3 = (uint16) input->readShort();
  487. input->read (subFormat.data4, sizeof (subFormat.data4));
  488. const ExtensibleWavSubFormat pcmFormat
  489. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  490. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  491. {
  492. const ExtensibleWavSubFormat ambisonicFormat
  493. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  494. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  495. bytesPerFrame = 0;
  496. }
  497. }
  498. }
  499. else if (format != 1)
  500. {
  501. bytesPerFrame = 0;
  502. }
  503. hasGotType = true;
  504. }
  505. else if (chunkType == chunkName ("data"))
  506. {
  507. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  508. dataLength = length;
  509. dataChunkStart = input->getPosition();
  510. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  511. hasGotData = true;
  512. }
  513. else if (chunkType == chunkName ("bext"))
  514. {
  515. bwavChunkStart = input->getPosition();
  516. bwavSize = length;
  517. HeapBlock <BWAVChunk> bwav;
  518. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  519. input->read (bwav, (int) length);
  520. bwav->copyTo (metadataValues, (int) length);
  521. }
  522. else if (chunkType == chunkName ("smpl"))
  523. {
  524. HeapBlock <SMPLChunk> smpl;
  525. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  526. input->read (smpl, (int) length);
  527. smpl->copyTo (metadataValues, (int) length);
  528. }
  529. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  530. {
  531. HeapBlock <InstChunk> inst;
  532. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  533. input->read (inst, (int) length);
  534. inst->copyTo (metadataValues);
  535. }
  536. else if (chunkType == chunkName ("cue "))
  537. {
  538. HeapBlock <CueChunk> cue;
  539. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  540. input->read (cue, (int) length);
  541. cue->copyTo (metadataValues, (int) length);
  542. }
  543. else if (chunkType == chunkName ("LIST"))
  544. {
  545. if (input->readInt() == chunkName ("adtl"))
  546. {
  547. while (input->getPosition() < chunkEnd)
  548. {
  549. const int adtlChunkType = input->readInt();
  550. const uint32 adtlLength = (uint32) input->readInt();
  551. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  552. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  553. {
  554. String prefix;
  555. if (adtlChunkType == chunkName ("labl"))
  556. prefix << "CueLabel" << cueLabelIndex++;
  557. else if (adtlChunkType == chunkName ("note"))
  558. prefix << "CueNote" << cueNoteIndex++;
  559. const uint32 identifier = (uint32) input->readInt();
  560. const int stringLength = (int) adtlLength - 4;
  561. MemoryBlock textBlock;
  562. input->readIntoMemoryBlock (textBlock, stringLength);
  563. metadataValues.set (prefix + "Identifier", String (identifier));
  564. metadataValues.set (prefix + "Text", textBlock.toString());
  565. }
  566. else if (adtlChunkType == chunkName ("ltxt"))
  567. {
  568. const String prefix ("CueRegion" + String (cueRegionIndex++));
  569. const uint32 identifier = (uint32) input->readInt();
  570. const uint32 sampleLength = (uint32) input->readInt();
  571. const uint32 purpose = (uint32) input->readInt();
  572. const uint16 country = (uint16) input->readInt();
  573. const uint16 language = (uint16) input->readInt();
  574. const uint16 dialect = (uint16) input->readInt();
  575. const uint16 codePage = (uint16) input->readInt();
  576. const uint32 stringLength = adtlLength - 20;
  577. MemoryBlock textBlock;
  578. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  579. metadataValues.set (prefix + "Identifier", String (identifier));
  580. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  581. metadataValues.set (prefix + "Purpose", String (purpose));
  582. metadataValues.set (prefix + "Country", String (country));
  583. metadataValues.set (prefix + "Language", String (language));
  584. metadataValues.set (prefix + "Dialect", String (dialect));
  585. metadataValues.set (prefix + "CodePage", String (codePage));
  586. metadataValues.set (prefix + "Text", textBlock.toString());
  587. }
  588. input->setPosition (adtlChunkEnd);
  589. }
  590. }
  591. }
  592. else if (chunkEnd <= input->getPosition())
  593. {
  594. break;
  595. }
  596. input->setPosition (chunkEnd);
  597. }
  598. }
  599. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  600. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  601. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  602. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  603. }
  604. //==============================================================================
  605. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  606. int64 startSampleInFile, int numSamples)
  607. {
  608. jassert (destSamples != nullptr);
  609. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  610. if (samplesAvailable < numSamples)
  611. {
  612. for (int i = numDestChannels; --i >= 0;)
  613. if (destSamples[i] != nullptr)
  614. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  615. numSamples = (int) samplesAvailable;
  616. }
  617. if (numSamples <= 0)
  618. return true;
  619. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  620. while (numSamples > 0)
  621. {
  622. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  623. char tempBuffer [tempBufSize];
  624. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  625. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  626. if (bytesRead < numThisTime * bytesPerFrame)
  627. {
  628. jassert (bytesRead >= 0);
  629. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  630. }
  631. switch (bitsPerSample)
  632. {
  633. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  634. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  635. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  636. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime);
  637. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  638. default: jassertfalse; break;
  639. }
  640. startOffsetInDestBuffer += numThisTime;
  641. numSamples -= numThisTime;
  642. }
  643. return true;
  644. }
  645. int64 bwavChunkStart, bwavSize;
  646. private:
  647. ScopedPointer<AudioData::Converter> converter;
  648. int bytesPerFrame;
  649. int64 dataChunkStart, dataLength;
  650. bool isRF64;
  651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  652. };
  653. //==============================================================================
  654. class WavAudioFormatWriter : public AudioFormatWriter
  655. {
  656. public:
  657. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  658. const unsigned int numChannels_, const unsigned int bits,
  659. const StringPairArray& metadataValues)
  660. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  661. lengthInSamples (0),
  662. bytesWritten (0),
  663. writeFailed (false)
  664. {
  665. using namespace WavFileHelpers;
  666. if (metadataValues.size() > 0)
  667. {
  668. // The meta data should have been santised for the WAV format.
  669. // If it was originally sourced from an AIFF file the MetaDataSource
  670. // key should be removed (or set to "WAV") once this has been done
  671. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  672. bwavChunk = BWAVChunk::createFrom (metadataValues);
  673. smplChunk = SMPLChunk::createFrom (metadataValues);
  674. instChunk = InstChunk::createFrom (metadataValues);
  675. CueChunk ::create (cueChunk, metadataValues);
  676. ListChunk::create (listChunk, metadataValues);
  677. }
  678. headerPosition = out->getPosition();
  679. writeHeader();
  680. }
  681. ~WavAudioFormatWriter()
  682. {
  683. if ((bytesWritten & 1) != 0) // pad to an even length
  684. {
  685. ++bytesWritten;
  686. output->writeByte (0);
  687. }
  688. writeHeader();
  689. }
  690. //==============================================================================
  691. bool write (const int** data, int numSamples)
  692. {
  693. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  694. if (writeFailed)
  695. return false;
  696. const size_t bytes = numChannels * numSamples * bitsPerSample / 8;
  697. tempBlock.ensureSize (bytes, false);
  698. switch (bitsPerSample)
  699. {
  700. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  701. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  702. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  703. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  704. default: jassertfalse; break;
  705. }
  706. if (! output->write (tempBlock.getData(), (int) bytes))
  707. {
  708. // failed to write to disk, so let's try writing the header.
  709. // If it's just run out of disk space, then if it does manage
  710. // to write the header, we'll still have a useable file..
  711. writeHeader();
  712. writeFailed = true;
  713. return false;
  714. }
  715. else
  716. {
  717. bytesWritten += bytes;
  718. lengthInSamples += numSamples;
  719. return true;
  720. }
  721. }
  722. private:
  723. ScopedPointer<AudioData::Converter> converter;
  724. MemoryBlock tempBlock, bwavChunk, smplChunk, instChunk, cueChunk, listChunk;
  725. uint64 lengthInSamples, bytesWritten;
  726. int64 headerPosition;
  727. bool writeFailed;
  728. static int getChannelMask (const int numChannels) noexcept
  729. {
  730. switch (numChannels)
  731. {
  732. case 1: return 0;
  733. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  734. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  735. 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
  736. 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
  737. 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
  738. default: break;
  739. }
  740. return 0;
  741. }
  742. void writeHeader()
  743. {
  744. using namespace WavFileHelpers;
  745. const bool seekedOk = output->setPosition (headerPosition);
  746. (void) seekedOk;
  747. // if this fails, you've given it an output stream that can't seek! It needs
  748. // to be able to seek back to write the header
  749. jassert (seekedOk);
  750. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  751. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  752. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  753. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  754. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  755. + 8 + audioDataSize + (audioDataSize & 1)
  756. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  757. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  758. + (instChunk.getSize() > 0 ? (8 + instChunk.getSize()) : 0)
  759. + (cueChunk .getSize() > 0 ? (8 + cueChunk .getSize()) : 0)
  760. + (listChunk.getSize() > 0 ? (12 + listChunk.getSize()) : 0)
  761. + (8 + 28); // (ds64 chunk)
  762. riffChunkSize += (riffChunkSize & 1);
  763. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  764. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  765. output->writeInt (chunkName ("WAVE"));
  766. if (! isRF64)
  767. {
  768. output->writeInt (chunkName ("JUNK"));
  769. output->writeInt (28 + (isWaveFmtEx? 0 : 24));
  770. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  771. }
  772. else
  773. {
  774. // write ds64 chunk
  775. output->writeInt (chunkName ("ds64"));
  776. output->writeInt (28); // chunk size for uncompressed data (no table)
  777. output->writeInt64 (riffChunkSize);
  778. output->writeInt64 (audioDataSize);
  779. output->writeRepeatedByte (0, 12);
  780. }
  781. output->writeInt (chunkName ("fmt "));
  782. if (isWaveFmtEx)
  783. {
  784. output->writeInt (40); // chunk size
  785. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  786. }
  787. else
  788. {
  789. output->writeInt (16); // chunk size
  790. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  791. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  792. }
  793. output->writeShort ((short) numChannels);
  794. output->writeInt ((int) sampleRate);
  795. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  796. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  797. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  798. if (isWaveFmtEx)
  799. {
  800. output->writeShort (22); // cbSize (size of the extension)
  801. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  802. output->writeInt (getChannelMask ((int) numChannels));
  803. const ExtensibleWavSubFormat pcmFormat
  804. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  805. const ExtensibleWavSubFormat IEEEFloatFormat
  806. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  807. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  808. output->writeInt ((int) subFormat.data1);
  809. output->writeShort ((short) subFormat.data2);
  810. output->writeShort ((short) subFormat.data3);
  811. output->write (subFormat.data4, sizeof (subFormat.data4));
  812. }
  813. if (bwavChunk.getSize() > 0)
  814. {
  815. output->writeInt (chunkName ("bext"));
  816. output->writeInt ((int) bwavChunk.getSize());
  817. *output << bwavChunk;
  818. }
  819. if (smplChunk.getSize() > 0)
  820. {
  821. output->writeInt (chunkName ("smpl"));
  822. output->writeInt ((int) smplChunk.getSize());
  823. *output << smplChunk;
  824. }
  825. if (instChunk.getSize() > 0)
  826. {
  827. output->writeInt (chunkName ("inst"));
  828. output->writeInt (7);
  829. *output << instChunk;
  830. }
  831. if (cueChunk.getSize() > 0)
  832. {
  833. output->writeInt (chunkName ("cue "));
  834. output->writeInt ((int) cueChunk.getSize());
  835. *output << cueChunk;
  836. }
  837. if (listChunk.getSize() > 0)
  838. {
  839. output->writeInt (chunkName ("LIST"));
  840. output->writeInt ((int) listChunk.getSize() + 4);
  841. output->writeInt (chunkName ("adtl"));
  842. *output << listChunk;
  843. }
  844. output->writeInt (chunkName ("data"));
  845. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  846. usesFloatingPointData = (bitsPerSample == 32);
  847. }
  848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  849. };
  850. //==============================================================================
  851. WavAudioFormat::WavAudioFormat()
  852. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  853. {
  854. }
  855. WavAudioFormat::~WavAudioFormat()
  856. {
  857. }
  858. Array<int> WavAudioFormat::getPossibleSampleRates()
  859. {
  860. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  861. return Array <int> (rates);
  862. }
  863. Array<int> WavAudioFormat::getPossibleBitDepths()
  864. {
  865. const int depths[] = { 8, 16, 24, 32, 0 };
  866. return Array <int> (depths);
  867. }
  868. bool WavAudioFormat::canDoStereo() { return true; }
  869. bool WavAudioFormat::canDoMono() { return true; }
  870. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  871. const bool deleteStreamIfOpeningFails)
  872. {
  873. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  874. if (r->sampleRate > 0 && r->numChannels > 0)
  875. return r.release();
  876. if (! deleteStreamIfOpeningFails)
  877. r->input = nullptr;
  878. return nullptr;
  879. }
  880. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  881. unsigned int numChannels, int bitsPerSample,
  882. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  883. {
  884. if (getPossibleBitDepths().contains (bitsPerSample))
  885. return new WavAudioFormatWriter (out, sampleRate, (int) numChannels, bitsPerSample, metadataValues);
  886. return nullptr;
  887. }
  888. namespace WavFileHelpers
  889. {
  890. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  891. {
  892. TemporaryFile tempFile (file);
  893. WavAudioFormat wav;
  894. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  895. if (reader != nullptr)
  896. {
  897. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  898. if (outStream != nullptr)
  899. {
  900. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  901. reader->numChannels, (int) reader->bitsPerSample,
  902. metadata, 0));
  903. if (writer != nullptr)
  904. {
  905. outStream.release();
  906. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  907. writer = nullptr;
  908. reader = nullptr;
  909. return ok && tempFile.overwriteTargetFileWithTemporary();
  910. }
  911. }
  912. }
  913. return false;
  914. }
  915. }
  916. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  917. {
  918. using namespace WavFileHelpers;
  919. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  920. if (reader != nullptr)
  921. {
  922. const int64 bwavPos = reader->bwavChunkStart;
  923. const int64 bwavSize = reader->bwavSize;
  924. reader = nullptr;
  925. if (bwavSize > 0)
  926. {
  927. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  928. if (chunk.getSize() <= (size_t) bwavSize)
  929. {
  930. // the new one will fit in the space available, so write it directly..
  931. const int64 oldSize = wavFile.getSize();
  932. {
  933. FileOutputStream out (wavFile);
  934. if (! out.failedToOpen())
  935. {
  936. out.setPosition (bwavPos);
  937. out << chunk;
  938. out.setPosition (oldSize);
  939. }
  940. }
  941. jassert (wavFile.getSize() == oldSize);
  942. return true;
  943. }
  944. }
  945. }
  946. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  947. }