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.

619 lines
22KB

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