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.

713 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 void create (MemoryBlock& block, const StringPairArray& values)
  64. {
  65. if (values.getAllKeys().contains ("MidiUnityNote", true))
  66. {
  67. block.setSize ((sizeof (InstChunk) + 3) & ~(size_t) 3, true);
  68. InstChunk* const inst = static_cast <InstChunk*> (block.getData());
  69. inst->baseNote = (int8) values.getValue ("MidiUnityNote", "60").getIntValue();
  70. inst->detune = (int8) values.getValue ("Detune", "0").getIntValue();
  71. inst->lowNote = (int8) values.getValue ("LowNote", "0").getIntValue();
  72. inst->highNote = (int8) values.getValue ("HighNote", "127").getIntValue();
  73. inst->lowVelocity = (int8) values.getValue ("LowVelocity", "1").getIntValue();
  74. inst->highVelocity = (int8) values.getValue ("HighVelocity", "127").getIntValue();
  75. inst->gain = (int16) ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Gain", "0").getIntValue());
  76. inst->sustainLoop.type = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop0Type", "0").getIntValue());
  77. inst->sustainLoop.startIdentifier = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop0StartIdentifier", "0").getIntValue());
  78. inst->sustainLoop.endIdentifier = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop0EndIdentifier", "0").getIntValue());
  79. inst->releaseLoop.type = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop1Type", "0").getIntValue());
  80. inst->releaseLoop.startIdentifier = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop1StartIdentifier", "0").getIntValue());
  81. inst->releaseLoop.endIdentifier = ByteOrder::swapIfLittleEndian ((uint16) values.getValue ("Loop1EndIdentifier", "0").getIntValue());
  82. }
  83. }
  84. } JUCE_PACKED;
  85. #if JUCE_MSVC
  86. #pragma pack (pop)
  87. #endif
  88. //==============================================================================
  89. namespace MarkChunk
  90. {
  91. static bool metaDataContainsZeroIdentifiers (const StringPairArray& values)
  92. {
  93. // (zero cue identifiers are valid for WAV but not for AIFF)
  94. const String cueString ("Cue");
  95. const String noteString ("CueNote");
  96. const String identifierString ("Identifier");
  97. const StringArray& keys = values.getAllKeys();
  98. for (int i = 0; i < keys.size(); ++i)
  99. {
  100. const String key (keys[i]);
  101. if (key.startsWith (noteString))
  102. continue; // zero identifier IS valid in a COMT chunk
  103. if (key.startsWith (cueString) && key.contains (identifierString))
  104. {
  105. const int value = values.getValue (key, "-1").getIntValue();
  106. if (value == 0)
  107. return true;
  108. }
  109. }
  110. return false;
  111. }
  112. static void create (MemoryBlock& block, const StringPairArray& values)
  113. {
  114. const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
  115. if (numCues > 0)
  116. {
  117. MemoryOutputStream out (block, false);
  118. out.writeShortBigEndian ((short) numCues);
  119. const int numCueLabels = values.getValue ("NumCueLabels", "0").getIntValue();
  120. const int idOffset = metaDataContainsZeroIdentifiers (values) ? 1 : 0; // can't have zero IDs in AIFF
  121. #if JUCE_DEBUG
  122. Array<int> identifiers;
  123. #endif
  124. for (int i = 0; i < numCues; ++i)
  125. {
  126. const String prefixCue ("Cue" + String (i));
  127. const int identifier = idOffset + values.getValue (prefixCue + "Identifier", "1").getIntValue();
  128. #if JUCE_DEBUG
  129. jassert (! identifiers.contains (identifier));
  130. identifiers.add (identifier);
  131. #endif
  132. const int offset = values.getValue (prefixCue + "Offset", "0").getIntValue();
  133. String label ("CueLabel" + String (i));
  134. for (int labelIndex = 0; labelIndex < numCueLabels; ++labelIndex)
  135. {
  136. const String prefixLabel ("CueLabel" + String (labelIndex));
  137. const int labelIdentifier = idOffset + values.getValue (prefixLabel + "Identifier", "1").getIntValue();
  138. if (labelIdentifier == identifier)
  139. {
  140. label = values.getValue (prefixLabel + "Text", label);
  141. break;
  142. }
  143. }
  144. out.writeShortBigEndian ((short) identifier);
  145. out.writeIntBigEndian (offset);
  146. const int labelLength = jmin (254, label.getNumBytesAsUTF8()); // seems to need null terminator even though it's a pstring
  147. out.writeByte ((char) labelLength + 1);
  148. out.write (label.toUTF8(), labelLength);
  149. out.writeByte (0);
  150. }
  151. if ((out.getDataSize() & 1) != 0)
  152. out.writeByte (0);
  153. }
  154. }
  155. }
  156. //==============================================================================
  157. namespace COMTChunk
  158. {
  159. static void create (MemoryBlock& block, const StringPairArray& values)
  160. {
  161. const int numNotes = values.getValue ("NumCueNotes", "0").getIntValue();
  162. if (numNotes > 0)
  163. {
  164. MemoryOutputStream out (block, false);
  165. out.writeShortBigEndian ((short) numNotes);
  166. for (int i = 0; i < numNotes; ++i)
  167. {
  168. const String prefix ("CueNote" + String (i));
  169. out.writeIntBigEndian (values.getValue (prefix + "TimeStamp", "0").getIntValue());
  170. out.writeShortBigEndian ((short) values.getValue (prefix + "Identifier", "0").getIntValue());
  171. const String comment (values.getValue (prefix + "Text", String::empty));
  172. out.write (comment.toUTF8(), jmin (comment.getNumBytesAsUTF8(), 65534));
  173. out.writeByte (0);
  174. if ((out.getDataSize() & 1) != 0)
  175. out.writeByte (0);
  176. }
  177. }
  178. }
  179. }
  180. }
  181. //==============================================================================
  182. class AiffAudioFormatReader : public AudioFormatReader
  183. {
  184. public:
  185. AiffAudioFormatReader (InputStream* in)
  186. : AudioFormatReader (in, TRANS (aiffFormatName))
  187. {
  188. using namespace AiffFileHelpers;
  189. if (input->readInt() == chunkName ("FORM"))
  190. {
  191. const int len = input->readIntBigEndian();
  192. const int64 end = input->getPosition() + len;
  193. const int nextType = input->readInt();
  194. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  195. {
  196. bool hasGotVer = false;
  197. bool hasGotData = false;
  198. bool hasGotType = false;
  199. while (input->getPosition() < end)
  200. {
  201. const int type = input->readInt();
  202. const uint32 length = (uint32) input->readIntBigEndian();
  203. const int64 chunkEnd = input->getPosition() + length;
  204. if (type == chunkName ("FVER"))
  205. {
  206. hasGotVer = true;
  207. const int ver = input->readIntBigEndian();
  208. if (ver != 0 && ver != (int) 0xa2805140)
  209. break;
  210. }
  211. else if (type == chunkName ("COMM"))
  212. {
  213. hasGotType = true;
  214. numChannels = (unsigned int) input->readShortBigEndian();
  215. lengthInSamples = input->readIntBigEndian();
  216. bitsPerSample = (unsigned int) input->readShortBigEndian();
  217. bytesPerFrame = (int) ((numChannels * bitsPerSample) >> 3);
  218. unsigned char sampleRateBytes[10];
  219. input->read (sampleRateBytes, 10);
  220. const int byte0 = sampleRateBytes[0];
  221. if ((byte0 & 0x80) != 0
  222. || byte0 <= 0x3F || byte0 > 0x40
  223. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  224. break;
  225. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  226. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  227. sampleRate = (int) sampRate;
  228. if (length <= 18)
  229. {
  230. // some types don't have a chunk large enough to include a compression
  231. // type, so assume it's just big-endian pcm
  232. littleEndian = false;
  233. }
  234. else
  235. {
  236. const int compType = input->readInt();
  237. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  238. {
  239. littleEndian = false;
  240. }
  241. else if (compType == chunkName ("sowt"))
  242. {
  243. littleEndian = true;
  244. }
  245. else
  246. {
  247. sampleRate = 0;
  248. break;
  249. }
  250. }
  251. }
  252. else if (type == chunkName ("SSND"))
  253. {
  254. hasGotData = true;
  255. const int offset = input->readIntBigEndian();
  256. dataChunkStart = input->getPosition() + 4 + offset;
  257. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, ((int64) length) / (int64) bytesPerFrame) : 0;
  258. }
  259. else if (type == chunkName ("MARK"))
  260. {
  261. const uint16 numCues = (uint16) input->readShortBigEndian();
  262. // these two are always the same for AIFF-read files
  263. metadataValues.set ("NumCuePoints", String (numCues));
  264. metadataValues.set ("NumCueLabels", String (numCues));
  265. for (uint16 i = 0; i < numCues; ++i)
  266. {
  267. uint16 identifier = (uint16) input->readShortBigEndian();
  268. uint32 offset = (uint32) input->readIntBigEndian();
  269. uint8 stringLength = (uint8) input->readByte();
  270. MemoryBlock textBlock;
  271. input->readIntoMemoryBlock (textBlock, stringLength);
  272. // if the stringLength is even then read one more byte as the
  273. // string needs to be an even number of bytes INCLUDING the
  274. // leading length character in the pascal string
  275. if ((stringLength & 1) == 0)
  276. input->readByte();
  277. const String prefixCue ("Cue" + String (i));
  278. metadataValues.set (prefixCue + "Identifier", String (identifier));
  279. metadataValues.set (prefixCue + "Offset", String (offset));
  280. const String prefixLabel ("CueLabel" + String (i));
  281. metadataValues.set (prefixLabel + "Identifier", String (identifier));
  282. metadataValues.set (prefixLabel + "Text", textBlock.toString());
  283. }
  284. }
  285. else if (type == chunkName ("COMT"))
  286. {
  287. const uint16 numNotes = (uint16) input->readShortBigEndian();
  288. metadataValues.set ("NumCueNotes", String (numNotes));
  289. for (uint16 i = 0; i < numNotes; ++i)
  290. {
  291. uint32 timestamp = (uint32) input->readIntBigEndian();
  292. uint16 identifier = (uint16) input->readShortBigEndian(); // may be zero in this case
  293. uint16 stringLength = (uint16) input->readShortBigEndian();
  294. MemoryBlock textBlock;
  295. input->readIntoMemoryBlock (textBlock, stringLength + (stringLength & 1));
  296. const String prefix ("CueNote" + String (i));
  297. metadataValues.set (prefix + "TimeStamp", String (timestamp));
  298. metadataValues.set (prefix + "Identifier", String (identifier));
  299. metadataValues.set (prefix + "Text", textBlock.toString());
  300. }
  301. }
  302. else if (type == chunkName ("INST"))
  303. {
  304. HeapBlock <InstChunk> inst;
  305. inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
  306. input->read (inst, (int) length);
  307. inst->copyTo (metadataValues);
  308. }
  309. else if ((hasGotVer && hasGotData && hasGotType)
  310. || chunkEnd < input->getPosition()
  311. || input->isExhausted())
  312. {
  313. break;
  314. }
  315. input->setPosition (chunkEnd + (chunkEnd & 1)); // (chunks should be aligned to an even byte address)
  316. }
  317. }
  318. }
  319. if (metadataValues.size() > 0)
  320. metadataValues.set ("MetaDataSource", "AIFF");
  321. }
  322. //==============================================================================
  323. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  324. int64 startSampleInFile, int numSamples)
  325. {
  326. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  327. if (samplesAvailable < numSamples)
  328. {
  329. for (int i = numDestChannels; --i >= 0;)
  330. if (destSamples[i] != nullptr)
  331. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * (size_t) numSamples);
  332. numSamples = (int) samplesAvailable;
  333. }
  334. if (numSamples <= 0)
  335. return true;
  336. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  337. while (numSamples > 0)
  338. {
  339. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  340. char tempBuffer [tempBufSize];
  341. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  342. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  343. if (bytesRead < numThisTime * bytesPerFrame)
  344. {
  345. jassert (bytesRead >= 0);
  346. zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
  347. }
  348. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  349. if (littleEndian)
  350. {
  351. switch (bitsPerSample)
  352. {
  353. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  354. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  355. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  356. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  357. default: jassertfalse; break;
  358. }
  359. }
  360. else
  361. {
  362. switch (bitsPerSample)
  363. {
  364. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  365. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  366. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  367. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); break;
  368. default: jassertfalse; break;
  369. }
  370. }
  371. startOffsetInDestBuffer += numThisTime;
  372. numSamples -= numThisTime;
  373. }
  374. return true;
  375. }
  376. int bytesPerFrame;
  377. int64 dataChunkStart;
  378. bool littleEndian;
  379. private:
  380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  381. };
  382. //==============================================================================
  383. class AiffAudioFormatWriter : public AudioFormatWriter
  384. {
  385. public:
  386. AiffAudioFormatWriter (OutputStream* out, double sampleRate_,
  387. unsigned int numChans, unsigned int bits,
  388. const StringPairArray& metadataValues)
  389. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  390. lengthInSamples (0),
  391. bytesWritten (0),
  392. writeFailed (false)
  393. {
  394. using namespace AiffFileHelpers;
  395. if (metadataValues.size() > 0)
  396. {
  397. // The meta data should have been santised for the AIFF format.
  398. // If it was originally sourced from a WAV file the MetaDataSource
  399. // key should be removed (or set to "AIFF") once this has been done
  400. jassert (metadataValues.getValue ("MetaDataSource", "None") != "WAV");
  401. MarkChunk::create (markChunk, metadataValues);
  402. COMTChunk::create (comtChunk, metadataValues);
  403. InstChunk::create (instChunk, metadataValues);
  404. }
  405. headerPosition = out->getPosition();
  406. writeHeader();
  407. }
  408. ~AiffAudioFormatWriter()
  409. {
  410. if ((bytesWritten & 1) != 0)
  411. output->writeByte (0);
  412. writeHeader();
  413. }
  414. //==============================================================================
  415. bool write (const int** data, int numSamples)
  416. {
  417. jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
  418. if (writeFailed)
  419. return false;
  420. const size_t bytes = (size_t) numSamples * numChannels * bitsPerSample / 8;
  421. tempBlock.ensureSize ((size_t) bytes, false);
  422. switch (bitsPerSample)
  423. {
  424. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  425. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  426. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  427. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
  428. default: jassertfalse; break;
  429. }
  430. if (bytesWritten + bytes >= (size_t) 0xfff00000
  431. || ! output->write (tempBlock.getData(), (int) bytes))
  432. {
  433. // failed to write to disk, so let's try writing the header.
  434. // If it's just run out of disk space, then if it does manage
  435. // to write the header, we'll still have a useable file..
  436. writeHeader();
  437. writeFailed = true;
  438. return false;
  439. }
  440. else
  441. {
  442. bytesWritten += bytes;
  443. lengthInSamples += (uint64) numSamples;
  444. return true;
  445. }
  446. }
  447. private:
  448. MemoryBlock tempBlock, markChunk, comtChunk, instChunk;
  449. uint64 lengthInSamples, bytesWritten;
  450. int64 headerPosition;
  451. bool writeFailed;
  452. void writeHeader()
  453. {
  454. using namespace AiffFileHelpers;
  455. const bool couldSeekOk = output->setPosition (headerPosition);
  456. (void) couldSeekOk;
  457. // if this fails, you've given it an output stream that can't seek! It needs
  458. // to be able to seek back to write the header
  459. jassert (couldSeekOk);
  460. const int headerLen = (int) (54 + (markChunk.getSize() > 0 ? markChunk.getSize() + 8 : 0)
  461. + (comtChunk.getSize() > 0 ? comtChunk.getSize() + 8 : 0)
  462. + (instChunk.getSize() > 0 ? instChunk.getSize() + 8 : 0));
  463. int audioBytes = (int) (lengthInSamples * ((bitsPerSample * numChannels) / 8));
  464. audioBytes += (audioBytes & 1);
  465. output->writeInt (chunkName ("FORM"));
  466. output->writeIntBigEndian (headerLen + audioBytes - 8);
  467. output->writeInt (chunkName ("AIFF"));
  468. output->writeInt (chunkName ("COMM"));
  469. output->writeIntBigEndian (18);
  470. output->writeShortBigEndian ((short) numChannels);
  471. output->writeIntBigEndian ((int) lengthInSamples);
  472. output->writeShortBigEndian ((short) bitsPerSample);
  473. uint8 sampleRateBytes[10] = { 0 };
  474. if (sampleRate <= 1)
  475. {
  476. sampleRateBytes[0] = 0x3f;
  477. sampleRateBytes[1] = 0xff;
  478. sampleRateBytes[2] = 0x80;
  479. }
  480. else
  481. {
  482. int mask = 0x40000000;
  483. sampleRateBytes[0] = 0x40;
  484. if (sampleRate >= mask)
  485. {
  486. jassertfalse;
  487. sampleRateBytes[1] = 0x1d;
  488. }
  489. else
  490. {
  491. int n = (int) sampleRate;
  492. int i;
  493. for (i = 0; i <= 32 ; ++i)
  494. {
  495. if ((n & mask) != 0)
  496. break;
  497. mask >>= 1;
  498. }
  499. n = n << (i + 1);
  500. sampleRateBytes[1] = (uint8) (29 - i);
  501. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  502. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  503. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  504. sampleRateBytes[5] = (uint8) (n & 0xff);
  505. }
  506. }
  507. output->write (sampleRateBytes, 10);
  508. if (markChunk.getSize() > 0)
  509. {
  510. output->writeInt (chunkName ("MARK"));
  511. output->writeIntBigEndian ((int) markChunk.getSize());
  512. *output << markChunk;
  513. }
  514. if (comtChunk.getSize() > 0)
  515. {
  516. output->writeInt (chunkName ("COMT"));
  517. output->writeIntBigEndian ((int) comtChunk.getSize());
  518. *output << comtChunk;
  519. }
  520. if (instChunk.getSize() > 0)
  521. {
  522. output->writeInt (chunkName ("INST"));
  523. output->writeIntBigEndian ((int) instChunk.getSize());
  524. *output << instChunk;
  525. }
  526. output->writeInt (chunkName ("SSND"));
  527. output->writeIntBigEndian (audioBytes + 8);
  528. output->writeInt (0);
  529. output->writeInt (0);
  530. jassert (output->getPosition() == headerLen);
  531. }
  532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  533. };
  534. //==============================================================================
  535. AiffAudioFormat::AiffAudioFormat()
  536. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  537. {
  538. }
  539. AiffAudioFormat::~AiffAudioFormat()
  540. {
  541. }
  542. Array<int> AiffAudioFormat::getPossibleSampleRates()
  543. {
  544. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  545. return Array <int> (rates);
  546. }
  547. Array<int> AiffAudioFormat::getPossibleBitDepths()
  548. {
  549. const int depths[] = { 8, 16, 24, 0 };
  550. return Array <int> (depths);
  551. }
  552. bool AiffAudioFormat::canDoStereo() { return true; }
  553. bool AiffAudioFormat::canDoMono() { return true; }
  554. #if JUCE_MAC
  555. bool AiffAudioFormat::canHandleFile (const File& f)
  556. {
  557. if (AudioFormat::canHandleFile (f))
  558. return true;
  559. const OSType type = f.getMacOSType();
  560. return type == 'AIFF' || type == 'AIFC'
  561. || type == 'aiff' || type == 'aifc';
  562. }
  563. #endif
  564. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  565. {
  566. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  567. if (w->sampleRate > 0 && w->numChannels > 0)
  568. return w.release();
  569. if (! deleteStreamIfOpeningFails)
  570. w->input = nullptr;
  571. return nullptr;
  572. }
  573. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  574. double sampleRate,
  575. unsigned int numberOfChannels,
  576. int bitsPerSample,
  577. const StringPairArray& metadataValues,
  578. int /*qualityOptionIndex*/)
  579. {
  580. if (getPossibleBitDepths().contains (bitsPerSample))
  581. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, (unsigned int) bitsPerSample, metadataValues);
  582. return nullptr;
  583. }