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.

600 lines
22KB

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