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.

1107 lines
49KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. //==============================================================================
  19. static const char* const wavFormatName = "WAV file";
  20. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  21. //==============================================================================
  22. const char* const WavAudioFormat::bwavDescription = "bwav description";
  23. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  24. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  25. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  26. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  27. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  28. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  29. StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  30. const String& originator,
  31. const String& originatorRef,
  32. const Time& date,
  33. const int64 timeReferenceSamples,
  34. const String& codingHistory)
  35. {
  36. StringPairArray m;
  37. m.set (bwavDescription, description);
  38. m.set (bwavOriginator, originator);
  39. m.set (bwavOriginatorRef, originatorRef);
  40. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  41. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  42. m.set (bwavTimeReference, String (timeReferenceSamples));
  43. m.set (bwavCodingHistory, codingHistory);
  44. return m;
  45. }
  46. //==============================================================================
  47. namespace WavFileHelpers
  48. {
  49. inline int chunkName (const char* const name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
  50. #if JUCE_MSVC
  51. #pragma pack (push, 1)
  52. #endif
  53. struct BWAVChunk
  54. {
  55. char description [256];
  56. char originator [32];
  57. char originatorRef [32];
  58. char originationDate [10];
  59. char originationTime [8];
  60. uint32 timeRefLow;
  61. uint32 timeRefHigh;
  62. uint16 version;
  63. uint8 umid[64];
  64. uint8 reserved[190];
  65. char codingHistory[1];
  66. void copyTo (StringPairArray& values, const int totalSize) const
  67. {
  68. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  69. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  70. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  71. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  72. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  73. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  74. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  75. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  76. values.set (WavAudioFormat::bwavTimeReference, String (time));
  77. values.set (WavAudioFormat::bwavCodingHistory,
  78. String::fromUTF8 (codingHistory, totalSize - offsetof (BWAVChunk, codingHistory)));
  79. }
  80. static MemoryBlock createFrom (const StringPairArray& values)
  81. {
  82. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  83. MemoryBlock data ((sizeNeeded + 3) & ~3);
  84. data.fillWith (0);
  85. BWAVChunk* b = (BWAVChunk*) data.getData();
  86. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  87. // as they get called in the right order..
  88. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  89. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  90. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  91. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  92. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  93. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  94. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  95. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  96. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  97. if (b->description[0] != 0
  98. || b->originator[0] != 0
  99. || b->originationDate[0] != 0
  100. || b->originationTime[0] != 0
  101. || b->codingHistory[0] != 0
  102. || time != 0)
  103. {
  104. return data;
  105. }
  106. return MemoryBlock();
  107. }
  108. } JUCE_PACKED;
  109. //==============================================================================
  110. struct SMPLChunk
  111. {
  112. struct SampleLoop
  113. {
  114. uint32 identifier;
  115. uint32 type; // these are different in AIFF and WAV
  116. uint32 start;
  117. uint32 end;
  118. uint32 fraction;
  119. uint32 playCount;
  120. } JUCE_PACKED;
  121. uint32 manufacturer;
  122. uint32 product;
  123. uint32 samplePeriod;
  124. uint32 midiUnityNote;
  125. uint32 midiPitchFraction;
  126. uint32 smpteFormat;
  127. uint32 smpteOffset;
  128. uint32 numSampleLoops;
  129. uint32 samplerData;
  130. SampleLoop loops[1];
  131. void copyTo (StringPairArray& values, const int totalSize) const
  132. {
  133. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  134. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  135. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  136. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  137. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  138. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  139. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  140. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  141. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  142. for (uint32 i = 0; i < numSampleLoops; ++i)
  143. {
  144. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  145. break;
  146. const String prefix ("Loop" + String(i));
  147. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  148. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  149. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  150. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  151. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  152. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  153. }
  154. }
  155. static MemoryBlock createFrom (const StringPairArray& values)
  156. {
  157. MemoryBlock data;
  158. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  159. if (numLoops > 0)
  160. {
  161. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  162. data.setSize ((sizeNeeded + 3) & ~3, true);
  163. SMPLChunk* const s = static_cast <SMPLChunk*> (data.getData());
  164. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  165. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  166. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  167. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  168. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  169. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  170. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  171. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  172. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  173. for (int i = 0; i < numLoops; ++i)
  174. {
  175. const String prefix ("Loop" + String(i));
  176. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  177. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  178. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  179. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  180. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  181. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  182. }
  183. }
  184. return data;
  185. }
  186. } JUCE_PACKED;
  187. //==============================================================================
  188. struct InstChunk
  189. {
  190. int8 baseNote;
  191. int8 detune;
  192. int8 gain;
  193. int8 lowNote;
  194. int8 highNote;
  195. int8 lowVelocity;
  196. int8 highVelocity;
  197. void copyTo (StringPairArray& values) const
  198. {
  199. values.set ("MidiUnityNote", String (baseNote));
  200. values.set ("Detune", String (detune));
  201. values.set ("Gain", String (gain));
  202. values.set ("LowNote", String (lowNote));
  203. values.set ("HighNote", String (highNote));
  204. values.set ("LowVelocity", String (lowVelocity));
  205. values.set ("HighVelocity", String (highVelocity));
  206. }
  207. static MemoryBlock createFrom (const StringPairArray& values)
  208. {
  209. MemoryBlock data;
  210. const StringArray& keys = values.getAllKeys();
  211. if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true))
  212. {
  213. data.setSize (8, true);
  214. InstChunk* const inst = static_cast <InstChunk*> (data.getData());
  215. inst->baseNote = (int8) values.getValue ("MidiUnityNote", "60").getIntValue();
  216. inst->detune = (int8) values.getValue ("Detune", "0").getIntValue();
  217. inst->gain = (int8) values.getValue ("Gain", "0").getIntValue();
  218. inst->lowNote = (int8) values.getValue ("LowNote", "0").getIntValue();
  219. inst->highNote = (int8) values.getValue ("HighNote", "127").getIntValue();
  220. inst->lowVelocity = (int8) values.getValue ("LowVelocity", "1").getIntValue();
  221. inst->highVelocity = (int8) values.getValue ("HighVelocity", "127").getIntValue();
  222. }
  223. return data;
  224. }
  225. } JUCE_PACKED;
  226. //==============================================================================
  227. struct CueChunk
  228. {
  229. struct Cue
  230. {
  231. uint32 identifier;
  232. uint32 order;
  233. uint32 chunkID;
  234. uint32 chunkStart;
  235. uint32 blockStart;
  236. uint32 offset;
  237. } JUCE_PACKED;
  238. uint32 numCues;
  239. Cue cues[1];
  240. void copyTo (StringPairArray& values, const int totalSize) const
  241. {
  242. values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues)));
  243. for (uint32 i = 0; i < numCues; ++i)
  244. {
  245. if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize)
  246. break;
  247. const String prefix ("Cue" + String(i));
  248. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (cues[i].identifier)));
  249. values.set (prefix + "Order", String (ByteOrder::swapIfBigEndian (cues[i].order)));
  250. values.set (prefix + "ChunkID", String (ByteOrder::swapIfBigEndian (cues[i].chunkID)));
  251. values.set (prefix + "ChunkStart", String (ByteOrder::swapIfBigEndian (cues[i].chunkStart)));
  252. values.set (prefix + "BlockStart", String (ByteOrder::swapIfBigEndian (cues[i].blockStart)));
  253. values.set (prefix + "Offset", String (ByteOrder::swapIfBigEndian (cues[i].offset)));
  254. }
  255. }
  256. static void create (MemoryBlock& data, const StringPairArray& values)
  257. {
  258. const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  259. if (numCues > 0)
  260. {
  261. const size_t sizeNeeded = sizeof (CueChunk) + (numCues - 1) * sizeof (Cue);
  262. data.setSize ((sizeNeeded + 3) & ~3, true);
  263. CueChunk* const c = static_cast <CueChunk*> (data.getData());
  264. c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues);
  265. const String dataChunkID (chunkName ("data"));
  266. int nextOrder = 0;
  267. #if JUCE_DEBUG
  268. Array<uint32> identifiers;
  269. #endif
  270. for (int i = 0; i < numCues; ++i)
  271. {
  272. const String prefix ("Cue" + String (i));
  273. uint32 identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue();
  274. #if JUCE_DEBUG
  275. jassert (! identifiers.contains (identifier));
  276. identifiers.add (identifier);
  277. #endif
  278. c->cues[i].identifier = ByteOrder::swapIfBigEndian ((uint32) identifier);
  279. const int order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue();
  280. nextOrder = jmax (nextOrder, order) + 1;
  281. c->cues[i].order = ByteOrder::swapIfBigEndian ((uint32) order);
  282. c->cues[i].chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue());
  283. c->cues[i].chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue());
  284. c->cues[i].blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue());
  285. c->cues[i].offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue());
  286. }
  287. }
  288. }
  289. } JUCE_PACKED;
  290. //==============================================================================
  291. namespace ListChunk
  292. {
  293. static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix,
  294. const int chunkType, MemoryOutputStream& out)
  295. {
  296. const String label (values.getValue (prefix + "Text", prefix));
  297. const int labelLength = label.getNumBytesAsUTF8() + 1;
  298. const int chunkLength = 4 + labelLength + (labelLength & 1);
  299. out.writeInt (chunkType);
  300. out.writeInt (chunkLength);
  301. out.writeInt (values.getValue (prefix + "Identifier", "0").getIntValue());
  302. out.write (label.toUTF8(), labelLength);
  303. if ((out.getDataSize() & 1) != 0)
  304. out.writeByte (0);
  305. }
  306. static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out)
  307. {
  308. const String text (values.getValue (prefix + "Text", prefix));
  309. const int textLength = text.getNumBytesAsUTF8() + 1; // include null terminator
  310. int chunkLength = textLength + 20 + (textLength & 1);
  311. out.writeInt (chunkName ("ltxt"));
  312. out.writeInt (chunkLength);
  313. out.writeInt (values.getValue (prefix + "Identifier", "0").getIntValue());
  314. out.writeInt (values.getValue (prefix + "SampleLength", "0").getIntValue());
  315. out.writeInt (values.getValue (prefix + "Purpose", "0").getIntValue());
  316. out.writeShort ((short) values.getValue (prefix + "Country", "0").getIntValue());
  317. out.writeShort ((short) values.getValue (prefix + "Language", "0").getIntValue());
  318. out.writeShort ((short) values.getValue (prefix + "Dialect", "0").getIntValue());
  319. out.writeShort ((short) values.getValue (prefix + "CodePage", "0").getIntValue());
  320. out.write (text.toUTF8(), textLength);
  321. if ((out.getDataSize() & 1) != 0)
  322. out.writeByte (0);
  323. }
  324. static void create (MemoryBlock& block, const StringPairArray& values)
  325. {
  326. const int numCueLabels = values.getValue ("NumCueLabels", "0").getIntValue();
  327. const int numCueNotes = values.getValue ("NumCueNotes", "0").getIntValue();
  328. const int numCueRegions = values.getValue ("NumCueRegions", "0").getIntValue();
  329. if (numCueLabels > 0 || numCueNotes > 0 || numCueRegions > 0)
  330. {
  331. MemoryOutputStream out (block, false);
  332. int i;
  333. for (i = 0; i < numCueLabels; ++i)
  334. appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out);
  335. for (i = 0; i < numCueNotes; ++i)
  336. appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out);
  337. for (i = 0; i < numCueRegions; ++i)
  338. appendExtraChunk (values, "CueRegion" + String (i), out);
  339. }
  340. }
  341. }
  342. //==============================================================================
  343. struct ExtensibleWavSubFormat
  344. {
  345. uint32 data1;
  346. uint16 data2;
  347. uint16 data3;
  348. uint8 data4[8];
  349. } JUCE_PACKED;
  350. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  351. {
  352. uint32 riffSizeLow; // low 4 byte size of RF64 block
  353. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  354. uint32 dataSizeLow; // low 4 byte size of data chunk
  355. uint32 dataSizeHigh; // high 4 byte size of data chunk
  356. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  357. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  358. uint32 tableLength; // number of valid entries in array 'table'
  359. } JUCE_PACKED;
  360. #if JUCE_MSVC
  361. #pragma pack (pop)
  362. #endif
  363. }
  364. //==============================================================================
  365. class WavAudioFormatReader : public AudioFormatReader
  366. {
  367. public:
  368. WavAudioFormatReader (InputStream* const in)
  369. : AudioFormatReader (in, TRANS (wavFormatName)),
  370. bwavChunkStart (0),
  371. bwavSize (0),
  372. dataLength (0),
  373. isRF64 (false)
  374. {
  375. using namespace WavFileHelpers;
  376. uint64 len = 0;
  377. uint64 end = 0;
  378. bool hasGotType = false;
  379. bool hasGotData = false;
  380. int cueNoteIndex = 0;
  381. int cueLabelIndex = 0;
  382. int cueRegionIndex = 0;
  383. const int firstChunkType = input->readInt();
  384. if (firstChunkType == chunkName ("RF64"))
  385. {
  386. input->skipNextBytes (4); // size is -1 for RF64
  387. isRF64 = true;
  388. }
  389. else if (firstChunkType == chunkName ("RIFF"))
  390. {
  391. len = (uint64) (uint32) input->readInt();
  392. end = input->getPosition() + len;
  393. }
  394. else
  395. {
  396. return;
  397. }
  398. const int64 startOfRIFFChunk = input->getPosition();
  399. if (input->readInt() == chunkName ("WAVE"))
  400. {
  401. if (isRF64 && input->readInt() == chunkName ("ds64"))
  402. {
  403. uint32 length = (uint32) input->readInt();
  404. if (length < 28)
  405. {
  406. return;
  407. }
  408. else
  409. {
  410. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  411. len = (uint64) input->readInt64();
  412. end = startOfRIFFChunk + len;
  413. dataLength = input->readInt64();
  414. input->setPosition (chunkEnd);
  415. }
  416. }
  417. while ((uint64) input->getPosition() < end && ! input->isExhausted())
  418. {
  419. const int chunkType = input->readInt();
  420. uint32 length = (uint32) input->readInt();
  421. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  422. if (chunkType == chunkName ("fmt "))
  423. {
  424. // read the format chunk
  425. const unsigned short format = (unsigned short) input->readShort();
  426. numChannels = (unsigned int) input->readShort();
  427. sampleRate = input->readInt();
  428. const int bytesPerSec = input->readInt();
  429. input->skipNextBytes (2);
  430. bitsPerSample = (unsigned int) (int) input->readShort();
  431. if (bitsPerSample > 64)
  432. {
  433. bytesPerFrame = bytesPerSec / (int) sampleRate;
  434. bitsPerSample = 8 * bytesPerFrame / numChannels;
  435. }
  436. else
  437. {
  438. bytesPerFrame = numChannels * bitsPerSample / 8;
  439. }
  440. if (format == 3)
  441. {
  442. usesFloatingPointData = true;
  443. }
  444. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  445. {
  446. if (length < 40) // too short
  447. {
  448. bytesPerFrame = 0;
  449. }
  450. else
  451. {
  452. input->skipNextBytes (6); // skip over bitsPerSample
  453. metadataValues.set ("ChannelMask", String (input->readInt()));
  454. ExtensibleWavSubFormat subFormat;
  455. subFormat.data1 = (uint32) input->readInt();
  456. subFormat.data2 = (uint16) input->readShort();
  457. subFormat.data3 = (uint16) input->readShort();
  458. input->read (subFormat.data4, sizeof (subFormat.data4));
  459. const ExtensibleWavSubFormat pcmFormat
  460. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  461. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  462. {
  463. const ExtensibleWavSubFormat ambisonicFormat
  464. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  465. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  466. bytesPerFrame = 0;
  467. }
  468. }
  469. }
  470. else if (format != 1)
  471. {
  472. bytesPerFrame = 0;
  473. }
  474. hasGotType = true;
  475. }
  476. else if (chunkType == chunkName ("data"))
  477. {
  478. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  479. dataLength = length;
  480. dataChunkStart = input->getPosition();
  481. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  482. hasGotData = true;
  483. }
  484. else if (chunkType == chunkName ("bext"))
  485. {
  486. bwavChunkStart = input->getPosition();
  487. bwavSize = length;
  488. HeapBlock <BWAVChunk> bwav;
  489. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  490. input->read (bwav, (int) length);
  491. bwav->copyTo (metadataValues, (int) length);
  492. }
  493. else if (chunkType == chunkName ("smpl"))
  494. {
  495. HeapBlock <SMPLChunk> smpl;
  496. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  497. input->read (smpl, (int) length);
  498. smpl->copyTo (metadataValues, (int) length);
  499. }
  500. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  501. {
  502. HeapBlock <InstChunk> inst;
  503. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  504. input->read (inst, (int) length);
  505. inst->copyTo (metadataValues);
  506. }
  507. else if (chunkType == chunkName ("cue "))
  508. {
  509. HeapBlock <CueChunk> cue;
  510. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  511. input->read (cue, (int) length);
  512. cue->copyTo (metadataValues, (int) length);
  513. }
  514. else if (chunkType == chunkName ("LIST"))
  515. {
  516. if (input->readInt() == chunkName ("adtl"))
  517. {
  518. while (input->getPosition() < chunkEnd)
  519. {
  520. const int adtlChunkType = input->readInt();
  521. const uint32 adtlLength = (uint32) input->readInt();
  522. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  523. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  524. {
  525. String prefix;
  526. if (adtlChunkType == chunkName ("labl"))
  527. prefix << "CueLabel" << cueLabelIndex++;
  528. else if (adtlChunkType == chunkName ("note"))
  529. prefix << "CueNote" << cueNoteIndex++;
  530. const uint32 identifier = (uint32) input->readInt();
  531. const int stringLength = (int) adtlLength - 4;
  532. MemoryBlock textBlock;
  533. input->readIntoMemoryBlock (textBlock, stringLength);
  534. metadataValues.set (prefix + "Identifier", String (identifier));
  535. metadataValues.set (prefix + "Text", textBlock.toString());
  536. }
  537. else if (adtlChunkType == chunkName ("ltxt"))
  538. {
  539. const String prefix ("CueRegion" + String (cueRegionIndex++));
  540. const uint32 identifier = (uint32) input->readInt();
  541. const uint32 sampleLength = (uint32) input->readInt();
  542. const uint32 purpose = (uint32) input->readInt();
  543. const uint16 country = (uint16) input->readInt();
  544. const uint16 language = (uint16) input->readInt();
  545. const uint16 dialect = (uint16) input->readInt();
  546. const uint16 codePage = (uint16) input->readInt();
  547. const uint32 stringLength = adtlLength - 20;
  548. MemoryBlock textBlock;
  549. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  550. metadataValues.set (prefix + "Identifier", String (identifier));
  551. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  552. metadataValues.set (prefix + "Purpose", String (purpose));
  553. metadataValues.set (prefix + "Country", String (country));
  554. metadataValues.set (prefix + "Language", String (language));
  555. metadataValues.set (prefix + "Dialect", String (dialect));
  556. metadataValues.set (prefix + "CodePage", String (codePage));
  557. metadataValues.set (prefix + "Text", textBlock.toString());
  558. }
  559. input->setPosition (adtlChunkEnd);
  560. }
  561. }
  562. }
  563. else if (chunkEnd <= input->getPosition())
  564. {
  565. break;
  566. }
  567. input->setPosition (chunkEnd);
  568. }
  569. }
  570. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  571. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  572. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  573. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  574. }
  575. //==============================================================================
  576. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  577. int64 startSampleInFile, int numSamples)
  578. {
  579. jassert (destSamples != nullptr);
  580. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  581. if (samplesAvailable < numSamples)
  582. {
  583. for (int i = numDestChannels; --i >= 0;)
  584. if (destSamples[i] != nullptr)
  585. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  586. numSamples = (int) samplesAvailable;
  587. }
  588. if (numSamples <= 0)
  589. return true;
  590. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  591. while (numSamples > 0)
  592. {
  593. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  594. char tempBuffer [tempBufSize];
  595. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  596. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  597. if (bytesRead < numThisTime * bytesPerFrame)
  598. {
  599. jassert (bytesRead >= 0);
  600. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  601. }
  602. switch (bitsPerSample)
  603. {
  604. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  605. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  606. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  607. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime);
  608. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  609. default: jassertfalse; break;
  610. }
  611. startOffsetInDestBuffer += numThisTime;
  612. numSamples -= numThisTime;
  613. }
  614. return true;
  615. }
  616. int64 bwavChunkStart, bwavSize;
  617. private:
  618. ScopedPointer<AudioData::Converter> converter;
  619. int bytesPerFrame;
  620. int64 dataChunkStart, dataLength;
  621. bool isRF64;
  622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  623. };
  624. //==============================================================================
  625. class WavAudioFormatWriter : public AudioFormatWriter
  626. {
  627. public:
  628. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  629. const unsigned int numChannels_, const unsigned int bits,
  630. const StringPairArray& metadataValues)
  631. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  632. lengthInSamples (0),
  633. bytesWritten (0),
  634. writeFailed (false)
  635. {
  636. using namespace WavFileHelpers;
  637. if (metadataValues.size() > 0)
  638. {
  639. // The meta data should have been santised for the WAV format.
  640. // If it was originally sourced from an AIFF file the MetaDataSource
  641. // key should be removed (or set to "WAV") once this has been done
  642. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  643. bwavChunk = BWAVChunk::createFrom (metadataValues);
  644. smplChunk = SMPLChunk::createFrom (metadataValues);
  645. instChunk = InstChunk::createFrom (metadataValues);
  646. CueChunk ::create (cueChunk, metadataValues);
  647. ListChunk::create (listChunk, metadataValues);
  648. }
  649. headerPosition = out->getPosition();
  650. writeHeader();
  651. }
  652. ~WavAudioFormatWriter()
  653. {
  654. if ((bytesWritten & 1) != 0) // pad to an even length
  655. {
  656. ++bytesWritten;
  657. output->writeByte (0);
  658. }
  659. writeHeader();
  660. }
  661. //==============================================================================
  662. bool write (const int** data, int numSamples)
  663. {
  664. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  665. if (writeFailed)
  666. return false;
  667. const size_t bytes = numChannels * numSamples * bitsPerSample / 8;
  668. tempBlock.ensureSize (bytes, false);
  669. switch (bitsPerSample)
  670. {
  671. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  672. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  673. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  674. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  675. default: jassertfalse; break;
  676. }
  677. if (! output->write (tempBlock.getData(), (int) bytes))
  678. {
  679. // failed to write to disk, so let's try writing the header.
  680. // If it's just run out of disk space, then if it does manage
  681. // to write the header, we'll still have a useable file..
  682. writeHeader();
  683. writeFailed = true;
  684. return false;
  685. }
  686. else
  687. {
  688. bytesWritten += bytes;
  689. lengthInSamples += numSamples;
  690. return true;
  691. }
  692. }
  693. private:
  694. ScopedPointer<AudioData::Converter> converter;
  695. MemoryBlock tempBlock, bwavChunk, smplChunk, instChunk, cueChunk, listChunk;
  696. uint64 lengthInSamples, bytesWritten;
  697. int64 headerPosition;
  698. bool writeFailed;
  699. static int getChannelMask (const int numChannels) noexcept
  700. {
  701. switch (numChannels)
  702. {
  703. case 1: return 0;
  704. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  705. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  706. 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
  707. 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
  708. 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
  709. default: break;
  710. }
  711. return 0;
  712. }
  713. void writeHeader()
  714. {
  715. using namespace WavFileHelpers;
  716. const bool seekedOk = output->setPosition (headerPosition);
  717. (void) seekedOk;
  718. // if this fails, you've given it an output stream that can't seek! It needs
  719. // to be able to seek back to write the header
  720. jassert (seekedOk);
  721. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  722. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  723. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  724. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  725. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  726. + 8 + audioDataSize + (audioDataSize & 1)
  727. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  728. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  729. + (instChunk.getSize() > 0 ? (8 + instChunk.getSize()) : 0)
  730. + (cueChunk .getSize() > 0 ? (8 + cueChunk .getSize()) : 0)
  731. + (listChunk.getSize() > 0 ? (12 + listChunk.getSize()) : 0)
  732. + (8 + 28); // (ds64 chunk)
  733. riffChunkSize += (riffChunkSize & 0x1);
  734. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  735. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  736. output->writeInt (chunkName ("WAVE"));
  737. if (! isRF64)
  738. {
  739. output->writeInt (chunkName ("JUNK"));
  740. output->writeInt (28 + (isWaveFmtEx? 0 : 24));
  741. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  742. }
  743. else
  744. {
  745. // write ds64 chunk
  746. output->writeInt (chunkName ("ds64"));
  747. output->writeInt (28); // chunk size for uncompressed data (no table)
  748. output->writeInt64 (riffChunkSize);
  749. output->writeInt64 (audioDataSize);
  750. output->writeRepeatedByte (0, 12);
  751. }
  752. output->writeInt (chunkName ("fmt "));
  753. if (isWaveFmtEx)
  754. {
  755. output->writeInt (40); // chunk size
  756. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  757. }
  758. else
  759. {
  760. output->writeInt (16); // chunk size
  761. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  762. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  763. }
  764. output->writeShort ((short) numChannels);
  765. output->writeInt ((int) sampleRate);
  766. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  767. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  768. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  769. if (isWaveFmtEx)
  770. {
  771. output->writeShort (22); // cbSize (size of the extension)
  772. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  773. output->writeInt (getChannelMask ((int) numChannels));
  774. const ExtensibleWavSubFormat pcmFormat
  775. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  776. const ExtensibleWavSubFormat IEEEFloatFormat
  777. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  778. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  779. output->writeInt ((int) subFormat.data1);
  780. output->writeShort ((short) subFormat.data2);
  781. output->writeShort ((short) subFormat.data3);
  782. output->write (subFormat.data4, sizeof (subFormat.data4));
  783. }
  784. if (bwavChunk.getSize() > 0)
  785. {
  786. output->writeInt (chunkName ("bext"));
  787. output->writeInt ((int) bwavChunk.getSize());
  788. *output << bwavChunk;
  789. }
  790. if (smplChunk.getSize() > 0)
  791. {
  792. output->writeInt (chunkName ("smpl"));
  793. output->writeInt ((int) smplChunk.getSize());
  794. *output << smplChunk;
  795. }
  796. if (instChunk.getSize() > 0)
  797. {
  798. output->writeInt (chunkName ("inst"));
  799. output->writeInt (7);
  800. *output << instChunk;
  801. }
  802. if (cueChunk.getSize() > 0)
  803. {
  804. output->writeInt (chunkName ("cue "));
  805. output->writeInt ((int) cueChunk.getSize());
  806. *output << cueChunk;
  807. }
  808. if (listChunk.getSize() > 0)
  809. {
  810. output->writeInt (chunkName ("LIST"));
  811. output->writeInt ((int) listChunk.getSize() + 4);
  812. output->writeInt (chunkName ("adtl"));
  813. *output << listChunk;
  814. }
  815. output->writeInt (chunkName ("data"));
  816. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  817. usesFloatingPointData = (bitsPerSample == 32);
  818. }
  819. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  820. };
  821. //==============================================================================
  822. WavAudioFormat::WavAudioFormat()
  823. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  824. {
  825. }
  826. WavAudioFormat::~WavAudioFormat()
  827. {
  828. }
  829. Array<int> WavAudioFormat::getPossibleSampleRates()
  830. {
  831. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  832. return Array <int> (rates);
  833. }
  834. Array<int> WavAudioFormat::getPossibleBitDepths()
  835. {
  836. const int depths[] = { 8, 16, 24, 32, 0 };
  837. return Array <int> (depths);
  838. }
  839. bool WavAudioFormat::canDoStereo() { return true; }
  840. bool WavAudioFormat::canDoMono() { return true; }
  841. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  842. const bool deleteStreamIfOpeningFails)
  843. {
  844. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  845. if (r->sampleRate > 0 && r->numChannels > 0)
  846. return r.release();
  847. if (! deleteStreamIfOpeningFails)
  848. r->input = nullptr;
  849. return nullptr;
  850. }
  851. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  852. unsigned int numChannels, int bitsPerSample,
  853. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  854. {
  855. if (getPossibleBitDepths().contains (bitsPerSample))
  856. return new WavAudioFormatWriter (out, sampleRate, (int) numChannels, bitsPerSample, metadataValues);
  857. return nullptr;
  858. }
  859. namespace WavFileHelpers
  860. {
  861. static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  862. {
  863. TemporaryFile tempFile (file);
  864. WavAudioFormat wav;
  865. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  866. if (reader != nullptr)
  867. {
  868. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  869. if (outStream != nullptr)
  870. {
  871. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  872. reader->numChannels, (int) reader->bitsPerSample,
  873. metadata, 0));
  874. if (writer != nullptr)
  875. {
  876. outStream.release();
  877. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  878. writer = nullptr;
  879. reader = nullptr;
  880. return ok && tempFile.overwriteTargetFileWithTemporary();
  881. }
  882. }
  883. }
  884. return false;
  885. }
  886. }
  887. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  888. {
  889. using namespace WavFileHelpers;
  890. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  891. if (reader != nullptr)
  892. {
  893. const int64 bwavPos = reader->bwavChunkStart;
  894. const int64 bwavSize = reader->bwavSize;
  895. reader = nullptr;
  896. if (bwavSize > 0)
  897. {
  898. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  899. if (chunk.getSize() <= (size_t) bwavSize)
  900. {
  901. // the new one will fit in the space available, so write it directly..
  902. const int64 oldSize = wavFile.getSize();
  903. {
  904. FileOutputStream out (wavFile);
  905. if (! out.failedToOpen())
  906. {
  907. out.setPosition (bwavPos);
  908. out << chunk;
  909. out.setPosition (oldSize);
  910. }
  911. }
  912. jassert (wavFile.getSize() == oldSize);
  913. return true;
  914. }
  915. }
  916. }
  917. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  918. }