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.

546 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) override
  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. FlacWriter (OutputStream* const out, double rate, uint32 numChans, uint32 bits, int qualityOptionIndex)
  259. : AudioFormatWriter (out, TRANS (flacFormatName), rate, numChans, bits)
  260. {
  261. using namespace FlacNamespace;
  262. encoder = FLAC__stream_encoder_new();
  263. if (qualityOptionIndex > 0)
  264. FLAC__stream_encoder_set_compression_level (encoder, (uint32) jmin (8, qualityOptionIndex));
  265. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  266. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  267. FLAC__stream_encoder_set_channels (encoder, numChannels);
  268. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  269. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  270. FLAC__stream_encoder_set_blocksize (encoder, 0);
  271. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  272. ok = FLAC__stream_encoder_init_stream (encoder,
  273. encodeWriteCallback, encodeSeekCallback,
  274. encodeTellCallback, encodeMetadataCallback,
  275. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  276. }
  277. ~FlacWriter()
  278. {
  279. if (ok)
  280. {
  281. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  282. output->flush();
  283. }
  284. else
  285. {
  286. output = nullptr; // to stop the base class deleting this, as it needs to be returned
  287. // to the caller of createWriter()
  288. }
  289. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  290. }
  291. //==============================================================================
  292. bool write (const int** samplesToWrite, int numSamples) override
  293. {
  294. using namespace FlacNamespace;
  295. if (! ok)
  296. return false;
  297. HeapBlock<int*> channels;
  298. HeapBlock<int> temp;
  299. const int bitsToShift = 32 - (int) bitsPerSample;
  300. if (bitsToShift > 0)
  301. {
  302. temp.malloc (numChannels * (size_t) numSamples);
  303. channels.calloc (numChannels + 1);
  304. for (unsigned int i = 0; i < numChannels; ++i)
  305. {
  306. if (samplesToWrite[i] == nullptr)
  307. break;
  308. int* const destData = temp.getData() + i * (size_t) numSamples;
  309. channels[i] = destData;
  310. for (int j = 0; j < numSamples; ++j)
  311. destData[j] = (samplesToWrite[i][j] >> bitsToShift);
  312. }
  313. samplesToWrite = const_cast<const int**> (channels.getData());
  314. }
  315. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, (size_t) numSamples) != 0;
  316. }
  317. bool writeData (const void* const data, const int size) const
  318. {
  319. return output->write (data, (size_t) size);
  320. }
  321. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  322. {
  323. b += bytes;
  324. for (int i = 0; i < bytes; ++i)
  325. {
  326. *(--b) = (FlacNamespace::FLAC__byte) (val & 0xff);
  327. val >>= 8;
  328. }
  329. }
  330. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  331. {
  332. using namespace FlacNamespace;
  333. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  334. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  335. const unsigned int channelsMinus1 = info.channels - 1;
  336. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  337. packUint32 (info.min_blocksize, buffer, 2);
  338. packUint32 (info.max_blocksize, buffer + 2, 2);
  339. packUint32 (info.min_framesize, buffer + 4, 3);
  340. packUint32 (info.max_framesize, buffer + 7, 3);
  341. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  342. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  343. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  344. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  345. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  346. memcpy (buffer + 18, info.md5sum, 16);
  347. const bool seekOk = output->setPosition (4);
  348. (void) seekOk;
  349. // if this fails, you've given it an output stream that can't seek! It needs
  350. // to be able to seek back to write the header
  351. jassert (seekOk);
  352. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  353. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  354. }
  355. //==============================================================================
  356. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  357. const FlacNamespace::FLAC__byte buffer[],
  358. size_t bytes,
  359. unsigned int /*samples*/,
  360. unsigned int /*current_frame*/,
  361. void* client_data)
  362. {
  363. using namespace FlacNamespace;
  364. return static_cast<FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  365. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  366. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  367. }
  368. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  369. {
  370. using namespace FlacNamespace;
  371. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  372. }
  373. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  374. {
  375. using namespace FlacNamespace;
  376. if (client_data == nullptr)
  377. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  378. *absolute_byte_offset = (FLAC__uint64) static_cast<FlacWriter*> (client_data)->output->getPosition();
  379. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  380. }
  381. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  382. {
  383. static_cast<FlacWriter*> (client_data)->writeMetaData (metadata);
  384. }
  385. bool ok;
  386. private:
  387. FlacNamespace::FLAC__StreamEncoder* encoder;
  388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter)
  389. };
  390. //==============================================================================
  391. FlacAudioFormat::FlacAudioFormat()
  392. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  393. {
  394. }
  395. FlacAudioFormat::~FlacAudioFormat()
  396. {
  397. }
  398. Array<int> FlacAudioFormat::getPossibleSampleRates()
  399. {
  400. const int rates[] = { 8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000,
  401. 88200, 96000, 176400, 192000, 352800, 384000 };
  402. return Array<int> (rates, numElementsInArray (rates));
  403. }
  404. Array<int> FlacAudioFormat::getPossibleBitDepths()
  405. {
  406. const int depths[] = { 16, 24 };
  407. return Array<int> (depths, numElementsInArray (depths));
  408. }
  409. bool FlacAudioFormat::canDoStereo() { return true; }
  410. bool FlacAudioFormat::canDoMono() { return true; }
  411. bool FlacAudioFormat::isCompressed() { return true; }
  412. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in, const bool deleteStreamIfOpeningFails)
  413. {
  414. ScopedPointer<FlacReader> r (new FlacReader (in));
  415. if (r->sampleRate > 0)
  416. return r.release();
  417. if (! deleteStreamIfOpeningFails)
  418. r->input = nullptr;
  419. return nullptr;
  420. }
  421. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  422. double sampleRate,
  423. unsigned int numberOfChannels,
  424. int bitsPerSample,
  425. const StringPairArray& /*metadataValues*/,
  426. int qualityOptionIndex)
  427. {
  428. if (getPossibleBitDepths().contains (bitsPerSample))
  429. {
  430. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels,
  431. (uint32) bitsPerSample, qualityOptionIndex));
  432. if (w->ok)
  433. return w.release();
  434. }
  435. return nullptr;
  436. }
  437. StringArray FlacAudioFormat::getQualityOptions()
  438. {
  439. const char* options[] = { "0 (Fastest)", "1", "2", "3", "4", "5 (Default)","6", "7", "8 (Highest quality)", 0 };
  440. return StringArray (options);
  441. }
  442. #endif