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.

907 lines
38KB

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