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.

726 lines
30KB

  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. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  337. if (samplesAvailable < numSamples)
  338. {
  339. for (int i = numDestChannels; --i >= 0;)
  340. if (destSamples[i] != nullptr)
  341. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * (size_t) numSamples);
  342. numSamples = (int) samplesAvailable;
  343. }
  344. if (numSamples <= 0)
  345. return true;
  346. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  347. while (numSamples > 0)
  348. {
  349. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  350. char tempBuffer [tempBufSize];
  351. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  352. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  353. if (bytesRead < numThisTime * bytesPerFrame)
  354. {
  355. jassert (bytesRead >= 0);
  356. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  357. }
  358. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  359. if (littleEndian)
  360. {
  361. switch (bitsPerSample)
  362. {
  363. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  364. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  365. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  366. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  367. default: jassertfalse; break;
  368. }
  369. }
  370. else
  371. {
  372. switch (bitsPerSample)
  373. {
  374. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  375. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  376. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  377. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  378. default: jassertfalse; break;
  379. }
  380. }
  381. startOffsetInDestBuffer += numThisTime;
  382. numSamples -= numThisTime;
  383. }
  384. return true;
  385. }
  386. int bytesPerFrame;
  387. int64 dataChunkStart;
  388. bool littleEndian;
  389. private:
  390. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader)
  391. };
  392. //==============================================================================
  393. class AiffAudioFormatWriter : public AudioFormatWriter
  394. {
  395. public:
  396. AiffAudioFormatWriter (OutputStream* out, double sampleRate_,
  397. unsigned int numChans, unsigned int bits,
  398. const StringPairArray& metadataValues)
  399. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  400. lengthInSamples (0),
  401. bytesWritten (0),
  402. writeFailed (false)
  403. {
  404. using namespace AiffFileHelpers;
  405. if (metadataValues.size() > 0)
  406. {
  407. // The meta data should have been santised for the AIFF format.
  408. // If it was originally sourced from a WAV file the MetaDataSource
  409. // key should be removed (or set to "AIFF") once this has been done
  410. jassert (metadataValues.getValue ("MetaDataSource", "None") != "WAV");
  411. MarkChunk::create (markChunk, metadataValues);
  412. COMTChunk::create (comtChunk, metadataValues);
  413. InstChunk::create (instChunk, metadataValues);
  414. }
  415. headerPosition = out->getPosition();
  416. writeHeader();
  417. }
  418. ~AiffAudioFormatWriter()
  419. {
  420. if ((bytesWritten & 1) != 0)
  421. output->writeByte (0);
  422. writeHeader();
  423. }
  424. //==============================================================================
  425. bool write (const int** data, int numSamples)
  426. {
  427. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  428. if (writeFailed)
  429. return false;
  430. const size_t bytes = (size_t) numSamples * numChannels * bitsPerSample / 8;
  431. tempBlock.ensureSize ((size_t) bytes, false);
  432. switch (bitsPerSample)
  433. {
  434. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  435. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  436. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  437. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  438. default: jassertfalse; break;
  439. }
  440. if (bytesWritten + bytes >= (size_t) 0xfff00000
  441. || ! output->write (tempBlock.getData(), (int) bytes))
  442. {
  443. // failed to write to disk, so let's try writing the header.
  444. // If it's just run out of disk space, then if it does manage
  445. // to write the header, we'll still have a useable file..
  446. writeHeader();
  447. writeFailed = true;
  448. return false;
  449. }
  450. else
  451. {
  452. bytesWritten += bytes;
  453. lengthInSamples += (uint64) numSamples;
  454. return true;
  455. }
  456. }
  457. private:
  458. MemoryBlock tempBlock, markChunk, comtChunk, instChunk;
  459. uint64 lengthInSamples, bytesWritten;
  460. int64 headerPosition;
  461. bool writeFailed;
  462. void writeHeader()
  463. {
  464. using namespace AiffFileHelpers;
  465. const bool couldSeekOk = output->setPosition (headerPosition);
  466. (void) couldSeekOk;
  467. // if this fails, you've given it an output stream that can't seek! It needs
  468. // to be able to seek back to write the header
  469. jassert (couldSeekOk);
  470. const int headerLen = (int) (54 + (markChunk.getSize() > 0 ? markChunk.getSize() + 8 : 0)
  471. + (comtChunk.getSize() > 0 ? comtChunk.getSize() + 8 : 0)
  472. + (instChunk.getSize() > 0 ? instChunk.getSize() + 8 : 0));
  473. int audioBytes = (int) (lengthInSamples * ((bitsPerSample * numChannels) / 8));
  474. audioBytes += (audioBytes & 1);
  475. output->writeInt (chunkName ("FORM"));
  476. output->writeIntBigEndian (headerLen + audioBytes - 8);
  477. output->writeInt (chunkName ("AIFF"));
  478. output->writeInt (chunkName ("COMM"));
  479. output->writeIntBigEndian (18);
  480. output->writeShortBigEndian ((short) numChannels);
  481. output->writeIntBigEndian ((int) lengthInSamples);
  482. output->writeShortBigEndian ((short) bitsPerSample);
  483. uint8 sampleRateBytes[10] = { 0 };
  484. if (sampleRate <= 1)
  485. {
  486. sampleRateBytes[0] = 0x3f;
  487. sampleRateBytes[1] = 0xff;
  488. sampleRateBytes[2] = 0x80;
  489. }
  490. else
  491. {
  492. int mask = 0x40000000;
  493. sampleRateBytes[0] = 0x40;
  494. if (sampleRate >= mask)
  495. {
  496. jassertfalse;
  497. sampleRateBytes[1] = 0x1d;
  498. }
  499. else
  500. {
  501. int n = (int) sampleRate;
  502. int i;
  503. for (i = 0; i <= 32 ; ++i)
  504. {
  505. if ((n & mask) != 0)
  506. break;
  507. mask >>= 1;
  508. }
  509. n = n << (i + 1);
  510. sampleRateBytes[1] = (uint8) (29 - i);
  511. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  512. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  513. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  514. sampleRateBytes[5] = (uint8) (n & 0xff);
  515. }
  516. }
  517. output->write (sampleRateBytes, 10);
  518. if (markChunk.getSize() > 0)
  519. {
  520. output->writeInt (chunkName ("MARK"));
  521. output->writeIntBigEndian ((int) markChunk.getSize());
  522. *output << markChunk;
  523. }
  524. if (comtChunk.getSize() > 0)
  525. {
  526. output->writeInt (chunkName ("COMT"));
  527. output->writeIntBigEndian ((int) comtChunk.getSize());
  528. *output << comtChunk;
  529. }
  530. if (instChunk.getSize() > 0)
  531. {
  532. output->writeInt (chunkName ("INST"));
  533. output->writeIntBigEndian ((int) instChunk.getSize());
  534. *output << instChunk;
  535. }
  536. output->writeInt (chunkName ("SSND"));
  537. output->writeIntBigEndian (audioBytes + 8);
  538. output->writeInt (0);
  539. output->writeInt (0);
  540. jassert (output->getPosition() == headerLen);
  541. }
  542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter)
  543. };
  544. //==============================================================================
  545. AiffAudioFormat::AiffAudioFormat()
  546. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  547. {
  548. }
  549. AiffAudioFormat::~AiffAudioFormat()
  550. {
  551. }
  552. Array<int> AiffAudioFormat::getPossibleSampleRates()
  553. {
  554. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  555. return Array <int> (rates);
  556. }
  557. Array<int> AiffAudioFormat::getPossibleBitDepths()
  558. {
  559. const int depths[] = { 8, 16, 24, 0 };
  560. return Array <int> (depths);
  561. }
  562. bool AiffAudioFormat::canDoStereo() { return true; }
  563. bool AiffAudioFormat::canDoMono() { return true; }
  564. #if JUCE_MAC
  565. bool AiffAudioFormat::canHandleFile (const File& f)
  566. {
  567. if (AudioFormat::canHandleFile (f))
  568. return true;
  569. const OSType type = f.getMacOSType();
  570. return type == 'AIFF' || type == 'AIFC'
  571. || type == 'aiff' || type == 'aifc';
  572. }
  573. #endif
  574. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  575. {
  576. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  577. if (w->sampleRate > 0 && w->numChannels > 0)
  578. return w.release();
  579. if (! deleteStreamIfOpeningFails)
  580. w->input = nullptr;
  581. return nullptr;
  582. }
  583. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  584. double sampleRate,
  585. unsigned int numberOfChannels,
  586. int bitsPerSample,
  587. const StringPairArray& metadataValues,
  588. int /*qualityOptionIndex*/)
  589. {
  590. if (getPossibleBitDepths().contains (bitsPerSample))
  591. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, (unsigned int) bitsPerSample, metadataValues);
  592. return nullptr;
  593. }