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.

1341 lines
58KB

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