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.

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