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.

1010 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. static const char* const aiffFormatName = "AIFF file";
  22. //==============================================================================
  23. const char* const AiffAudioFormat::appleOneShot = "apple one shot";
  24. const char* const AiffAudioFormat::appleRootSet = "apple root set";
  25. const char* const AiffAudioFormat::appleRootNote = "apple root note";
  26. const char* const AiffAudioFormat::appleBeats = "apple beats";
  27. const char* const AiffAudioFormat::appleDenominator = "apple denominator";
  28. const char* const AiffAudioFormat::appleNumerator = "apple numerator";
  29. const char* const AiffAudioFormat::appleTag = "apple tag";
  30. const char* const AiffAudioFormat::appleKey = "apple key";
  31. //==============================================================================
  32. namespace AiffFileHelpers
  33. {
  34. inline int chunkName (const char* name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
  35. #if JUCE_MSVC
  36. #pragma pack (push, 1)
  37. #endif
  38. //==============================================================================
  39. struct InstChunk
  40. {
  41. struct Loop
  42. {
  43. uint16 type; // these are different in AIFF and WAV
  44. uint16 startIdentifier;
  45. uint16 endIdentifier;
  46. } JUCE_PACKED;
  47. int8 baseNote;
  48. int8 detune;
  49. int8 lowNote;
  50. int8 highNote;
  51. int8 lowVelocity;
  52. int8 highVelocity;
  53. int16 gain;
  54. Loop sustainLoop;
  55. Loop releaseLoop;
  56. void copyTo (StringPairArray& values) const
  57. {
  58. values.set ("MidiUnityNote", String (baseNote));
  59. values.set ("Detune", String (detune));
  60. values.set ("LowNote", String (lowNote));
  61. values.set ("HighNote", String (highNote));
  62. values.set ("LowVelocity", String (lowVelocity));
  63. values.set ("HighVelocity", String (highVelocity));
  64. values.set ("Gain", String ((int16) ByteOrder::swapIfLittleEndian ((uint16) gain)));
  65. values.set ("NumSampleLoops", String (2)); // always 2 with AIFF, WAV can have more
  66. values.set ("Loop0Type", String (ByteOrder::swapIfLittleEndian (sustainLoop.type)));
  67. values.set ("Loop0StartIdentifier", String (ByteOrder::swapIfLittleEndian (sustainLoop.startIdentifier)));
  68. values.set ("Loop0EndIdentifier", String (ByteOrder::swapIfLittleEndian (sustainLoop.endIdentifier)));
  69. values.set ("Loop1Type", String (ByteOrder::swapIfLittleEndian (releaseLoop.type)));
  70. values.set ("Loop1StartIdentifier", String (ByteOrder::swapIfLittleEndian (releaseLoop.startIdentifier)));
  71. values.set ("Loop1EndIdentifier", String (ByteOrder::swapIfLittleEndian (releaseLoop.endIdentifier)));
  72. }
  73. static uint16 getValue16 (const StringPairArray& values, const char* name, const char* def)
  74. {
  75. return ByteOrder::swapIfLittleEndian ((uint16) values.getValue (name, def).getIntValue());
  76. }
  77. static int8 getValue8 (const StringPairArray& values, const char* name, const char* def)
  78. {
  79. return (int8) values.getValue (name, def).getIntValue();
  80. }
  81. static void create (MemoryBlock& block, const StringPairArray& values)
  82. {
  83. if (values.getAllKeys().contains ("MidiUnityNote", true))
  84. {
  85. block.setSize ((sizeof (InstChunk) + 3) & ~(size_t) 3, true);
  86. auto& inst = *static_cast<InstChunk*> (block.getData());
  87. inst.baseNote = getValue8 (values, "MidiUnityNote", "60");
  88. inst.detune = getValue8 (values, "Detune", "0");
  89. inst.lowNote = getValue8 (values, "LowNote", "0");
  90. inst.highNote = getValue8 (values, "HighNote", "127");
  91. inst.lowVelocity = getValue8 (values, "LowVelocity", "1");
  92. inst.highVelocity = getValue8 (values, "HighVelocity", "127");
  93. inst.gain = (int16) getValue16 (values, "Gain", "0");
  94. inst.sustainLoop.type = getValue16 (values, "Loop0Type", "0");
  95. inst.sustainLoop.startIdentifier = getValue16 (values, "Loop0StartIdentifier", "0");
  96. inst.sustainLoop.endIdentifier = getValue16 (values, "Loop0EndIdentifier", "0");
  97. inst.releaseLoop.type = getValue16 (values, "Loop1Type", "0");
  98. inst.releaseLoop.startIdentifier = getValue16 (values, "Loop1StartIdentifier", "0");
  99. inst.releaseLoop.endIdentifier = getValue16 (values, "Loop1EndIdentifier", "0");
  100. }
  101. }
  102. } JUCE_PACKED;
  103. //==============================================================================
  104. struct BASCChunk
  105. {
  106. enum Key
  107. {
  108. minor = 1,
  109. major = 2,
  110. neither = 3,
  111. both = 4
  112. };
  113. BASCChunk (InputStream& input)
  114. {
  115. zerostruct (*this);
  116. flags = (uint32) input.readIntBigEndian();
  117. numBeats = (uint32) input.readIntBigEndian();
  118. rootNote = (uint16) input.readShortBigEndian();
  119. key = (uint16) input.readShortBigEndian();
  120. timeSigNum = (uint16) input.readShortBigEndian();
  121. timeSigDen = (uint16) input.readShortBigEndian();
  122. oneShot = (uint16) input.readShortBigEndian();
  123. input.read (unknown, sizeof (unknown));
  124. }
  125. void addToMetadata (StringPairArray& metadata) const
  126. {
  127. const bool rootNoteSet = rootNote != 0;
  128. setBoolFlag (metadata, AiffAudioFormat::appleOneShot, oneShot == 2);
  129. setBoolFlag (metadata, AiffAudioFormat::appleRootSet, rootNoteSet);
  130. if (rootNoteSet)
  131. metadata.set (AiffAudioFormat::appleRootNote, String (rootNote));
  132. metadata.set (AiffAudioFormat::appleBeats, String (numBeats));
  133. metadata.set (AiffAudioFormat::appleDenominator, String (timeSigDen));
  134. metadata.set (AiffAudioFormat::appleNumerator, String (timeSigNum));
  135. const char* keyString = nullptr;
  136. switch (key)
  137. {
  138. case minor: keyString = "minor"; break;
  139. case major: keyString = "major"; break;
  140. case neither: keyString = "neither"; break;
  141. case both: keyString = "both"; break;
  142. default: break;
  143. }
  144. if (keyString != nullptr)
  145. metadata.set (AiffAudioFormat::appleKey, keyString);
  146. }
  147. void setBoolFlag (StringPairArray& values, const char* name, bool shouldBeSet) const
  148. {
  149. values.set (name, shouldBeSet ? "1" : "0");
  150. }
  151. uint32 flags;
  152. uint32 numBeats;
  153. uint16 rootNote;
  154. uint16 key;
  155. uint16 timeSigNum;
  156. uint16 timeSigDen;
  157. uint16 oneShot;
  158. uint8 unknown[66];
  159. } JUCE_PACKED;
  160. #if JUCE_MSVC
  161. #pragma pack (pop)
  162. #endif
  163. //==============================================================================
  164. namespace CATEChunk
  165. {
  166. static bool isValidTag (const char* d) noexcept
  167. {
  168. return CharacterFunctions::isLetterOrDigit (d[0]) && CharacterFunctions::isUpperCase (static_cast<juce_wchar> (d[0]))
  169. && CharacterFunctions::isLetterOrDigit (d[1]) && CharacterFunctions::isLowerCase (static_cast<juce_wchar> (d[1]))
  170. && CharacterFunctions::isLetterOrDigit (d[2]) && CharacterFunctions::isLowerCase (static_cast<juce_wchar> (d[2]));
  171. }
  172. static bool isAppleGenre (const String& tag) noexcept
  173. {
  174. static const char* appleGenres[] =
  175. {
  176. "Rock/Blues",
  177. "Electronic/Dance",
  178. "Jazz",
  179. "Urban",
  180. "World/Ethnic",
  181. "Cinematic/New Age",
  182. "Orchestral",
  183. "Country/Folk",
  184. "Experimental",
  185. "Other Genre"
  186. };
  187. for (int i = 0; i < numElementsInArray (appleGenres); ++i)
  188. if (tag == appleGenres[i])
  189. return true;
  190. return false;
  191. }
  192. static String read (InputStream& input, const uint32 length)
  193. {
  194. MemoryBlock mb;
  195. input.skipNextBytes (4);
  196. input.readIntoMemoryBlock (mb, (ssize_t) length - 4);
  197. StringArray tagsArray;
  198. auto* data = static_cast<const char*> (mb.getData());
  199. auto* dataEnd = data + mb.getSize();
  200. while (data < dataEnd)
  201. {
  202. bool isGenre = false;
  203. if (isValidTag (data))
  204. {
  205. auto tag = String (CharPointer_UTF8 (data), CharPointer_UTF8 (dataEnd));
  206. isGenre = isAppleGenre (tag);
  207. tagsArray.add (tag);
  208. }
  209. data += isGenre ? 118 : 50;
  210. if (data < dataEnd && data[0] == 0)
  211. {
  212. if (data + 52 < dataEnd && isValidTag (data + 50)) data += 50;
  213. else if (data + 120 < dataEnd && isValidTag (data + 118)) data += 118;
  214. else if (data + 170 < dataEnd && isValidTag (data + 168)) data += 168;
  215. }
  216. }
  217. return tagsArray.joinIntoString (";");
  218. }
  219. }
  220. //==============================================================================
  221. namespace MarkChunk
  222. {
  223. static bool metaDataContainsZeroIdentifiers (const StringPairArray& values)
  224. {
  225. // (zero cue identifiers are valid for WAV but not for AIFF)
  226. const String cueString ("Cue");
  227. const String noteString ("CueNote");
  228. const String identifierString ("Identifier");
  229. for (auto& key : values.getAllKeys())
  230. {
  231. if (key.startsWith (noteString))
  232. continue; // zero identifier IS valid in a COMT chunk
  233. if (key.startsWith (cueString) && key.contains (identifierString))
  234. if (values.getValue (key, "-1").getIntValue() == 0)
  235. return true;
  236. }
  237. return false;
  238. }
  239. static void create (MemoryBlock& block, const StringPairArray& values)
  240. {
  241. auto numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  242. if (numCues > 0)
  243. {
  244. MemoryOutputStream out (block, false);
  245. out.writeShortBigEndian ((short) numCues);
  246. auto numCueLabels = values.getValue ("NumCueLabels", "0").getIntValue();
  247. auto idOffset = metaDataContainsZeroIdentifiers (values) ? 1 : 0; // can't have zero IDs in AIFF
  248. #if JUCE_DEBUG
  249. Array<int> identifiers;
  250. #endif
  251. for (int i = 0; i < numCues; ++i)
  252. {
  253. auto prefixCue = "Cue" + String (i);
  254. auto identifier = idOffset + values.getValue (prefixCue + "Identifier", "1").getIntValue();
  255. #if JUCE_DEBUG
  256. jassert (! identifiers.contains (identifier));
  257. identifiers.add (identifier);
  258. #endif
  259. auto offset = values.getValue (prefixCue + "Offset", "0").getIntValue();
  260. auto label = "CueLabel" + String (i);
  261. for (int labelIndex = 0; labelIndex < numCueLabels; ++labelIndex)
  262. {
  263. auto prefixLabel = "CueLabel" + String (labelIndex);
  264. auto labelIdentifier = idOffset + values.getValue (prefixLabel + "Identifier", "1").getIntValue();
  265. if (labelIdentifier == identifier)
  266. {
  267. label = values.getValue (prefixLabel + "Text", label);
  268. break;
  269. }
  270. }
  271. out.writeShortBigEndian ((short) identifier);
  272. out.writeIntBigEndian (offset);
  273. auto labelLength = jmin ((size_t) 254, label.getNumBytesAsUTF8()); // seems to need null terminator even though it's a pstring
  274. out.writeByte (static_cast<char> (labelLength + 1));
  275. out.write (label.toUTF8(), labelLength);
  276. out.writeByte (0);
  277. if ((out.getDataSize() & 1) != 0)
  278. out.writeByte (0);
  279. }
  280. }
  281. }
  282. }
  283. //==============================================================================
  284. namespace COMTChunk
  285. {
  286. static void create (MemoryBlock& block, const StringPairArray& values)
  287. {
  288. auto numNotes = values.getValue ("NumCueNotes", "0").getIntValue();
  289. if (numNotes > 0)
  290. {
  291. MemoryOutputStream out (block, false);
  292. out.writeShortBigEndian ((short) numNotes);
  293. for (int i = 0; i < numNotes; ++i)
  294. {
  295. auto prefix = "CueNote" + String (i);
  296. out.writeIntBigEndian (values.getValue (prefix + "TimeStamp", "0").getIntValue());
  297. out.writeShortBigEndian ((short) values.getValue (prefix + "Identifier", "0").getIntValue());
  298. auto comment = values.getValue (prefix + "Text", String());
  299. auto commentLength = jmin (comment.getNumBytesAsUTF8(), (size_t) 65534);
  300. out.writeShortBigEndian (static_cast<short> (commentLength + 1));
  301. out.write (comment.toUTF8(), commentLength);
  302. out.writeByte (0);
  303. if ((out.getDataSize() & 1) != 0)
  304. out.writeByte (0);
  305. }
  306. }
  307. }
  308. }
  309. }
  310. //==============================================================================
  311. class AiffAudioFormatReader : public AudioFormatReader
  312. {
  313. public:
  314. AiffAudioFormatReader (InputStream* in)
  315. : AudioFormatReader (in, aiffFormatName)
  316. {
  317. using namespace AiffFileHelpers;
  318. if (input->readInt() == chunkName ("FORM"))
  319. {
  320. auto len = input->readIntBigEndian();
  321. auto end = input->getPosition() + len;
  322. auto nextType = input->readInt();
  323. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  324. {
  325. bool hasGotVer = false;
  326. bool hasGotData = false;
  327. bool hasGotType = false;
  328. while (input->getPosition() < end)
  329. {
  330. auto type = input->readInt();
  331. auto length = (uint32) input->readIntBigEndian();
  332. auto chunkEnd = input->getPosition() + length;
  333. if (type == chunkName ("FVER"))
  334. {
  335. hasGotVer = true;
  336. auto ver = input->readIntBigEndian();
  337. if (ver != 0 && ver != (int) 0xa2805140)
  338. break;
  339. }
  340. else if (type == chunkName ("COMM"))
  341. {
  342. hasGotType = true;
  343. numChannels = (unsigned int) input->readShortBigEndian();
  344. lengthInSamples = input->readIntBigEndian();
  345. bitsPerSample = (unsigned int) input->readShortBigEndian();
  346. bytesPerFrame = (int) ((numChannels * bitsPerSample) >> 3);
  347. unsigned char sampleRateBytes[10];
  348. input->read (sampleRateBytes, 10);
  349. const int byte0 = sampleRateBytes[0];
  350. if ((byte0 & 0x80) != 0
  351. || byte0 <= 0x3F || byte0 > 0x40
  352. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  353. break;
  354. auto sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  355. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  356. sampleRate = (int) sampRate;
  357. if (length <= 18)
  358. {
  359. // some types don't have a chunk large enough to include a compression
  360. // type, so assume it's just big-endian pcm
  361. littleEndian = false;
  362. }
  363. else
  364. {
  365. auto compType = input->readInt();
  366. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  367. {
  368. littleEndian = false;
  369. }
  370. else if (compType == chunkName ("sowt"))
  371. {
  372. littleEndian = true;
  373. }
  374. else if (compType == chunkName ("fl32") || compType == chunkName ("FL32"))
  375. {
  376. littleEndian = false;
  377. usesFloatingPointData = true;
  378. }
  379. else
  380. {
  381. sampleRate = 0;
  382. break;
  383. }
  384. }
  385. }
  386. else if (type == chunkName ("SSND"))
  387. {
  388. hasGotData = true;
  389. auto offset = input->readIntBigEndian();
  390. dataChunkStart = input->getPosition() + 4 + offset;
  391. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, ((int64) length) / (int64) bytesPerFrame) : 0;
  392. }
  393. else if (type == chunkName ("MARK"))
  394. {
  395. auto numCues = (uint16) input->readShortBigEndian();
  396. // these two are always the same for AIFF-read files
  397. metadataValues.set ("NumCuePoints", String (numCues));
  398. metadataValues.set ("NumCueLabels", String (numCues));
  399. for (uint16 i = 0; i < numCues; ++i)
  400. {
  401. auto identifier = (uint16) input->readShortBigEndian();
  402. auto offset = (uint32) input->readIntBigEndian();
  403. auto stringLength = (uint8) input->readByte();
  404. MemoryBlock textBlock;
  405. input->readIntoMemoryBlock (textBlock, stringLength);
  406. // if the stringLength is even then read one more byte as the
  407. // string needs to be an even number of bytes INCLUDING the
  408. // leading length character in the pascal string
  409. if ((stringLength & 1) == 0)
  410. input->readByte();
  411. auto prefixCue = "Cue" + String (i);
  412. metadataValues.set (prefixCue + "Identifier", String (identifier));
  413. metadataValues.set (prefixCue + "Offset", String (offset));
  414. auto prefixLabel = "CueLabel" + String (i);
  415. metadataValues.set (prefixLabel + "Identifier", String (identifier));
  416. metadataValues.set (prefixLabel + "Text", textBlock.toString());
  417. }
  418. }
  419. else if (type == chunkName ("COMT"))
  420. {
  421. auto numNotes = (uint16) input->readShortBigEndian();
  422. metadataValues.set ("NumCueNotes", String (numNotes));
  423. for (uint16 i = 0; i < numNotes; ++i)
  424. {
  425. auto timestamp = (uint32) input->readIntBigEndian();
  426. auto identifier = (uint16) input->readShortBigEndian(); // may be zero in this case
  427. auto stringLength = (uint16) input->readShortBigEndian();
  428. MemoryBlock textBlock;
  429. input->readIntoMemoryBlock (textBlock, stringLength + (stringLength & 1));
  430. auto prefix = "CueNote" + String (i);
  431. metadataValues.set (prefix + "TimeStamp", String (timestamp));
  432. metadataValues.set (prefix + "Identifier", String (identifier));
  433. metadataValues.set (prefix + "Text", textBlock.toString());
  434. }
  435. }
  436. else if (type == chunkName ("INST"))
  437. {
  438. HeapBlock<InstChunk> inst;
  439. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  440. input->read (inst, (int) length);
  441. inst->copyTo (metadataValues);
  442. }
  443. else if (type == chunkName ("basc"))
  444. {
  445. AiffFileHelpers::BASCChunk (*input).addToMetadata (metadataValues);
  446. }
  447. else if (type == chunkName ("cate"))
  448. {
  449. metadataValues.set (AiffAudioFormat::appleTag,
  450. AiffFileHelpers::CATEChunk::read (*input, length));
  451. }
  452. else if ((hasGotVer && hasGotData && hasGotType)
  453. || chunkEnd < input->getPosition()
  454. || input->isExhausted())
  455. {
  456. break;
  457. }
  458. input->setPosition (chunkEnd + (chunkEnd & 1)); // (chunks should be aligned to an even byte address)
  459. }
  460. }
  461. }
  462. if (metadataValues.size() > 0)
  463. metadataValues.set ("MetaDataSource", "AIFF");
  464. }
  465. //==============================================================================
  466. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  467. int64 startSampleInFile, int numSamples) override
  468. {
  469. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  470. startSampleInFile, numSamples, lengthInSamples);
  471. if (numSamples <= 0)
  472. return true;
  473. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  474. while (numSamples > 0)
  475. {
  476. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  477. char tempBuffer [tempBufSize];
  478. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  479. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  480. if (bytesRead < numThisTime * bytesPerFrame)
  481. {
  482. jassert (bytesRead >= 0);
  483. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  484. }
  485. if (littleEndian)
  486. copySampleData<AudioData::LittleEndian> (bitsPerSample, usesFloatingPointData,
  487. destSamples, startOffsetInDestBuffer, numDestChannels,
  488. tempBuffer, (int) numChannels, numThisTime);
  489. else
  490. copySampleData<AudioData::BigEndian> (bitsPerSample, usesFloatingPointData,
  491. destSamples, startOffsetInDestBuffer, numDestChannels,
  492. tempBuffer, (int) numChannels, numThisTime);
  493. startOffsetInDestBuffer += numThisTime;
  494. numSamples -= numThisTime;
  495. }
  496. return true;
  497. }
  498. template <typename Endianness>
  499. static void copySampleData (unsigned int numBitsPerSample, bool floatingPointData,
  500. int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
  501. const void* sourceData, int numberOfChannels, int numSamples) noexcept
  502. {
  503. switch (numBitsPerSample)
  504. {
  505. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  506. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  507. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
  508. case 32: if (floatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
  509. else ReadHelper<AudioData::Int32, AudioData::Int32, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
  510. break;
  511. default: jassertfalse; break;
  512. }
  513. }
  514. int bytesPerFrame;
  515. int64 dataChunkStart;
  516. bool littleEndian;
  517. private:
  518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader)
  519. };
  520. //==============================================================================
  521. class AiffAudioFormatWriter : public AudioFormatWriter
  522. {
  523. public:
  524. AiffAudioFormatWriter (OutputStream* out, double rate,
  525. unsigned int numChans, unsigned int bits,
  526. const StringPairArray& metadataValues)
  527. : AudioFormatWriter (out, aiffFormatName, rate, numChans, bits)
  528. {
  529. using namespace AiffFileHelpers;
  530. if (metadataValues.size() > 0)
  531. {
  532. // The meta data should have been sanitised for the AIFF format.
  533. // If it was originally sourced from a WAV file the MetaDataSource
  534. // key should be removed (or set to "AIFF") once this has been done
  535. jassert (metadataValues.getValue ("MetaDataSource", "None") != "WAV");
  536. MarkChunk::create (markChunk, metadataValues);
  537. COMTChunk::create (comtChunk, metadataValues);
  538. InstChunk::create (instChunk, metadataValues);
  539. }
  540. headerPosition = out->getPosition();
  541. writeHeader();
  542. }
  543. ~AiffAudioFormatWriter() override
  544. {
  545. if ((bytesWritten & 1) != 0)
  546. output->writeByte (0);
  547. writeHeader();
  548. }
  549. //==============================================================================
  550. bool write (const int** data, int numSamples) override
  551. {
  552. jassert (numSamples >= 0);
  553. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  554. if (writeFailed)
  555. return false;
  556. auto bytes = numChannels * (size_t) numSamples * bitsPerSample / 8;
  557. tempBlock.ensureSize (bytes, false);
  558. switch (bitsPerSample)
  559. {
  560. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  561. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  562. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  563. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  564. default: jassertfalse; break;
  565. }
  566. if (bytesWritten + bytes >= (size_t) 0xfff00000
  567. || ! output->write (tempBlock.getData(), bytes))
  568. {
  569. // failed to write to disk, so let's try writing the header.
  570. // If it's just run out of disk space, then if it does manage
  571. // to write the header, we'll still have a useable file..
  572. writeHeader();
  573. writeFailed = true;
  574. return false;
  575. }
  576. bytesWritten += bytes;
  577. lengthInSamples += (uint64) numSamples;
  578. return true;
  579. }
  580. private:
  581. MemoryBlock tempBlock, markChunk, comtChunk, instChunk;
  582. uint64 lengthInSamples = 0, bytesWritten = 0;
  583. int64 headerPosition = 0;
  584. bool writeFailed = false;
  585. void writeHeader()
  586. {
  587. using namespace AiffFileHelpers;
  588. const bool couldSeekOk = output->setPosition (headerPosition);
  589. ignoreUnused (couldSeekOk);
  590. // if this fails, you've given it an output stream that can't seek! It needs
  591. // to be able to seek back to write the header
  592. jassert (couldSeekOk);
  593. auto headerLen = (int) (54 + (markChunk.getSize() > 0 ? markChunk.getSize() + 8 : 0)
  594. + (comtChunk.getSize() > 0 ? comtChunk.getSize() + 8 : 0)
  595. + (instChunk.getSize() > 0 ? instChunk.getSize() + 8 : 0));
  596. auto audioBytes = (int) (lengthInSamples * ((bitsPerSample * numChannels) / 8));
  597. audioBytes += (audioBytes & 1);
  598. output->writeInt (chunkName ("FORM"));
  599. output->writeIntBigEndian (headerLen + audioBytes - 8);
  600. output->writeInt (chunkName ("AIFF"));
  601. output->writeInt (chunkName ("COMM"));
  602. output->writeIntBigEndian (18);
  603. output->writeShortBigEndian ((short) numChannels);
  604. output->writeIntBigEndian ((int) lengthInSamples);
  605. output->writeShortBigEndian ((short) bitsPerSample);
  606. uint8 sampleRateBytes[10] = {};
  607. if (sampleRate <= 1)
  608. {
  609. sampleRateBytes[0] = 0x3f;
  610. sampleRateBytes[1] = 0xff;
  611. sampleRateBytes[2] = 0x80;
  612. }
  613. else
  614. {
  615. int mask = 0x40000000;
  616. sampleRateBytes[0] = 0x40;
  617. if (sampleRate >= mask)
  618. {
  619. jassertfalse;
  620. sampleRateBytes[1] = 0x1d;
  621. }
  622. else
  623. {
  624. int n = (int) sampleRate;
  625. int i;
  626. for (i = 0; i <= 32 ; ++i)
  627. {
  628. if ((n & mask) != 0)
  629. break;
  630. mask >>= 1;
  631. }
  632. n = n << (i + 1);
  633. sampleRateBytes[1] = (uint8) (29 - i);
  634. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  635. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  636. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  637. sampleRateBytes[5] = (uint8) (n & 0xff);
  638. }
  639. }
  640. output->write (sampleRateBytes, 10);
  641. if (markChunk.getSize() > 0)
  642. {
  643. output->writeInt (chunkName ("MARK"));
  644. output->writeIntBigEndian ((int) markChunk.getSize());
  645. *output << markChunk;
  646. }
  647. if (comtChunk.getSize() > 0)
  648. {
  649. output->writeInt (chunkName ("COMT"));
  650. output->writeIntBigEndian ((int) comtChunk.getSize());
  651. *output << comtChunk;
  652. }
  653. if (instChunk.getSize() > 0)
  654. {
  655. output->writeInt (chunkName ("INST"));
  656. output->writeIntBigEndian ((int) instChunk.getSize());
  657. *output << instChunk;
  658. }
  659. output->writeInt (chunkName ("SSND"));
  660. output->writeIntBigEndian (audioBytes + 8);
  661. output->writeInt (0);
  662. output->writeInt (0);
  663. jassert (output->getPosition() == headerLen);
  664. }
  665. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter)
  666. };
  667. //==============================================================================
  668. class MemoryMappedAiffReader : public MemoryMappedAudioFormatReader
  669. {
  670. public:
  671. MemoryMappedAiffReader (const File& f, const AiffAudioFormatReader& reader)
  672. : MemoryMappedAudioFormatReader (f, reader, reader.dataChunkStart,
  673. reader.bytesPerFrame * reader.lengthInSamples, reader.bytesPerFrame),
  674. littleEndian (reader.littleEndian)
  675. {
  676. }
  677. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  678. int64 startSampleInFile, int numSamples) override
  679. {
  680. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  681. startSampleInFile, numSamples, lengthInSamples);
  682. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  683. {
  684. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  685. return false;
  686. }
  687. if (littleEndian)
  688. AiffAudioFormatReader::copySampleData<AudioData::LittleEndian>
  689. (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer,
  690. numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  691. else
  692. AiffAudioFormatReader::copySampleData<AudioData::BigEndian>
  693. (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer,
  694. numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  695. return true;
  696. }
  697. void getSample (int64 sample, float* result) const noexcept override
  698. {
  699. auto num = (int) numChannels;
  700. if (map == nullptr || ! mappedSection.contains (sample))
  701. {
  702. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  703. zeromem (result, (size_t) num * sizeof (float));
  704. return;
  705. }
  706. float** dest = &result;
  707. const void* source = sampleToPointer (sample);
  708. if (littleEndian)
  709. {
  710. switch (bitsPerSample)
  711. {
  712. case 8: ReadHelper<AudioData::Float32, AudioData::UInt8, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  713. case 16: ReadHelper<AudioData::Float32, AudioData::Int16, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  714. case 24: ReadHelper<AudioData::Float32, AudioData::Int24, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
  715. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
  716. else ReadHelper<AudioData::Float32, AudioData::Int32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
  717. break;
  718. default: jassertfalse; break;
  719. }
  720. }
  721. else
  722. {
  723. switch (bitsPerSample)
  724. {
  725. case 8: ReadHelper<AudioData::Float32, AudioData::UInt8, AudioData::BigEndian>::read (dest, 0, 1, source, 1, num); break;
  726. case 16: ReadHelper<AudioData::Float32, AudioData::Int16, AudioData::BigEndian>::read (dest, 0, 1, source, 1, num); break;
  727. case 24: ReadHelper<AudioData::Float32, AudioData::Int24, AudioData::BigEndian>::read (dest, 0, 1, source, 1, num); break;
  728. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::BigEndian>::read (dest, 0, 1, source, 1, num);
  729. else ReadHelper<AudioData::Float32, AudioData::Int32, AudioData::BigEndian>::read (dest, 0, 1, source, 1, num);
  730. break;
  731. default: jassertfalse; break;
  732. }
  733. }
  734. }
  735. void readMaxLevels (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) override
  736. {
  737. numSamples = jmin (numSamples, lengthInSamples - startSampleInFile);
  738. if (map == nullptr || numSamples <= 0 || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  739. {
  740. jassert (numSamples <= 0); // you must make sure that the window contains all the samples you're going to attempt to read.
  741. for (int i = 0; i < numChannelsToRead; ++i)
  742. results[i] = Range<float>();
  743. return;
  744. }
  745. switch (bitsPerSample)
  746. {
  747. case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  748. case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  749. case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, results, numChannelsToRead); break;
  750. case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, results, numChannelsToRead);
  751. else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, results, numChannelsToRead);
  752. break;
  753. default: jassertfalse; break;
  754. }
  755. }
  756. using AudioFormatReader::readMaxLevels;
  757. private:
  758. const bool littleEndian;
  759. template <typename SampleType>
  760. void scanMinAndMax (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) const noexcept
  761. {
  762. for (int i = 0; i < numChannelsToRead; ++i)
  763. results[i] = scanMinAndMaxForChannel<SampleType> (i, startSampleInFile, numSamples);
  764. }
  765. template <typename SampleType>
  766. Range<float> scanMinAndMaxForChannel (int channel, int64 startSampleInFile, int64 numSamples) const noexcept
  767. {
  768. return littleEndian ? scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (channel, startSampleInFile, numSamples)
  769. : scanMinAndMaxInterleaved<SampleType, AudioData::BigEndian> (channel, startSampleInFile, numSamples);
  770. }
  771. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedAiffReader)
  772. };
  773. //==============================================================================
  774. AiffAudioFormat::AiffAudioFormat() : AudioFormat (aiffFormatName, ".aiff .aif") {}
  775. AiffAudioFormat::~AiffAudioFormat() {}
  776. Array<int> AiffAudioFormat::getPossibleSampleRates()
  777. {
  778. return { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000 };
  779. }
  780. Array<int> AiffAudioFormat::getPossibleBitDepths()
  781. {
  782. return { 8, 16, 24 };
  783. }
  784. bool AiffAudioFormat::canDoStereo() { return true; }
  785. bool AiffAudioFormat::canDoMono() { return true; }
  786. #if JUCE_MAC
  787. bool AiffAudioFormat::canHandleFile (const File& f)
  788. {
  789. if (AudioFormat::canHandleFile (f))
  790. return true;
  791. auto type = f.getMacOSType();
  792. // (NB: written as hex to avoid four-char-constant warnings)
  793. return type == 0x41494646 /* AIFF */ || type == 0x41494643 /* AIFC */
  794. || type == 0x61696666 /* aiff */ || type == 0x61696663 /* aifc */;
  795. }
  796. #endif
  797. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails)
  798. {
  799. std::unique_ptr<AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  800. if (w->sampleRate > 0 && w->numChannels > 0)
  801. return w.release();
  802. if (! deleteStreamIfOpeningFails)
  803. w->input = nullptr;
  804. return nullptr;
  805. }
  806. MemoryMappedAudioFormatReader* AiffAudioFormat::createMemoryMappedReader (const File& file)
  807. {
  808. return createMemoryMappedReader (file.createInputStream().release());
  809. }
  810. MemoryMappedAudioFormatReader* AiffAudioFormat::createMemoryMappedReader (FileInputStream* fin)
  811. {
  812. if (fin != nullptr)
  813. {
  814. AiffAudioFormatReader reader (fin);
  815. if (reader.lengthInSamples > 0)
  816. return new MemoryMappedAiffReader (fin->getFile(), reader);
  817. }
  818. return nullptr;
  819. }
  820. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  821. double sampleRate,
  822. unsigned int numberOfChannels,
  823. int bitsPerSample,
  824. const StringPairArray& metadataValues,
  825. int /*qualityOptionIndex*/)
  826. {
  827. if (out != nullptr && getPossibleBitDepths().contains (bitsPerSample))
  828. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels,
  829. (unsigned int) bitsPerSample, metadataValues);
  830. return nullptr;
  831. }
  832. } // namespace juce