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.

603 lines
22KB

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