SampleLibrary.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #include "engine/SampleLibrary.h"
  2. #include "platform/Paths.h"
  3. #include <condition_variable>
  4. #include <mutex>
  5. #include <set>
  6. #include "core/OggVorbis.h"
  7. #include "core/Mp3Decoder.h"
  8. #include "core/TimeStretch.h"
  9. #include "engine/Mp3Format.h"
  10. #include "engine/WavPackFormat.h"
  11. namespace lynx
  12. {
  13. namespace
  14. {
  15. // Decoded samples are shared by every SampleLibrary of the process (the export's engine finds what the open project
  16. // already decoded) and may be loaded from several threads at once (round 112: an open decodes its samples in parallel,
  17. // off the message thread). A path being decoded is waited for, not decoded twice (its stream cache file is written once).
  18. struct SharedCache
  19. {
  20. std::mutex lock;
  21. std::condition_variable done;
  22. std::map<juce::String, std::weak_ptr<const SampleData>> entries;
  23. std::set<juce::String> loading;
  24. // stretched copies (pitch-preserving tempo follow): the latest length per file, kept (shared like the decoded ones)
  25. std::mutex stretchLock;
  26. std::map<juce::String, std::shared_ptr<const SampleData>> stretched;
  27. };
  28. SharedCache& sharedCache()
  29. {
  30. static SharedCache c;
  31. return c;
  32. }
  33. } // namespace
  34. namespace
  35. {
  36. // FL stores many factory samples as WAV whose "data" is an Ogg Vorbis stream
  37. // (format tag 0x674F/0x6750/0x6751, "Og"). JUCE's WAV reader doesn't understand this.
  38. std::unique_ptr<juce::MemoryBlock> extractOggFromWav (const juce::File& file)
  39. {
  40. juce::MemoryBlock bytes;
  41. if (! file.loadFileAsData (bytes) || bytes.getSize() < 12)
  42. return nullptr;
  43. const auto* d = static_cast<const juce::uint8*> (bytes.getData());
  44. if (std::memcmp (d, "RIFF", 4) != 0 || std::memcmp (d + 8, "WAVE", 4) != 0)
  45. return nullptr;
  46. bool isOgg = false;
  47. for (size_t pos = 12; pos + 8 <= bytes.getSize();)
  48. {
  49. const auto size = (size_t) juce::ByteOrder::littleEndianInt (d + pos + 4);
  50. const auto body = pos + 8;
  51. if (std::memcmp (d + pos, "fmt ", 4) == 0 && body + 2 <= bytes.getSize())
  52. {
  53. const auto tag = juce::ByteOrder::littleEndianShort (d + body);
  54. isOgg = tag == 0x674F || tag == 0x6750 || tag == 0x6751;
  55. }
  56. else if (std::memcmp (d + pos, "data", 4) == 0 && isOgg)
  57. {
  58. const auto available = juce::jmin (size, bytes.getSize() - body);
  59. return std::make_unique<juce::MemoryBlock> (d + body, available);
  60. }
  61. pos = body + size + (size & 1);
  62. }
  63. return nullptr;
  64. }
  65. // Serves samples decoded up front (FL-exact Ogg Vorbis, core/OggVorbis.h) through JUCE's reader interface.
  66. class DecodedReader final : public juce::AudioFormatReader
  67. {
  68. public:
  69. explicit DecodedReader (oggvorbis::Decoded d) : juce::AudioFormatReader (nullptr, "Ogg Vorbis (FL)"), decoded (std::move (d))
  70. {
  71. sampleRate = decoded.sampleRate;
  72. bitsPerSample = 32;
  73. usesFloatingPointData = true;
  74. numChannels = (unsigned int) decoded.channels;
  75. lengthInSamples = decoded.data.empty() ? 0 : (juce::int64) decoded.data[0].size();
  76. }
  77. bool readSamples (int* const* destSamples, int numDestChannels, int startOffsetInDestBuffer,
  78. juce::int64 startSampleInFile, int numSamples) override
  79. {
  80. for (int c = 0; c < numDestChannels; ++c)
  81. {
  82. if (destSamples[c] == nullptr)
  83. continue;
  84. auto* dest = reinterpret_cast<float*> (destSamples[c]) + startOffsetInDestBuffer;
  85. if (c >= decoded.channels)
  86. {
  87. std::fill (dest, dest + numSamples, 0.0f);
  88. continue;
  89. }
  90. const auto& src = decoded.data[(size_t) c];
  91. for (int i = 0; i < numSamples; ++i)
  92. {
  93. const auto pos = startSampleInFile + i;
  94. dest[i] = pos >= 0 && pos < (juce::int64) src.size() ? src[(size_t) pos] : 0.0f;
  95. }
  96. }
  97. return true;
  98. }
  99. private:
  100. oggvorbis::Decoded decoded;
  101. };
  102. // FL's Ogg-in-WAV samples and .ogg files, decoded the way FL decodes them (REA_rodada77); null when the file is
  103. // something else or does not decode.
  104. std::unique_ptr<juce::AudioFormatReader> createFlOggReader (const juce::File& file)
  105. {
  106. juce::MemoryBlock head;
  107. if (auto in = file.createInputStream())
  108. in->readIntoMemoryBlock (head, 4096);
  109. const auto* h = static_cast<const std::uint8_t*> (head.getData());
  110. if (! oggvorbis::isOggWav (h, head.getSize()) && ! oggvorbis::isOggStream (h, head.getSize()))
  111. return nullptr;
  112. juce::MemoryBlock bytes;
  113. if (! file.loadFileAsData (bytes))
  114. return nullptr;
  115. oggvorbis::Decoded decoded;
  116. if (! oggvorbis::decode (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), decoded)
  117. || decoded.sampleRate <= 0 || decoded.data.empty() || decoded.data[0].empty())
  118. return nullptr;
  119. return std::make_unique<DecodedReader> (std::move (decoded));
  120. }
  121. } // namespace
  122. SampleLibrary::SampleLibrary()
  123. {
  124. registerAudioFormats (formats); // LYNX's MP3 reader first (round 157b), then JUCE's
  125. formats.registerFormat (new WavPackAudioFormat(), false); // .wv files from FL packs
  126. }
  127. juce::String SampleLibrary::wildcard() const
  128. {
  129. return formats.getWildcardForAllFormats();
  130. }
  131. std::unique_ptr<juce::AudioFormatReader> SampleLibrary::createReader (const juce::File& file)
  132. {
  133. // before JUCE's own Ogg reader (vorbisfile), which drops blocks in many of FL's files (REA_rodada77 §3)
  134. if (auto reader = createFlOggReader (file))
  135. return reader;
  136. if (auto reader = std::unique_ptr<juce::AudioFormatReader> (formats.createReaderFor (file)))
  137. return reader;
  138. // Misleading extension (e.g. an Ogg saved as .wav): try every format by content.
  139. if (auto* reader = formats.createReaderFor (file.createInputStream()))
  140. return std::unique_ptr<juce::AudioFormatReader> (reader);
  141. if (auto ogg = extractOggFromWav (file))
  142. {
  143. juce::OggVorbisAudioFormat vorbis;
  144. // The reader takes ownership of the stream; on failure, JUCE itself deletes the stream.
  145. if (auto* reader = vorbis.createReaderFor (new juce::MemoryInputStream (std::move (*ogg)), true))
  146. return std::unique_ptr<juce::AudioFormatReader> (reader);
  147. }
  148. return nullptr;
  149. }
  150. std::shared_ptr<const SampleData> SampleLibrary::loadStretched (const juce::String& path, double ratio, StretchMethod method)
  151. {
  152. // 10 significant digits: ratios within 0.1 % of 1 are resampled to the exact length, so 4 decimals were too coarse
  153. const auto key = path + "|" + juce::String (ratio, 10) + "|" + juce::String ((int) method);
  154. auto& shared = sharedCache();
  155. {
  156. const std::scoped_lock l (shared.stretchLock);
  157. if (auto it = shared.stretched.find (key); it != shared.stretched.end())
  158. return it->second;
  159. }
  160. auto original = load (path);
  161. if (original == nullptr)
  162. return nullptr;
  163. std::shared_ptr<const SampleData> stretched = timeStretch (*original, ratio, method);
  164. // only one length per file is kept (changing the BPM replaces the stretched one)
  165. const std::scoped_lock l (shared.stretchLock);
  166. for (auto it = shared.stretched.begin(); it != shared.stretched.end();)
  167. it = it->first.startsWith (path + "|") ? shared.stretched.erase (it) : std::next (it);
  168. shared.stretched[key] = stretched;
  169. return stretched;
  170. }
  171. juce::File SampleLibrary::cacheFolder()
  172. {
  173. // (under a test profile, LYNX_PROFILE_DIR: inside it)
  174. const auto profile = platform::profileOverride();
  175. auto folder = (profile != juce::File() ? profile.getChildFile ("cache") : juce::File::getSpecialLocation (juce::File::tempDirectory)).getChildFile ("LYNX-cache");
  176. folder.createDirectory();
  177. return folder;
  178. }
  179. namespace
  180. {
  181. // One cache file per channel: 32-byte header + contiguous float32.
  182. constexpr char cacheMagic[8] = { 'L', 'Y', 'N', 'X', 'P', 'C', 'M', '1' };
  183. constexpr int cacheHeader = 32;
  184. struct Mapped
  185. {
  186. std::unique_ptr<juce::MemoryMappedFile> left, right;
  187. };
  188. bool writeHeader (juce::OutputStream& out, double sampleRate, juce::int64 frames)
  189. {
  190. out.write (cacheMagic, 8);
  191. out.writeDouble (sampleRate);
  192. out.writeInt64 (frames);
  193. out.writeInt64 (0);
  194. return out.getPosition() == cacheHeader;
  195. }
  196. std::unique_ptr<juce::MemoryMappedFile> mapChannel (const juce::File& file, double sampleRate, juce::int64 frames)
  197. {
  198. if (file.getSize() != cacheHeader + frames * (juce::int64) sizeof (float))
  199. return nullptr;
  200. auto mapped = std::make_unique<juce::MemoryMappedFile> (file, juce::MemoryMappedFile::readOnly);
  201. const auto* d = static_cast<const char*> (mapped->getData());
  202. if (d == nullptr || (juce::int64) mapped->getSize() != file.getSize() || std::memcmp (d, cacheMagic, 8) != 0)
  203. return nullptr;
  204. double rate = 0.0;
  205. juce::int64 count = 0;
  206. std::memcpy (&rate, d + 8, 8);
  207. std::memcpy (&count, d + 16, 8);
  208. return rate == sampleRate && count == frames ? std::move (mapped) : nullptr;
  209. }
  210. // Reads one sample per page so the OS brings the range in from disk now (off the audio thread).
  211. float touch (const float* data, std::size_t from, std::size_t to)
  212. {
  213. float sum = 0.0f;
  214. for (auto i = from; i < to; i += 1024)
  215. sum += data[i];
  216. return sum;
  217. }
  218. } // namespace
  219. std::shared_ptr<const SampleData> SampleLibrary::loadStreamed (const juce::File& file, juce::AudioFormatReader& reader)
  220. {
  221. const auto frames = reader.lengthInSamples;
  222. const auto channels = juce::jmin (2, (int) reader.numChannels);
  223. const auto key = juce::String::toHexString ((file.getFullPathName() + "|" + juce::String (file.getSize()) + "|"
  224. + juce::String (file.getLastModificationTime().toMilliseconds())
  225. // the decoder too: a file read by another one is decoded again
  226. + (reader.getFormatName() == Mp3AudioFormat::formatName ? juce::String ("|") + mp3::decoderId : juce::String()))
  227. .hashCode64());
  228. const auto leftFile = cacheFolder().getChildFile (key + ".L.pcm");
  229. const auto rightFile = cacheFolder().getChildFile (key + ".R.pcm");
  230. auto mapped = std::make_shared<Mapped>();
  231. mapped->left = mapChannel (leftFile, reader.sampleRate, frames);
  232. mapped->right = channels > 1 ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
  233. if (mapped->left == nullptr || (channels > 1 && mapped->right == nullptr))
  234. {
  235. // decode once, in chunks, straight into the cache files
  236. leftFile.deleteFile();
  237. rightFile.deleteFile();
  238. {
  239. juce::FileOutputStream outL (leftFile);
  240. std::unique_ptr<juce::FileOutputStream> outR;
  241. if (channels > 1)
  242. outR = std::make_unique<juce::FileOutputStream> (rightFile);
  243. if (outL.failedToOpen() || (outR != nullptr && outR->failedToOpen()) || ! writeHeader (outL, reader.sampleRate, frames)
  244. || (outR != nullptr && ! writeHeader (*outR, reader.sampleRate, frames)))
  245. return nullptr;
  246. constexpr int block = 1 << 16;
  247. juce::AudioBuffer<float> buffer (channels, block);
  248. for (juce::int64 done = 0; done < frames; done += block)
  249. {
  250. const auto n = (int) juce::jmin<juce::int64> (block, frames - done);
  251. reader.read (&buffer, 0, n, done, true, channels > 1);
  252. outL.write (buffer.getReadPointer (0), (size_t) n * sizeof (float));
  253. if (outR != nullptr)
  254. outR->write (buffer.getReadPointer (1), (size_t) n * sizeof (float));
  255. }
  256. outL.flush();
  257. if (outR != nullptr)
  258. outR->flush();
  259. }
  260. mapped->left = mapChannel (leftFile, reader.sampleRate, frames);
  261. mapped->right = channels > 1 ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
  262. if (mapped->left == nullptr || (channels > 1 && mapped->right == nullptr))
  263. return nullptr;
  264. }
  265. auto data = std::make_shared<SampleData>();
  266. data->sampleRate = reader.sampleRate;
  267. data->mappedFrames = (std::size_t) frames;
  268. data->mappedLeft = reinterpret_cast<const float*> (static_cast<const char*> (mapped->left->getData()) + cacheHeader);
  269. data->mappedRight = mapped->right != nullptr
  270. ? reinterpret_cast<const float*> (static_cast<const char*> (mapped->right->getData()) + cacheHeader)
  271. : nullptr;
  272. data->mapping = mapped;
  273. // the first seconds already in memory: the clip start doesn't wait for the disk
  274. const auto head = juce::jmin ((std::size_t) frames, (std::size_t) (reader.sampleRate * 3.0));
  275. volatile float sink = touch (data->leftData(), 0, head) + touch (data->rightData(), 0, head);
  276. juce::ignoreUnused (sink);
  277. return data;
  278. }
  279. void prefetchSample (const SampleData& data, double fromSeconds, double toSeconds)
  280. {
  281. if (! data.isMapped())
  282. return;
  283. const auto from = (std::size_t) juce::jlimit (0.0, (double) data.frames(), fromSeconds * data.sampleRate);
  284. const auto to = (std::size_t) juce::jlimit (0.0, (double) data.frames(), toSeconds * data.sampleRate);
  285. volatile float sink = touch (data.leftData(), from, to) + (data.isStereo() ? touch (data.rightData(), from, to) : 0.0f);
  286. juce::ignoreUnused (sink);
  287. }
  288. void SampleLibrary::forget (const juce::String& path)
  289. {
  290. auto& shared = sharedCache();
  291. {
  292. const std::scoped_lock l (shared.lock);
  293. shared.entries.erase (path);
  294. }
  295. const std::scoped_lock l (shared.stretchLock);
  296. for (auto it = shared.stretched.begin(); it != shared.stretched.end();)
  297. it = it->first.startsWith (path + "|") ? shared.stretched.erase (it) : std::next (it);
  298. }
  299. std::shared_ptr<const SampleData> SampleLibrary::load (const juce::String& path)
  300. {
  301. auto& shared = sharedCache();
  302. {
  303. std::unique_lock l (shared.lock);
  304. for (;;)
  305. {
  306. if (const auto it = shared.entries.find (path); it != shared.entries.end())
  307. if (auto cached = it->second.lock())
  308. return cached;
  309. if (shared.loading.count (path) == 0)
  310. break;
  311. shared.done.wait (l);
  312. }
  313. shared.loading.insert (path);
  314. }
  315. auto data = decode (path);
  316. {
  317. const std::scoped_lock l (shared.lock);
  318. shared.loading.erase (path);
  319. if (data != nullptr)
  320. shared.entries[path] = data;
  321. }
  322. shared.done.notify_all();
  323. return data;
  324. }
  325. std::shared_ptr<const SampleData> SampleLibrary::findLoaded (const juce::String& path)
  326. {
  327. auto& shared = sharedCache();
  328. const std::scoped_lock l (shared.lock);
  329. if (const auto it = shared.entries.find (path); it != shared.entries.end())
  330. return it->second.lock();
  331. return nullptr;
  332. }
  333. std::shared_ptr<const SampleData> SampleLibrary::decode (const juce::String& path)
  334. {
  335. const auto file = platform::localFile (path); // FL's Windows spelling on macOS/Linux (platform/Paths.h)
  336. if (! file.existsAsFile())
  337. return nullptr;
  338. auto reader = createReader (file);
  339. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->numChannels == 0)
  340. return nullptr;
  341. if ((double) reader->lengthInSamples > reader->sampleRate * streamAboveSeconds)
  342. if (auto streamed = loadStreamed (file, *reader))
  343. return streamed;
  344. // In memory: 10-minute safety limit (long ones go through the disk cache).
  345. const auto frames = (int) juce::jmin<juce::int64> (reader->lengthInSamples, (juce::int64) (reader->sampleRate * 600.0));
  346. const auto channels = juce::jmin (2, (int) reader->numChannels);
  347. juce::AudioBuffer<float> buffer (channels, frames);
  348. reader->read (&buffer, 0, frames, 0, true, channels > 1);
  349. auto data = std::make_shared<SampleData>();
  350. data->sampleRate = reader->sampleRate;
  351. data->left.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + frames);
  352. // the file's own loop (WAV smpl, first loop; JUCE gives the end frame inclusive)
  353. {
  354. const auto& meta = reader->metadataValues;
  355. if (meta.getValue ("NumSampleLoops", "0").getIntValue() > 0)
  356. {
  357. const auto start = meta.getValue ("Loop0Start", "-1").getLargeIntValue();
  358. const auto end = meta.getValue ("Loop0End", "-1").getLargeIntValue() + 1;
  359. if (start >= 0 && end > start && end <= frames)
  360. data->loopStart = start, data->loopEnd = end;
  361. }
  362. }
  363. if (channels > 1)
  364. data->right.assign (buffer.getReadPointer (1), buffer.getReadPointer (1) + frames);
  365. return data;
  366. }
  367. } // namespace lynx