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.

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