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.

557 lines
21KB

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