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.

958 lines
40KB

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