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.

1113 lines
49KB

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