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.

593 lines
22KB

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