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.

549 lines
21KB

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