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.

1109 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. numChannels = (unsigned int) input->readShort();
  432. sampleRate = input->readInt();
  433. const int bytesPerSec = input->readInt();
  434. input->skipNextBytes (2);
  435. bitsPerSample = (unsigned int) (int) input->readShort();
  436. if (bitsPerSample > 64)
  437. {
  438. bytesPerFrame = bytesPerSec / (int) sampleRate;
  439. bitsPerSample = 8 * bytesPerFrame / numChannels;
  440. }
  441. else
  442. {
  443. bytesPerFrame = numChannels * bitsPerSample / 8;
  444. }
  445. if (format == 3)
  446. {
  447. usesFloatingPointData = true;
  448. }
  449. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  450. {
  451. if (length < 40) // too short
  452. {
  453. bytesPerFrame = 0;
  454. }
  455. else
  456. {
  457. input->skipNextBytes (10); // skip over bitsPerSample and speakerPosition mask
  458. ExtensibleWavSubFormat subFormat;
  459. subFormat.data1 = (uint32) input->readInt();
  460. subFormat.data2 = (uint16) input->readShort();
  461. subFormat.data3 = (uint16) input->readShort();
  462. input->read (subFormat.data4, sizeof (subFormat.data4));
  463. const ExtensibleWavSubFormat pcmFormat
  464. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  465. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  466. {
  467. const ExtensibleWavSubFormat ambisonicFormat
  468. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  469. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  470. bytesPerFrame = 0;
  471. }
  472. }
  473. }
  474. else if (format != 1)
  475. {
  476. bytesPerFrame = 0;
  477. }
  478. hasGotType = true;
  479. }
  480. else if (chunkType == chunkName ("data"))
  481. {
  482. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  483. dataLength = length;
  484. dataChunkStart = input->getPosition();
  485. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  486. hasGotData = true;
  487. }
  488. else if (chunkType == chunkName ("bext"))
  489. {
  490. bwavChunkStart = input->getPosition();
  491. bwavSize = length;
  492. HeapBlock <BWAVChunk> bwav;
  493. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  494. input->read (bwav, (int) length);
  495. bwav->copyTo (metadataValues);
  496. }
  497. else if (chunkType == chunkName ("smpl"))
  498. {
  499. HeapBlock <SMPLChunk> smpl;
  500. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  501. input->read (smpl, (int) length);
  502. smpl->copyTo (metadataValues, (int) length);
  503. }
  504. else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
  505. {
  506. HeapBlock <InstChunk> inst;
  507. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  508. input->read (inst, (int) length);
  509. inst->copyTo (metadataValues);
  510. }
  511. else if (chunkType == chunkName ("cue "))
  512. {
  513. HeapBlock <CueChunk> cue;
  514. cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
  515. input->read (cue, (int) length);
  516. cue->copyTo (metadataValues, (int) length);
  517. }
  518. else if (chunkType == chunkName ("LIST"))
  519. {
  520. if (input->readInt() == chunkName ("adtl"))
  521. {
  522. while (input->getPosition() < chunkEnd)
  523. {
  524. const int adtlChunkType = input->readInt();
  525. const uint32 adtlLength = (uint32) input->readInt();
  526. const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
  527. if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
  528. {
  529. String prefix;
  530. if (adtlChunkType == chunkName ("labl"))
  531. prefix << "CueLabel" << cueLabelIndex++;
  532. else if (adtlChunkType == chunkName ("note"))
  533. prefix << "CueNote" << cueNoteIndex++;
  534. const uint32 identifier = (uint32) input->readInt();
  535. const int stringLength = (int) adtlLength - 4;
  536. MemoryBlock textBlock;
  537. input->readIntoMemoryBlock (textBlock, stringLength);
  538. metadataValues.set (prefix + "Identifier", String (identifier));
  539. metadataValues.set (prefix + "Text", textBlock.toString());
  540. }
  541. else if (adtlChunkType == chunkName ("ltxt"))
  542. {
  543. const String prefix ("CueRegion" + String (cueRegionIndex++));
  544. const uint32 identifier = (uint32) input->readInt();
  545. const uint32 sampleLength = (uint32) input->readInt();
  546. const uint32 purpose = (uint32) input->readInt();
  547. const uint16 country = (uint16) input->readInt();
  548. const uint16 language = (uint16) input->readInt();
  549. const uint16 dialect = (uint16) input->readInt();
  550. const uint16 codePage = (uint16) input->readInt();
  551. const uint32 stringLength = adtlLength - 20;
  552. MemoryBlock textBlock;
  553. input->readIntoMemoryBlock (textBlock, (int) stringLength);
  554. metadataValues.set (prefix + "Identifier", String (identifier));
  555. metadataValues.set (prefix + "SampleLength", String (sampleLength));
  556. metadataValues.set (prefix + "Purpose", String (purpose));
  557. metadataValues.set (prefix + "Country", String (country));
  558. metadataValues.set (prefix + "Language", String (language));
  559. metadataValues.set (prefix + "Dialect", String (dialect));
  560. metadataValues.set (prefix + "CodePage", String (codePage));
  561. metadataValues.set (prefix + "Text", textBlock.toString());
  562. }
  563. input->setPosition (adtlChunkEnd);
  564. }
  565. }
  566. }
  567. else if (chunkEnd <= input->getPosition())
  568. {
  569. break;
  570. }
  571. input->setPosition (chunkEnd);
  572. }
  573. }
  574. if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
  575. if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
  576. if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
  577. if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
  578. }
  579. //==============================================================================
  580. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  581. int64 startSampleInFile, int numSamples)
  582. {
  583. jassert (destSamples != nullptr);
  584. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  585. if (samplesAvailable < numSamples)
  586. {
  587. for (int i = numDestChannels; --i >= 0;)
  588. if (destSamples[i] != nullptr)
  589. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  590. numSamples = (int) samplesAvailable;
  591. }
  592. if (numSamples <= 0)
  593. return true;
  594. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  595. while (numSamples > 0)
  596. {
  597. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  598. char tempBuffer [tempBufSize];
  599. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  600. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  601. if (bytesRead < numThisTime * bytesPerFrame)
  602. {
  603. jassert (bytesRead >= 0);
  604. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  605. }
  606. switch (bitsPerSample)
  607. {
  608. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  609. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  610. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  611. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime);
  612. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  613. default: jassertfalse; break;
  614. }
  615. startOffsetInDestBuffer += numThisTime;
  616. numSamples -= numThisTime;
  617. }
  618. return true;
  619. }
  620. int64 bwavChunkStart, bwavSize;
  621. private:
  622. ScopedPointer<AudioData::Converter> converter;
  623. int bytesPerFrame;
  624. int64 dataChunkStart, dataLength;
  625. bool isRF64;
  626. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  627. };
  628. //==============================================================================
  629. class WavAudioFormatWriter : public AudioFormatWriter
  630. {
  631. public:
  632. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  633. const unsigned int numChannels_, const unsigned int bits,
  634. const StringPairArray& metadataValues)
  635. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  636. lengthInSamples (0),
  637. bytesWritten (0),
  638. writeFailed (false)
  639. {
  640. using namespace WavFileHelpers;
  641. if (metadataValues.size() > 0)
  642. {
  643. // The meta data should have been santised for the WAV format.
  644. // If it was originally sourced from an AIFF file the MetaDataSource
  645. // key should be removed (or set to "WAV") once this has been done
  646. jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
  647. bwavChunk = BWAVChunk::createFrom (metadataValues);
  648. smplChunk = SMPLChunk::createFrom (metadataValues);
  649. instChunk = InstChunk::createFrom (metadataValues);
  650. CueChunk ::create (cueChunk, metadataValues);
  651. ListChunk::create (listChunk, metadataValues);
  652. }
  653. headerPosition = out->getPosition();
  654. writeHeader();
  655. }
  656. ~WavAudioFormatWriter()
  657. {
  658. if ((bytesWritten & 1) != 0) // pad to an even length
  659. {
  660. ++bytesWritten;
  661. output->writeByte (0);
  662. }
  663. writeHeader();
  664. }
  665. //==============================================================================
  666. bool write (const int** data, int numSamples)
  667. {
  668. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  669. if (writeFailed)
  670. return false;
  671. const size_t bytes = numChannels * numSamples * bitsPerSample / 8;
  672. tempBlock.ensureSize (bytes, false);
  673. switch (bitsPerSample)
  674. {
  675. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  676. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  677. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  678. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  679. default: jassertfalse; break;
  680. }
  681. if (! output->write (tempBlock.getData(), (int) bytes))
  682. {
  683. // failed to write to disk, so let's try writing the header.
  684. // If it's just run out of disk space, then if it does manage
  685. // to write the header, we'll still have a useable file..
  686. writeHeader();
  687. writeFailed = true;
  688. return false;
  689. }
  690. else
  691. {
  692. bytesWritten += bytes;
  693. lengthInSamples += numSamples;
  694. return true;
  695. }
  696. }
  697. private:
  698. ScopedPointer<AudioData::Converter> converter;
  699. MemoryBlock tempBlock, bwavChunk, smplChunk, instChunk, cueChunk, listChunk;
  700. uint64 lengthInSamples, bytesWritten;
  701. int64 headerPosition;
  702. bool writeFailed;
  703. static int getChannelMask (const int numChannels) noexcept
  704. {
  705. switch (numChannels)
  706. {
  707. case 1: return 0;
  708. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  709. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  710. 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
  711. default: break;
  712. }
  713. return 0;
  714. }
  715. void writeHeader()
  716. {
  717. using namespace WavFileHelpers;
  718. const bool seekedOk = output->setPosition (headerPosition);
  719. (void) seekedOk;
  720. // if this fails, you've given it an output stream that can't seek! It needs
  721. // to be able to seek back to write the header
  722. jassert (seekedOk);
  723. const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
  724. uint64 audioDataSize = bytesPerFrame * lengthInSamples;
  725. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  726. const bool isWaveFmtEx = isRF64 || (numChannels > 2);
  727. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  728. + 8 + audioDataSize + (audioDataSize & 1)
  729. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  730. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  731. + (instChunk.getSize() > 0 ? (8 + instChunk.getSize()) : 0)
  732. + (cueChunk .getSize() > 0 ? (8 + cueChunk .getSize()) : 0)
  733. + (listChunk.getSize() > 0 ? (12 + listChunk.getSize()) : 0)
  734. + (8 + 28); // (ds64 chunk)
  735. riffChunkSize += (riffChunkSize & 0x1);
  736. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  737. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  738. output->writeInt (chunkName ("WAVE"));
  739. if (! isRF64)
  740. {
  741. output->writeInt (chunkName ("JUNK"));
  742. output->writeInt (28 + (isWaveFmtEx? 0 : 24));
  743. output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
  744. }
  745. else
  746. {
  747. // write ds64 chunk
  748. output->writeInt (chunkName ("ds64"));
  749. output->writeInt (28); // chunk size for uncompressed data (no table)
  750. output->writeInt64 (riffChunkSize);
  751. output->writeInt64 (audioDataSize);
  752. output->writeRepeatedByte (0, 12);
  753. }
  754. output->writeInt (chunkName ("fmt "));
  755. if (isWaveFmtEx)
  756. {
  757. output->writeInt (40); // chunk size
  758. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  759. }
  760. else
  761. {
  762. output->writeInt (16); // chunk size
  763. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  764. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  765. }
  766. output->writeShort ((short) numChannels);
  767. output->writeInt ((int) sampleRate);
  768. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  769. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  770. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  771. if (isWaveFmtEx)
  772. {
  773. output->writeShort (22); // cbSize (size of the extension)
  774. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  775. output->writeInt (getChannelMask ((int) numChannels));
  776. const ExtensibleWavSubFormat pcmFormat
  777. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  778. const ExtensibleWavSubFormat IEEEFloatFormat
  779. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  780. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  781. output->writeInt ((int) subFormat.data1);
  782. output->writeShort ((short) subFormat.data2);
  783. output->writeShort ((short) subFormat.data3);
  784. output->write (subFormat.data4, sizeof (subFormat.data4));
  785. }
  786. if (bwavChunk.getSize() > 0)
  787. {
  788. output->writeInt (chunkName ("bext"));
  789. output->writeInt ((int) bwavChunk.getSize());
  790. *output << bwavChunk;
  791. }
  792. if (smplChunk.getSize() > 0)
  793. {
  794. output->writeInt (chunkName ("smpl"));
  795. output->writeInt ((int) smplChunk.getSize());
  796. *output << smplChunk;
  797. }
  798. if (instChunk.getSize() > 0)
  799. {
  800. output->writeInt (chunkName ("inst"));
  801. output->writeInt (7);
  802. *output << instChunk;
  803. }
  804. if (cueChunk.getSize() > 0)
  805. {
  806. output->writeInt (chunkName ("cue "));
  807. output->writeInt ((int) cueChunk.getSize());
  808. *output << cueChunk;
  809. }
  810. if (listChunk.getSize() > 0)
  811. {
  812. output->writeInt (chunkName ("LIST"));
  813. output->writeInt ((int) listChunk.getSize() + 4);
  814. output->writeInt (chunkName ("adtl"));
  815. *output << listChunk;
  816. }
  817. output->writeInt (chunkName ("data"));
  818. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  819. usesFloatingPointData = (bitsPerSample == 32);
  820. }
  821. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  822. };
  823. //==============================================================================
  824. WavAudioFormat::WavAudioFormat()
  825. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  826. {
  827. }
  828. WavAudioFormat::~WavAudioFormat()
  829. {
  830. }
  831. Array<int> WavAudioFormat::getPossibleSampleRates()
  832. {
  833. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  834. return Array <int> (rates);
  835. }
  836. Array<int> WavAudioFormat::getPossibleBitDepths()
  837. {
  838. const int depths[] = { 8, 16, 24, 32, 0 };
  839. return Array <int> (depths);
  840. }
  841. bool WavAudioFormat::canDoStereo() { return true; }
  842. bool WavAudioFormat::canDoMono() { return true; }
  843. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  844. const bool deleteStreamIfOpeningFails)
  845. {
  846. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  847. if (r->sampleRate > 0)
  848. return r.release();
  849. if (! deleteStreamIfOpeningFails)
  850. r->input = nullptr;
  851. return nullptr;
  852. }
  853. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  854. unsigned int numChannels, int bitsPerSample,
  855. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  856. {
  857. if (getPossibleBitDepths().contains (bitsPerSample))
  858. return new WavAudioFormatWriter (out, sampleRate, (int) numChannels, bitsPerSample, metadataValues);
  859. return nullptr;
  860. }
  861. namespace WavFileHelpers
  862. {
  863. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  864. {
  865. TemporaryFile tempFile (file);
  866. WavAudioFormat wav;
  867. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  868. if (reader != nullptr)
  869. {
  870. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  871. if (outStream != nullptr)
  872. {
  873. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  874. reader->numChannels, (int) reader->bitsPerSample,
  875. metadata, 0));
  876. if (writer != nullptr)
  877. {
  878. outStream.release();
  879. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  880. writer = nullptr;
  881. reader = nullptr;
  882. return ok && tempFile.overwriteTargetFileWithTemporary();
  883. }
  884. }
  885. }
  886. return false;
  887. }
  888. }
  889. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  890. {
  891. using namespace WavFileHelpers;
  892. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  893. if (reader != nullptr)
  894. {
  895. const int64 bwavPos = reader->bwavChunkStart;
  896. const int64 bwavSize = reader->bwavSize;
  897. reader = nullptr;
  898. if (bwavSize > 0)
  899. {
  900. MemoryBlock chunk (BWAVChunk::createFrom (newMetadata));
  901. if (chunk.getSize() <= (size_t) bwavSize)
  902. {
  903. // the new one will fit in the space available, so write it directly..
  904. const int64 oldSize = wavFile.getSize();
  905. {
  906. FileOutputStream out (wavFile);
  907. if (! out.failedToOpen())
  908. {
  909. out.setPosition (bwavPos);
  910. out << chunk;
  911. out.setPosition (oldSize);
  912. }
  913. }
  914. jassert (wavFile.getSize() == oldSize);
  915. return true;
  916. }
  917. }
  918. }
  919. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  920. }