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.

1432 lines
63KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. static const char* const wavFormatName = "WAV file";
  18. //==============================================================================
  19. const char* const WavAudioFormat::bwavDescription = "bwav description";
  20. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  21. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  22. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  23. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  24. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  25. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  26. StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  27. const String& originator,
  28. const String& originatorRef,
  29. const Time date,
  30. const int64 timeReferenceSamples,
  31. const String& codingHistory)
  32. {
  33. StringPairArray m;
  34. m.set (bwavDescription, description);
  35. m.set (bwavOriginator, originator);
  36. m.set (bwavOriginatorRef, originatorRef);
  37. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  38. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  39. m.set (bwavTimeReference, String (timeReferenceSamples));
  40. m.set (bwavCodingHistory, codingHistory);
  41. return m;
  42. }
  43. const char* const WavAudioFormat::acidOneShot = "acid one shot";
  44. const char* const WavAudioFormat::acidRootSet = "acid root set";
  45. const char* const WavAudioFormat::acidStretch = "acid stretch";
  46. const char* const WavAudioFormat::acidDiskBased = "acid disk based";
  47. const char* const WavAudioFormat::acidizerFlag = "acidizer flag";
  48. const char* const WavAudioFormat::acidRootNote = "acid root note";
  49. const char* const WavAudioFormat::acidBeats = "acid beats";
  50. const char* const WavAudioFormat::acidDenominator = "acid denominator";
  51. const char* const WavAudioFormat::acidNumerator = "acid numerator";
  52. const char* const WavAudioFormat::acidTempo = "acid tempo";
  53. const char* const WavAudioFormat::ISRC = "ISRC";
  54. const char* const WavAudioFormat::tracktionLoopInfo = "tracktion loop info";
  55. //==============================================================================
  56. namespace WavFileHelpers
  57. {
  58. inline int chunkName (const char* const name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
  59. inline size_t roundUpSize (size_t sz) noexcept { return (sz + 3) & ~3u; }
  60. #if JUCE_MSVC
  61. #pragma pack (push, 1)
  62. #endif
  63. struct BWAVChunk
  64. {
  65. char description [256];
  66. char originator [32];
  67. char originatorRef [32];
  68. char originationDate [10];
  69. char originationTime [8];
  70. uint32 timeRefLow;
  71. uint32 timeRefHigh;
  72. uint16 version;
  73. uint8 umid[64];
  74. uint8 reserved[190];
  75. char codingHistory[1];
  76. void copyTo (StringPairArray& values, const int totalSize) const
  77. {
  78. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description)));
  79. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator)));
  80. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef)));
  81. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate)));
  82. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime)));
  83. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  84. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  85. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  86. values.set (WavAudioFormat::bwavTimeReference, String (time));
  87. values.set (WavAudioFormat::bwavCodingHistory,
  88. String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory)));
  89. }
  90. static MemoryBlock createFrom (const StringPairArray& values)
  91. {
  92. MemoryBlock data (roundUpSize (sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8()));
  93. data.fillWith (0);
  94. BWAVChunk* b = (BWAVChunk*) data.getData();
  95. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  96. // as they get called in the right order..
  97. values [WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257);
  98. values [WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33);
  99. values [WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33);
  100. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  101. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  102. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  103. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  104. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  105. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  106. if (b->description[0] != 0
  107. || b->originator[0] != 0
  108. || b->originationDate[0] != 0
  109. || b->originationTime[0] != 0
  110. || b->codingHistory[0] != 0
  111. || time != 0)
  112. {
  113. return data;
  114. }
  115. return MemoryBlock();
  116. }
  117. } JUCE_PACKED;
  118. //==============================================================================
  119. struct SMPLChunk
  120. {
  121. struct SampleLoop
  122. {
  123. uint32 identifier;
  124. uint32 type; // these are different in AIFF and WAV
  125. uint32 start;
  126. uint32 end;
  127. uint32 fraction;
  128. uint32 playCount;
  129. } JUCE_PACKED;
  130. uint32 manufacturer;
  131. uint32 product;
  132. uint32 samplePeriod;
  133. uint32 midiUnityNote;
  134. uint32 midiPitchFraction;
  135. uint32 smpteFormat;
  136. uint32 smpteOffset;
  137. uint32 numSampleLoops;
  138. uint32 samplerData;
  139. SampleLoop loops[1];
  140. template <typename NameType>
  141. static void setValue (StringPairArray& values, NameType name, uint32 val)
  142. {
  143. values.set (name, String (ByteOrder::swapIfBigEndian (val)));
  144. }
  145. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  146. {
  147. setValue (values, "Loop" + String (prefix) + name, val);
  148. }
  149. void copyTo (StringPairArray& values, const int totalSize) const
  150. {
  151. setValue (values, "Manufacturer", manufacturer);
  152. setValue (values, "Product", product);
  153. setValue (values, "SamplePeriod", samplePeriod);
  154. setValue (values, "MidiUnityNote", midiUnityNote);
  155. setValue (values, "MidiPitchFraction", midiPitchFraction);
  156. setValue (values, "SmpteFormat", smpteFormat);
  157. setValue (values, "SmpteOffset", smpteOffset);
  158. setValue (values, "NumSampleLoops", numSampleLoops);
  159. setValue (values, "SamplerData", samplerData);
  160. for (int i = 0; i < (int) numSampleLoops; ++i)
  161. {
  162. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  163. break;
  164. setValue (values, i, "Identifier", loops[i].identifier);
  165. setValue (values, i, "Type", loops[i].type);
  166. setValue (values, i, "Start", loops[i].start);
  167. setValue (values, i, "End", loops[i].end);
  168. setValue (values, i, "Fraction", loops[i].fraction);
  169. setValue (values, i, "PlayCount", loops[i].playCount);
  170. }
  171. }
  172. template <typename NameType>
  173. static uint32 getValue (const StringPairArray& values, NameType name, const char* def)
  174. {
  175. return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue());
  176. }
  177. static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def)
  178. {
  179. return getValue (values, "Loop" + String (prefix) + name, def);
  180. }
  181. static MemoryBlock createFrom (const StringPairArray& values)
  182. {
  183. MemoryBlock data;
  184. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  185. if (numLoops > 0)
  186. {
  187. data.setSize (roundUpSize (sizeof (SMPLChunk) + (size_t) (numLoops - 1) * sizeof (SampleLoop)), true);
  188. SMPLChunk* const s = static_cast<SMPLChunk*> (data.getData());
  189. s->manufacturer = getValue (values, "Manufacturer", "0");
  190. s->product = getValue (values, "Product", "0");
  191. s->samplePeriod = getValue (values, "SamplePeriod", "0");
  192. s->midiUnityNote = getValue (values, "MidiUnityNote", "60");
  193. s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0");
  194. s->smpteFormat = getValue (values, "SmpteFormat", "0");
  195. s->smpteOffset = getValue (values, "SmpteOffset", "0");
  196. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  197. s->samplerData = getValue (values, "SamplerData", "0");
  198. for (int i = 0; i < numLoops; ++i)
  199. {
  200. SampleLoop& loop = s->loops[i];
  201. loop.identifier = getValue (values, i, "Identifier", "0");
  202. loop.type = getValue (values, i, "Type", "0");
  203. loop.start = getValue (values, i, "Start", "0");
  204. loop.end = getValue (values, i, "End", "0");
  205. loop.fraction = getValue (values, i, "Fraction", "0");
  206. loop.playCount = getValue (values, i, "PlayCount", "0");
  207. }
  208. }
  209. return data;
  210. }
  211. } JUCE_PACKED;
  212. //==============================================================================
  213. struct InstChunk
  214. {
  215. int8 baseNote;
  216. int8 detune;
  217. int8 gain;
  218. int8 lowNote;
  219. int8 highNote;
  220. int8 lowVelocity;
  221. int8 highVelocity;
  222. static void setValue (StringPairArray& values, const char* name, int val)
  223. {
  224. values.set (name, String (val));
  225. }
  226. void copyTo (StringPairArray& values) const
  227. {
  228. setValue (values, "MidiUnityNote", baseNote);
  229. setValue (values, "Detune", detune);
  230. setValue (values, "Gain", gain);
  231. setValue (values, "LowNote", lowNote);
  232. setValue (values, "HighNote", highNote);
  233. setValue (values, "LowVelocity", lowVelocity);
  234. setValue (values, "HighVelocity", highVelocity);
  235. }
  236. static int8 getValue (const StringPairArray& values, const char* name, const char* def)
  237. {
  238. return (int8) values.getValue (name, def).getIntValue();
  239. }
  240. static MemoryBlock createFrom (const StringPairArray& values)
  241. {
  242. MemoryBlock data;
  243. const StringArray& keys = values.getAllKeys();
  244. if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true))
  245. {
  246. data.setSize (8, true);
  247. InstChunk* const inst = static_cast<InstChunk*> (data.getData());
  248. inst->baseNote = getValue (values, "MidiUnityNote", "60");
  249. inst->detune = getValue (values, "Detune", "0");
  250. inst->gain = getValue (values, "Gain", "0");
  251. inst->lowNote = getValue (values, "LowNote", "0");
  252. inst->highNote = getValue (values, "HighNote", "127");
  253. inst->lowVelocity = getValue (values, "LowVelocity", "1");
  254. inst->highVelocity = getValue (values, "HighVelocity", "127");
  255. }
  256. return data;
  257. }
  258. } JUCE_PACKED;
  259. //==============================================================================
  260. struct CueChunk
  261. {
  262. struct Cue
  263. {
  264. uint32 identifier;
  265. uint32 order;
  266. uint32 chunkID;
  267. uint32 chunkStart;
  268. uint32 blockStart;
  269. uint32 offset;
  270. } JUCE_PACKED;
  271. uint32 numCues;
  272. Cue cues[1];
  273. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  274. {
  275. values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val)));
  276. }
  277. void copyTo (StringPairArray& values, const int totalSize) const
  278. {
  279. values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues)));
  280. for (int i = 0; i < (int) numCues; ++i)
  281. {
  282. if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize)
  283. break;
  284. setValue (values, i, "Identifier", cues[i].identifier);
  285. setValue (values, i, "Order", cues[i].order);
  286. setValue (values, i, "ChunkID", cues[i].chunkID);
  287. setValue (values, i, "ChunkStart", cues[i].chunkStart);
  288. setValue (values, i, "BlockStart", cues[i].blockStart);
  289. setValue (values, i, "Offset", cues[i].offset);
  290. }
  291. }
  292. static MemoryBlock createFrom (const StringPairArray& values)
  293. {
  294. MemoryBlock data;
  295. const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  296. if (numCues > 0)
  297. {
  298. data.setSize (roundUpSize (sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue)), true);
  299. CueChunk* const c = static_cast<CueChunk*> (data.getData());
  300. c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues);
  301. const String dataChunkID (chunkName ("data"));
  302. int nextOrder = 0;
  303. #if JUCE_DEBUG
  304. Array<uint32> identifiers;
  305. #endif
  306. for (int i = 0; i < numCues; ++i)
  307. {
  308. const String prefix ("Cue" + String (i));
  309. const uint32 identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue();
  310. #if JUCE_DEBUG
  311. jassert (! identifiers.contains (identifier));
  312. identifiers.add (identifier);
  313. #endif
  314. const int order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue();
  315. nextOrder = jmax (nextOrder, order) + 1;
  316. Cue& cue = c->cues[i];
  317. cue.identifier = ByteOrder::swapIfBigEndian ((uint32) identifier);
  318. cue.order = ByteOrder::swapIfBigEndian ((uint32) order);
  319. cue.chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue());
  320. cue.chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue());
  321. cue.blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue());
  322. cue.offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue());
  323. }
  324. }
  325. return data;
  326. }
  327. } JUCE_PACKED;
  328. //==============================================================================
  329. namespace ListChunk
  330. {
  331. static int getValue (const StringPairArray& values, const String& name)
  332. {
  333. return values.getValue (name, "0").getIntValue();
  334. }
  335. static int getValue (const StringPairArray& values, const String& prefix, const char* name)
  336. {
  337. return getValue (values, prefix + name);
  338. }
  339. static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix,
  340. const int chunkType, MemoryOutputStream& out)
  341. {
  342. const String label (values.getValue (prefix + "Text", prefix));
  343. const int labelLength = (int) label.getNumBytesAsUTF8() + 1;
  344. const int chunkLength = 4 + labelLength + (labelLength & 1);
  345. out.writeInt (chunkType);
  346. out.writeInt (chunkLength);
  347. out.writeInt (getValue (values, prefix, "Identifier"));
  348. out.write (label.toUTF8(), (size_t) labelLength);
  349. if ((out.getDataSize() & 1) != 0)
  350. out.writeByte (0);
  351. }
  352. static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out)
  353. {
  354. const String text (values.getValue (prefix + "Text", prefix));
  355. const int textLength = (int) text.getNumBytesAsUTF8() + 1; // include null terminator
  356. int chunkLength = textLength + 20 + (textLength & 1);
  357. out.writeInt (chunkName ("ltxt"));
  358. out.writeInt (chunkLength);
  359. out.writeInt (getValue (values, prefix, "Identifier"));
  360. out.writeInt (getValue (values, prefix, "SampleLength"));
  361. out.writeInt (getValue (values, prefix, "Purpose"));
  362. out.writeShort ((short) getValue (values, prefix, "Country"));
  363. out.writeShort ((short) getValue (values, prefix, "Language"));
  364. out.writeShort ((short) getValue (values, prefix, "Dialect"));
  365. out.writeShort ((short) getValue (values, prefix, "CodePage"));
  366. out.write (text.toUTF8(), (size_t) textLength);
  367. if ((out.getDataSize() & 1) != 0)
  368. out.writeByte (0);
  369. }
  370. static MemoryBlock createFrom (const StringPairArray& values)
  371. {
  372. const int numCueLabels = getValue (values, "NumCueLabels");
  373. const int numCueNotes = getValue (values, "NumCueNotes");
  374. const int numCueRegions = getValue (values, "NumCueRegions");
  375. MemoryOutputStream out;
  376. if (numCueLabels + numCueNotes + numCueRegions > 0)
  377. {
  378. out.writeInt (chunkName ("adtl"));
  379. for (int i = 0; i < numCueLabels; ++i)
  380. appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out);
  381. for (int i = 0; i < numCueNotes; ++i)
  382. appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out);
  383. for (int i = 0; i < numCueRegions; ++i)
  384. appendExtraChunk (values, "CueRegion" + String (i), out);
  385. }
  386. return out.getMemoryBlock();
  387. }
  388. }
  389. //==============================================================================
  390. struct AcidChunk
  391. {
  392. /** Reads an acid RIFF chunk from a stream positioned just after the size byte. */
  393. AcidChunk (InputStream& input, size_t length)
  394. {
  395. zerostruct (*this);
  396. input.read (this, (int) jmin (sizeof (*this), length));
  397. }
  398. void addToMetadata (StringPairArray& values) const
  399. {
  400. setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01);
  401. setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02);
  402. setBoolFlag (values, WavAudioFormat::acidStretch, 0x04);
  403. setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08);
  404. setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10);
  405. if (flags & 0x02) // root note set
  406. values.set (WavAudioFormat::acidRootNote, String (ByteOrder::swapIfBigEndian (rootNote)));
  407. values.set (WavAudioFormat::acidBeats, String (ByteOrder::swapIfBigEndian (numBeats)));
  408. values.set (WavAudioFormat::acidDenominator, String (ByteOrder::swapIfBigEndian (meterDenominator)));
  409. values.set (WavAudioFormat::acidNumerator, String (ByteOrder::swapIfBigEndian (meterNumerator)));
  410. values.set (WavAudioFormat::acidTempo, String (swapFloatByteOrder (tempo)));
  411. }
  412. void setBoolFlag (StringPairArray& values, const char* name, uint32 mask) const
  413. {
  414. values.set (name, (flags & ByteOrder::swapIfBigEndian (mask)) ? "1" : "0");
  415. }
  416. template<typename IntType>
  417. static void setIntFlagIfPresent (IntType& flag, const StringPairArray& values, const char* name)
  418. {
  419. if (values.containsKey (name))
  420. flag = ByteOrder::swapIfBigEndian ((IntType) values[name].getIntValue());
  421. }
  422. static uint32 getFlagIfPresent (const StringPairArray& values, const char* name, uint32 flag)
  423. {
  424. return values[name].getIntValue() != 0 ? ByteOrder::swapIfBigEndian (flag) : 0;
  425. }
  426. static float swapFloatByteOrder (const float x) noexcept
  427. {
  428. #ifdef JUCE_BIG_ENDIAN
  429. union { uint32 asInt; float asFloat; } n;
  430. n.asFloat = x;
  431. n.asInt = ByteOrder::swap (n.asInt);
  432. return n.asFloat;
  433. #else
  434. return x;
  435. #endif
  436. }
  437. static MemoryBlock createFrom (const StringPairArray& values)
  438. {
  439. MemoryBlock data (sizeof (AcidChunk), true);
  440. AcidChunk* const acid = static_cast<AcidChunk*> (data.getData());
  441. acid->flags = getFlagIfPresent (values, WavAudioFormat::acidOneShot, 0x01)
  442. | getFlagIfPresent (values, WavAudioFormat::acidRootSet, 0x02)
  443. | getFlagIfPresent (values, WavAudioFormat::acidStretch, 0x04)
  444. | getFlagIfPresent (values, WavAudioFormat::acidDiskBased, 0x08)
  445. | getFlagIfPresent (values, WavAudioFormat::acidizerFlag, 0x10);
  446. if (values[WavAudioFormat::acidRootSet].getIntValue() != 0)
  447. setIntFlagIfPresent (acid->rootNote, values, WavAudioFormat::acidRootNote);
  448. setIntFlagIfPresent (acid->numBeats, values, WavAudioFormat::acidBeats);
  449. setIntFlagIfPresent (acid->meterDenominator, values, WavAudioFormat::acidDenominator);
  450. setIntFlagIfPresent (acid->meterNumerator, values, WavAudioFormat::acidNumerator);
  451. if (values.containsKey (WavAudioFormat::acidTempo))
  452. acid->tempo = swapFloatByteOrder (values[WavAudioFormat::acidTempo].getFloatValue());
  453. if (acid->flags == 0 && acid->rootNote == 0 && acid->numBeats == 0
  454. && acid->meterDenominator == 0 && acid->meterNumerator == 0)
  455. return MemoryBlock();
  456. return data;
  457. }
  458. uint32 flags;
  459. uint16 rootNote;
  460. uint16 reserved1;
  461. float reserved2;
  462. uint32 numBeats;
  463. uint16 meterDenominator;
  464. uint16 meterNumerator;
  465. float tempo;
  466. } JUCE_PACKED;
  467. //==============================================================================
  468. struct TracktionChunk
  469. {
  470. static MemoryBlock createFrom (const StringPairArray& values)
  471. {
  472. const String s = values[WavAudioFormat::tracktionLoopInfo];
  473. MemoryBlock data;
  474. if (s.isNotEmpty())
  475. {
  476. MemoryOutputStream os (data, false);
  477. os.writeString (s);
  478. }
  479. return data;
  480. }
  481. };
  482. //==============================================================================
  483. namespace AXMLChunk
  484. {
  485. static void addToMetadata (StringPairArray& destValues, const String& source)
  486. {
  487. ScopedPointer<XmlElement> xml (XmlDocument::parse (source));
  488. if (xml != nullptr && xml->hasTagName ("ebucore:ebuCoreMain"))
  489. {
  490. if (XmlElement* xml2 = xml->getChildByName ("ebucore:coreMetadata"))
  491. {
  492. if (XmlElement* xml3 = xml2->getChildByName ("ebucore:identifier"))
  493. {
  494. if (XmlElement* xml4 = xml3->getChildByName ("dc:identifier"))
  495. {
  496. const String ISRCCode (xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true));
  497. if (ISRCCode.isNotEmpty())
  498. destValues.set (WavAudioFormat::ISRC, ISRCCode);
  499. }
  500. }
  501. }
  502. }
  503. }
  504. static MemoryBlock createFrom (const StringPairArray& values)
  505. {
  506. const String ISRC (values.getValue (WavAudioFormat::ISRC, String::empty));
  507. MemoryOutputStream xml;
  508. if (ISRC.isNotEmpty())
  509. {
  510. xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" "
  511. "xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">"
  512. "<ebucore:coreMetadata>"
  513. "<ebucore:identifier typeLabel=\"GUID\" "
  514. "typeDefinition=\"Globally Unique Identifier\" "
  515. "formatLabel=\"ISRC\" "
  516. "formatDefinition=\"International Standard Recording Code\" "
  517. "formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">"
  518. "<dc:identifier>ISRC:" << ISRC << "</dc:identifier>"
  519. "</ebucore:identifier>"
  520. "</ebucore:coreMetadata>"
  521. "</ebucore:ebuCoreMain>";
  522. xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing
  523. }
  524. return xml.getMemoryBlock();
  525. }
  526. };
  527. //==============================================================================
  528. struct ExtensibleWavSubFormat
  529. {
  530. uint32 data1;
  531. uint16 data2;
  532. uint16 data3;
  533. uint8 data4[8];
  534. bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; }
  535. bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); }
  536. } JUCE_PACKED;
  537. static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  538. static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  539. static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  540. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  541. {
  542. uint32 riffSizeLow; // low 4 byte size of RF64 block
  543. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  544. uint32 dataSizeLow; // low 4 byte size of data chunk
  545. uint32 dataSizeHigh; // high 4 byte size of data chunk
  546. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  547. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  548. uint32 tableLength; // number of valid entries in array 'table'
  549. } JUCE_PACKED;
  550. #if JUCE_MSVC
  551. #pragma pack (pop)
  552. #endif
  553. }
  554. //==============================================================================
  555. class WavAudioFormatReader : public AudioFormatReader
  556. {
  557. public:
  558. WavAudioFormatReader (InputStream* const in)
  559. : AudioFormatReader (in, wavFormatName),
  560. bwavChunkStart (0),
  561. bwavSize (0),
  562. dataLength (0),
  563. isRF64 (false)
  564. {
  565. using namespace WavFileHelpers;
  566. uint64 len = 0;
  567. uint64 end = 0;
  568. int cueNoteIndex = 0;
  569. int cueLabelIndex = 0;
  570. int cueRegionIndex = 0;
  571. const int firstChunkType = input->readInt();
  572. if (firstChunkType == chunkName ("RF64"))
  573. {
  574. input->skipNextBytes (4); // size is -1 for RF64
  575. isRF64 = true;
  576. }
  577. else if (firstChunkType == chunkName ("RIFF"))
  578. {
  579. len = (uint64) (uint32) input->readInt();
  580. end = len + (uint64) input->getPosition();
  581. }
  582. else
  583. {
  584. return;
  585. }
  586. const int64 startOfRIFFChunk = input->getPosition();
  587. if (input->readInt() == chunkName ("WAVE"))
  588. {
  589. if (isRF64 && input->readInt() == chunkName ("ds64"))
  590. {
  591. const uint32 length = (uint32) input->readInt();
  592. if (length < 28)
  593. return;
  594. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  595. len = (uint64) input->readInt64();
  596. end = len + (uint64) startOfRIFFChunk;
  597. dataLength = input->readInt64();
  598. input->setPosition (chunkEnd);
  599. }
  600. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  601. {
  602. const int chunkType = input->readInt();
  603. uint32 length = (uint32) input->readInt();
  604. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  605. if (chunkType == chunkName ("fmt "))
  606. {
  607. // read the format chunk
  608. const unsigned short format = (unsigned short) input->readShort();
  609. numChannels = (unsigned int) input->readShort();
  610. sampleRate = input->readInt();
  611. const int bytesPerSec = input->readInt();
  612. input->skipNextBytes (2);
  613. bitsPerSample = (unsigned int) (int) input->readShort();
  614. if (bitsPerSample > 64)
  615. {
  616. bytesPerFrame = bytesPerSec / (int) sampleRate;
  617. bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels;
  618. }
  619. else
  620. {
  621. bytesPerFrame = numChannels * bitsPerSample / 8;
  622. }
  623. if (format == 3)
  624. {
  625. usesFloatingPointData = true;
  626. }
  627. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  628. {
  629. if (length < 40) // too short
  630. {
  631. bytesPerFrame = 0;
  632. }
  633. else
  634. {
  635. input->skipNextBytes (4); // skip over size and bitsPerSample
  636. metadataValues.set ("ChannelMask", String (input->readInt()));
  637. ExtensibleWavSubFormat subFormat;
  638. subFormat.data1 = (uint32) input->readInt();
  639. subFormat.data2 = (uint16) input->readShort();
  640. subFormat.data3 = (uint16) input->readShort();
  641. input->read (subFormat.data4, sizeof (subFormat.data4));
  642. if (subFormat == IEEEFloatFormat)
  643. usesFloatingPointData = true;
  644. else if (subFormat != pcmFormat && subFormat != ambisonicFormat)
  645. bytesPerFrame = 0;
  646. }
  647. }
  648. else if (format != 1)
  649. {
  650. bytesPerFrame = 0;
  651. }
  652. }
  653. else if (chunkType == chunkName ("data"))
  654. {
  655. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  656. dataLength = length;
  657. dataChunkStart = input->getPosition();
  658. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  659. }
  660. else if (chunkType == chunkName ("bext"))
  661. {
  662. bwavChunkStart = input->getPosition();
  663. bwavSize = length;
  664. HeapBlock <BWAVChunk> bwav;
  665. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  666. input->read (bwav, (int) length);
  667. bwav->copyTo (metadataValues, (int) length);
  668. }
  669. else if (chunkType == chunkName ("smpl"))
  670. {
  671. HeapBlock <SMPLChunk> smpl;
  672. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  673. input->read (smpl, (int) length);
  674. smpl->copyTo (metadataValues, (int) length);
  675. }
  676. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  677. {
  678. HeapBlock <InstChunk> inst;
  679. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  680. input->read (inst, (int) length);
  681. inst->copyTo (metadataValues);
  682. }
  683. else if (chunkType == chunkName ("cue "))
  684. {
  685. HeapBlock <CueChunk> cue;
  686. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  687. input->read (cue, (int) length);
  688. cue->copyTo (metadataValues, (int) length);
  689. }
  690. else if (chunkType == chunkName ("axml"))
  691. {
  692. MemoryBlock axml;
  693. input->readIntoMemoryBlock (axml, (ssize_t) length);
  694. AXMLChunk::addToMetadata (metadataValues, axml.toString());
  695. }
  696. else if (chunkType == chunkName ("LIST"))
  697. {
  698. if (input->readInt() == chunkName ("adtl"))
  699. {
  700. while (input->getPosition() < chunkEnd)
  701. {
  702. const int adtlChunkType = input->readInt();
  703. const uint32 adtlLength = (uint32) input->readInt();
  704. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  705. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  706. {
  707. String prefix;
  708. if (adtlChunkType == chunkName ("labl"))
  709. prefix << "CueLabel" << cueLabelIndex++;
  710. else if (adtlChunkType == chunkName ("note"))
  711. prefix << "CueNote" << cueNoteIndex++;
  712. const uint32 identifier = (uint32) input->readInt();
  713. const int stringLength = (int) adtlLength - 4;
  714. MemoryBlock textBlock;
  715. input->readIntoMemoryBlock (textBlock, stringLength);
  716. metadataValues.set (prefix + "Identifier", String (identifier));
  717. metadataValues.set (prefix + "Text", textBlock.toString());
  718. }
  719. else if (adtlChunkType == chunkName ("ltxt"))
  720. {
  721. const String prefix ("CueRegion" + String (cueRegionIndex++));
  722. const uint32 identifier = (uint32) input->readInt();
  723. const uint32 sampleLength = (uint32) input->readInt();
  724. const uint32 purpose = (uint32) input->readInt();
  725. const uint16 country = (uint16) input->readInt();
  726. const uint16 language = (uint16) input->readInt();
  727. const uint16 dialect = (uint16) input->readInt();
  728. const uint16 codePage = (uint16) input->readInt();
  729. const uint32 stringLength = adtlLength - 20;
  730. MemoryBlock textBlock;
  731. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  732. metadataValues.set (prefix + "Identifier", String (identifier));
  733. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  734. metadataValues.set (prefix + "Purpose", String (purpose));
  735. metadataValues.set (prefix + "Country", String (country));
  736. metadataValues.set (prefix + "Language", String (language));
  737. metadataValues.set (prefix + "Dialect", String (dialect));
  738. metadataValues.set (prefix + "CodePage", String (codePage));
  739. metadataValues.set (prefix + "Text", textBlock.toString());
  740. }
  741. input->setPosition (adtlChunkEnd);
  742. }
  743. }
  744. }
  745. else if (chunkType == chunkName ("acid"))
  746. {
  747. AcidChunk (*input, length).addToMetadata (metadataValues);
  748. }
  749. else if (chunkType == chunkName ("Trkn"))
  750. {
  751. MemoryBlock tracktion;
  752. input->readIntoMemoryBlock (tracktion, (ssize_t) length);
  753. metadataValues.set (WavAudioFormat::tracktionLoopInfo, tracktion.toString());
  754. }
  755. else if (chunkEnd <= input->getPosition())
  756. {
  757. break;
  758. }
  759. input->setPosition (chunkEnd);
  760. }
  761. }
  762. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  763. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  764. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  765. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  766. }
  767. //==============================================================================
  768. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  769. int64 startSampleInFile, int numSamples) override
  770. {
  771. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  772. startSampleInFile, numSamples, lengthInSamples);
  773. if (numSamples <= 0)
  774. return true;
  775. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  776. while (numSamples > 0)
  777. {
  778. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  779. char tempBuffer [tempBufSize];
  780. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  781. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  782. if (bytesRead < numThisTime * bytesPerFrame)
  783. {
  784. jassert (bytesRead >= 0);
  785. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  786. }
  787. copySampleData (bitsPerSample, usesFloatingPointData,
  788. destSamples, startOffsetInDestBuffer, numDestChannels,
  789. tempBuffer, (int) numChannels, numThisTime);
  790. startOffsetInDestBuffer += numThisTime;
  791. numSamples -= numThisTime;
  792. }
  793. return true;
  794. }
  795. static void copySampleData (unsigned int bitsPerSample, const bool usesFloatingPointData,
  796. int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
  797. const void* sourceData, int numChannels, int numSamples) noexcept
  798. {
  799. switch (bitsPerSample)
  800. {
  801. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  802. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  803. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  804. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples);
  805. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  806. default: jassertfalse; break;
  807. }
  808. }
  809. int64 bwavChunkStart, bwavSize;
  810. int64 dataChunkStart, dataLength;
  811. int bytesPerFrame;
  812. bool isRF64;
  813. private:
  814. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader)
  815. };
  816. //==============================================================================
  817. class WavAudioFormatWriter : public AudioFormatWriter
  818. {
  819. public:
  820. WavAudioFormatWriter (OutputStream* const out, const double rate,
  821. const unsigned int numChans, const unsigned int bits,
  822. const StringPairArray& metadataValues)
  823. : AudioFormatWriter (out, wavFormatName, rate, numChans, bits),
  824. lengthInSamples (0),
  825. bytesWritten (0),
  826. writeFailed (false)
  827. {
  828. using namespace WavFileHelpers;
  829. if (metadataValues.size() > 0)
  830. {
  831. // The meta data should have been santised for the WAV format.
  832. // If it was originally sourced from an AIFF file the MetaDataSource
  833. // key should be removed (or set to "WAV") once this has been done
  834. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  835. bwavChunk = BWAVChunk::createFrom (metadataValues);
  836. axmlChunk = AXMLChunk::createFrom (metadataValues);
  837. smplChunk = SMPLChunk::createFrom (metadataValues);
  838. instChunk = InstChunk::createFrom (metadataValues);
  839. cueChunk = CueChunk ::createFrom (metadataValues);
  840. listChunk = ListChunk::createFrom (metadataValues);
  841. acidChunk = AcidChunk::createFrom (metadataValues);
  842. trckChunk = TracktionChunk::createFrom (metadataValues);
  843. }
  844. headerPosition = out->getPosition();
  845. writeHeader();
  846. }
  847. ~WavAudioFormatWriter()
  848. {
  849. writeHeader();
  850. }
  851. //==============================================================================
  852. bool write (const int** data, int numSamples) override
  853. {
  854. jassert (numSamples >= 0);
  855. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  856. if (writeFailed)
  857. return false;
  858. const size_t bytes = numChannels * (unsigned int) numSamples * bitsPerSample / 8;
  859. tempBlock.ensureSize (bytes, false);
  860. switch (bitsPerSample)
  861. {
  862. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  863. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  864. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  865. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  866. default: jassertfalse; break;
  867. }
  868. if (! output->write (tempBlock.getData(), bytes))
  869. {
  870. // failed to write to disk, so let's try writing the header.
  871. // If it's just run out of disk space, then if it does manage
  872. // to write the header, we'll still have a useable file..
  873. writeHeader();
  874. writeFailed = true;
  875. return false;
  876. }
  877. bytesWritten += bytes;
  878. lengthInSamples += (uint64) numSamples;
  879. return true;
  880. }
  881. bool flush() override
  882. {
  883. const int64 lastWritePos = output->getPosition();
  884. writeHeader();
  885. if (output->setPosition (lastWritePos))
  886. return true;
  887. // if this fails, you've given it an output stream that can't seek! It needs
  888. // to be able to seek back to write the header
  889. jassertfalse;
  890. return false;
  891. }
  892. private:
  893. MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk, acidChunk, trckChunk;
  894. uint64 lengthInSamples, bytesWritten;
  895. int64 headerPosition;
  896. bool writeFailed;
  897. static int getChannelMask (const int numChannels) noexcept
  898. {
  899. switch (numChannels)
  900. {
  901. case 1: return 0;
  902. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  903. case 3: return 1 + 2 + 4; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER
  904. case 4: return 1 + 2 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  905. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  906. 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
  907. 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
  908. 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
  909. default: break;
  910. }
  911. return 0;
  912. }
  913. void writeHeader()
  914. {
  915. if ((bytesWritten & 1) != 0) // pad to an even length
  916. output->writeByte (0);
  917. using namespace WavFileHelpers;
  918. if (headerPosition != output->getPosition() && ! output->setPosition (headerPosition))
  919. {
  920. // if this fails, you've given it an output stream that can't seek! It needs to be
  921. // able to seek back to go back and write the header after the data has been written.
  922. jassertfalse;
  923. return;
  924. }
  925. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  926. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  927. const bool isRF64 = (bytesWritten >= 0x100000000LL);
  928. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  929. int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  930. + 8 + audioDataSize + (audioDataSize & 1)
  931. + chunkSize (bwavChunk)
  932. + chunkSize (axmlChunk)
  933. + chunkSize (smplChunk)
  934. + chunkSize (instChunk)
  935. + chunkSize (cueChunk)
  936. + chunkSize (listChunk)
  937. + chunkSize (acidChunk)
  938. + chunkSize (trckChunk)
  939. + (8 + 28)); // (ds64 chunk)
  940. riffChunkSize += (riffChunkSize & 1);
  941. if (isRF64)
  942. writeChunkHeader (chunkName ("RF64"), -1);
  943. else
  944. writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize);
  945. output->writeInt (chunkName ("WAVE"));
  946. if (! isRF64)
  947. {
  948. #if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  949. /* NB: This junk chunk is added for padding, so that the header is a fixed size
  950. regardless of whether it's RF64 or not. That way, we can begin recording a file,
  951. and when it's finished, can go back and write either a RIFF or RF64 header,
  952. depending on whether more than 2^32 samples were written.
  953. The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case
  954. you need to create files for crappy WAV players with bugs that stop them skipping chunks
  955. which they don't recognise. But DO NOT USE THIS option unless you really have no choice,
  956. because it means that if you write more than 2^32 samples to the file, you'll corrupt it.
  957. */
  958. writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24));
  959. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  960. #endif
  961. }
  962. else
  963. {
  964. #if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  965. // If you disable padding, then you MUST NOT write more than 2^32 samples to a file.
  966. jassertfalse;
  967. #endif
  968. writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table)
  969. output->writeInt64 (riffChunkSize);
  970. output->writeInt64 ((int64) audioDataSize);
  971. output->writeRepeatedByte (0, 12);
  972. }
  973. if (isWaveFmtEx)
  974. {
  975. writeChunkHeader (chunkName ("fmt "), 40);
  976. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  977. }
  978. else
  979. {
  980. writeChunkHeader (chunkName ("fmt "), 16);
  981. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  982. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  983. }
  984. output->writeShort ((short) numChannels);
  985. output->writeInt ((int) sampleRate);
  986. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  987. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  988. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  989. if (isWaveFmtEx)
  990. {
  991. output->writeShort (22); // cbSize (size of the extension)
  992. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  993. output->writeInt (getChannelMask ((int) numChannels));
  994. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  995. output->writeInt ((int) subFormat.data1);
  996. output->writeShort ((short) subFormat.data2);
  997. output->writeShort ((short) subFormat.data3);
  998. output->write (subFormat.data4, sizeof (subFormat.data4));
  999. }
  1000. writeChunk (bwavChunk, chunkName ("bext"));
  1001. writeChunk (axmlChunk, chunkName ("axml"));
  1002. writeChunk (smplChunk, chunkName ("smpl"));
  1003. writeChunk (instChunk, chunkName ("inst"), 7);
  1004. writeChunk (cueChunk, chunkName ("cue "));
  1005. writeChunk (listChunk, chunkName ("LIST"));
  1006. writeChunk (acidChunk, chunkName ("acid"));
  1007. writeChunk (trckChunk, chunkName ("Trkn"));
  1008. writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  1009. usesFloatingPointData = (bitsPerSample == 32);
  1010. }
  1011. static size_t chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; }
  1012. void writeChunkHeader (int chunkType, int size) const
  1013. {
  1014. output->writeInt (chunkType);
  1015. output->writeInt (size);
  1016. }
  1017. void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const
  1018. {
  1019. if (data.getSize() > 0)
  1020. {
  1021. writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize());
  1022. *output << data;
  1023. }
  1024. }
  1025. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter)
  1026. };
  1027. //==============================================================================
  1028. class MemoryMappedWavReader : public MemoryMappedAudioFormatReader
  1029. {
  1030. public:
  1031. MemoryMappedWavReader (const File& file, const WavAudioFormatReader& reader)
  1032. : MemoryMappedAudioFormatReader (file, reader, reader.dataChunkStart,
  1033. reader.dataLength, reader.bytesPerFrame)
  1034. {
  1035. }
  1036. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  1037. int64 startSampleInFile, int numSamples) override
  1038. {
  1039. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  1040. startSampleInFile, numSamples, lengthInSamples);
  1041. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1042. {
  1043. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1044. return false;
  1045. }
  1046. WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData,
  1047. destSamples, startOffsetInDestBuffer, numDestChannels,
  1048. sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  1049. return true;
  1050. }
  1051. void readMaxLevels (int64 startSampleInFile, int64 numSamples,
  1052. float& min0, float& max0, float& min1, float& max1) override
  1053. {
  1054. if (numSamples <= 0)
  1055. {
  1056. min0 = max0 = min1 = max1 = 0;
  1057. return;
  1058. }
  1059. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1060. {
  1061. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1062. min0 = max0 = min1 = max1 = 0;
  1063. return;
  1064. }
  1065. switch (bitsPerSample)
  1066. {
  1067. case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1068. case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1069. case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1070. case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, min0, max0, min1, max1);
  1071. else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1072. default: jassertfalse; break;
  1073. }
  1074. }
  1075. private:
  1076. template <typename SampleType>
  1077. void scanMinAndMax (int64 startSampleInFile, int64 numSamples,
  1078. float& min0, float& max0, float& min1, float& max1) const noexcept
  1079. {
  1080. scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (0, startSampleInFile, numSamples, min0, max0);
  1081. if (numChannels > 1)
  1082. scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (1, startSampleInFile, numSamples, min1, max1);
  1083. else
  1084. min1 = max1 = 0;
  1085. }
  1086. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader)
  1087. };
  1088. //==============================================================================
  1089. WavAudioFormat::WavAudioFormat() : AudioFormat (wavFormatName, ".wav .bwf") {}
  1090. WavAudioFormat::~WavAudioFormat() {}
  1091. Array<int> WavAudioFormat::getPossibleSampleRates()
  1092. {
  1093. const int rates[] = { 8000, 11025, 12000, 16000, 22050, 32000, 44100,
  1094. 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
  1095. return Array<int> (rates, numElementsInArray (rates));
  1096. }
  1097. Array<int> WavAudioFormat::getPossibleBitDepths()
  1098. {
  1099. const int depths[] = { 8, 16, 24, 32 };
  1100. return Array<int> (depths, numElementsInArray (depths));
  1101. }
  1102. bool WavAudioFormat::canDoStereo() { return true; }
  1103. bool WavAudioFormat::canDoMono() { return true; }
  1104. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  1105. const bool deleteStreamIfOpeningFails)
  1106. {
  1107. ScopedPointer<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  1108. if (r->sampleRate > 0 && r->numChannels > 0 && r->bytesPerFrame > 0)
  1109. return r.release();
  1110. if (! deleteStreamIfOpeningFails)
  1111. r->input = nullptr;
  1112. return nullptr;
  1113. }
  1114. MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file)
  1115. {
  1116. if (FileInputStream* fin = file.createInputStream())
  1117. {
  1118. WavAudioFormatReader reader (fin);
  1119. if (reader.lengthInSamples > 0)
  1120. return new MemoryMappedWavReader (file, reader);
  1121. }
  1122. return nullptr;
  1123. }
  1124. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  1125. unsigned int numChannels, int bitsPerSample,
  1126. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  1127. {
  1128. if (getPossibleBitDepths().contains (bitsPerSample))
  1129. return new WavAudioFormatWriter (out, sampleRate, (unsigned int) numChannels,
  1130. (unsigned int) bitsPerSample, metadataValues);
  1131. return nullptr;
  1132. }
  1133. namespace WavFileHelpers
  1134. {
  1135. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  1136. {
  1137. TemporaryFile tempFile (file);
  1138. WavAudioFormat wav;
  1139. ScopedPointer<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  1140. if (reader != nullptr)
  1141. {
  1142. ScopedPointer<OutputStream> outStream (tempFile.getFile().createOutputStream());
  1143. if (outStream != nullptr)
  1144. {
  1145. ScopedPointer<AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  1146. reader->numChannels, (int) reader->bitsPerSample,
  1147. metadata, 0));
  1148. if (writer != nullptr)
  1149. {
  1150. outStream.release();
  1151. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  1152. writer = nullptr;
  1153. reader = nullptr;
  1154. return ok && tempFile.overwriteTargetFileWithTemporary();
  1155. }
  1156. }
  1157. }
  1158. return false;
  1159. }
  1160. }
  1161. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  1162. {
  1163. using namespace WavFileHelpers;
  1164. ScopedPointer<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  1165. if (reader != nullptr)
  1166. {
  1167. const int64 bwavPos = reader->bwavChunkStart;
  1168. const int64 bwavSize = reader->bwavSize;
  1169. reader = nullptr;
  1170. if (bwavSize > 0)
  1171. {
  1172. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  1173. if (chunk.getSize() <= (size_t) bwavSize)
  1174. {
  1175. // the new one will fit in the space available, so write it directly..
  1176. const int64 oldSize = wavFile.getSize();
  1177. {
  1178. FileOutputStream out (wavFile);
  1179. if (! out.failedToOpen())
  1180. {
  1181. out.setPosition (bwavPos);
  1182. out << chunk;
  1183. out.setPosition (oldSize);
  1184. }
  1185. }
  1186. jassert (wavFile.getSize() == oldSize);
  1187. return true;
  1188. }
  1189. }
  1190. }
  1191. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  1192. }