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.

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