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.

828 lines
35KB

  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 int labelLength = jmin (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 int commentLength = jmin (comment.getNumBytesAsUTF8(), 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, usesFloatingPointData,
  355. destSamples, startOffsetInDestBuffer, numDestChannels,
  356. tempBuffer, (int) numChannels, numThisTime);
  357. else
  358. copySampleData<AudioData::BigEndian> (bitsPerSample, usesFloatingPointData,
  359. destSamples, startOffsetInDestBuffer, numDestChannels,
  360. tempBuffer, (int) numChannels, numThisTime);
  361. startOffsetInDestBuffer += numThisTime;
  362. numSamples -= numThisTime;
  363. }
  364. return true;
  365. }
  366. template <typename Endianness>
  367. static void copySampleData (unsigned int bitsPerSample, const bool usesFloatingPointData,
  368. int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
  369. const void* sourceData, int numChannels, int numSamples) noexcept
  370. {
  371. switch (bitsPerSample)
  372. {
  373. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  374. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  375. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  376. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, Endianness>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break;
  377. default: jassertfalse; break;
  378. }
  379. }
  380. int bytesPerFrame;
  381. int64 dataChunkStart;
  382. bool littleEndian;
  383. private:
  384. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader)
  385. };
  386. //==============================================================================
  387. class AiffAudioFormatWriter : public AudioFormatWriter
  388. {
  389. public:
  390. AiffAudioFormatWriter (OutputStream* out, double sampleRate_,
  391. unsigned int numChans, unsigned int bits,
  392. const StringPairArray& metadataValues)
  393. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  394. lengthInSamples (0),
  395. bytesWritten (0),
  396. writeFailed (false)
  397. {
  398. using namespace AiffFileHelpers;
  399. if (metadataValues.size() > 0)
  400. {
  401. // The meta data should have been santised for the AIFF format.
  402. // If it was originally sourced from a WAV file the MetaDataSource
  403. // key should be removed (or set to "AIFF") once this has been done
  404. jassert (metadataValues.getValue ("MetaDataSource", "None") != "WAV");
  405. MarkChunk::create (markChunk, metadataValues);
  406. COMTChunk::create (comtChunk, metadataValues);
  407. InstChunk::create (instChunk, metadataValues);
  408. }
  409. headerPosition = out->getPosition();
  410. writeHeader();
  411. }
  412. ~AiffAudioFormatWriter()
  413. {
  414. if ((bytesWritten & 1) != 0)
  415. output->writeByte (0);
  416. writeHeader();
  417. }
  418. //==============================================================================
  419. bool write (const int** data, int numSamples)
  420. {
  421. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  422. if (writeFailed)
  423. return false;
  424. const size_t bytes = (size_t) numSamples * numChannels * bitsPerSample / 8;
  425. tempBlock.ensureSize ((size_t) bytes, false);
  426. switch (bitsPerSample)
  427. {
  428. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  429. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  430. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  431. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  432. default: jassertfalse; break;
  433. }
  434. if (bytesWritten + bytes >= (size_t) 0xfff00000
  435. || ! output->write (tempBlock.getData(), (int) bytes))
  436. {
  437. // failed to write to disk, so let's try writing the header.
  438. // If it's just run out of disk space, then if it does manage
  439. // to write the header, we'll still have a useable file..
  440. writeHeader();
  441. writeFailed = true;
  442. return false;
  443. }
  444. else
  445. {
  446. bytesWritten += bytes;
  447. lengthInSamples += (uint64) numSamples;
  448. return true;
  449. }
  450. }
  451. private:
  452. MemoryBlock tempBlock, markChunk, comtChunk, instChunk;
  453. uint64 lengthInSamples, bytesWritten;
  454. int64 headerPosition;
  455. bool writeFailed;
  456. void writeHeader()
  457. {
  458. using namespace AiffFileHelpers;
  459. const bool couldSeekOk = output->setPosition (headerPosition);
  460. (void) couldSeekOk;
  461. // if this fails, you've given it an output stream that can't seek! It needs
  462. // to be able to seek back to write the header
  463. jassert (couldSeekOk);
  464. const int headerLen = (int) (54 + (markChunk.getSize() > 0 ? markChunk.getSize() + 8 : 0)
  465. + (comtChunk.getSize() > 0 ? comtChunk.getSize() + 8 : 0)
  466. + (instChunk.getSize() > 0 ? instChunk.getSize() + 8 : 0));
  467. int audioBytes = (int) (lengthInSamples * ((bitsPerSample * numChannels) / 8));
  468. audioBytes += (audioBytes & 1);
  469. output->writeInt (chunkName ("FORM"));
  470. output->writeIntBigEndian (headerLen + audioBytes - 8);
  471. output->writeInt (chunkName ("AIFF"));
  472. output->writeInt (chunkName ("COMM"));
  473. output->writeIntBigEndian (18);
  474. output->writeShortBigEndian ((short) numChannels);
  475. output->writeIntBigEndian ((int) lengthInSamples);
  476. output->writeShortBigEndian ((short) bitsPerSample);
  477. uint8 sampleRateBytes[10] = { 0 };
  478. if (sampleRate <= 1)
  479. {
  480. sampleRateBytes[0] = 0x3f;
  481. sampleRateBytes[1] = 0xff;
  482. sampleRateBytes[2] = 0x80;
  483. }
  484. else
  485. {
  486. int mask = 0x40000000;
  487. sampleRateBytes[0] = 0x40;
  488. if (sampleRate >= mask)
  489. {
  490. jassertfalse;
  491. sampleRateBytes[1] = 0x1d;
  492. }
  493. else
  494. {
  495. int n = (int) sampleRate;
  496. int i;
  497. for (i = 0; i <= 32 ; ++i)
  498. {
  499. if ((n & mask) != 0)
  500. break;
  501. mask >>= 1;
  502. }
  503. n = n << (i + 1);
  504. sampleRateBytes[1] = (uint8) (29 - i);
  505. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  506. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  507. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  508. sampleRateBytes[5] = (uint8) (n & 0xff);
  509. }
  510. }
  511. output->write (sampleRateBytes, 10);
  512. if (markChunk.getSize() > 0)
  513. {
  514. output->writeInt (chunkName ("MARK"));
  515. output->writeIntBigEndian ((int) markChunk.getSize());
  516. *output << markChunk;
  517. }
  518. if (comtChunk.getSize() > 0)
  519. {
  520. output->writeInt (chunkName ("COMT"));
  521. output->writeIntBigEndian ((int) comtChunk.getSize());
  522. *output << comtChunk;
  523. }
  524. if (instChunk.getSize() > 0)
  525. {
  526. output->writeInt (chunkName ("INST"));
  527. output->writeIntBigEndian ((int) instChunk.getSize());
  528. *output << instChunk;
  529. }
  530. output->writeInt (chunkName ("SSND"));
  531. output->writeIntBigEndian (audioBytes + 8);
  532. output->writeInt (0);
  533. output->writeInt (0);
  534. jassert (output->getPosition() == headerLen);
  535. }
  536. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter)
  537. };
  538. //==============================================================================
  539. class MemoryMappedAiffReader : public MemoryMappedAudioFormatReader
  540. {
  541. public:
  542. MemoryMappedAiffReader (const File& file, const AiffAudioFormatReader& reader)
  543. : MemoryMappedAudioFormatReader (file, reader, reader.dataChunkStart,
  544. reader.bytesPerFrame * reader.lengthInSamples, reader.bytesPerFrame),
  545. littleEndian (reader.littleEndian)
  546. {
  547. }
  548. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  549. int64 startSampleInFile, int numSamples)
  550. {
  551. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  552. startSampleInFile, numSamples, lengthInSamples);
  553. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  554. {
  555. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  556. return false;
  557. }
  558. if (littleEndian)
  559. AiffAudioFormatReader::copySampleData<AudioData::LittleEndian>
  560. (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer,
  561. numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  562. else
  563. AiffAudioFormatReader::copySampleData<AudioData::BigEndian>
  564. (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer,
  565. numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
  566. return true;
  567. }
  568. void readMaxLevels (int64 startSampleInFile, int64 numSamples,
  569. float& min0, float& max0, float& min1, float& max1)
  570. {
  571. if (numSamples <= 0)
  572. {
  573. min0 = max0 = min1 = max1 = 0;
  574. return;
  575. }
  576. if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
  577. {
  578. jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
  579. min0 = max0 = min1 = max1 = 0;
  580. return;
  581. }
  582. switch (bitsPerSample)
  583. {
  584. case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  585. case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  586. case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  587. case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, min0, max0, min1, max1);
  588. else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, min0, max0, min1, max1); break;
  589. default: jassertfalse; break;
  590. }
  591. }
  592. private:
  593. const bool littleEndian;
  594. template <typename SampleType>
  595. void scanMinAndMax (int64 startSampleInFile, int64 numSamples,
  596. float& min0, float& max0, float& min1, float& max1) const noexcept
  597. {
  598. if (littleEndian)
  599. scanMinAndMax2<SampleType, AudioData::LittleEndian> (startSampleInFile, numSamples, min0, max0, min1, max1);
  600. else
  601. scanMinAndMax2<SampleType, AudioData::BigEndian> (startSampleInFile, numSamples, min0, max0, min1, max1);
  602. }
  603. template <typename SampleType, typename Endianness>
  604. void scanMinAndMax2 (int64 startSampleInFile, int64 numSamples,
  605. float& min0, float& max0, float& min1, float& max1) const noexcept
  606. {
  607. typedef AudioData::Pointer <SampleType, Endianness, AudioData::Interleaved, AudioData::Const> SourceType;
  608. SourceType (sampleToPointer (startSampleInFile), (int) numChannels)
  609. .findMinAndMax ((size_t) numSamples, min0, max0);
  610. if (numChannels > 1)
  611. SourceType (addBytesToPointer (sampleToPointer (startSampleInFile), bitsPerSample / 8), (int) numChannels)
  612. .findMinAndMax ((size_t) numSamples, min1, max1);
  613. else
  614. min1 = max1 = 0;
  615. }
  616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedAiffReader)
  617. };
  618. //==============================================================================
  619. AiffAudioFormat::AiffAudioFormat()
  620. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  621. {
  622. }
  623. AiffAudioFormat::~AiffAudioFormat()
  624. {
  625. }
  626. Array<int> AiffAudioFormat::getPossibleSampleRates()
  627. {
  628. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  629. return Array <int> (rates);
  630. }
  631. Array<int> AiffAudioFormat::getPossibleBitDepths()
  632. {
  633. const int depths[] = { 8, 16, 24, 0 };
  634. return Array <int> (depths);
  635. }
  636. bool AiffAudioFormat::canDoStereo() { return true; }
  637. bool AiffAudioFormat::canDoMono() { return true; }
  638. #if JUCE_MAC
  639. bool AiffAudioFormat::canHandleFile (const File& f)
  640. {
  641. if (AudioFormat::canHandleFile (f))
  642. return true;
  643. const OSType type = f.getMacOSType();
  644. return type == 'AIFF' || type == 'AIFC'
  645. || type == 'aiff' || type == 'aifc';
  646. }
  647. #endif
  648. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  649. {
  650. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  651. if (w->sampleRate > 0 && w->numChannels > 0)
  652. return w.release();
  653. if (! deleteStreamIfOpeningFails)
  654. w->input = nullptr;
  655. return nullptr;
  656. }
  657. MemoryMappedAudioFormatReader* AiffAudioFormat::createMemoryMappedReader (const File& file)
  658. {
  659. if (FileInputStream* fin = file.createInputStream())
  660. {
  661. AiffAudioFormatReader reader (fin);
  662. if (reader.lengthInSamples > 0)
  663. return new MemoryMappedAiffReader (file, reader);
  664. }
  665. return nullptr;
  666. }
  667. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  668. double sampleRate,
  669. unsigned int numberOfChannels,
  670. int bitsPerSample,
  671. const StringPairArray& metadataValues,
  672. int /*qualityOptionIndex*/)
  673. {
  674. if (getPossibleBitDepths().contains (bitsPerSample))
  675. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, (unsigned int) bitsPerSample, metadataValues);
  676. return nullptr;
  677. }