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.

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