SampleLibrary.cpp 15 KB

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