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.

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