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.

1104 lines
48KB

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