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.

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