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.

955 lines
39KB

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