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.

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