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.

1903 lines
84KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. static const char* const wavFormatName = "WAV file";
  16. //==============================================================================
  17. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  19. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  20. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  21. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  22. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  23. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  24. StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  25. const String& originator,
  26. const String& originatorRef,
  27. Time date,
  28. int64 timeReferenceSamples,
  29. const String& codingHistory)
  30. {
  31. StringPairArray m;
  32. m.set (bwavDescription, description);
  33. m.set (bwavOriginator, originator);
  34. m.set (bwavOriginatorRef, originatorRef);
  35. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  36. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  37. m.set (bwavTimeReference, String (timeReferenceSamples));
  38. m.set (bwavCodingHistory, codingHistory);
  39. return m;
  40. }
  41. const char* const WavAudioFormat::acidOneShot = "acid one shot";
  42. const char* const WavAudioFormat::acidRootSet = "acid root set";
  43. const char* const WavAudioFormat::acidStretch = "acid stretch";
  44. const char* const WavAudioFormat::acidDiskBased = "acid disk based";
  45. const char* const WavAudioFormat::acidizerFlag = "acidizer flag";
  46. const char* const WavAudioFormat::acidRootNote = "acid root note";
  47. const char* const WavAudioFormat::acidBeats = "acid beats";
  48. const char* const WavAudioFormat::acidDenominator = "acid denominator";
  49. const char* const WavAudioFormat::acidNumerator = "acid numerator";
  50. const char* const WavAudioFormat::acidTempo = "acid tempo";
  51. const char* const WavAudioFormat::riffInfoArchivalLocation = "IARL";
  52. const char* const WavAudioFormat::riffInfoArtist = "IART";
  53. const char* const WavAudioFormat::riffInfoBaseURL = "IBSU";
  54. const char* const WavAudioFormat::riffInfoCinematographer = "ICNM";
  55. const char* const WavAudioFormat::riffInfoComment = "CMNT";
  56. const char* const WavAudioFormat::riffInfoComment2 = "ICMT";
  57. const char* const WavAudioFormat::riffInfoComments = "COMM";
  58. const char* const WavAudioFormat::riffInfoCommissioned = "ICMS";
  59. const char* const WavAudioFormat::riffInfoCopyright = "ICOP";
  60. const char* const WavAudioFormat::riffInfoCostumeDesigner = "ICDS";
  61. const char* const WavAudioFormat::riffInfoCountry = "ICNT";
  62. const char* const WavAudioFormat::riffInfoCropped = "ICRP";
  63. const char* const WavAudioFormat::riffInfoDateCreated = "ICRD";
  64. const char* const WavAudioFormat::riffInfoDateTimeOriginal = "IDIT";
  65. const char* const WavAudioFormat::riffInfoDefaultAudioStream = "ICAS";
  66. const char* const WavAudioFormat::riffInfoDimension = "IDIM";
  67. const char* const WavAudioFormat::riffInfoDirectory = "DIRC";
  68. const char* const WavAudioFormat::riffInfoDistributedBy = "IDST";
  69. const char* const WavAudioFormat::riffInfoDotsPerInch = "IDPI";
  70. const char* const WavAudioFormat::riffInfoEditedBy = "IEDT";
  71. const char* const WavAudioFormat::riffInfoEighthLanguage = "IAS8";
  72. const char* const WavAudioFormat::riffInfoEncodedBy = "CODE";
  73. const char* const WavAudioFormat::riffInfoEndTimecode = "TCDO";
  74. const char* const WavAudioFormat::riffInfoEngineer = "IENG";
  75. const char* const WavAudioFormat::riffInfoFifthLanguage = "IAS5";
  76. const char* const WavAudioFormat::riffInfoFirstLanguage = "IAS1";
  77. const char* const WavAudioFormat::riffInfoFourthLanguage = "IAS4";
  78. const char* const WavAudioFormat::riffInfoGenre = "GENR";
  79. const char* const WavAudioFormat::riffInfoKeywords = "IKEY";
  80. const char* const WavAudioFormat::riffInfoLanguage = "LANG";
  81. const char* const WavAudioFormat::riffInfoLength = "TLEN";
  82. const char* const WavAudioFormat::riffInfoLightness = "ILGT";
  83. const char* const WavAudioFormat::riffInfoLocation = "LOCA";
  84. const char* const WavAudioFormat::riffInfoLogoIconURL = "ILIU";
  85. const char* const WavAudioFormat::riffInfoLogoURL = "ILGU";
  86. const char* const WavAudioFormat::riffInfoMedium = "IMED";
  87. const char* const WavAudioFormat::riffInfoMoreInfoBannerImage = "IMBI";
  88. const char* const WavAudioFormat::riffInfoMoreInfoBannerURL = "IMBU";
  89. const char* const WavAudioFormat::riffInfoMoreInfoText = "IMIT";
  90. const char* const WavAudioFormat::riffInfoMoreInfoURL = "IMIU";
  91. const char* const WavAudioFormat::riffInfoMusicBy = "IMUS";
  92. const char* const WavAudioFormat::riffInfoNinthLanguage = "IAS9";
  93. const char* const WavAudioFormat::riffInfoNumberOfParts = "PRT2";
  94. const char* const WavAudioFormat::riffInfoOrganisation = "TORG";
  95. const char* const WavAudioFormat::riffInfoPart = "PRT1";
  96. const char* const WavAudioFormat::riffInfoProducedBy = "IPRO";
  97. const char* const WavAudioFormat::riffInfoProductName = "IPRD";
  98. const char* const WavAudioFormat::riffInfoProductionDesigner = "IPDS";
  99. const char* const WavAudioFormat::riffInfoProductionStudio = "ISDT";
  100. const char* const WavAudioFormat::riffInfoRate = "RATE";
  101. const char* const WavAudioFormat::riffInfoRated = "AGES";
  102. const char* const WavAudioFormat::riffInfoRating = "IRTD";
  103. const char* const WavAudioFormat::riffInfoRippedBy = "IRIP";
  104. const char* const WavAudioFormat::riffInfoSecondaryGenre = "ISGN";
  105. const char* const WavAudioFormat::riffInfoSecondLanguage = "IAS2";
  106. const char* const WavAudioFormat::riffInfoSeventhLanguage = "IAS7";
  107. const char* const WavAudioFormat::riffInfoSharpness = "ISHP";
  108. const char* const WavAudioFormat::riffInfoSixthLanguage = "IAS6";
  109. const char* const WavAudioFormat::riffInfoSoftware = "ISFT";
  110. const char* const WavAudioFormat::riffInfoSoundSchemeTitle = "DISP";
  111. const char* const WavAudioFormat::riffInfoSource = "ISRC";
  112. const char* const WavAudioFormat::riffInfoSourceFrom = "ISRF";
  113. const char* const WavAudioFormat::riffInfoStarring_ISTR = "ISTR";
  114. const char* const WavAudioFormat::riffInfoStarring_STAR = "STAR";
  115. const char* const WavAudioFormat::riffInfoStartTimecode = "TCOD";
  116. const char* const WavAudioFormat::riffInfoStatistics = "STAT";
  117. const char* const WavAudioFormat::riffInfoSubject = "ISBJ";
  118. const char* const WavAudioFormat::riffInfoTapeName = "TAPE";
  119. const char* const WavAudioFormat::riffInfoTechnician = "ITCH";
  120. const char* const WavAudioFormat::riffInfoThirdLanguage = "IAS3";
  121. const char* const WavAudioFormat::riffInfoTimeCode = "ISMP";
  122. const char* const WavAudioFormat::riffInfoTitle = "INAM";
  123. const char* const WavAudioFormat::riffInfoTrackNo = "IPRT";
  124. const char* const WavAudioFormat::riffInfoTrackNumber = "TRCK";
  125. const char* const WavAudioFormat::riffInfoURL = "TURL";
  126. const char* const WavAudioFormat::riffInfoVegasVersionMajor = "VMAJ";
  127. const char* const WavAudioFormat::riffInfoVegasVersionMinor = "VMIN";
  128. const char* const WavAudioFormat::riffInfoVersion = "TVER";
  129. const char* const WavAudioFormat::riffInfoWatermarkURL = "IWMU";
  130. const char* const WavAudioFormat::riffInfoWrittenBy = "IWRI";
  131. const char* const WavAudioFormat::riffInfoYear = "YEAR";
  132. const char* const WavAudioFormat::ISRC = "ISRC";
  133. const char* const WavAudioFormat::tracktionLoopInfo = "tracktion loop info";
  134. //==============================================================================
  135. namespace WavFileHelpers
  136. {
  137. constexpr inline int chunkName (const char* name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
  138. constexpr inline size_t roundUpSize (size_t sz) noexcept { return (sz + 3) & ~3u; }
  139. #if JUCE_MSVC
  140. #pragma pack (push, 1)
  141. #endif
  142. struct BWAVChunk
  143. {
  144. char description[256];
  145. char originator[32];
  146. char originatorRef[32];
  147. char originationDate[10];
  148. char originationTime[8];
  149. uint32 timeRefLow;
  150. uint32 timeRefHigh;
  151. uint16 version;
  152. uint8 umid[64];
  153. uint8 reserved[190];
  154. char codingHistory[1];
  155. void copyTo (StringPairArray& values, const int totalSize) const
  156. {
  157. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description)));
  158. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator)));
  159. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef)));
  160. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate)));
  161. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime)));
  162. auto timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  163. auto timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  164. auto time = (((int64) timeHigh) << 32) + timeLow;
  165. values.set (WavAudioFormat::bwavTimeReference, String (time));
  166. values.set (WavAudioFormat::bwavCodingHistory,
  167. String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory)));
  168. }
  169. static MemoryBlock createFrom (const StringPairArray& values)
  170. {
  171. MemoryBlock data (roundUpSize (sizeof (BWAVChunk) + values[WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8()));
  172. data.fillWith (0);
  173. auto* b = (BWAVChunk*) data.getData();
  174. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  175. // as they get called in the right order..
  176. values[WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257);
  177. values[WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33);
  178. values[WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33);
  179. values[WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  180. values[WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  181. auto time = values[WavAudioFormat::bwavTimeReference].getLargeIntValue();
  182. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  183. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  184. values[WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  185. if (b->description[0] != 0
  186. || b->originator[0] != 0
  187. || b->originationDate[0] != 0
  188. || b->originationTime[0] != 0
  189. || b->codingHistory[0] != 0
  190. || time != 0)
  191. {
  192. return data;
  193. }
  194. return {};
  195. }
  196. } JUCE_PACKED;
  197. //==============================================================================
  198. inline AudioChannelSet canonicalWavChannelSet (int numChannels)
  199. {
  200. if (numChannels == 1) return AudioChannelSet::mono();
  201. if (numChannels == 2) return AudioChannelSet::stereo();
  202. if (numChannels == 3) return AudioChannelSet::createLCR();
  203. if (numChannels == 4) return AudioChannelSet::quadraphonic();
  204. if (numChannels == 5) return AudioChannelSet::create5point0();
  205. if (numChannels == 6) return AudioChannelSet::create5point1();
  206. if (numChannels == 7) return AudioChannelSet::create7point0SDDS();
  207. if (numChannels == 8) return AudioChannelSet::create7point1SDDS();
  208. return AudioChannelSet::discreteChannels (numChannels);
  209. }
  210. //==============================================================================
  211. struct SMPLChunk
  212. {
  213. struct SampleLoop
  214. {
  215. uint32 identifier;
  216. uint32 type; // these are different in AIFF and WAV
  217. uint32 start;
  218. uint32 end;
  219. uint32 fraction;
  220. uint32 playCount;
  221. } JUCE_PACKED;
  222. uint32 manufacturer;
  223. uint32 product;
  224. uint32 samplePeriod;
  225. uint32 midiUnityNote;
  226. uint32 midiPitchFraction;
  227. uint32 smpteFormat;
  228. uint32 smpteOffset;
  229. uint32 numSampleLoops;
  230. uint32 samplerData;
  231. SampleLoop loops[1];
  232. template <typename NameType>
  233. static void setValue (StringPairArray& values, NameType name, uint32 val)
  234. {
  235. values.set (name, String (ByteOrder::swapIfBigEndian (val)));
  236. }
  237. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  238. {
  239. setValue (values, "Loop" + String (prefix) + name, val);
  240. }
  241. void copyTo (StringPairArray& values, const int totalSize) const
  242. {
  243. setValue (values, "Manufacturer", manufacturer);
  244. setValue (values, "Product", product);
  245. setValue (values, "SamplePeriod", samplePeriod);
  246. setValue (values, "MidiUnityNote", midiUnityNote);
  247. setValue (values, "MidiPitchFraction", midiPitchFraction);
  248. setValue (values, "SmpteFormat", smpteFormat);
  249. setValue (values, "SmpteOffset", smpteOffset);
  250. setValue (values, "NumSampleLoops", numSampleLoops);
  251. setValue (values, "SamplerData", samplerData);
  252. for (int i = 0; i < (int) numSampleLoops; ++i)
  253. {
  254. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  255. break;
  256. setValue (values, i, "Identifier", loops[i].identifier);
  257. setValue (values, i, "Type", loops[i].type);
  258. setValue (values, i, "Start", loops[i].start);
  259. setValue (values, i, "End", loops[i].end);
  260. setValue (values, i, "Fraction", loops[i].fraction);
  261. setValue (values, i, "PlayCount", loops[i].playCount);
  262. }
  263. }
  264. template <typename NameType>
  265. static uint32 getValue (const StringPairArray& values, NameType name, const char* def)
  266. {
  267. return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue());
  268. }
  269. static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def)
  270. {
  271. return getValue (values, "Loop" + String (prefix) + name, def);
  272. }
  273. static MemoryBlock createFrom (const StringPairArray& values)
  274. {
  275. MemoryBlock data;
  276. auto numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  277. data.setSize (roundUpSize (sizeof (SMPLChunk) + (size_t) (jmax (0, numLoops - 1)) * sizeof (SampleLoop)), true);
  278. auto s = static_cast<SMPLChunk*> (data.getData());
  279. s->manufacturer = getValue (values, "Manufacturer", "0");
  280. s->product = getValue (values, "Product", "0");
  281. s->samplePeriod = getValue (values, "SamplePeriod", "0");
  282. s->midiUnityNote = getValue (values, "MidiUnityNote", "60");
  283. s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0");
  284. s->smpteFormat = getValue (values, "SmpteFormat", "0");
  285. s->smpteOffset = getValue (values, "SmpteOffset", "0");
  286. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  287. s->samplerData = getValue (values, "SamplerData", "0");
  288. for (int i = 0; i < numLoops; ++i)
  289. {
  290. auto& loop = s->loops[i];
  291. loop.identifier = getValue (values, i, "Identifier", "0");
  292. loop.type = getValue (values, i, "Type", "0");
  293. loop.start = getValue (values, i, "Start", "0");
  294. loop.end = getValue (values, i, "End", "0");
  295. loop.fraction = getValue (values, i, "Fraction", "0");
  296. loop.playCount = getValue (values, i, "PlayCount", "0");
  297. }
  298. return data;
  299. }
  300. } JUCE_PACKED;
  301. //==============================================================================
  302. struct InstChunk
  303. {
  304. int8 baseNote;
  305. int8 detune;
  306. int8 gain;
  307. int8 lowNote;
  308. int8 highNote;
  309. int8 lowVelocity;
  310. int8 highVelocity;
  311. static void setValue (StringPairArray& values, const char* name, int val)
  312. {
  313. values.set (name, String (val));
  314. }
  315. void copyTo (StringPairArray& values) const
  316. {
  317. setValue (values, "MidiUnityNote", baseNote);
  318. setValue (values, "Detune", detune);
  319. setValue (values, "Gain", gain);
  320. setValue (values, "LowNote", lowNote);
  321. setValue (values, "HighNote", highNote);
  322. setValue (values, "LowVelocity", lowVelocity);
  323. setValue (values, "HighVelocity", highVelocity);
  324. }
  325. static int8 getValue (const StringPairArray& values, const char* name, const char* def)
  326. {
  327. return (int8) values.getValue (name, def).getIntValue();
  328. }
  329. static MemoryBlock createFrom (const StringPairArray& values)
  330. {
  331. MemoryBlock data;
  332. auto& keys = values.getAllKeys();
  333. if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true))
  334. {
  335. data.setSize (8, true);
  336. auto* inst = static_cast<InstChunk*> (data.getData());
  337. inst->baseNote = getValue (values, "MidiUnityNote", "60");
  338. inst->detune = getValue (values, "Detune", "0");
  339. inst->gain = getValue (values, "Gain", "0");
  340. inst->lowNote = getValue (values, "LowNote", "0");
  341. inst->highNote = getValue (values, "HighNote", "127");
  342. inst->lowVelocity = getValue (values, "LowVelocity", "1");
  343. inst->highVelocity = getValue (values, "HighVelocity", "127");
  344. }
  345. return data;
  346. }
  347. } JUCE_PACKED;
  348. //==============================================================================
  349. struct CueChunk
  350. {
  351. struct Cue
  352. {
  353. uint32 identifier;
  354. uint32 order;
  355. uint32 chunkID;
  356. uint32 chunkStart;
  357. uint32 blockStart;
  358. uint32 offset;
  359. } JUCE_PACKED;
  360. uint32 numCues;
  361. Cue cues[1];
  362. static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
  363. {
  364. values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val)));
  365. }
  366. void copyTo (StringPairArray& values, const int totalSize) const
  367. {
  368. values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues)));
  369. for (int i = 0; i < (int) numCues; ++i)
  370. {
  371. if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize)
  372. break;
  373. setValue (values, i, "Identifier", cues[i].identifier);
  374. setValue (values, i, "Order", cues[i].order);
  375. setValue (values, i, "ChunkID", cues[i].chunkID);
  376. setValue (values, i, "ChunkStart", cues[i].chunkStart);
  377. setValue (values, i, "BlockStart", cues[i].blockStart);
  378. setValue (values, i, "Offset", cues[i].offset);
  379. }
  380. }
  381. static MemoryBlock createFrom (const StringPairArray& values)
  382. {
  383. MemoryBlock data;
  384. const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  385. if (numCues > 0)
  386. {
  387. data.setSize (roundUpSize (sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue)), true);
  388. auto c = static_cast<CueChunk*> (data.getData());
  389. c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues);
  390. const String dataChunkID (chunkName ("data"));
  391. int nextOrder = 0;
  392. #if JUCE_DEBUG
  393. Array<uint32> identifiers;
  394. #endif
  395. for (int i = 0; i < numCues; ++i)
  396. {
  397. auto prefix = "Cue" + String (i);
  398. auto identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue();
  399. #if JUCE_DEBUG
  400. jassert (! identifiers.contains (identifier));
  401. identifiers.add (identifier);
  402. #endif
  403. auto order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue();
  404. nextOrder = jmax (nextOrder, order) + 1;
  405. auto& cue = c->cues[i];
  406. cue.identifier = ByteOrder::swapIfBigEndian ((uint32) identifier);
  407. cue.order = ByteOrder::swapIfBigEndian ((uint32) order);
  408. cue.chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue());
  409. cue.chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue());
  410. cue.blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue());
  411. cue.offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue());
  412. }
  413. }
  414. return data;
  415. }
  416. } JUCE_PACKED;
  417. //==============================================================================
  418. namespace ListChunk
  419. {
  420. static int getValue (const StringPairArray& values, const String& name)
  421. {
  422. return values.getValue (name, "0").getIntValue();
  423. }
  424. static int getValue (const StringPairArray& values, const String& prefix, const char* name)
  425. {
  426. return getValue (values, prefix + name);
  427. }
  428. static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix,
  429. const int chunkType, MemoryOutputStream& out)
  430. {
  431. auto label = values.getValue (prefix + "Text", prefix);
  432. auto labelLength = (int) label.getNumBytesAsUTF8() + 1;
  433. auto chunkLength = 4 + labelLength + (labelLength & 1);
  434. out.writeInt (chunkType);
  435. out.writeInt (chunkLength);
  436. out.writeInt (getValue (values, prefix, "Identifier"));
  437. out.write (label.toUTF8(), (size_t) labelLength);
  438. if ((out.getDataSize() & 1) != 0)
  439. out.writeByte (0);
  440. }
  441. static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out)
  442. {
  443. auto text = values.getValue (prefix + "Text", prefix);
  444. auto textLength = (int) text.getNumBytesAsUTF8() + 1; // include null terminator
  445. auto chunkLength = textLength + 20 + (textLength & 1);
  446. out.writeInt (chunkName ("ltxt"));
  447. out.writeInt (chunkLength);
  448. out.writeInt (getValue (values, prefix, "Identifier"));
  449. out.writeInt (getValue (values, prefix, "SampleLength"));
  450. out.writeInt (getValue (values, prefix, "Purpose"));
  451. out.writeShort ((short) getValue (values, prefix, "Country"));
  452. out.writeShort ((short) getValue (values, prefix, "Language"));
  453. out.writeShort ((short) getValue (values, prefix, "Dialect"));
  454. out.writeShort ((short) getValue (values, prefix, "CodePage"));
  455. out.write (text.toUTF8(), (size_t) textLength);
  456. if ((out.getDataSize() & 1) != 0)
  457. out.writeByte (0);
  458. }
  459. static MemoryBlock createFrom (const StringPairArray& values)
  460. {
  461. auto numCueLabels = getValue (values, "NumCueLabels");
  462. auto numCueNotes = getValue (values, "NumCueNotes");
  463. auto numCueRegions = getValue (values, "NumCueRegions");
  464. MemoryOutputStream out;
  465. if (numCueLabels + numCueNotes + numCueRegions > 0)
  466. {
  467. out.writeInt (chunkName ("adtl"));
  468. for (int i = 0; i < numCueLabels; ++i)
  469. appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out);
  470. for (int i = 0; i < numCueNotes; ++i)
  471. appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out);
  472. for (int i = 0; i < numCueRegions; ++i)
  473. appendExtraChunk (values, "CueRegion" + String (i), out);
  474. }
  475. return out.getMemoryBlock();
  476. }
  477. }
  478. //==============================================================================
  479. /** Reads a RIFF List Info chunk from a stream positioned just after the size byte. */
  480. namespace ListInfoChunk
  481. {
  482. static const char* const types[] =
  483. {
  484. WavAudioFormat::riffInfoArchivalLocation,
  485. WavAudioFormat::riffInfoArtist,
  486. WavAudioFormat::riffInfoBaseURL,
  487. WavAudioFormat::riffInfoCinematographer,
  488. WavAudioFormat::riffInfoComment,
  489. WavAudioFormat::riffInfoComments,
  490. WavAudioFormat::riffInfoComment2,
  491. WavAudioFormat::riffInfoCommissioned,
  492. WavAudioFormat::riffInfoCopyright,
  493. WavAudioFormat::riffInfoCostumeDesigner,
  494. WavAudioFormat::riffInfoCountry,
  495. WavAudioFormat::riffInfoCropped,
  496. WavAudioFormat::riffInfoDateCreated,
  497. WavAudioFormat::riffInfoDateTimeOriginal,
  498. WavAudioFormat::riffInfoDefaultAudioStream,
  499. WavAudioFormat::riffInfoDimension,
  500. WavAudioFormat::riffInfoDirectory,
  501. WavAudioFormat::riffInfoDistributedBy,
  502. WavAudioFormat::riffInfoDotsPerInch,
  503. WavAudioFormat::riffInfoEditedBy,
  504. WavAudioFormat::riffInfoEighthLanguage,
  505. WavAudioFormat::riffInfoEncodedBy,
  506. WavAudioFormat::riffInfoEndTimecode,
  507. WavAudioFormat::riffInfoEngineer,
  508. WavAudioFormat::riffInfoFifthLanguage,
  509. WavAudioFormat::riffInfoFirstLanguage,
  510. WavAudioFormat::riffInfoFourthLanguage,
  511. WavAudioFormat::riffInfoGenre,
  512. WavAudioFormat::riffInfoKeywords,
  513. WavAudioFormat::riffInfoLanguage,
  514. WavAudioFormat::riffInfoLength,
  515. WavAudioFormat::riffInfoLightness,
  516. WavAudioFormat::riffInfoLocation,
  517. WavAudioFormat::riffInfoLogoIconURL,
  518. WavAudioFormat::riffInfoLogoURL,
  519. WavAudioFormat::riffInfoMedium,
  520. WavAudioFormat::riffInfoMoreInfoBannerImage,
  521. WavAudioFormat::riffInfoMoreInfoBannerURL,
  522. WavAudioFormat::riffInfoMoreInfoText,
  523. WavAudioFormat::riffInfoMoreInfoURL,
  524. WavAudioFormat::riffInfoMusicBy,
  525. WavAudioFormat::riffInfoNinthLanguage,
  526. WavAudioFormat::riffInfoNumberOfParts,
  527. WavAudioFormat::riffInfoOrganisation,
  528. WavAudioFormat::riffInfoPart,
  529. WavAudioFormat::riffInfoProducedBy,
  530. WavAudioFormat::riffInfoProductName,
  531. WavAudioFormat::riffInfoProductionDesigner,
  532. WavAudioFormat::riffInfoProductionStudio,
  533. WavAudioFormat::riffInfoRate,
  534. WavAudioFormat::riffInfoRated,
  535. WavAudioFormat::riffInfoRating,
  536. WavAudioFormat::riffInfoRippedBy,
  537. WavAudioFormat::riffInfoSecondaryGenre,
  538. WavAudioFormat::riffInfoSecondLanguage,
  539. WavAudioFormat::riffInfoSeventhLanguage,
  540. WavAudioFormat::riffInfoSharpness,
  541. WavAudioFormat::riffInfoSixthLanguage,
  542. WavAudioFormat::riffInfoSoftware,
  543. WavAudioFormat::riffInfoSoundSchemeTitle,
  544. WavAudioFormat::riffInfoSource,
  545. WavAudioFormat::riffInfoSourceFrom,
  546. WavAudioFormat::riffInfoStarring_ISTR,
  547. WavAudioFormat::riffInfoStarring_STAR,
  548. WavAudioFormat::riffInfoStartTimecode,
  549. WavAudioFormat::riffInfoStatistics,
  550. WavAudioFormat::riffInfoSubject,
  551. WavAudioFormat::riffInfoTapeName,
  552. WavAudioFormat::riffInfoTechnician,
  553. WavAudioFormat::riffInfoThirdLanguage,
  554. WavAudioFormat::riffInfoTimeCode,
  555. WavAudioFormat::riffInfoTitle,
  556. WavAudioFormat::riffInfoTrackNo,
  557. WavAudioFormat::riffInfoTrackNumber,
  558. WavAudioFormat::riffInfoURL,
  559. WavAudioFormat::riffInfoVegasVersionMajor,
  560. WavAudioFormat::riffInfoVegasVersionMinor,
  561. WavAudioFormat::riffInfoVersion,
  562. WavAudioFormat::riffInfoWatermarkURL,
  563. WavAudioFormat::riffInfoWrittenBy,
  564. WavAudioFormat::riffInfoYear
  565. };
  566. static bool isMatchingTypeIgnoringCase (const int value, const char* const name) noexcept
  567. {
  568. for (int i = 0; i < 4; ++i)
  569. if ((juce_wchar) name[i] != CharacterFunctions::toUpperCase ((juce_wchar) ((value >> (i * 8)) & 0xff)))
  570. return false;
  571. return true;
  572. }
  573. static void addToMetadata (StringPairArray& values, InputStream& input, int64 chunkEnd)
  574. {
  575. while (input.getPosition() < chunkEnd)
  576. {
  577. auto infoType = input.readInt();
  578. auto infoLength = chunkEnd - input.getPosition();
  579. if (infoLength > 0)
  580. {
  581. infoLength = jmin (infoLength, (int64) input.readInt());
  582. if (infoLength <= 0)
  583. return;
  584. for (auto& type : types)
  585. {
  586. if (isMatchingTypeIgnoringCase (infoType, type))
  587. {
  588. MemoryBlock mb;
  589. input.readIntoMemoryBlock (mb, (ssize_t) infoLength);
  590. values.set (type, String::createStringFromData ((const char*) mb.getData(),
  591. (int) mb.getSize()));
  592. break;
  593. }
  594. }
  595. }
  596. }
  597. }
  598. static bool writeValue (const StringPairArray& values, MemoryOutputStream& out, const char* paramName)
  599. {
  600. auto value = values.getValue (paramName, {});
  601. if (value.isEmpty())
  602. return false;
  603. auto valueLength = (int) value.getNumBytesAsUTF8() + 1;
  604. auto chunkLength = valueLength + (valueLength & 1);
  605. out.writeInt (chunkName (paramName));
  606. out.writeInt (chunkLength);
  607. out.write (value.toUTF8(), (size_t) valueLength);
  608. if ((out.getDataSize() & 1) != 0)
  609. out.writeByte (0);
  610. return true;
  611. }
  612. static MemoryBlock createFrom (const StringPairArray& values)
  613. {
  614. MemoryOutputStream out;
  615. out.writeInt (chunkName ("INFO"));
  616. bool anyParamsDefined = false;
  617. for (auto& type : types)
  618. if (writeValue (values, out, type))
  619. anyParamsDefined = true;
  620. return anyParamsDefined ? out.getMemoryBlock() : MemoryBlock();
  621. }
  622. }
  623. //==============================================================================
  624. struct AcidChunk
  625. {
  626. /** Reads an acid RIFF chunk from a stream positioned just after the size byte. */
  627. AcidChunk (InputStream& input, size_t length)
  628. {
  629. zerostruct (*this);
  630. input.read (this, (int) jmin (sizeof (*this), length));
  631. }
  632. AcidChunk (const StringPairArray& values)
  633. {
  634. zerostruct (*this);
  635. flags = getFlagIfPresent (values, WavAudioFormat::acidOneShot, 0x01)
  636. | getFlagIfPresent (values, WavAudioFormat::acidRootSet, 0x02)
  637. | getFlagIfPresent (values, WavAudioFormat::acidStretch, 0x04)
  638. | getFlagIfPresent (values, WavAudioFormat::acidDiskBased, 0x08)
  639. | getFlagIfPresent (values, WavAudioFormat::acidizerFlag, 0x10);
  640. if (values[WavAudioFormat::acidRootSet].getIntValue() != 0)
  641. rootNote = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidRootNote].getIntValue());
  642. numBeats = ByteOrder::swapIfBigEndian ((uint32) values[WavAudioFormat::acidBeats].getIntValue());
  643. meterDenominator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidDenominator].getIntValue());
  644. meterNumerator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidNumerator].getIntValue());
  645. if (values.containsKey (WavAudioFormat::acidTempo))
  646. tempo = swapFloatByteOrder (values[WavAudioFormat::acidTempo].getFloatValue());
  647. }
  648. static MemoryBlock createFrom (const StringPairArray& values)
  649. {
  650. return AcidChunk (values).toMemoryBlock();
  651. }
  652. MemoryBlock toMemoryBlock() const
  653. {
  654. return (flags != 0 || rootNote != 0 || numBeats != 0 || meterDenominator != 0 || meterNumerator != 0)
  655. ? MemoryBlock (this, sizeof (*this)) : MemoryBlock();
  656. }
  657. void addToMetadata (StringPairArray& values) const
  658. {
  659. setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01);
  660. setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02);
  661. setBoolFlag (values, WavAudioFormat::acidStretch, 0x04);
  662. setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08);
  663. setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10);
  664. if (flags & 0x02) // root note set
  665. values.set (WavAudioFormat::acidRootNote, String (ByteOrder::swapIfBigEndian (rootNote)));
  666. values.set (WavAudioFormat::acidBeats, String (ByteOrder::swapIfBigEndian (numBeats)));
  667. values.set (WavAudioFormat::acidDenominator, String (ByteOrder::swapIfBigEndian (meterDenominator)));
  668. values.set (WavAudioFormat::acidNumerator, String (ByteOrder::swapIfBigEndian (meterNumerator)));
  669. values.set (WavAudioFormat::acidTempo, String (swapFloatByteOrder (tempo)));
  670. }
  671. void setBoolFlag (StringPairArray& values, const char* name, uint32 mask) const
  672. {
  673. values.set (name, (flags & ByteOrder::swapIfBigEndian (mask)) ? "1" : "0");
  674. }
  675. static uint32 getFlagIfPresent (const StringPairArray& values, const char* name, uint32 flag)
  676. {
  677. return values[name].getIntValue() != 0 ? ByteOrder::swapIfBigEndian (flag) : 0;
  678. }
  679. static float swapFloatByteOrder (const float x) noexcept
  680. {
  681. #ifdef JUCE_BIG_ENDIAN
  682. union { uint32 asInt; float asFloat; } n;
  683. n.asFloat = x;
  684. n.asInt = ByteOrder::swap (n.asInt);
  685. return n.asFloat;
  686. #else
  687. return x;
  688. #endif
  689. }
  690. uint32 flags;
  691. uint16 rootNote;
  692. uint16 reserved1;
  693. float reserved2;
  694. uint32 numBeats;
  695. uint16 meterDenominator;
  696. uint16 meterNumerator;
  697. float tempo;
  698. } JUCE_PACKED;
  699. //==============================================================================
  700. struct TracktionChunk
  701. {
  702. static MemoryBlock createFrom (const StringPairArray& values)
  703. {
  704. MemoryOutputStream out;
  705. auto s = values[WavAudioFormat::tracktionLoopInfo];
  706. if (s.isNotEmpty())
  707. {
  708. out.writeString (s);
  709. if ((out.getDataSize() & 1) != 0)
  710. out.writeByte (0);
  711. }
  712. return out.getMemoryBlock();
  713. }
  714. };
  715. //==============================================================================
  716. namespace AXMLChunk
  717. {
  718. static void addToMetadata (StringPairArray& destValues, const String& source)
  719. {
  720. if (auto xml = parseXML (source))
  721. {
  722. if (xml->hasTagName ("ebucore:ebuCoreMain"))
  723. {
  724. if (auto xml2 = xml->getChildByName ("ebucore:coreMetadata"))
  725. {
  726. if (auto xml3 = xml2->getChildByName ("ebucore:identifier"))
  727. {
  728. if (auto xml4 = xml3->getChildByName ("dc:identifier"))
  729. {
  730. auto ISRCCode = xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true);
  731. if (ISRCCode.isNotEmpty())
  732. destValues.set (WavAudioFormat::ISRC, ISRCCode);
  733. }
  734. }
  735. }
  736. }
  737. }
  738. }
  739. static MemoryBlock createFrom (const StringPairArray& values)
  740. {
  741. auto ISRC = values.getValue (WavAudioFormat::ISRC, {});
  742. MemoryOutputStream xml;
  743. if (ISRC.isNotEmpty())
  744. {
  745. xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" "
  746. "xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">"
  747. "<ebucore:coreMetadata>"
  748. "<ebucore:identifier typeLabel=\"GUID\" "
  749. "typeDefinition=\"Globally Unique Identifier\" "
  750. "formatLabel=\"ISRC\" "
  751. "formatDefinition=\"International Standard Recording Code\" "
  752. "formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">"
  753. "<dc:identifier>ISRC:" << ISRC << "</dc:identifier>"
  754. "</ebucore:identifier>"
  755. "</ebucore:coreMetadata>"
  756. "</ebucore:ebuCoreMain>";
  757. xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing
  758. }
  759. return xml.getMemoryBlock();
  760. }
  761. }
  762. //==============================================================================
  763. struct ExtensibleWavSubFormat
  764. {
  765. uint32 data1;
  766. uint16 data2;
  767. uint16 data3;
  768. uint8 data4[8];
  769. bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; }
  770. bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); }
  771. } JUCE_PACKED;
  772. static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  773. static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  774. static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  775. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  776. {
  777. uint32 riffSizeLow; // low 4 byte size of RF64 block
  778. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  779. uint32 dataSizeLow; // low 4 byte size of data chunk
  780. uint32 dataSizeHigh; // high 4 byte size of data chunk
  781. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  782. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  783. uint32 tableLength; // number of valid entries in array 'table'
  784. } JUCE_PACKED;
  785. #if JUCE_MSVC
  786. #pragma pack (pop)
  787. #endif
  788. }
  789. //==============================================================================
  790. class WavAudioFormatReader : public AudioFormatReader
  791. {
  792. public:
  793. WavAudioFormatReader (InputStream* in) : AudioFormatReader (in, wavFormatName)
  794. {
  795. using namespace WavFileHelpers;
  796. uint64 len = 0, end = 0;
  797. int cueNoteIndex = 0;
  798. int cueLabelIndex = 0;
  799. int cueRegionIndex = 0;
  800. auto streamStartPos = input->getPosition();
  801. auto firstChunkType = input->readInt();
  802. if (firstChunkType == chunkName ("RF64"))
  803. {
  804. input->skipNextBytes (4); // size is -1 for RF64
  805. isRF64 = true;
  806. }
  807. else if (firstChunkType == chunkName ("RIFF"))
  808. {
  809. len = (uint64) (uint32) input->readInt();
  810. end = len + (uint64) input->getPosition();
  811. }
  812. else
  813. {
  814. return;
  815. }
  816. auto startOfRIFFChunk = input->getPosition();
  817. if (input->readInt() == chunkName ("WAVE"))
  818. {
  819. if (isRF64 && input->readInt() == chunkName ("ds64"))
  820. {
  821. auto length = (uint32) input->readInt();
  822. if (length < 28)
  823. return;
  824. auto chunkEnd = input->getPosition() + length + (length & 1);
  825. len = (uint64) input->readInt64();
  826. end = len + (uint64) startOfRIFFChunk;
  827. dataLength = input->readInt64();
  828. input->setPosition (chunkEnd);
  829. }
  830. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  831. {
  832. auto chunkType = input->readInt();
  833. auto length = (uint32) input->readInt();
  834. auto chunkEnd = input->getPosition() + length + (length & 1);
  835. if (chunkType == chunkName ("fmt "))
  836. {
  837. // read the format chunk
  838. auto format = (unsigned short) input->readShort();
  839. numChannels = (unsigned int) input->readShort();
  840. sampleRate = input->readInt();
  841. auto bytesPerSec = input->readInt();
  842. input->skipNextBytes (2);
  843. bitsPerSample = (unsigned int) (int) input->readShort();
  844. if (bitsPerSample > 64)
  845. {
  846. bytesPerFrame = bytesPerSec / (int) sampleRate;
  847. bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels;
  848. }
  849. else
  850. {
  851. bytesPerFrame = (int) (numChannels * bitsPerSample / 8);
  852. }
  853. if (format == 3)
  854. {
  855. usesFloatingPointData = true;
  856. }
  857. else if (format == 0xfffe) // WAVE_FORMAT_EXTENSIBLE
  858. {
  859. if (length < 40) // too short
  860. {
  861. bytesPerFrame = 0;
  862. }
  863. else
  864. {
  865. input->skipNextBytes (4); // skip over size and bitsPerSample
  866. auto channelMask = input->readInt();
  867. metadataValues.set ("ChannelMask", String (channelMask));
  868. channelLayout = getChannelLayoutFromMask (channelMask, numChannels);
  869. ExtensibleWavSubFormat subFormat;
  870. subFormat.data1 = (uint32) input->readInt();
  871. subFormat.data2 = (uint16) input->readShort();
  872. subFormat.data3 = (uint16) input->readShort();
  873. input->read (subFormat.data4, sizeof (subFormat.data4));
  874. if (subFormat == IEEEFloatFormat)
  875. usesFloatingPointData = true;
  876. else if (subFormat != pcmFormat && subFormat != ambisonicFormat)
  877. bytesPerFrame = 0;
  878. }
  879. }
  880. else if (format == 0x674f // WAVE_FORMAT_OGG_VORBIS_MODE_1
  881. || format == 0x6750 // WAVE_FORMAT_OGG_VORBIS_MODE_2
  882. || format == 0x6751 // WAVE_FORMAT_OGG_VORBIS_MODE_3
  883. || format == 0x676f // WAVE_FORMAT_OGG_VORBIS_MODE_1_PLUS
  884. || format == 0x6770 // WAVE_FORMAT_OGG_VORBIS_MODE_2_PLUS
  885. || format == 0x6771) // WAVE_FORMAT_OGG_VORBIS_MODE_3_PLUS
  886. {
  887. isSubformatOggVorbis = true;
  888. sampleRate = 0; // to mark the wav reader as failed
  889. input->setPosition (streamStartPos);
  890. return;
  891. }
  892. else if (format != 1)
  893. {
  894. bytesPerFrame = 0;
  895. }
  896. }
  897. else if (chunkType == chunkName ("data"))
  898. {
  899. if (isRF64)
  900. {
  901. if (dataLength > 0)
  902. chunkEnd = input->getPosition() + dataLength + (dataLength & 1);
  903. }
  904. else
  905. {
  906. dataLength = length;
  907. }
  908. dataChunkStart = input->getPosition();
  909. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  910. }
  911. else if (chunkType == chunkName ("bext"))
  912. {
  913. bwavChunkStart = input->getPosition();
  914. bwavSize = length;
  915. HeapBlock<BWAVChunk> bwav;
  916. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  917. input->read (bwav, (int) length);
  918. bwav->copyTo (metadataValues, (int) length);
  919. }
  920. else if (chunkType == chunkName ("smpl"))
  921. {
  922. HeapBlock<SMPLChunk> smpl;
  923. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  924. input->read (smpl, (int) length);
  925. smpl->copyTo (metadataValues, (int) length);
  926. }
  927. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  928. {
  929. HeapBlock<InstChunk> inst;
  930. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  931. input->read (inst, (int) length);
  932. inst->copyTo (metadataValues);
  933. }
  934. else if (chunkType == chunkName ("cue "))
  935. {
  936. HeapBlock<CueChunk> cue;
  937. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  938. input->read (cue, (int) length);
  939. cue->copyTo (metadataValues, (int) length);
  940. }
  941. else if (chunkType == chunkName ("axml"))
  942. {
  943. MemoryBlock axml;
  944. input->readIntoMemoryBlock (axml, (ssize_t) length);
  945. AXMLChunk::addToMetadata (metadataValues, axml.toString());
  946. }
  947. else if (chunkType == chunkName ("LIST"))
  948. {
  949. auto subChunkType = input->readInt();
  950. if (subChunkType == chunkName ("info") || subChunkType == chunkName ("INFO"))
  951. {
  952. ListInfoChunk::addToMetadata (metadataValues, *input, chunkEnd);
  953. }
  954. else if (subChunkType == chunkName ("adtl"))
  955. {
  956. while (input->getPosition() < chunkEnd)
  957. {
  958. auto adtlChunkType = input->readInt();
  959. auto adtlLength = (uint32) input->readInt();
  960. auto adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  961. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  962. {
  963. String prefix;
  964. if (adtlChunkType == chunkName ("labl"))
  965. prefix << "CueLabel" << cueLabelIndex++;
  966. else if (adtlChunkType == chunkName ("note"))
  967. prefix << "CueNote" << cueNoteIndex++;
  968. auto identifier = (uint32) input->readInt();
  969. auto stringLength = (int) adtlLength - 4;
  970. MemoryBlock textBlock;
  971. input->readIntoMemoryBlock (textBlock, stringLength);
  972. metadataValues.set (prefix + "Identifier", String (identifier));
  973. metadataValues.set (prefix + "Text", textBlock.toString());
  974. }
  975. else if (adtlChunkType == chunkName ("ltxt"))
  976. {
  977. auto prefix = "CueRegion" + String (cueRegionIndex++);
  978. auto identifier = (uint32) input->readInt();
  979. auto sampleLength = (uint32) input->readInt();
  980. auto purpose = (uint32) input->readInt();
  981. auto country = (uint16) input->readShort();
  982. auto language = (uint16) input->readShort();
  983. auto dialect = (uint16) input->readShort();
  984. auto codePage = (uint16) input->readShort();
  985. auto stringLength = adtlLength - 20;
  986. MemoryBlock textBlock;
  987. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  988. metadataValues.set (prefix + "Identifier", String (identifier));
  989. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  990. metadataValues.set (prefix + "Purpose", String (purpose));
  991. metadataValues.set (prefix + "Country", String (country));
  992. metadataValues.set (prefix + "Language", String (language));
  993. metadataValues.set (prefix + "Dialect", String (dialect));
  994. metadataValues.set (prefix + "CodePage", String (codePage));
  995. metadataValues.set (prefix + "Text", textBlock.toString());
  996. }
  997. input->setPosition (adtlChunkEnd);
  998. }
  999. }
  1000. }
  1001. else if (chunkType == chunkName ("acid"))
  1002. {
  1003. AcidChunk (*input, length).addToMetadata (metadataValues);
  1004. }
  1005. else if (chunkType == chunkName ("Trkn"))
  1006. {
  1007. MemoryBlock tracktion;
  1008. input->readIntoMemoryBlock (tracktion, (ssize_t) length);
  1009. metadataValues.set (WavAudioFormat::tracktionLoopInfo, tracktion.toString());
  1010. }
  1011. else if (chunkEnd <= input->getPosition())
  1012. {
  1013. break;
  1014. }
  1015. input->setPosition (chunkEnd);
  1016. }
  1017. }
  1018. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  1019. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  1020. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  1021. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  1022. }
  1023. //==============================================================================
  1024. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  1025. int64 startSampleInFile, int numSamples) override
  1026. {
  1027. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  1028. startSampleInFile, numSamples, lengthInSamples);
  1029. if (numSamples <= 0)
  1030. return true;
  1031. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  1032. while (numSamples > 0)
  1033. {
  1034. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  1035. char tempBuffer[tempBufSize];
  1036. auto numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  1037. auto bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  1038. if (bytesRead < numThisTime * bytesPerFrame)
  1039. {
  1040. jassert (bytesRead >= 0);
  1041. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  1042. }
  1043. copySampleData (bitsPerSample, usesFloatingPointData,
  1044. destSamples, startOffsetInDestBuffer, numDestChannels,
  1045. tempBuffer, (int) numChannels, numThisTime);
  1046. startOffsetInDestBuffer += numThisTime;
  1047. numSamples -= numThisTime;
  1048. }
  1049. return true;
  1050. }
  1051. static void copySampleData (unsigned int numBitsPerSample, const bool floatingPointData,
  1052. int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
  1053. const void* sourceData, int numberOfChannels, int numSamples) noexcept
  1054. {
  1055. switch (numBitsPerSample)
  1056. {
  1057. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  1058. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  1059. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  1060. case 32: if (floatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
  1061. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
  1062. break;
  1063. default: jassertfalse; break;
  1064. }
  1065. }
  1066. //==============================================================================
  1067. AudioChannelSet getChannelLayout() override
  1068. {
  1069. if (channelLayout.size() == static_cast<int> (numChannels))
  1070. return channelLayout;
  1071. return WavFileHelpers::canonicalWavChannelSet (static_cast<int> (numChannels));
  1072. }
  1073. static AudioChannelSet getChannelLayoutFromMask (int dwChannelMask, size_t totalNumChannels)
  1074. {
  1075. AudioChannelSet wavFileChannelLayout;
  1076. // AudioChannelSet and wav's dwChannelMask are compatible
  1077. BigInteger channelBits (dwChannelMask);
  1078. for (auto bit = channelBits.findNextSetBit (0); bit >= 0; bit = channelBits.findNextSetBit (bit + 1))
  1079. wavFileChannelLayout.addChannel (static_cast<AudioChannelSet::ChannelType> (bit + 1));
  1080. // channel layout and number of channels do not match
  1081. if (wavFileChannelLayout.size() != static_cast<int> (totalNumChannels))
  1082. {
  1083. // for backward compatibility with old wav files, assume 1 or 2
  1084. // channel wav files are mono/stereo respectively
  1085. if (totalNumChannels <= 2 && dwChannelMask == 0)
  1086. wavFileChannelLayout = AudioChannelSet::canonicalChannelSet (static_cast<int> (totalNumChannels));
  1087. else
  1088. {
  1089. auto discreteSpeaker = static_cast<int> (AudioChannelSet::discreteChannel0);
  1090. while (wavFileChannelLayout.size() < static_cast<int> (totalNumChannels))
  1091. wavFileChannelLayout.addChannel (static_cast<AudioChannelSet::ChannelType> (discreteSpeaker++));
  1092. }
  1093. }
  1094. return wavFileChannelLayout;
  1095. }
  1096. int64 bwavChunkStart = 0, bwavSize = 0;
  1097. int64 dataChunkStart = 0, dataLength = 0;
  1098. int bytesPerFrame = 0;
  1099. bool isRF64 = false;
  1100. bool isSubformatOggVorbis = false;
  1101. AudioChannelSet channelLayout;
  1102. private:
  1103. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader)
  1104. };
  1105. //==============================================================================
  1106. class WavAudioFormatWriter : public AudioFormatWriter
  1107. {
  1108. public:
  1109. WavAudioFormatWriter (OutputStream* const out, const double rate,
  1110. const AudioChannelSet& channelLayoutToUse, const unsigned int bits,
  1111. const StringPairArray& metadataValues)
  1112. : AudioFormatWriter (out, wavFormatName, rate, channelLayoutToUse, bits)
  1113. {
  1114. using namespace WavFileHelpers;
  1115. if (metadataValues.size() > 0)
  1116. {
  1117. // The meta data should have been sanitised for the WAV format.
  1118. // If it was originally sourced from an AIFF file the MetaDataSource
  1119. // key should be removed (or set to "WAV") once this has been done
  1120. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  1121. bwavChunk = BWAVChunk::createFrom (metadataValues);
  1122. axmlChunk = AXMLChunk::createFrom (metadataValues);
  1123. smplChunk = SMPLChunk::createFrom (metadataValues);
  1124. instChunk = InstChunk::createFrom (metadataValues);
  1125. cueChunk = CueChunk ::createFrom (metadataValues);
  1126. listChunk = ListChunk::createFrom (metadataValues);
  1127. listInfoChunk = ListInfoChunk::createFrom (metadataValues);
  1128. acidChunk = AcidChunk::createFrom (metadataValues);
  1129. trckChunk = TracktionChunk::createFrom (metadataValues);
  1130. }
  1131. headerPosition = out->getPosition();
  1132. writeHeader();
  1133. }
  1134. ~WavAudioFormatWriter() override
  1135. {
  1136. writeHeader();
  1137. }
  1138. //==============================================================================
  1139. bool write (const int** data, int numSamples) override
  1140. {
  1141. jassert (numSamples >= 0);
  1142. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  1143. if (writeFailed)
  1144. return false;
  1145. auto bytes = numChannels * (size_t) numSamples * bitsPerSample / 8;
  1146. tempBlock.ensureSize (bytes, false);
  1147. switch (bitsPerSample)
  1148. {
  1149. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  1150. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  1151. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  1152. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  1153. default: jassertfalse; break;
  1154. }
  1155. if (! output->write (tempBlock.getData(), bytes))
  1156. {
  1157. // failed to write to disk, so let's try writing the header.
  1158. // If it's just run out of disk space, then if it does manage
  1159. // to write the header, we'll still have a usable file..
  1160. writeHeader();
  1161. writeFailed = true;
  1162. return false;
  1163. }
  1164. bytesWritten += bytes;
  1165. lengthInSamples += (uint64) numSamples;
  1166. return true;
  1167. }
  1168. bool flush() override
  1169. {
  1170. auto lastWritePos = output->getPosition();
  1171. writeHeader();
  1172. if (output->setPosition (lastWritePos))
  1173. return true;
  1174. // if this fails, you've given it an output stream that can't seek! It needs
  1175. // to be able to seek back to write the header
  1176. jassertfalse;
  1177. return false;
  1178. }
  1179. private:
  1180. MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk, listInfoChunk, acidChunk, trckChunk;
  1181. uint64 lengthInSamples = 0, bytesWritten = 0;
  1182. int64 headerPosition = 0;
  1183. bool writeFailed = false;
  1184. void writeHeader()
  1185. {
  1186. if ((bytesWritten & 1) != 0) // pad to an even length
  1187. output->writeByte (0);
  1188. using namespace WavFileHelpers;
  1189. if (headerPosition != output->getPosition() && ! output->setPosition (headerPosition))
  1190. {
  1191. // if this fails, you've given it an output stream that can't seek! It needs to be
  1192. // able to seek back to go back and write the header after the data has been written.
  1193. jassertfalse;
  1194. return;
  1195. }
  1196. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  1197. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  1198. auto channelMask = getChannelMaskFromChannelLayout (channelLayout);
  1199. const bool isRF64 = (bytesWritten >= 0x100000000LL);
  1200. const bool isWaveFmtEx = isRF64 || (channelMask != 0);
  1201. int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  1202. + 8 + audioDataSize + (audioDataSize & 1)
  1203. + chunkSize (bwavChunk)
  1204. + chunkSize (axmlChunk)
  1205. + chunkSize (smplChunk)
  1206. + chunkSize (instChunk)
  1207. + chunkSize (cueChunk)
  1208. + chunkSize (listChunk)
  1209. + chunkSize (listInfoChunk)
  1210. + chunkSize (acidChunk)
  1211. + chunkSize (trckChunk)
  1212. + (8 + 28)); // (ds64 chunk)
  1213. riffChunkSize += (riffChunkSize & 1);
  1214. if (isRF64)
  1215. writeChunkHeader (chunkName ("RF64"), -1);
  1216. else
  1217. writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize);
  1218. output->writeInt (chunkName ("WAVE"));
  1219. if (! isRF64)
  1220. {
  1221. #if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  1222. /* NB: This junk chunk is added for padding, so that the header is a fixed size
  1223. regardless of whether it's RF64 or not. That way, we can begin recording a file,
  1224. and when it's finished, can go back and write either a RIFF or RF64 header,
  1225. depending on whether more than 2^32 samples were written.
  1226. The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case
  1227. you need to create files for crappy WAV players with bugs that stop them skipping chunks
  1228. which they don't recognise. But DO NOT USE THIS option unless you really have no choice,
  1229. because it means that if you write more than 2^32 samples to the file, you'll corrupt it.
  1230. */
  1231. writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24));
  1232. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  1233. #endif
  1234. }
  1235. else
  1236. {
  1237. #if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
  1238. // If you disable padding, then you MUST NOT write more than 2^32 samples to a file.
  1239. jassertfalse;
  1240. #endif
  1241. writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table)
  1242. output->writeInt64 (riffChunkSize);
  1243. output->writeInt64 ((int64) audioDataSize);
  1244. output->writeRepeatedByte (0, 12);
  1245. }
  1246. if (isWaveFmtEx)
  1247. {
  1248. writeChunkHeader (chunkName ("fmt "), 40);
  1249. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  1250. }
  1251. else
  1252. {
  1253. writeChunkHeader (chunkName ("fmt "), 16);
  1254. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  1255. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  1256. }
  1257. output->writeShort ((short) numChannels);
  1258. output->writeInt ((int) sampleRate);
  1259. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  1260. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  1261. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  1262. if (isWaveFmtEx)
  1263. {
  1264. output->writeShort (22); // cbSize (size of the extension)
  1265. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  1266. output->writeInt (channelMask);
  1267. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  1268. output->writeInt ((int) subFormat.data1);
  1269. output->writeShort ((short) subFormat.data2);
  1270. output->writeShort ((short) subFormat.data3);
  1271. output->write (subFormat.data4, sizeof (subFormat.data4));
  1272. }
  1273. writeChunk (bwavChunk, chunkName ("bext"));
  1274. writeChunk (axmlChunk, chunkName ("axml"));
  1275. writeChunk (smplChunk, chunkName ("smpl"));
  1276. writeChunk (instChunk, chunkName ("inst"), 7);
  1277. writeChunk (cueChunk, chunkName ("cue "));
  1278. writeChunk (listChunk, chunkName ("LIST"));
  1279. writeChunk (listInfoChunk, chunkName ("LIST"));
  1280. writeChunk (acidChunk, chunkName ("acid"));
  1281. writeChunk (trckChunk, chunkName ("Trkn"));
  1282. writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  1283. usesFloatingPointData = (bitsPerSample == 32);
  1284. }
  1285. static size_t chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; }
  1286. void writeChunkHeader (int chunkType, int size) const
  1287. {
  1288. output->writeInt (chunkType);
  1289. output->writeInt (size);
  1290. }
  1291. void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const
  1292. {
  1293. if (data.getSize() > 0)
  1294. {
  1295. writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize());
  1296. *output << data;
  1297. }
  1298. }
  1299. static int getChannelMaskFromChannelLayout (const AudioChannelSet& layout)
  1300. {
  1301. if (layout.isDiscreteLayout())
  1302. return 0;
  1303. // Don't add an extended format chunk for mono and stereo. Basically, all wav players
  1304. // interpret a wav file with only one or two channels to be mono or stereo anyway.
  1305. if (layout == AudioChannelSet::mono() || layout == AudioChannelSet::stereo())
  1306. return 0;
  1307. auto channels = layout.getChannelTypes();
  1308. auto wavChannelMask = 0;
  1309. for (auto channel : channels)
  1310. {
  1311. int wavChannelBit = static_cast<int> (channel) - 1;
  1312. jassert (wavChannelBit >= 0 && wavChannelBit <= 31);
  1313. wavChannelMask |= (1 << wavChannelBit);
  1314. }
  1315. return wavChannelMask;
  1316. }
  1317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter)
  1318. };
  1319. //==============================================================================
  1320. class MemoryMappedWavReader : public MemoryMappedAudioFormatReader
  1321. {
  1322. public:
  1323. MemoryMappedWavReader (const File& wavFile, const WavAudioFormatReader& reader)
  1324. : MemoryMappedAudioFormatReader (wavFile, reader, reader.dataChunkStart,
  1325. reader.dataLength, reader.bytesPerFrame)
  1326. {
  1327. }
  1328. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  1329. int64 startSampleInFile, int numSamples) override
  1330. {
  1331. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  1332. startSampleInFile, numSamples, lengthInSamples);
  1333. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1334. {
  1335. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1336. return false;
  1337. }
  1338. WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData,
  1339. destSamples, startOffsetInDestBuffer, numDestChannels,
  1340. sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  1341. return true;
  1342. }
  1343. void getSample (int64 sample, float* result) const noexcept override
  1344. {
  1345. auto num = (int) numChannels;
  1346. if (map == nullptr || ! mappedSection.contains (sample))
  1347. {
  1348. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  1349. zeromem (result, (size_t) num * sizeof (float));
  1350. return;
  1351. }
  1352. auto dest = &result;
  1353. auto source = sampleToPointer (sample);
  1354. switch (bitsPerSample)
  1355. {
  1356. case 8: ReadHelper<AudioData::Float32, AudioData::UInt8, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  1357. case 16: ReadHelper<AudioData::Float32, AudioData::Int16, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  1358. case 24: ReadHelper<AudioData::Float32, AudioData::Int24, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  1359. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
  1360. else ReadHelper<AudioData::Float32, AudioData::Int32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
  1361. break;
  1362. default: jassertfalse; break;
  1363. }
  1364. }
  1365. void readMaxLevels (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) override
  1366. {
  1367. numSamples = jmin (numSamples, lengthInSamples - startSampleInFile);
  1368. if (map == nullptr || numSamples <= 0 || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  1369. {
  1370. jassert (numSamples <= 0); // you must make sure that the window contains all the samples you're going to attempt to read.
  1371. for (int i = 0; i < numChannelsToRead; ++i)
  1372. results[i] = {};
  1373. return;
  1374. }
  1375. switch (bitsPerSample)
  1376. {
  1377. case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  1378. case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  1379. case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  1380. case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, results, numChannelsToRead);
  1381. else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, results, numChannelsToRead);
  1382. break;
  1383. default: jassertfalse; break;
  1384. }
  1385. }
  1386. using AudioFormatReader::readMaxLevels;
  1387. private:
  1388. template <typename SampleType>
  1389. void scanMinAndMax (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) const noexcept
  1390. {
  1391. for (int i = 0; i < numChannelsToRead; ++i)
  1392. results[i] = scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (i, startSampleInFile, numSamples);
  1393. }
  1394. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader)
  1395. };
  1396. //==============================================================================
  1397. WavAudioFormat::WavAudioFormat() : AudioFormat (wavFormatName, ".wav .bwf") {}
  1398. WavAudioFormat::~WavAudioFormat() {}
  1399. Array<int> WavAudioFormat::getPossibleSampleRates()
  1400. {
  1401. return { 8000, 11025, 12000, 16000, 22050, 32000, 44100,
  1402. 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
  1403. }
  1404. Array<int> WavAudioFormat::getPossibleBitDepths()
  1405. {
  1406. return { 8, 16, 24, 32 };
  1407. }
  1408. bool WavAudioFormat::canDoStereo() { return true; }
  1409. bool WavAudioFormat::canDoMono() { return true; }
  1410. bool WavAudioFormat::isChannelLayoutSupported (const AudioChannelSet& channelSet)
  1411. {
  1412. auto channelTypes = channelSet.getChannelTypes();
  1413. // When
  1414. if (channelSet.isDiscreteLayout())
  1415. return true;
  1416. // WAV supports all channel types from left ... topRearRight
  1417. for (auto channel : channelTypes)
  1418. if (channel < AudioChannelSet::left || channel > AudioChannelSet::topRearRight)
  1419. return false;
  1420. return true;
  1421. }
  1422. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails)
  1423. {
  1424. std::unique_ptr<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  1425. #if JUCE_USE_OGGVORBIS
  1426. if (r->isSubformatOggVorbis)
  1427. {
  1428. r->input = nullptr;
  1429. return OggVorbisAudioFormat().createReaderFor (sourceStream, deleteStreamIfOpeningFails);
  1430. }
  1431. #endif
  1432. if (r->sampleRate > 0 && r->numChannels > 0 && r->bytesPerFrame > 0 && r->bitsPerSample <= 32)
  1433. return r.release();
  1434. if (! deleteStreamIfOpeningFails)
  1435. r->input = nullptr;
  1436. return nullptr;
  1437. }
  1438. MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file)
  1439. {
  1440. return createMemoryMappedReader (file.createInputStream().release());
  1441. }
  1442. MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (FileInputStream* fin)
  1443. {
  1444. if (fin != nullptr)
  1445. {
  1446. WavAudioFormatReader reader (fin);
  1447. if (reader.lengthInSamples > 0)
  1448. return new MemoryMappedWavReader (fin->getFile(), reader);
  1449. }
  1450. return nullptr;
  1451. }
  1452. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  1453. unsigned int numChannels, int bitsPerSample,
  1454. const StringPairArray& metadataValues, int qualityOptionIndex)
  1455. {
  1456. return createWriterFor (out, sampleRate, WavFileHelpers::canonicalWavChannelSet (static_cast<int> (numChannels)),
  1457. bitsPerSample, metadataValues, qualityOptionIndex);
  1458. }
  1459. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  1460. double sampleRate,
  1461. const AudioChannelSet& channelLayout,
  1462. int bitsPerSample,
  1463. const StringPairArray& metadataValues,
  1464. int /*qualityOptionIndex*/)
  1465. {
  1466. if (out != nullptr && getPossibleBitDepths().contains (bitsPerSample) && isChannelLayoutSupported (channelLayout))
  1467. return new WavAudioFormatWriter (out, sampleRate, channelLayout,
  1468. (unsigned int) bitsPerSample, metadataValues);
  1469. return nullptr;
  1470. }
  1471. namespace WavFileHelpers
  1472. {
  1473. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  1474. {
  1475. TemporaryFile tempFile (file);
  1476. WavAudioFormat wav;
  1477. std::unique_ptr<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  1478. if (reader != nullptr)
  1479. {
  1480. std::unique_ptr<OutputStream> outStream (tempFile.getFile().createOutputStream());
  1481. if (outStream != nullptr)
  1482. {
  1483. std::unique_ptr<AudioFormatWriter> writer (wav.createWriterFor (outStream.get(), reader->sampleRate,
  1484. reader->numChannels, (int) reader->bitsPerSample,
  1485. metadata, 0));
  1486. if (writer != nullptr)
  1487. {
  1488. outStream.release();
  1489. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  1490. writer.reset();
  1491. reader.reset();
  1492. return ok && tempFile.overwriteTargetFileWithTemporary();
  1493. }
  1494. }
  1495. }
  1496. return false;
  1497. }
  1498. }
  1499. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  1500. {
  1501. using namespace WavFileHelpers;
  1502. std::unique_ptr<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream().release(), true)));
  1503. if (reader != nullptr)
  1504. {
  1505. auto bwavPos = reader->bwavChunkStart;
  1506. auto bwavSize = reader->bwavSize;
  1507. reader.reset();
  1508. if (bwavSize > 0)
  1509. {
  1510. auto chunk = BWAVChunk::createFrom (newMetadata);
  1511. if (chunk.getSize() <= (size_t) bwavSize)
  1512. {
  1513. // the new one will fit in the space available, so write it directly..
  1514. auto oldSize = wavFile.getSize();
  1515. {
  1516. FileOutputStream out (wavFile);
  1517. if (out.openedOk())
  1518. {
  1519. out.setPosition (bwavPos);
  1520. out << chunk;
  1521. out.setPosition (oldSize);
  1522. }
  1523. }
  1524. jassert (wavFile.getSize() == oldSize);
  1525. return true;
  1526. }
  1527. }
  1528. }
  1529. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  1530. }
  1531. //==============================================================================
  1532. //==============================================================================
  1533. #if JUCE_UNIT_TESTS
  1534. struct WaveAudioFormatTests : public UnitTest
  1535. {
  1536. WaveAudioFormatTests()
  1537. : UnitTest ("Wave audio format tests", UnitTestCategories::audio)
  1538. {}
  1539. void runTest() override
  1540. {
  1541. beginTest ("Setting up metadata");
  1542. StringPairArray metadataValues = WavAudioFormat::createBWAVMetadata ("description",
  1543. "originator",
  1544. "originatorRef",
  1545. Time::getCurrentTime(),
  1546. numTestAudioBufferSamples,
  1547. "codingHistory");
  1548. for (int i = numElementsInArray (WavFileHelpers::ListInfoChunk::types); --i >= 0;)
  1549. metadataValues.set (WavFileHelpers::ListInfoChunk::types[i],
  1550. WavFileHelpers::ListInfoChunk::types[i]);
  1551. if (metadataValues.size() > 0)
  1552. metadataValues.set ("MetaDataSource", "WAV");
  1553. metadataValues.addArray (createDefaultSMPLMetadata());
  1554. WavAudioFormat format;
  1555. MemoryBlock memoryBlock;
  1556. {
  1557. beginTest ("Creating a basic wave writer");
  1558. std::unique_ptr<AudioFormatWriter> writer (format.createWriterFor (new MemoryOutputStream (memoryBlock, false),
  1559. 44100.0, numTestAudioBufferChannels,
  1560. 32, metadataValues, 0));
  1561. expect (writer != nullptr);
  1562. AudioBuffer<float> buffer (numTestAudioBufferChannels, numTestAudioBufferSamples);
  1563. buffer.clear();
  1564. beginTest ("Writing audio data to the basic wave writer");
  1565. expect (writer->writeFromAudioSampleBuffer (buffer, 0, numTestAudioBufferSamples));
  1566. }
  1567. {
  1568. beginTest ("Creating a basic wave reader");
  1569. std::unique_ptr<AudioFormatReader> reader (format.createReaderFor (new MemoryInputStream (memoryBlock, false), false));
  1570. expect (reader != nullptr);
  1571. expect (reader->metadataValues == metadataValues, "Somehow, the metadata is different!");
  1572. }
  1573. }
  1574. private:
  1575. enum
  1576. {
  1577. numTestAudioBufferChannels = 2,
  1578. numTestAudioBufferSamples = 256
  1579. };
  1580. StringPairArray createDefaultSMPLMetadata() const
  1581. {
  1582. StringPairArray m;
  1583. m.set ("Manufacturer", "0");
  1584. m.set ("Product", "0");
  1585. m.set ("SamplePeriod", "0");
  1586. m.set ("MidiUnityNote", "60");
  1587. m.set ("MidiPitchFraction", "0");
  1588. m.set ("SmpteFormat", "0");
  1589. m.set ("SmpteOffset", "0");
  1590. m.set ("NumSampleLoops", "0");
  1591. m.set ("SamplerData", "0");
  1592. return m;
  1593. }
  1594. JUCE_DECLARE_NON_COPYABLE (WaveAudioFormatTests)
  1595. };
  1596. static const WaveAudioFormatTests waveAudioFormatTests;
  1597. #endif
  1598. } // namespace juce