Просмотр исходного кода

Cache check: a decoded sample found damaged after the open is decoded again and swapped in now, in every channel that plays it, on the message thread; logged "was damaged (...); rebuilt and reloaded (N channels)" (round 190tg)

The coordinator (30 Nov): the damaged copy must not keep playing for the rest of the session. The background check
decodes the sample again itself (new files where Windows still holds the old ones), holds the new copy and posts the
swap to the message thread: AudioEngine::reloadSampleEverywhere forgets the sample and makes each channel that plays it
(its file or a zone of it) a new instrument at the rack build that follows, the publish a sample change makes. An ARA
channel's plugin keeps the audio it read itself: the log says it can't be swapped. Stretched copies made from a sample
whose check is still running are written to disk only once it passes (a failed one drops them).
--cachecheck190tgtest: an engine's sampler channel plays a damaged copy; it is found, logged, swapped, the engine lets
the damaged copy go and plays the fresh one bit for bit.

(cherry picked from commit b15f43487ef10b6703aa60eddac5f3f7a07ef56d)
Ka1-S 5 дней назад
Родитель
Сommit
8a08babffd

+ 46 - 11
src/CacheCheck190tgCheck.inc

@@ -211,7 +211,7 @@
         }
 
         // --- the decoded copies' check after the open (the app's way: load() checks the header and size; the samples are
-        // checked on the checker thread, a damaged copy is marked and the next load decodes the file again) -------------
+        // checked on the checker thread; a damaged copy is decoded again and swapped in where it plays) -------------
         {
             SampleLibrary::setInlineCacheChecks (false);
             const auto wav = writeWav ("later 190tg.wav", 2, 44100 * 32);
@@ -239,28 +239,63 @@
             library.forget (path);
             check ("after the open: a clean copy is mapped again, checked in the background, nothing logged",
                    ! fresh.empty() && read == fresh && idle && cachecheck::rebuiltCount() == before);
-            const auto flipped = left != juce::File() && flipByte (left, left.getSize() / 2, 0x40);
-            before = cachecheck::rebuiltCount();
-            bool loadedAtOnce = false;
+            // the swap where it plays (the coordinator, 30 Nov): a sampler channel of an engine plays the sample; its decoded
+            // copy is damaged; the check after the open finds it, decodes it again, and the message thread swaps the new copy
+            // into the channel (AudioEngine::reloadSampleEverywhere), logged "was damaged (...); rebuilt and reloaded"
             {
-                const auto again = library.load (path); // (the open does not read the samples: the flip is not seen yet)
-                loadedAtOnce = again != nullptr;
+                AudioEngine engine (false);
+                auto song = Song::makeDefault();
+                song.channels.edit()[0].instrument = InstrumentKind::sampler;
+                song.channels.edit()[0].samplePath = path.toStdString();
+                engine.setSong (song);
+                SampleLibrary::waitForCacheChecks (60000);
+                engine.setSong (Song::makeDefault()); // (nothing holds the copy: the file can be changed, also on Windows)
+                library.forget (path);
+                const auto flipped = left != juce::File() && flipByte (left, left.getSize() / 2, 0x40);
+                before = cachecheck::rebuiltCount();
+                engine.setSong (song); // (the open: header and size checked, the samples later)
+                auto playing = library.findLoaded (path);
+                const auto damagedNow = playing != nullptr && samplesOf (*playing) != fresh;
                 const auto done = SampleLibrary::waitForCacheChecks (60000);
-                check ("after the open: a flipped bit is found by the background check, logged once, the file marked",
-                       flipped && loadedAtOnce && done && cachecheck::rebuiltCount() == before + 1
-                           && juce::String (cachecheck::lastReport()).contains (left.getFileName()));
+                const auto pump = [] (int ms, const std::function<bool()>& until) {
+                    const auto start = juce::Time::getMillisecondCounter();
+                    while (juce::Time::getMillisecondCounter() - start < (juce::uint32) ms && ! until())
+                    {
+#if JUCE_LINUX || JUCE_WINDOWS
+                        for (int i = 0; i < 256 && juce::detail::dispatchNextMessageOnSystemQueue (true); ++i) {}
+#elif JUCE_MAC
+                        for (int i = 0; i < 256 && CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource; ++i) {}
+#endif
+                        juce::Thread::sleep (5);
+                    }
+                };
+                pump (60000, [before] { return cachecheck::rebuiltCount() > before; });
+                const auto line = juce::String (cachecheck::lastReport());
+                const auto now = library.findLoaded (path);
+                check ("after the open: the damaged copy that plays (" + juce::String (damagedNow ? "damaged" : "NOT damaged") + ") is found by the background check: \""
+                           + line.fromFirstOccurrenceOf ("was damaged", true, false) + "\"",
+                       flipped && damagedNow && done && cachecheck::rebuiltCount() == before + 1 && line.contains (left.getFileName())
+                           && line.contains ("was damaged (its content hash does not match") && line.contains ("rebuilt and reloaded (1 channel)"));
+                // the damaged copy is let go by the engine (its rack holds the new one): nothing but this check holds it
+                std::weak_ptr<const SampleData> old = playing;
+                const auto oldPtr = playing.get();
+                playing.reset();
+                pump (5000, [&old, &engine] { engine.dispatchPendingMessages(); return old.expired(); });
+                check ("after the open: the channel now plays the copy decoded again, bit for bit the fresh one; the engine let the damaged one go",
+                       now != nullptr && now.get() != oldPtr && samplesOf (*now) == fresh && old.expired());
             }
             library.forget (path);
+            // the next load (nothing holds the old copy now; on Windows the damaged file goes only now) and its files
             read.clear();
             {
-                const auto again = library.load (path); // (the next load decodes again)
+                const auto again = library.load (path);
                 if (again != nullptr)
                     read = samplesOf (*again);
             }
             SampleLibrary::waitForCacheChecks (60000);
             library.forget (path);
             juce::MemoryBlock b;
-            check ("after the open: the next load decodes the file again, bit for bit the fresh one, a valid file, nothing more logged",
+            check ("after the open: a later load is bit for bit the fresh one, from a valid file, nothing more logged, no marker left",
                    read == fresh && cachecheck::rebuiltCount() == before + 1 && left.loadFileAsData (b)
                        && cachecheck::pcm::verify (b.getData(), b.getSize(), 44100.0, (std::int64_t) (fresh.size() / 2)) == cachecheck::Verdict::ok
                        && ! left.getSiblingFile (left.getFileName() + ".bad").exists());

+ 18 - 1
src/core/CacheCheck.cpp

@@ -83,10 +83,26 @@ void setLogFile (const std::string& path)
     logFile = path;
 }
 
+namespace
+{
+void logLine (const std::string& line);
+}
+
 void reportRebuilt (const std::string& file, Verdict why)
+{
+    logLine ("cache file " + file + " failed its check (" + describe (why) + ") and was rebuilt");
+}
+
+void reportDamaged (const std::string& file, Verdict why, const std::string& outcome)
+{
+    logLine ("cache file " + file + " was damaged (" + describe (why) + "); " + outcome);
+}
+
+namespace
+{
+void logLine (const std::string& line)
 {
     ++rebuilt;
-    const auto line = "cache file " + file + " failed its check (" + describe (why) + ") and was rebuilt";
     std::fprintf (stderr, "LYNX: %s\n", line.c_str());
     const std::lock_guard<std::mutex> l (logLock);
     lastLine = line;
@@ -110,6 +126,7 @@ void reportRebuilt (const std::string& file, Verdict why)
     std::ofstream out (path, std::ios::binary | std::ios::app);
     out << line << "\n";
 }
+} // namespace
 
 int rebuiltCount() noexcept
 {

+ 3 - 0
src/core/CacheCheck.h

@@ -65,6 +65,9 @@ const char* describe (Verdict v) noexcept;
 // stderr and, once the app named one (setLogFile), appended to that file (kept under 64 KB, the newest lines).
 void setLogFile (const std::string& path);
 void reportRebuilt (const std::string& file, Verdict why);
+// A file found damaged later (the decoded samples' check after the open) and what was done:
+// "cache file <path> was damaged (<why>); <outcome>"
+void reportDamaged (const std::string& file, Verdict why, const std::string& outcome);
 // How many files failed since start (the self-test counts them)
 int rebuiltCount() noexcept;
 std::string lastReport();

+ 102 - 0
src/engine/AudioEngine.cpp

@@ -56,6 +56,8 @@
 
 #include <limits>
 #include <map>
+#include <mutex>
+#include <set>
 #include <thread>
 #if defined(__GLIBC__)
  #include <malloc.h>
@@ -661,6 +663,68 @@ namespace
 std::atomic<const AudioEngine*> pluginHoldOwner { nullptr };
 } // namespace
 
+// Round 190tg: the engines alive now (the message thread reloads a damaged decoded sample in each) and the library's handler
+// that does it (SampleLibrary::setDamagedHandler), installed with the first engine
+void liveEngines190tg (AudioEngine* engine, bool add);
+namespace
+{
+std::mutex& liveEnginesLock()
+{
+    static std::mutex m;
+    return m;
+}
+std::set<AudioEngine*>& liveEnginesSet()
+{
+    static std::set<AudioEngine*> s;
+    return s;
+}
+} // namespace
+
+void liveEngines190tg (AudioEngine* engine, bool add)
+{
+    {
+        const std::scoped_lock l (liveEnginesLock());
+        if (add)
+            liveEnginesSet().insert (engine);
+        else
+            liveEnginesSet().erase (engine);
+    }
+    static std::once_flag installed;
+    if (add)
+        std::call_once (installed, [] {
+            SampleLibrary::setDamagedHandler ([] (const juce::String& path, const std::string& file, cachecheck::Verdict why,
+                                                 std::shared_ptr<const SampleData> fresh) {
+                const auto swap = [path, file, why, fresh] {
+                    int channels = 0;
+                    bool araKept = false;
+                    std::vector<AudioEngine*> engines;
+                    {
+                        const std::scoped_lock l (liveEnginesLock());
+                        engines.assign (liveEnginesSet().begin(), liveEnginesSet().end());
+                    }
+                    for (auto* e : engines) // (engines are made and destroyed on the message thread, where this runs)
+                    {
+                        bool alive = false;
+                        {
+                            const std::scoped_lock l (liveEnginesLock());
+                            alive = liveEnginesSet().count (e) > 0;
+                        }
+                        if (alive)
+                            channels += e->reloadSampleEverywhere (path, araKept);
+                    }
+                    std::string outcome = channels > 0 ? "rebuilt and reloaded (" + std::to_string (channels) + (channels == 1 ? " channel)" : " channels)")
+                                                       : std::string ("rebuilt (no channel plays it now)");
+                    if (araKept)
+                        outcome += "; an ARA plugin keeps the audio it read itself and can't be swapped: it is right from the project's next open";
+                    cachecheck::reportDamaged (file, why, outcome);
+                    juce::ignoreUnused (fresh); // (held until the reload's rack build found it decoded)
+                };
+                if (! juce::MessageManager::callAsync (swap))
+                    cachecheck::reportDamaged (file, why, "rebuilt; no message thread to swap it in: it plays from the next load");
+            });
+        });
+}
+
 AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPluginList, bool deferDeviceOpen)
     // (an engine without an audio device renders offline — exports, bounces, freezes: its workers run below normal
     // priority as FL's export threads do, rollup 0.1.28 / REA 190hb; the live engine's workers get the audio priority)
@@ -670,6 +734,7 @@ AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPlug
       plugins (userPluginList),
       song (Song::makeDefault())
 {
+    liveEngines190tg (this, true); // (round 190tg: a damaged decoded sample found after the open is reloaded here too)
     // Harmor's resynthesis (round natives190kj): the sample a part names, found as FL finds it (path variables, then the
     // file re-rooted to this PC's FL folders) and decoded by the core (WAV, FL's Ogg-in-WAV, Ogg Vorbis, WavPack)
     flStudioAccess(); // (round 190rh: found now, so FL's engine data is read from where FL is: core/NativeData.h)
@@ -830,6 +895,7 @@ AudioLogger& AudioEngine::getAudioLogger()
 
 AudioEngine::~AudioEngine()
 {
+    liveEngines190tg (this, false); // (round 190tg: no damaged-sample reload reaches it any more)
     // round 190rn: with LYNX_TRACE_STARTUP the engine's part of a quit is in startup.log (where a slow quit's time goes)
     static const bool traceQuit = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
     const auto mark = [] (const char* step) { if (traceQuit && startupMark != nullptr) startupMark (step); };
@@ -3713,6 +3779,42 @@ void AudioEngine::setLinkStartStopSync (bool on)
     setMidiPrefs (p);
 }
 
+int AudioEngine::reloadSampleEverywhere (const juce::String& path, bool& araKept)
+{
+    // Round 190tg: the sample's decoded copy on disk was damaged (SampleLibrary's check after the open); it is decoded
+    // again already. Every channel that plays the file gets a new instrument at the next rack build, as a channel whose
+    // sample changed does (its record in the last rack is made unlike it), so the rack swap that follows plays the new
+    // copy, glitch-free like any rack change. An ARA channel's plugin keeps the audio it read itself: not swapped.
+    const auto p = path.toStdString();
+    const auto uses = [&p] (const ChannelDef& c) {
+        if (c.samplePath == p)
+            return true;
+        for (const auto& z : c.zones)
+            if (z.path == p)
+                return true;
+        return false;
+    };
+    int count = 0;
+    for (const auto& c : song.channels)
+        if (uses (c))
+        {
+            ++count;
+            araKept = araKept || c.ara.active();
+        }
+    if (count == 0)
+        return 0;
+    samples.forget (path);
+    auto& last = lastPublishedShape.song.channels.edit();
+    for (auto& c : last)
+        if (uses (c))
+        {
+            c.samplePath.clear();
+            c.instrument = InstrumentKind::patcher; // (never reused: another instrument is made)
+        }
+    publishSong();
+    return count;
+}
+
 int AudioEngine::restretchAll()
 {
     // (round 190mp) the file read again and its stretched copies dropped, then the rack built anew: the copies come from

+ 4 - 0
src/engine/AudioEngine.h

@@ -972,6 +972,10 @@ public:
     // FL's Channel rack "Restretch all" (round 190mp, DE-38; FLEngine FUN_00fe7510): every channel that plays a copy stretched
     // ahead of time (pitch kept, a length in beats) is stretched again from its file now. Returns how many channels.
     int restretchAll();
+    // Round 190tg: a sample whose decoded copy on disk failed the check after the open is swapped in anew (it is decoded
+    // again already) in every channel that plays it: returns how many; `araKept` is set when one of them is an ARA channel,
+    // whose plugin keeps the audio it read itself. Message thread.
+    int reloadSampleEverywhere (const juce::String& path, bool& araKept);
     // FL's tempo menu "Half speed" (round 190mp, DF-16; capture 190mp A4): playback at half the tempo, the tempo shown and
     // saved unchanged; a temporary state (not saved, exports play at the normal speed)
     void setHalfSpeed (bool on) noexcept { transport.playSpeed.store (on ? 0.5 : 1.0, std::memory_order_relaxed); }

+ 98 - 7
src/engine/SampleLibrary.cpp

@@ -13,6 +13,8 @@
 #include <condition_variable>
 #include <cstring>
 #include <mutex>
+#include <functional>
+#include <map>
 #include <set>
 
 #include "core/AudioEdit.h"
@@ -720,7 +722,26 @@ juce::ThreadPool& cacheWriter()
     return *writer;
 }
 
-void writeStretchedLater (const juce::File& file, std::shared_ptr<const SampleData> data)
+// Round 190tg: a stretched copy made from a sample whose decoded copy on disk is still waiting for its check after the open
+// (checkPcmLater) is written only once that check passes: a copy stretched from damaged samples must not be kept on disk
+// with a hash that says it is good. A failed check drops it.
+std::mutex& unsettledLock()
+{
+    static std::mutex m;
+    return m;
+}
+std::map<juce::String, int>& unsettledPaths() // path -> checks still running
+{
+    static std::map<juce::String, int> m;
+    return m;
+}
+std::multimap<juce::String, std::function<void()>>& heldWrites()
+{
+    static std::multimap<juce::String, std::function<void()>> m;
+    return m;
+}
+
+void writeStretchedLater (const juce::File& file, std::shared_ptr<const SampleData> data, const juce::String& source = {})
 {
     if (file == juce::File() || data == nullptr || data->isMapped() || data->left.empty() || (! data->right.empty() && data->right.size() != data->left.size()))
         return;
@@ -737,7 +758,16 @@ void writeStretchedLater (const juce::File& file, std::shared_ptr<const SampleDa
         const loadtrace::Scope timing ("cache_seal"); // (the hash's own share of the write)
         cachecheck::str::makeHeader (header.data(), info, data->left.data(), data->right.empty() ? nullptr : data->right.data());
     }
-    cacheWriter().addJob ([file, data = std::move (data), header] { writeStretched (file, *data, header); });
+    std::function<void()> write = [file, data = std::move (data), header] { writeStretched (file, *data, header); };
+    {
+        const std::scoped_lock l (unsettledLock());
+        if (source.isNotEmpty() && unsettledPaths().count (source) > 0)
+        {
+            heldWrites().emplace (source, std::move (write));
+            return;
+        }
+    }
+    cacheWriter().addJob (std::move (write));
 }
 } // namespace
 
@@ -780,7 +810,7 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStretched (const juce::Stri
         }
         stretched = std::move (made);
         if (stretched != nullptr && onDisk != juce::File())
-            writeStretchedLater (onDisk, stretched);
+            writeStretchedLater (onDisk, stretched, path);
     }
 
     // the other lengths of this file go when nothing uses them any more (changing the BPM replaces the stretched one).
@@ -937,20 +967,75 @@ juce::ThreadPool& pcmChecker()
 // opening (the open's own reads come first). One that fails is logged, marked (<file>.bad) and deleted where the system
 // lets it (a mapped file stays on Windows: the marker makes the next load decode again), and the next load() of the
 // sample in this session reads the file again.
+SampleLibrary::DamagedHandler& damagedHandler()
+{
+    static SampleLibrary::DamagedHandler h;
+    return h;
+}
+std::mutex& damagedHandlerLock()
+{
+    static std::mutex m;
+    return m;
+}
+
 void checkPcmLater (const juce::String& path, std::vector<juce::File> files)
 {
     ++pendingPcmChecks;
+    {
+        const std::scoped_lock l (unsettledLock());
+        ++unsettledPaths()[path];
+    }
     pcmChecker().addJob ([path, files = std::move (files)] {
         for (int i = 0; i < 300 && loadtrace::active(); ++i) // (at most 30 s)
             juce::Thread::sleep (100);
+        juce::File damaged;
+        auto why = cachecheck::Verdict::ok;
         for (const auto& f : files)
-            if (const auto why = checkPcmContent (f, f.getSize()); why != cachecheck::Verdict::ok)
+            if (const auto v = checkPcmContent (f, f.getSize()); v != cachecheck::Verdict::ok)
             {
                 badMarker (f).create();
-                f.deleteFile();
-                cachecheck::reportRebuilt (f.getFullPathName().toStdString(), why);
-                SampleLibrary::forgetShared (path);
+                f.deleteFile(); // (where the system lets it: Windows keeps a file mapped by the copy that plays now)
+                if (damaged == juce::File())
+                    damaged = f, why = v;
+            }
+        // the stretched copies made from it meanwhile: written now, or dropped (they came from the damaged samples)
+        std::vector<std::function<void()>> writes;
+        {
+            const std::scoped_lock l (unsettledLock());
+            if (--unsettledPaths()[path] <= 0)
+                unsettledPaths().erase (path);
+            const auto [from, to] = heldWrites().equal_range (path);
+            for (auto it = from; it != to; ++it)
+                writes.push_back (std::move (it->second));
+            heldWrites().erase (from, to);
+        }
+        if (damaged == juce::File())
+            for (auto& w : writes)
+                cacheWriter().addJob (std::move (w));
+        else
+        {
+            // rebuilt now, here (decoded again into new files: the marker), then swapped in where it plays: the app's
+            // handler reloads it in every channel on the message thread (AudioEngine::reloadSampleEverywhere) and logs
+            // what was done; the new copy is held until then, so the reload finds it decoded
+            SampleLibrary::forgetShared (path);
+            std::shared_ptr<const SampleData> fresh;
+            {
+                SampleLibrary library;
+                fresh = library.load (path);
+            }
+            SampleLibrary::DamagedHandler handler;
+            {
+                const std::scoped_lock l (damagedHandlerLock());
+                handler = damagedHandler();
             }
+            const auto file = damaged.getFullPathName().toStdString();
+            if (fresh == nullptr)
+                cachecheck::reportDamaged (file, why, "it could not be decoded again (the source file is gone?); the copy loaded now plays until the project is opened again");
+            else if (handler == nullptr)
+                cachecheck::reportDamaged (file, why, "rebuilt; nothing here can swap it in, it plays from the next load");
+            else
+                handler (path, file, why, std::move (fresh));
+        }
         --pendingPcmChecks;
     });
 }
@@ -1162,6 +1247,12 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStreamed (const juce::File&
     return data;
 }
 
+void SampleLibrary::setDamagedHandler (DamagedHandler handler)
+{
+    const std::scoped_lock l (damagedHandlerLock());
+    damagedHandler() = std::move (handler);
+}
+
 void SampleLibrary::setInlineCacheChecks (bool checkInline) noexcept
 {
     inlinePcmChecks.store (checkInline);

+ 7 - 0
src/engine/SampleLibrary.h

@@ -1,11 +1,13 @@
 #pragma once
 
 #include <map>
+#include <functional>
 #include <memory>
 #include <mutex>
 
 #include <juce_audio_formats/juce_audio_formats.h>
 
+#include "core/CacheCheck.h"
 #include "core/Instruments.h"
 #include "core/TimeStretch.h"
 
@@ -58,6 +60,11 @@ public:
     static void setInlineCacheChecks (bool checkInline) noexcept;
     // Waits (at most `timeoutMs`) for the background checks; true when none is left
     static bool waitForCacheChecks (int timeoutMs);
+    // What the app does with a sample whose decoded copy failed the background check, once it is decoded again (`fresh`,
+    // held until the call returns): AudioEngine swaps it in where it plays and logs it. Called on the checker thread.
+    using DamagedHandler = std::function<void (const juce::String& path, const std::string& cacheFile, cachecheck::Verdict why,
+                                               std::shared_ptr<const SampleData> fresh)>;
+    static void setDamagedHandler (DamagedHandler handler);
 
     // What the decoded samples of the process hold now (round 190gd: the load log says where a project's megabytes go):
     // samples in RAM (float, both channels) and mapped from the disk cache, and the time-stretched copies kept