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.

824 lines
34KB

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