SampleLibrary.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #pragma once
  2. #include <map>
  3. #include <functional>
  4. #include <memory>
  5. #include <mutex>
  6. #include <juce_audio_formats/juce_audio_formats.h>
  7. #include "core/CacheCheck.h"
  8. #include "core/Instruments.h"
  9. #include "core/TimeStretch.h"
  10. namespace lynx
  11. {
  12. // Decodes audio files into SampleData, cached by path (one cache for the whole process).
  13. // Any thread except the audio thread.
  14. class SampleLibrary
  15. {
  16. public:
  17. SampleLibrary();
  18. std::shared_ptr<const SampleData> load (const juce::String& path);
  19. // The sample when something already holds it loaded (nullptr otherwise): never reads the file (round 149: the
  20. // stream prefetcher looked its clips up with load(), which decoded again every audio clip whose channel plays a
  21. // time-stretched copy, seconds on every edit of a song with many of them)
  22. std::shared_ptr<const SampleData> findLoaded (const juce::String& path);
  23. // The file changed on disk (the audio editor saved over it): the next load() reads it again.
  24. void forget (const juce::String& path);
  25. // the same for the process's one cache, without a library (round 190tg: a cache file that failed its check)
  26. static void forgetShared (const juce::String& path);
  27. // The sample time-stretched without changing pitch (core/TimeStretch), cached by (path, ratio, method).
  28. // `map` (round 175a, warp markers): stretched along that warp map instead of at one ratio (its own cache entries).
  29. std::shared_ptr<const SampleData> loadStretched (const juce::String& path, double ratio, StretchMethod method = StretchMethod::general,
  30. double semitones = 0.0, // semitones: Beats only (core/TimeStretch)
  31. const StretchMap& map = {}, const StretchOptions& options = {});
  32. // A channel's precomputed span (its region after its precomputed effects and Trim, core/SamplePrecompute.h) stretched
  33. // by `ratio` (core/TimeStretch timeStretchSpan), cached in memory by (path, variantKey, ratio, method): FL stretches
  34. // that span to TIME, not the whole file (round 180d). Dropped with the file's other unused lengths.
  35. std::shared_ptr<const SampleData> loadStretchedSpan (const juce::String& path, const std::string& variantKey,
  36. const std::shared_ptr<const SampleData>& span, double ratio,
  37. StretchMethod method = StretchMethod::general, double semitones = 0.0,
  38. const StretchOptions& options = {});
  39. // Above this, audio goes to a memory-mapped disk cache instead of staying entirely
  40. // in RAM ("disk streaming"). The cache is reused across sessions.
  41. static constexpr double streamAboveSeconds = 30.0;
  42. static juce::File cacheFolder();
  43. // The decoded copies (*.pcm) above `limitBytes`: the least recently used are deleted down to 3/4 of it (round 167e;
  44. // done once per session in the background). Returns the bytes left.
  45. static juce::int64 prunePcmCache (juce::int64 limitBytes);
  46. // Round 190tg (the caches' integrity check, core/CacheCheck.h): a decoded copy (*.pcm) found again on disk is checked in
  47. // full in the background once the project has opened (reading it whole at once cost seconds on a hard disk when it
  48. // was not in the system's memory any more; the open only checks its header and size). A copy that fails is logged and
  49. // marked, and the next load decodes the file again. `inline` true: checked in full before load() returns (--export,
  50. // tests: a render that must be exact). The stretched copies (*.str) are always checked before they are used.
  51. static void setInlineCacheChecks (bool checkInline) noexcept;
  52. // Waits (at most `timeoutMs`) for the background checks; true when none is left
  53. static bool waitForCacheChecks (int timeoutMs);
  54. // What the app does with a sample whose decoded copy failed the background check, once it is decoded again (`fresh`,
  55. // held until the call returns): AudioEngine swaps it in where it plays and logs it. Called on the checker thread.
  56. using DamagedHandler = std::function<void (const juce::String& path, const std::string& cacheFile, cachecheck::Verdict why,
  57. std::shared_ptr<const SampleData> fresh)>;
  58. static void setDamagedHandler (DamagedHandler handler);
  59. // What the decoded samples of the process hold now (round 190gd: the load log says where a project's megabytes go):
  60. // samples in RAM (float, both channels) and mapped from the disk cache, and the time-stretched copies kept
  61. struct MemoryUse
  62. {
  63. int samples = 0, mappedSamples = 0, stretched = 0;
  64. std::int64_t sampleBytes = 0, mappedBytes = 0, stretchedBytes = 0;
  65. // round 190gn (A2): the stretched copies mapped from the disk cache (locked in RAM: not the process's memory)
  66. int stretchedMapped = 0;
  67. std::int64_t stretchedMappedBytes = 0;
  68. };
  69. static MemoryUse memoryUse();
  70. // the bytes of the mapped stretched copies that are resident and locked right now (-1: can't tell); the load log
  71. // shows it next to stretchedMappedBytes: equal = no page of them can fault on the audio thread
  72. static std::int64_t lockedStretchedBytes();
  73. // Filter for FileChooser ("*.wav;*.flac;...")
  74. juce::String wildcard() const;
  75. // The audio files LYNX loads as samples (core/SampleFiles.h: wav, aif(f), flac, ogg, mp3 and FL's WavPack .wv).
  76. // Every drop target (Channel Rack, Playlist, Audio editor...) asks this, so they all take what the Browser lists.
  77. static bool isSampleFile (const juce::File& file);
  78. // The file's first `seconds` mixed to mono, read straight from the file: nothing is cached or kept (round 190as:
  79. // the Browser's "Find similar samples" analyses whole folders with it). False when the file can't be read.
  80. bool readMono (const juce::File& file, double seconds, std::vector<float>& mono, double& sampleRate);
  81. // Round 190kx (loop analysis, core/LoopAnalysis.h): readMono into `out` (mono, its rate, the WAV's ACID beats as a
  82. // load reads them) and the whole file's length in seconds (`totalSeconds`, also when only the first `seconds` are
  83. // read). Nothing is cached or kept. False when the file can't be read.
  84. bool readForAnalysis (const juce::File& file, double seconds, SampleData& out, double& totalSeconds);
  85. // Issue #193 (round als190ka): a video file's sound track (a Live set's video clips play their sound as audio
  86. // clips). The engine cannot decode video itself; the app hands it the system's decoder (ui/VideoMedia), which writes
  87. // the sound to a WAV in the cache and returns it (a non-existent file: no sound / no decoder). Set once at start-up.
  88. using VideoSoundDecoder = juce::File (*) (const juce::File& video);
  89. static void setVideoSoundDecoder (VideoSoundDecoder decoder) noexcept;
  90. private:
  91. std::unique_ptr<juce::AudioFormatReader> createReader (const juce::File& file);
  92. std::shared_ptr<const SampleData> loadStreamed (const juce::File& file, juce::AudioFormatReader& reader);
  93. std::shared_ptr<const SampleData> decode (const juce::String& path);
  94. juce::AudioFormatManager formats;
  95. };
  96. // Brings in from disk the range [from, to) (seconds) of a mapped sample. Any thread except the audio thread.
  97. void prefetchSample (const SampleData& data, double fromSeconds, double toSeconds);
  98. } // namespace lynx