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.

1472 lines
64KB

  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. namespace ListInfoChunk
  391. {
  392. static bool writeValue (const StringPairArray& values, MemoryOutputStream& out, const char* paramName)
  393. {
  394. const String value (values.getValue (paramName, String()));
  395. if (value.isEmpty())
  396. return false;
  397. const int valueLength = (int) value.getNumBytesAsUTF8() + 1;
  398. const int chunkLength = valueLength + (valueLength & 1);
  399. out.writeInt (chunkName (paramName));
  400. out.writeInt (chunkLength);
  401. out.write (value.toUTF8(), (size_t) valueLength);
  402. if ((out.getDataSize() & 1) != 0)
  403. out.writeByte (0);
  404. return true;
  405. }
  406. static MemoryBlock createFrom (const StringPairArray& values)
  407. {
  408. static const char* params[] = { "INAM", "IART", "IPRD", "IPRT", "ISFT",
  409. "ISRC", "IGNR", "ICMT", "ICOP", "ICRD" };
  410. MemoryOutputStream out;
  411. out.writeInt (chunkName ("INFO"));
  412. bool anyParamsDefined = false;
  413. for (int i = 0; i < numElementsInArray (params); ++i)
  414. if (writeValue (values, out, params[i]))
  415. anyParamsDefined = true;
  416. return anyParamsDefined ? out.getMemoryBlock() : MemoryBlock();
  417. }
  418. }
  419. //==============================================================================
  420. struct AcidChunk
  421. {
  422. /** Reads an acid RIFF chunk from a stream positioned just after the size byte. */
  423. AcidChunk (InputStream& input, size_t length)
  424. {
  425. zerostruct (*this);
  426. input.read (this, (int) jmin (sizeof (*this), length));
  427. }
  428. AcidChunk (const StringPairArray& values)
  429. {
  430. zerostruct (*this);
  431. flags = getFlagIfPresent (values, WavAudioFormat::acidOneShot, 0x01)
  432. | getFlagIfPresent (values, WavAudioFormat::acidRootSet, 0x02)
  433. | getFlagIfPresent (values, WavAudioFormat::acidStretch, 0x04)
  434. | getFlagIfPresent (values, WavAudioFormat::acidDiskBased, 0x08)
  435. | getFlagIfPresent (values, WavAudioFormat::acidizerFlag, 0x10);
  436. if (values[WavAudioFormat::acidRootSet].getIntValue() != 0)
  437. rootNote = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidRootNote].getIntValue());
  438. numBeats = ByteOrder::swapIfBigEndian ((uint32) values[WavAudioFormat::acidBeats].getIntValue());
  439. meterDenominator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidDenominator].getIntValue());
  440. meterNumerator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidNumerator].getIntValue());
  441. if (values.containsKey (WavAudioFormat::acidTempo))
  442. tempo = swapFloatByteOrder (values[WavAudioFormat::acidTempo].getFloatValue());
  443. }
  444. static MemoryBlock createFrom (const StringPairArray& values)
  445. {
  446. return AcidChunk (values).toMemoryBlock();
  447. }
  448. MemoryBlock toMemoryBlock() const
  449. {
  450. return (flags != 0 || rootNote != 0 || numBeats != 0 || meterDenominator != 0 || meterNumerator != 0)
  451. ? MemoryBlock (this, sizeof (*this)) : MemoryBlock();
  452. }
  453. void addToMetadata (StringPairArray& values) const
  454. {
  455. setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01);
  456. setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02);
  457. setBoolFlag (values, WavAudioFormat::acidStretch, 0x04);
  458. setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08);
  459. setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10);
  460. if (flags & 0x02) // root note set
  461. values.set (WavAudioFormat::acidRootNote, String (ByteOrder::swapIfBigEndian (rootNote)));
  462. values.set (WavAudioFormat::acidBeats, String (ByteOrder::swapIfBigEndian (numBeats)));
  463. values.set (WavAudioFormat::acidDenominator, String (ByteOrder::swapIfBigEndian (meterDenominator)));
  464. values.set (WavAudioFormat::acidNumerator, String (ByteOrder::swapIfBigEndian (meterNumerator)));
  465. values.set (WavAudioFormat::acidTempo, String (swapFloatByteOrder (tempo)));
  466. }
  467. void setBoolFlag (StringPairArray& values, const char* name, uint32 mask) const
  468. {
  469. values.set (name, (flags & ByteOrder::swapIfBigEndian (mask)) ? "1" : "0");
  470. }
  471. static uint32 getFlagIfPresent (const StringPairArray& values, const char* name, uint32 flag)
  472. {
  473. return values[name].getIntValue() != 0 ? ByteOrder::swapIfBigEndian (flag) : 0;
  474. }
  475. static float swapFloatByteOrder (const float x) noexcept
  476. {
  477. #ifdef JUCE_BIG_ENDIAN
  478. union { uint32 asInt; float asFloat; } n;
  479. n.asFloat = x;
  480. n.asInt = ByteOrder::swap (n.asInt);
  481. return n.asFloat;
  482. #else
  483. return x;
  484. #endif
  485. }
  486. uint32 flags;
  487. uint16 rootNote;
  488. uint16 reserved1;
  489. float reserved2;
  490. uint32 numBeats;
  491. uint16 meterDenominator;
  492. uint16 meterNumerator;
  493. float tempo;
  494. } JUCE_PACKED;
  495. //==============================================================================
  496. struct TracktionChunk
  497. {
  498. static MemoryBlock createFrom (const StringPairArray& values)
  499. {
  500. const String s = values[WavAudioFormat::tracktionLoopInfo];
  501. MemoryBlock data;
  502. if (s.isNotEmpty())
  503. {
  504. MemoryOutputStream os (data, false);
  505. os.writeString (s);
  506. }
  507. return data;
  508. }
  509. };
  510. //==============================================================================
  511. namespace AXMLChunk
  512. {
  513. static void addToMetadata (StringPairArray& destValues, const String& source)
  514. {
  515. ScopedPointer<XmlElement> xml (XmlDocument::parse (source));
  516. if (xml != nullptr && xml->hasTagName ("ebucore:ebuCoreMain"))
  517. {
  518. if (XmlElement* xml2 = xml->getChildByName ("ebucore:coreMetadata"))
  519. {
  520. if (XmlElement* xml3 = xml2->getChildByName ("ebucore:identifier"))
  521. {
  522. if (XmlElement* xml4 = xml3->getChildByName ("dc:identifier"))
  523. {
  524. const String ISRCCode (xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true));
  525. if (ISRCCode.isNotEmpty())
  526. destValues.set (WavAudioFormat::ISRC, ISRCCode);
  527. }
  528. }
  529. }
  530. }
  531. }
  532. static MemoryBlock createFrom (const StringPairArray& values)
  533. {
  534. const String ISRC (values.getValue (WavAudioFormat::ISRC, String::empty));
  535. MemoryOutputStream xml;
  536. if (ISRC.isNotEmpty())
  537. {
  538. xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" "
  539. "xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">"
  540. "<ebucore:coreMetadata>"
  541. "<ebucore:identifier typeLabel=\"GUID\" "
  542. "typeDefinition=\"Globally Unique Identifier\" "
  543. "formatLabel=\"ISRC\" "
  544. "formatDefinition=\"International Standard Recording Code\" "
  545. "formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">"
  546. "<dc:identifier>ISRC:" << ISRC << "</dc:identifier>"
  547. "</ebucore:identifier>"
  548. "</ebucore:coreMetadata>"
  549. "</ebucore:ebuCoreMain>";
  550. xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing
  551. }
  552. return xml.getMemoryBlock();
  553. }
  554. };
  555. //==============================================================================
  556. struct ExtensibleWavSubFormat
  557. {
  558. uint32 data1;
  559. uint16 data2;
  560. uint16 data3;
  561. uint8 data4[8];
  562. bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; }
  563. bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); }
  564. } JUCE_PACKED;
  565. static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  566. static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  567. static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  568. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  569. {
  570. uint32 riffSizeLow; // low 4 byte size of RF64 block
  571. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  572. uint32 dataSizeLow; // low 4 byte size of data chunk
  573. uint32 dataSizeHigh; // high 4 byte size of data chunk
  574. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  575. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  576. uint32 tableLength; // number of valid entries in array 'table'
  577. } JUCE_PACKED;
  578. #if JUCE_MSVC
  579. #pragma pack (pop)
  580. #endif
  581. }
  582. //==============================================================================
  583. class WavAudioFormatReader : public AudioFormatReader
  584. {
  585. public:
  586. WavAudioFormatReader (InputStream* const in)
  587. : AudioFormatReader (in, wavFormatName),
  588. bwavChunkStart (0),
  589. bwavSize (0),
  590. dataLength (0),
  591. isRF64 (false)
  592. {
  593. using namespace WavFileHelpers;
  594. uint64 len = 0;
  595. uint64 end = 0;
  596. int cueNoteIndex = 0;
  597. int cueLabelIndex = 0;
  598. int cueRegionIndex = 0;
  599. const int firstChunkType = input->readInt();
  600. if (firstChunkType == chunkName ("RF64"))
  601. {
  602. input->skipNextBytes (4); // size is -1 for RF64
  603. isRF64 = true;
  604. }
  605. else if (firstChunkType == chunkName ("RIFF"))
  606. {
  607. len = (uint64) (uint32) input->readInt();
  608. end = len + (uint64) input->getPosition();
  609. }
  610. else
  611. {
  612. return;
  613. }
  614. const int64 startOfRIFFChunk = input->getPosition();
  615. if (input->readInt() == chunkName ("WAVE"))
  616. {
  617. if (isRF64 && input->readInt() == chunkName ("ds64"))
  618. {
  619. const uint32 length = (uint32) input->readInt();
  620. if (length < 28)
  621. return;
  622. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  623. len = (uint64) input->readInt64();
  624. end = len + (uint64) startOfRIFFChunk;
  625. dataLength = input->readInt64();
  626. input->setPosition (chunkEnd);
  627. }
  628. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  629. {
  630. const int chunkType = input->readInt();
  631. uint32 length = (uint32) input->readInt();
  632. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  633. if (chunkType == chunkName ("fmt "))
  634. {
  635. // read the format chunk
  636. const unsigned short format = (unsigned short) input->readShort();
  637. numChannels = (unsigned int) input->readShort();
  638. sampleRate = input->readInt();
  639. const int bytesPerSec = input->readInt();
  640. input->skipNextBytes (2);
  641. bitsPerSample = (unsigned int) (int) input->readShort();
  642. if (bitsPerSample > 64)
  643. {
  644. bytesPerFrame = bytesPerSec / (int) sampleRate;
  645. bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels;
  646. }
  647. else
  648. {
  649. bytesPerFrame = numChannels * bitsPerSample / 8;
  650. }
  651. if (format == 3)
  652. {
  653. usesFloatingPointData = true;
  654. }
  655. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  656. {
  657. if (length < 40) // too short
  658. {
  659. bytesPerFrame = 0;
  660. }
  661. else
  662. {
  663. input->skipNextBytes (4); // skip over size and bitsPerSample
  664. metadataValues.set ("ChannelMask", String (input->readInt()));
  665. ExtensibleWavSubFormat subFormat;
  666. subFormat.data1 = (uint32) input->readInt();
  667. subFormat.data2 = (uint16) input->readShort();
  668. subFormat.data3 = (uint16) input->readShort();
  669. input->read (subFormat.data4, sizeof (subFormat.data4));
  670. if (subFormat == IEEEFloatFormat)
  671. usesFloatingPointData = true;
  672. else if (subFormat != pcmFormat && subFormat != ambisonicFormat)
  673. bytesPerFrame = 0;
  674. }
  675. }
  676. else if (format != 1)
  677. {
  678. bytesPerFrame = 0;
  679. }
  680. }
  681. else if (chunkType == chunkName ("data"))
  682. {
  683. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  684. dataLength = length;
  685. dataChunkStart = input->getPosition();
  686. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  687. }
  688. else if (chunkType == chunkName ("bext"))
  689. {
  690. bwavChunkStart = input->getPosition();
  691. bwavSize = length;
  692. HeapBlock <BWAVChunk> bwav;
  693. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  694. input->read (bwav, (int) length);
  695. bwav->copyTo (metadataValues, (int) length);
  696. }
  697. else if (chunkType == chunkName ("smpl"))
  698. {
  699. HeapBlock <SMPLChunk> smpl;
  700. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  701. input->read (smpl, (int) length);
  702. smpl->copyTo (metadataValues, (int) length);
  703. }
  704. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  705. {
  706. HeapBlock <InstChunk> inst;
  707. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  708. input->read (inst, (int) length);
  709. inst->copyTo (metadataValues);
  710. }
  711. else if (chunkType == chunkName ("cue "))
  712. {
  713. HeapBlock <CueChunk> cue;
  714. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  715. input->read (cue, (int) length);
  716. cue->copyTo (metadataValues, (int) length);
  717. }
  718. else if (chunkType == chunkName ("axml"))
  719. {
  720. MemoryBlock axml;
  721. input->readIntoMemoryBlock (axml, (ssize_t) length);
  722. AXMLChunk::addToMetadata (metadataValues, axml.toString());
  723. }
  724. else if (chunkType == chunkName ("LIST"))
  725. {
  726. if (input->readInt() == chunkName ("adtl"))
  727. {
  728. while (input->getPosition() < chunkEnd)
  729. {
  730. const int adtlChunkType = input->readInt();
  731. const uint32 adtlLength = (uint32) input->readInt();
  732. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  733. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  734. {
  735. String prefix;
  736. if (adtlChunkType == chunkName ("labl"))
  737. prefix << "CueLabel" << cueLabelIndex++;
  738. else if (adtlChunkType == chunkName ("note"))
  739. prefix << "CueNote" << cueNoteIndex++;
  740. const uint32 identifier = (uint32) input->readInt();
  741. const int stringLength = (int) adtlLength - 4;
  742. MemoryBlock textBlock;
  743. input->readIntoMemoryBlock (textBlock, stringLength);
  744. metadataValues.set (prefix + "Identifier", String (identifier));
  745. metadataValues.set (prefix + "Text", textBlock.toString());
  746. }
  747. else if (adtlChunkType == chunkName ("ltxt"))
  748. {
  749. const String prefix ("CueRegion" + String (cueRegionIndex++));
  750. const uint32 identifier = (uint32) input->readInt();
  751. const uint32 sampleLength = (uint32) input->readInt();
  752. const uint32 purpose = (uint32) input->readInt();
  753. const uint16 country = (uint16) input->readInt();
  754. const uint16 language = (uint16) input->readInt();
  755. const uint16 dialect = (uint16) input->readInt();
  756. const uint16 codePage = (uint16) input->readInt();
  757. const uint32 stringLength = adtlLength - 20;
  758. MemoryBlock textBlock;
  759. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  760. metadataValues.set (prefix + "Identifier", String (identifier));
  761. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  762. metadataValues.set (prefix + "Purpose", String (purpose));
  763. metadataValues.set (prefix + "Country", String (country));
  764. metadataValues.set (prefix + "Language", String (language));
  765. metadataValues.set (prefix + "Dialect", String (dialect));
  766. metadataValues.set (prefix + "CodePage", String (codePage));
  767. metadataValues.set (prefix + "Text", textBlock.toString());
  768. }
  769. input->setPosition (adtlChunkEnd);
  770. }
  771. }
  772. }
  773. else if (chunkType == chunkName ("acid"))
  774. {
  775. AcidChunk (*input, length).addToMetadata (metadataValues);
  776. }
  777. else if (chunkType == chunkName ("Trkn"))
  778. {
  779. MemoryBlock tracktion;
  780. input->readIntoMemoryBlock (tracktion, (ssize_t) length);
  781. metadataValues.set (WavAudioFormat::tracktionLoopInfo, tracktion.toString());
  782. }
  783. else if (chunkEnd <= input->getPosition())
  784. {
  785. break;
  786. }
  787. input->setPosition (chunkEnd);
  788. }
  789. }
  790. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  791. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  792. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  793. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  794. }
  795. //==============================================================================
  796. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  797. int64 startSampleInFile, int numSamples) override
  798. {
  799. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  800. startSampleInFile, numSamples, lengthInSamples);
  801. if (numSamples <= 0)
  802. return true;
  803. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  804. while (numSamples > 0)
  805. {
  806. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  807. char tempBuffer [tempBufSize];
  808. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  809. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  810. if (bytesRead < numThisTime * bytesPerFrame)
  811. {
  812. jassert (bytesRead >= 0);
  813. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  814. }
  815. copySampleData (bitsPerSample, usesFloatingPointData,
  816. destSamples, startOffsetInDestBuffer, numDestChannels,
  817. tempBuffer, (int) numChannels, numThisTime);
  818. startOffsetInDestBuffer += numThisTime;
  819. numSamples -= numThisTime;
  820. }
  821. return true;
  822. }
  823. static void copySampleData (unsigned int bitsPerSample, const bool usesFloatingPointData,
  824. int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
  825. const void* sourceData, int numChannels, int numSamples) noexcept
  826. {
  827. switch (bitsPerSample)
  828. {
  829. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  830. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  831. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  832. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples);
  833. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  834. default: jassertfalse; break;
  835. }
  836. }
  837. int64 bwavChunkStart, bwavSize;
  838. int64 dataChunkStart, dataLength;
  839. int bytesPerFrame;
  840. bool isRF64;
  841. private:
  842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader)
  843. };
  844. //==============================================================================
  845. class WavAudioFormatWriter : public AudioFormatWriter
  846. {
  847. public:
  848. WavAudioFormatWriter (OutputStream* const out, const double rate,
  849. const unsigned int numChans, const unsigned int bits,
  850. const StringPairArray& metadataValues)
  851. : AudioFormatWriter (out, wavFormatName, rate, numChans, bits),
  852. lengthInSamples (0),
  853. bytesWritten (0),
  854. writeFailed (false)
  855. {
  856. using namespace WavFileHelpers;
  857. if (metadataValues.size() > 0)
  858. {
  859. // The meta data should have been santised for the WAV format.
  860. // If it was originally sourced from an AIFF file the MetaDataSource
  861. // key should be removed (or set to "WAV") once this has been done
  862. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  863. bwavChunk = BWAVChunk::createFrom (metadataValues);
  864. axmlChunk = AXMLChunk::createFrom (metadataValues);
  865. smplChunk = SMPLChunk::createFrom (metadataValues);
  866. instChunk = InstChunk::createFrom (metadataValues);
  867. cueChunk = CueChunk ::createFrom (metadataValues);
  868. listChunk = ListChunk::createFrom (metadataValues);
  869. listInfoChunk = ListInfoChunk::createFrom (metadataValues);
  870. acidChunk = AcidChunk::createFrom (metadataValues);
  871. trckChunk = TracktionChunk::createFrom (metadataValues);
  872. }
  873. headerPosition = out->getPosition();
  874. writeHeader();
  875. }
  876. ~WavAudioFormatWriter()
  877. {
  878. writeHeader();
  879. }
  880. //==============================================================================
  881. bool write (const int** data, int numSamples) override
  882. {
  883. jassert (numSamples >= 0);
  884. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  885. if (writeFailed)
  886. return false;
  887. const size_t bytes = numChannels * (unsigned int) numSamples * bitsPerSample / 8;
  888. tempBlock.ensureSize (bytes, false);
  889. switch (bitsPerSample)
  890. {
  891. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  892. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  893. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  894. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  895. default: jassertfalse; break;
  896. }
  897. if (! output->write (tempBlock.getData(), bytes))
  898. {
  899. // failed to write to disk, so let's try writing the header.
  900. // If it's just run out of disk space, then if it does manage
  901. // to write the header, we'll still have a useable file..
  902. writeHeader();
  903. writeFailed = true;
  904. return false;
  905. }
  906. bytesWritten += bytes;
  907. lengthInSamples += (uint64) numSamples;
  908. return true;
  909. }
  910. bool flush() override
  911. {
  912. const int64 lastWritePos = output->getPosition();
  913. writeHeader();
  914. if (output->setPosition (lastWritePos))
  915. return true;
  916. // if this fails, you've given it an output stream that can't seek! It needs
  917. // to be able to seek back to write the header
  918. jassertfalse;
  919. return false;
  920. }
  921. private:
  922. MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk, listInfoChunk, acidChunk, trckChunk;
  923. uint64 lengthInSamples, bytesWritten;
  924. int64 headerPosition;
  925. bool writeFailed;
  926. static int getChannelMask (const int numChannels) noexcept
  927. {
  928. switch (numChannels)
  929. {
  930. case 1: return 0;
  931. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  932. case 3: return 1 + 2 + 4; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER
  933. case 4: return 1 + 2 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  934. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  935. 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
  936. 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
  937. 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
  938. default: break;
  939. }
  940. return 0;
  941. }
  942. void writeHeader()
  943. {
  944. if ((bytesWritten & 1) != 0) // pad to an even length
  945. output->writeByte (0);
  946. using namespace WavFileHelpers;
  947. if (headerPosition != output->getPosition() && ! output->setPosition (headerPosition))
  948. {
  949. // if this fails, you've given it an output stream that can't seek! It needs to be
  950. // able to seek back to go back and write the header after the data has been written.
  951. jassertfalse;
  952. return;
  953. }
  954. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  955. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  956. const bool isRF64 = (bytesWritten >= 0x100000000LL);
  957. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  958. int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  959. + 8 + audioDataSize + (audioDataSize & 1)
  960. + chunkSize (bwavChunk)
  961. + chunkSize (axmlChunk)
  962. + chunkSize (smplChunk)
  963. + chunkSize (instChunk)
  964. + chunkSize (cueChunk)
  965. + chunkSize (listChunk)
  966. + chunkSize (listInfoChunk)
  967. + chunkSize (acidChunk)
  968. + chunkSize (trckChunk)
  969. + (8 + 28)); // (ds64 chunk)
  970. riffChunkSize += (riffChunkSize & 1);
  971. if (isRF64)
  972. writeChunkHeader (chunkName ("RF64"), -1);
  973. else
  974. writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize);
  975. output->writeInt (chunkName ("WAVE"));
  976. if (! isRF64)
  977. {
  978. #if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  979. /* NB: This junk chunk is added for padding, so that the header is a fixed size
  980. regardless of whether it's RF64 or not. That way, we can begin recording a file,
  981. and when it's finished, can go back and write either a RIFF or RF64 header,
  982. depending on whether more than 2^32 samples were written.
  983. The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case
  984. you need to create files for crappy WAV players with bugs that stop them skipping chunks
  985. which they don't recognise. But DO NOT USE THIS option unless you really have no choice,
  986. because it means that if you write more than 2^32 samples to the file, you'll corrupt it.
  987. */
  988. writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24));
  989. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  990. #endif
  991. }
  992. else
  993. {
  994. #if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  995. // If you disable padding, then you MUST NOT write more than 2^32 samples to a file.
  996. jassertfalse;
  997. #endif
  998. writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table)
  999. output->writeInt64 (riffChunkSize);
  1000. output->writeInt64 ((int64) audioDataSize);
  1001. output->writeRepeatedByte (0, 12);
  1002. }
  1003. if (isWaveFmtEx)
  1004. {
  1005. writeChunkHeader (chunkName ("fmt "), 40);
  1006. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  1007. }
  1008. else
  1009. {
  1010. writeChunkHeader (chunkName ("fmt "), 16);
  1011. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  1012. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  1013. }
  1014. output->writeShort ((short) numChannels);
  1015. output->writeInt ((int) sampleRate);
  1016. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  1017. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  1018. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  1019. if (isWaveFmtEx)
  1020. {
  1021. output->writeShort (22); // cbSize (size of the extension)
  1022. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  1023. output->writeInt (getChannelMask ((int) numChannels));
  1024. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  1025. output->writeInt ((int) subFormat.data1);
  1026. output->writeShort ((short) subFormat.data2);
  1027. output->writeShort ((short) subFormat.data3);
  1028. output->write (subFormat.data4, sizeof (subFormat.data4));
  1029. }
  1030. writeChunk (bwavChunk, chunkName ("bext"));
  1031. writeChunk (axmlChunk, chunkName ("axml"));
  1032. writeChunk (smplChunk, chunkName ("smpl"));
  1033. writeChunk (instChunk, chunkName ("inst"), 7);
  1034. writeChunk (cueChunk, chunkName ("cue "));
  1035. writeChunk (listChunk, chunkName ("LIST"));
  1036. writeChunk (listInfoChunk, chunkName ("LIST"));
  1037. writeChunk (acidChunk, chunkName ("acid"));
  1038. writeChunk (trckChunk, chunkName ("Trkn"));
  1039. writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  1040. usesFloatingPointData = (bitsPerSample == 32);
  1041. }
  1042. static size_t chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; }
  1043. void writeChunkHeader (int chunkType, int size) const
  1044. {
  1045. output->writeInt (chunkType);
  1046. output->writeInt (size);
  1047. }
  1048. void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const
  1049. {
  1050. if (data.getSize() > 0)
  1051. {
  1052. writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize());
  1053. *output << data;
  1054. }
  1055. }
  1056. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter)
  1057. };
  1058. //==============================================================================
  1059. class MemoryMappedWavReader : public MemoryMappedAudioFormatReader
  1060. {
  1061. public:
  1062. MemoryMappedWavReader (const File& file, const WavAudioFormatReader& reader)
  1063. : MemoryMappedAudioFormatReader (file, reader, reader.dataChunkStart,
  1064. reader.dataLength, reader.bytesPerFrame)
  1065. {
  1066. }
  1067. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  1068. int64 startSampleInFile, int numSamples) override
  1069. {
  1070. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  1071. startSampleInFile, numSamples, lengthInSamples);
  1072. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1073. {
  1074. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1075. return false;
  1076. }
  1077. WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData,
  1078. destSamples, startOffsetInDestBuffer, numDestChannels,
  1079. sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  1080. return true;
  1081. }
  1082. void readMaxLevels (int64 startSampleInFile, int64 numSamples,
  1083. float& min0, float& max0, float& min1, float& max1) override
  1084. {
  1085. if (numSamples <= 0)
  1086. {
  1087. min0 = max0 = min1 = max1 = 0;
  1088. return;
  1089. }
  1090. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1091. {
  1092. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1093. min0 = max0 = min1 = max1 = 0;
  1094. return;
  1095. }
  1096. switch (bitsPerSample)
  1097. {
  1098. case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1099. case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1100. case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1101. case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, min0, max0, min1, max1);
  1102. else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  1103. default: jassertfalse; break;
  1104. }
  1105. }
  1106. private:
  1107. template <typename SampleType>
  1108. void scanMinAndMax (int64 startSampleInFile, int64 numSamples,
  1109. float& min0, float& max0, float& min1, float& max1) const noexcept
  1110. {
  1111. scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (0, startSampleInFile, numSamples, min0, max0);
  1112. if (numChannels > 1)
  1113. scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (1, startSampleInFile, numSamples, min1, max1);
  1114. else
  1115. min1 = max1 = 0;
  1116. }
  1117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader)
  1118. };
  1119. //==============================================================================
  1120. WavAudioFormat::WavAudioFormat() : AudioFormat (wavFormatName, ".wav .bwf") {}
  1121. WavAudioFormat::~WavAudioFormat() {}
  1122. Array<int> WavAudioFormat::getPossibleSampleRates()
  1123. {
  1124. const int rates[] = { 8000, 11025, 12000, 16000, 22050, 32000, 44100,
  1125. 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
  1126. return Array<int> (rates, numElementsInArray (rates));
  1127. }
  1128. Array<int> WavAudioFormat::getPossibleBitDepths()
  1129. {
  1130. const int depths[] = { 8, 16, 24, 32 };
  1131. return Array<int> (depths, numElementsInArray (depths));
  1132. }
  1133. bool WavAudioFormat::canDoStereo() { return true; }
  1134. bool WavAudioFormat::canDoMono() { return true; }
  1135. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  1136. const bool deleteStreamIfOpeningFails)
  1137. {
  1138. ScopedPointer<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  1139. if (r->sampleRate > 0 && r->numChannels > 0 && r->bytesPerFrame > 0)
  1140. return r.release();
  1141. if (! deleteStreamIfOpeningFails)
  1142. r->input = nullptr;
  1143. return nullptr;
  1144. }
  1145. MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file)
  1146. {
  1147. if (FileInputStream* fin = file.createInputStream())
  1148. {
  1149. WavAudioFormatReader reader (fin);
  1150. if (reader.lengthInSamples > 0)
  1151. return new MemoryMappedWavReader (file, reader);
  1152. }
  1153. return nullptr;
  1154. }
  1155. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  1156. unsigned int numChannels, int bitsPerSample,
  1157. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  1158. {
  1159. if (getPossibleBitDepths().contains (bitsPerSample))
  1160. return new WavAudioFormatWriter (out, sampleRate, (unsigned int) numChannels,
  1161. (unsigned int) bitsPerSample, metadataValues);
  1162. return nullptr;
  1163. }
  1164. namespace WavFileHelpers
  1165. {
  1166. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  1167. {
  1168. TemporaryFile tempFile (file);
  1169. WavAudioFormat wav;
  1170. ScopedPointer<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  1171. if (reader != nullptr)
  1172. {
  1173. ScopedPointer<OutputStream> outStream (tempFile.getFile().createOutputStream());
  1174. if (outStream != nullptr)
  1175. {
  1176. ScopedPointer<AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  1177. reader->numChannels, (int) reader->bitsPerSample,
  1178. metadata, 0));
  1179. if (writer != nullptr)
  1180. {
  1181. outStream.release();
  1182. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  1183. writer = nullptr;
  1184. reader = nullptr;
  1185. return ok && tempFile.overwriteTargetFileWithTemporary();
  1186. }
  1187. }
  1188. }
  1189. return false;
  1190. }
  1191. }
  1192. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  1193. {
  1194. using namespace WavFileHelpers;
  1195. ScopedPointer<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  1196. if (reader != nullptr)
  1197. {
  1198. const int64 bwavPos = reader->bwavChunkStart;
  1199. const int64 bwavSize = reader->bwavSize;
  1200. reader = nullptr;
  1201. if (bwavSize > 0)
  1202. {
  1203. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  1204. if (chunk.getSize() <= (size_t) bwavSize)
  1205. {
  1206. // the new one will fit in the space available, so write it directly..
  1207. const int64 oldSize = wavFile.getSize();
  1208. {
  1209. FileOutputStream out (wavFile);
  1210. if (! out.failedToOpen())
  1211. {
  1212. out.setPosition (bwavPos);
  1213. out << chunk;
  1214. out.setPosition (oldSize);
  1215. }
  1216. }
  1217. jassert (wavFile.getSize() == oldSize);
  1218. return true;
  1219. }
  1220. }
  1221. }
  1222. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  1223. }