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.

541 lines
21KB

  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. #if JUCE_USE_FLAC
  19. BEGIN_JUCE_NAMESPACE
  20. namespace FlacNamespace
  21. {
  22. #if JUCE_INCLUDE_FLAC_CODE || ! defined (JUCE_INCLUDE_FLAC_CODE)
  23. #undef VERSION
  24. #define VERSION "1.2.1"
  25. #define FLAC__NO_DLL 1
  26. #if JUCE_MSVC
  27. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312 4505 4365 4005 4334 181 111)
  28. #endif
  29. #if JUCE_MAC
  30. #define FLAC__SYS_DARWIN 1
  31. #endif
  32. #ifndef SIZE_MAX
  33. #define SIZE_MAX 0xffffffff
  34. #endif
  35. #define __STDC_LIMIT_MACROS 1
  36. #include "flac/all.h"
  37. #include "flac/libFLAC/bitmath.c"
  38. #include "flac/libFLAC/bitreader.c"
  39. #include "flac/libFLAC/bitwriter.c"
  40. #include "flac/libFLAC/cpu.c"
  41. #include "flac/libFLAC/crc.c"
  42. #include "flac/libFLAC/fixed.c"
  43. #include "flac/libFLAC/float.c"
  44. #include "flac/libFLAC/format.c"
  45. #include "flac/libFLAC/lpc_flac.c"
  46. #include "flac/libFLAC/md5.c"
  47. #include "flac/libFLAC/memory.c"
  48. #include "flac/libFLAC/stream_decoder.c"
  49. #include "flac/libFLAC/stream_encoder.c"
  50. #include "flac/libFLAC/stream_encoder_framing.c"
  51. #include "flac/libFLAC/window_flac.c"
  52. #undef VERSION
  53. #else
  54. #include <FLAC/all.h>
  55. #endif
  56. }
  57. #undef max
  58. #undef min
  59. //==============================================================================
  60. static const char* const flacFormatName = "FLAC file";
  61. static const char* const flacExtensions[] = { ".flac", 0 };
  62. //==============================================================================
  63. class FlacReader : public AudioFormatReader
  64. {
  65. public:
  66. //==============================================================================
  67. FlacReader (InputStream* const in)
  68. : AudioFormatReader (in, TRANS (flacFormatName)),
  69. reservoir (2, 0),
  70. reservoirStart (0),
  71. samplesInReservoir (0),
  72. scanningForLength (false)
  73. {
  74. using namespace FlacNamespace;
  75. lengthInSamples = 0;
  76. decoder = FLAC__stream_decoder_new();
  77. ok = FLAC__stream_decoder_init_stream (decoder,
  78. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  79. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  80. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  81. if (ok)
  82. {
  83. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  84. if (lengthInSamples == 0 && sampleRate > 0)
  85. {
  86. // the length hasn't been stored in the metadata, so we'll need to
  87. // work it out the length the hard way, by scanning the whole file..
  88. scanningForLength = true;
  89. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  90. scanningForLength = false;
  91. const int64 tempLength = lengthInSamples;
  92. FLAC__stream_decoder_reset (decoder);
  93. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  94. lengthInSamples = tempLength;
  95. }
  96. }
  97. }
  98. ~FlacReader()
  99. {
  100. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  101. }
  102. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  103. {
  104. sampleRate = info.sample_rate;
  105. bitsPerSample = info.bits_per_sample;
  106. lengthInSamples = (unsigned int) info.total_samples;
  107. numChannels = info.channels;
  108. reservoir.setSize ((int) numChannels, 2 * info.max_blocksize, false, false, true);
  109. }
  110. // returns the number of samples read
  111. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  112. int64 startSampleInFile, int numSamples)
  113. {
  114. using namespace FlacNamespace;
  115. if (! ok)
  116. return false;
  117. while (numSamples > 0)
  118. {
  119. if (startSampleInFile >= reservoirStart
  120. && startSampleInFile < reservoirStart + samplesInReservoir)
  121. {
  122. const int num = (int) jmin ((int64) numSamples,
  123. reservoirStart + samplesInReservoir - startSampleInFile);
  124. jassert (num > 0);
  125. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  126. if (destSamples[i] != nullptr)
  127. memcpy (destSamples[i] + startOffsetInDestBuffer,
  128. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  129. sizeof (int) * num);
  130. startOffsetInDestBuffer += num;
  131. startSampleInFile += num;
  132. numSamples -= num;
  133. }
  134. else
  135. {
  136. if (startSampleInFile >= (int) lengthInSamples)
  137. {
  138. samplesInReservoir = 0;
  139. }
  140. else if (startSampleInFile < reservoirStart
  141. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  142. {
  143. // had some problems with flac crashing if the read pos is aligned more
  144. // accurately than this. Probably fixed in newer versions of the library, though.
  145. reservoirStart = (int) (startSampleInFile & ~511);
  146. samplesInReservoir = 0;
  147. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  148. }
  149. else
  150. {
  151. reservoirStart += samplesInReservoir;
  152. samplesInReservoir = 0;
  153. FLAC__stream_decoder_process_single (decoder);
  154. }
  155. if (samplesInReservoir == 0)
  156. break;
  157. }
  158. }
  159. if (numSamples > 0)
  160. {
  161. for (int i = numDestChannels; --i >= 0;)
  162. if (destSamples[i] != nullptr)
  163. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  164. }
  165. return true;
  166. }
  167. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  168. {
  169. if (scanningForLength)
  170. {
  171. lengthInSamples += numSamples;
  172. }
  173. else
  174. {
  175. if (numSamples > reservoir.getNumSamples())
  176. reservoir.setSize ((int) numChannels, numSamples, false, false, true);
  177. const unsigned int bitsToShift = 32 - bitsPerSample;
  178. for (int i = 0; i < (int) numChannels; ++i)
  179. {
  180. const FlacNamespace::FLAC__int32* src = buffer[i];
  181. int n = i;
  182. while (src == 0 && n > 0)
  183. src = buffer [--n];
  184. if (src != nullptr)
  185. {
  186. int* const dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  187. for (int j = 0; j < numSamples; ++j)
  188. dest[j] = src[j] << bitsToShift;
  189. }
  190. }
  191. samplesInReservoir = numSamples;
  192. }
  193. }
  194. //==============================================================================
  195. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  196. {
  197. using namespace FlacNamespace;
  198. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  199. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  200. }
  201. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  202. {
  203. using namespace FlacNamespace;
  204. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  205. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  206. }
  207. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  208. {
  209. using namespace FlacNamespace;
  210. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  211. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  212. }
  213. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  214. {
  215. using namespace FlacNamespace;
  216. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  217. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  218. }
  219. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  220. {
  221. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  222. }
  223. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  224. const FlacNamespace::FLAC__Frame* frame,
  225. const FlacNamespace::FLAC__int32* const buffer[],
  226. void* client_data)
  227. {
  228. using namespace FlacNamespace;
  229. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  230. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  231. }
  232. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  233. const FlacNamespace::FLAC__StreamMetadata* metadata,
  234. void* client_data)
  235. {
  236. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  237. }
  238. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  239. {
  240. }
  241. private:
  242. FlacNamespace::FLAC__StreamDecoder* decoder;
  243. AudioSampleBuffer reservoir;
  244. int reservoirStart, samplesInReservoir;
  245. bool ok, scanningForLength;
  246. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  247. };
  248. //==============================================================================
  249. class FlacWriter : public AudioFormatWriter
  250. {
  251. public:
  252. //==============================================================================
  253. FlacWriter (OutputStream* const out, double sampleRate_,
  254. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  255. : AudioFormatWriter (out, TRANS (flacFormatName),
  256. sampleRate_, numChannels_, bitsPerSample_)
  257. {
  258. using namespace FlacNamespace;
  259. encoder = FLAC__stream_encoder_new();
  260. if (qualityOptionIndex > 0)
  261. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  262. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  263. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  264. FLAC__stream_encoder_set_channels (encoder, numChannels);
  265. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  266. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  267. FLAC__stream_encoder_set_blocksize (encoder, 0);
  268. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  269. ok = FLAC__stream_encoder_init_stream (encoder,
  270. encodeWriteCallback, encodeSeekCallback,
  271. encodeTellCallback, encodeMetadataCallback,
  272. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  273. }
  274. ~FlacWriter()
  275. {
  276. if (ok)
  277. {
  278. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  279. output->flush();
  280. }
  281. else
  282. {
  283. output = nullptr; // to stop the base class deleting this, as it needs to be returned
  284. // to the caller of createWriter()
  285. }
  286. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  287. }
  288. //==============================================================================
  289. bool write (const int** samplesToWrite, int numSamples)
  290. {
  291. using namespace FlacNamespace;
  292. if (! ok)
  293. return false;
  294. HeapBlock<int*> channels;
  295. HeapBlock<int> temp;
  296. const int bitsToShift = 32 - bitsPerSample;
  297. if (bitsToShift > 0)
  298. {
  299. temp.malloc (numSamples * numChannels);
  300. channels.calloc (numChannels + 1);
  301. for (unsigned int i = 0; i < numChannels; ++i)
  302. {
  303. if (samplesToWrite[i] == nullptr)
  304. break;
  305. int* const destData = temp.getData() + i * numSamples;
  306. channels[i] = destData;
  307. for (int j = 0; j < numSamples; ++j)
  308. destData[j] = (samplesToWrite[i][j] >> bitsToShift);
  309. }
  310. samplesToWrite = const_cast <const int**> (channels.getData());
  311. }
  312. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  313. }
  314. bool writeData (const void* const data, const int size) const
  315. {
  316. return output->write (data, size);
  317. }
  318. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  319. {
  320. b += bytes;
  321. for (int i = 0; i < bytes; ++i)
  322. {
  323. *(--b) = (FlacNamespace::FLAC__byte) (val & 0xff);
  324. val >>= 8;
  325. }
  326. }
  327. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  328. {
  329. using namespace FlacNamespace;
  330. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  331. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  332. const unsigned int channelsMinus1 = info.channels - 1;
  333. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  334. packUint32 (info.min_blocksize, buffer, 2);
  335. packUint32 (info.max_blocksize, buffer + 2, 2);
  336. packUint32 (info.min_framesize, buffer + 4, 3);
  337. packUint32 (info.max_framesize, buffer + 7, 3);
  338. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  339. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  340. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  341. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  342. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  343. memcpy (buffer + 18, info.md5sum, 16);
  344. const bool seekOk = output->setPosition (4);
  345. (void) seekOk;
  346. // if this fails, you've given it an output stream that can't seek! It needs
  347. // to be able to seek back to write the header
  348. jassert (seekOk);
  349. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  350. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  351. }
  352. //==============================================================================
  353. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  354. const FlacNamespace::FLAC__byte buffer[],
  355. size_t bytes,
  356. unsigned int /*samples*/,
  357. unsigned int /*current_frame*/,
  358. void* client_data)
  359. {
  360. using namespace FlacNamespace;
  361. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  362. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  363. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  364. }
  365. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  366. {
  367. using namespace FlacNamespace;
  368. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  369. }
  370. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  371. {
  372. using namespace FlacNamespace;
  373. if (client_data == nullptr)
  374. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  375. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  376. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  377. }
  378. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  379. {
  380. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  381. }
  382. bool ok;
  383. private:
  384. FlacNamespace::FLAC__StreamEncoder* encoder;
  385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  386. };
  387. //==============================================================================
  388. FlacAudioFormat::FlacAudioFormat()
  389. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  390. {
  391. }
  392. FlacAudioFormat::~FlacAudioFormat()
  393. {
  394. }
  395. Array<int> FlacAudioFormat::getPossibleSampleRates()
  396. {
  397. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000, 0 };
  398. return Array <int> (rates);
  399. }
  400. Array<int> FlacAudioFormat::getPossibleBitDepths()
  401. {
  402. const int depths[] = { 16, 24, 0 };
  403. return Array <int> (depths);
  404. }
  405. bool FlacAudioFormat::canDoStereo() { return true; }
  406. bool FlacAudioFormat::canDoMono() { return true; }
  407. bool FlacAudioFormat::isCompressed() { return true; }
  408. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in, const bool deleteStreamIfOpeningFails)
  409. {
  410. ScopedPointer<FlacReader> r (new FlacReader (in));
  411. if (r->sampleRate > 0)
  412. return r.release();
  413. if (! deleteStreamIfOpeningFails)
  414. r->input = nullptr;
  415. return nullptr;
  416. }
  417. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  418. double sampleRate,
  419. unsigned int numberOfChannels,
  420. int bitsPerSample,
  421. const StringPairArray& /*metadataValues*/,
  422. int qualityOptionIndex)
  423. {
  424. if (getPossibleBitDepths().contains (bitsPerSample))
  425. {
  426. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  427. if (w->ok)
  428. return w.release();
  429. }
  430. return nullptr;
  431. }
  432. StringArray FlacAudioFormat::getQualityOptions()
  433. {
  434. const char* options[] = { "0 (Fastest)", "1", "2", "3", "4", "5 (Default)","6", "7", "8 (Highest quality)", 0 };
  435. return StringArray (options);
  436. }
  437. END_JUCE_NAMESPACE
  438. #endif