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.

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