CacheCheck190tgCheck.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Round 190tg (0.1.33, QUEUE item 85): the disk caches' integrity check (core/CacheCheck.h), through the real
  2. // SampleLibrary and FL plugin database reader on files made here. For the time-stretched copies (*.str, stereo and
  3. // mono) and the decoded long samples (*.L.pcm / *.R.pcm): a flipped byte in the samples, a flipped byte in the header,
  4. // a file cut short and a file of the older format (no hash) are each found, the file is made again and logged, and
  5. // the audio read back is bit for bit the fresh one. FL's plugin database cache: a flipped byte is found and the database
  6. // read is the plain one. No window is opened. Included in the app class of Main.cpp; --cachecheck190tgtest <report>
  7. // and --selftest "cachecheck190tg".
  8. juce::String cachecheck190tgCheck (juce::String& log)
  9. {
  10. using namespace lynx;
  11. juce::String result = "OK";
  12. const auto check = [&] (const juce::String& what, bool ok) {
  13. log << (ok ? "ok " : "FAIL ") << what << "\n";
  14. if (! ok && result == "OK")
  15. result = "ERROR " + what;
  16. };
  17. const auto dir = SampleLibrary::cacheFolder().getParentDirectory().getChildFile ("selftest-190tg-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  18. dir.createDirectory();
  19. const auto writeWav = [&dir] (const juce::String& name, int channels, int frames) {
  20. const auto wav = dir.getChildFile (name);
  21. juce::WavAudioFormat format;
  22. juce::AudioBuffer<float> audio (channels, frames);
  23. for (int i = 0; i < frames; ++i)
  24. {
  25. audio.setSample (0, i, 0.4f * std::sin (0.031f * (float) i) + 0.2f * std::sin (0.0071f * (float) i));
  26. if (channels > 1)
  27. audio.setSample (1, i, 0.3f * std::sin (0.017f * (float) i) - 0.25f * std::sin (0.0123f * (float) i));
  28. }
  29. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  30. if (auto* w = format.createWriterFor (out.get(), 44100.0, (unsigned int) channels, 16, {}, 0))
  31. {
  32. out.release();
  33. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  34. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  35. }
  36. return wav;
  37. };
  38. const auto samplesOf = [] (const SampleData& d) {
  39. std::vector<float> v (d.leftData(), d.leftData() + d.frames());
  40. if (d.isStereo())
  41. v.insert (v.end(), d.rightData(), d.rightData() + d.frames());
  42. return v;
  43. };
  44. const auto flipByte = [] (const juce::File& f, juce::int64 at, std::uint8_t mask) {
  45. juce::MemoryBlock b;
  46. if (! f.loadFileAsData (b) || at < 0 || at >= (juce::int64) b.getSize())
  47. return false;
  48. static_cast<std::uint8_t*> (b.getData())[at] ^= mask;
  49. return f.replaceWithData (b.getData(), b.getSize());
  50. };
  51. const auto cutShort = [] (const juce::File& f, juce::int64 by) {
  52. juce::MemoryBlock b;
  53. return f.loadFileAsData (b) && (juce::int64) b.getSize() > by && f.replaceWithData (b.getData(), b.getSize() - (std::size_t) by);
  54. };
  55. const auto cache = SampleLibrary::cacheFolder();
  56. SampleLibrary library;
  57. SampleLibrary::setInlineCacheChecks (true); // (the decoded copies checked before load() returns; the background way below)
  58. // --- the time-stretched copies -------------------------------------------------------------------------------
  59. const auto strCase = [&] (const juce::String& label, const juce::File& wav, double ratio) {
  60. const auto path = wav.getFullPathName();
  61. const auto since = juce::Time::getCurrentTime() - juce::RelativeTime::seconds (2.0);
  62. std::vector<float> fresh;
  63. std::size_t frames = 0;
  64. {
  65. const auto made = library.loadStretched (path, ratio);
  66. if (made == nullptr)
  67. {
  68. check (label + ": stretched", false);
  69. return;
  70. }
  71. fresh = samplesOf (*made);
  72. frames = made->frames();
  73. }
  74. // its file, once the cache's writer has written it (checked: the hash is right)
  75. const auto findFile = [&] {
  76. for (int tries = 0; tries < 600; ++tries)
  77. {
  78. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, "*.str"))
  79. {
  80. juce::MemoryBlock b;
  81. cachecheck::str::Info info;
  82. if (f.getLastModificationTime() >= since && f.loadFileAsData (b)
  83. && cachecheck::str::verify (b.getData(), b.getSize(), info) == cachecheck::Verdict::ok && (std::size_t) info.frames == frames
  84. && std::memcmp (static_cast<const char*> (b.getData()) + cachecheck::str::headerBytes, fresh.data(), frames * sizeof (float)) == 0)
  85. return f;
  86. }
  87. juce::Thread::sleep (50);
  88. }
  89. return juce::File();
  90. };
  91. auto file = findFile();
  92. check (label + ": the copy's file written with its hash (version 2)", file != juce::File());
  93. if (file == juce::File())
  94. return;
  95. const auto readBack = [&] (const juce::String& what, cachecheck::Verdict expected) {
  96. library.forget (path); // (the next load reads the disk)
  97. const auto before = cachecheck::rebuiltCount();
  98. const auto read = library.loadStretched (path, ratio);
  99. const auto logged = cachecheck::rebuiltCount() - before;
  100. const auto same = read != nullptr && samplesOf (*read) == fresh;
  101. library.forget (path); // (unmapped: Windows can't replace a mapped file)
  102. const auto line = juce::String (cachecheck::lastReport());
  103. check (label + ", " + what + ": found (" + juce::String (logged) + " logged: " + line.fromFirstOccurrenceOf ("(", false, false).upToFirstOccurrenceOf (")", false, false)
  104. + "), made again, the audio bit for bit the fresh one",
  105. logged == 1 && same && line.contains (file.getFileName()) && line.contains (cachecheck::describe (expected)));
  106. // the file written again by the writer, valid
  107. file = findFile();
  108. check (label + ", " + what + ": the file written again, valid", file != juce::File());
  109. };
  110. // a clean read: nothing logged, the same audio
  111. {
  112. library.forget (path);
  113. const auto before = cachecheck::rebuiltCount();
  114. const auto read = library.loadStretched (path, ratio);
  115. check (label + ": read back from the disk, checked, the same audio, nothing logged",
  116. read != nullptr && samplesOf (*read) == fresh && cachecheck::rebuiltCount() == before);
  117. library.forget (path);
  118. }
  119. const auto payload = (juce::int64) cachecheck::str::headerBytes;
  120. if (flipByte (file, payload + (file.getSize() - payload) / 3, 0x40)) // (bit 6, as round 190sm's)
  121. readBack ("a flipped bit in the samples", cachecheck::Verdict::mismatch);
  122. if (file != juce::File() && flipByte (file, 9, 0x01)) // (the sample rate's low byte)
  123. readBack ("a flipped bit in the header", cachecheck::Verdict::mismatch);
  124. if (file != juce::File() && cutShort (file, 1000))
  125. readBack ("a file cut short", cachecheck::Verdict::truncated);
  126. if (file != juce::File())
  127. {
  128. // the older format: a 32-byte header "LYNXSTR1", no hash (rounds 165i..190tf)
  129. juce::MemoryBlock b, v1;
  130. if (file.loadFileAsData (b))
  131. {
  132. v1.append (cachecheck::str::magicV1, 8);
  133. v1.append (static_cast<const char*> (b.getData()) + 8, 24);
  134. v1.append (static_cast<const char*> (b.getData()) + cachecheck::str::headerBytes, b.getSize() - cachecheck::str::headerBytes);
  135. if (file.replaceWithData (v1.getData(), v1.getSize()))
  136. readBack ("an older file without the hash", cachecheck::Verdict::oldFormat);
  137. }
  138. }
  139. };
  140. strCase ("stretched stereo", writeWav ("stereo 190tg.wav", 2, 44100 * 2), 1.3);
  141. strCase ("stretched mono", writeWav ("mono 190tg.wav", 1, 44100), 0.8);
  142. // --- the decoded long samples (over 30 s: mapped from the disk cache) -----------------------------------------
  143. {
  144. const auto wav = writeWav ("long 190tg.wav", 2, 44100 * 31);
  145. const auto path = wav.getFullPathName();
  146. const auto since = juce::Time::getCurrentTime() - juce::RelativeTime::seconds (2.0);
  147. std::vector<float> fresh;
  148. {
  149. const auto made = library.load (path);
  150. check ("long sample: mapped from the disk cache, stereo", made != nullptr && made->isMapped() && made->isStereo());
  151. if (made != nullptr)
  152. fresh = samplesOf (*made);
  153. }
  154. library.forget (path); // (nothing holds it: unmapped, the files can be changed)
  155. juce::File left, right;
  156. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, "*.L.pcm"))
  157. if (f.getLastModificationTime() >= since && f.getSize() == (juce::int64) cachecheck::pcm::headerBytes + (juce::int64) (fresh.size() / 2) * (juce::int64) sizeof (float))
  158. left = f, right = f.getSiblingFile (f.getFileName().replace (".L.pcm", ".R.pcm"));
  159. const auto valid = [] (const juce::File& f, std::size_t frames) {
  160. juce::MemoryBlock b;
  161. return f.loadFileAsData (b) && cachecheck::pcm::verify (b.getData(), b.getSize(), 44100.0, (std::int64_t) frames) == cachecheck::Verdict::ok;
  162. };
  163. const auto frames = fresh.size() / 2;
  164. check ("long sample: both channels' files written with their hash", ! fresh.empty() && valid (left, frames) && valid (right, frames));
  165. const auto readBack = [&] (const juce::String& what, const juce::File& damaged, cachecheck::Verdict expected) {
  166. const auto before = cachecheck::rebuiltCount();
  167. std::vector<float> read;
  168. {
  169. const auto again = library.load (path);
  170. if (again != nullptr)
  171. read = samplesOf (*again);
  172. }
  173. library.forget (path);
  174. const auto logged = cachecheck::rebuiltCount() - before;
  175. const auto line = juce::String (cachecheck::lastReport());
  176. check ("long sample, " + what + ": found (" + juce::String (logged) + " logged), decoded again, bit for bit the fresh one, both files valid again",
  177. logged == 1 && read == fresh && line.contains (damaged.getFileName()) && line.contains (cachecheck::describe (expected))
  178. && valid (left, frames) && valid (right, frames));
  179. };
  180. {
  181. const auto before = cachecheck::rebuiltCount();
  182. std::vector<float> read;
  183. {
  184. const auto again = library.load (path);
  185. if (again != nullptr)
  186. read = samplesOf (*again);
  187. }
  188. library.forget (path);
  189. check ("long sample: mapped again, checked, the same audio, nothing logged", read == fresh && cachecheck::rebuiltCount() == before);
  190. }
  191. if (flipByte (left, left.getSize() / 2, 0x40))
  192. readBack ("a flipped bit in the left channel's samples", left, cachecheck::Verdict::mismatch);
  193. if (flipByte (right, 12, 0x04)) // (the sample rate)
  194. readBack ("a flipped bit in the right channel's header", right, cachecheck::Verdict::mismatch);
  195. if (cutShort (right, 4096))
  196. readBack ("the right channel's file cut short", right, cachecheck::Verdict::truncated);
  197. {
  198. // the older format: "LYNXPCM1", bytes 24..31 zero
  199. juce::MemoryBlock b;
  200. if (left.loadFileAsData (b))
  201. {
  202. std::memcpy (b.getData(), cachecheck::pcm::magicV1, 8);
  203. std::memset (static_cast<char*> (b.getData()) + 24, 0, 8);
  204. if (left.replaceWithData (b.getData(), b.getSize()))
  205. readBack ("an older left file without the hash", left, cachecheck::Verdict::oldFormat);
  206. }
  207. }
  208. }
  209. // --- the decoded copies' check after the open (the app's way: load() checks the header and size; the samples are
  210. // checked on the checker thread; a damaged copy is decoded again and swapped in where it plays) -------------
  211. {
  212. SampleLibrary::setInlineCacheChecks (false);
  213. const auto wav = writeWav ("later 190tg.wav", 2, 44100 * 32);
  214. const auto path = wav.getFullPathName();
  215. const auto since = juce::Time::getCurrentTime() - juce::RelativeTime::seconds (2.0);
  216. std::vector<float> fresh;
  217. {
  218. const auto made = library.load (path);
  219. if (made != nullptr)
  220. fresh = samplesOf (*made);
  221. }
  222. library.forget (path);
  223. juce::File left;
  224. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, "*.L.pcm"))
  225. if (f.getLastModificationTime() >= since && f.getSize() == (juce::int64) cachecheck::pcm::headerBytes + (juce::int64) (fresh.size() / 2) * (juce::int64) sizeof (float))
  226. left = f;
  227. auto before = cachecheck::rebuiltCount();
  228. std::vector<float> read;
  229. {
  230. const auto again = library.load (path);
  231. if (again != nullptr)
  232. read = samplesOf (*again);
  233. }
  234. const auto idle = SampleLibrary::waitForCacheChecks (60000);
  235. library.forget (path);
  236. check ("after the open: a clean copy is mapped again, checked in the background, nothing logged",
  237. ! fresh.empty() && read == fresh && idle && cachecheck::rebuiltCount() == before);
  238. // the swap where it plays (the coordinator, 30 Nov): a sampler channel of an engine plays the sample; its decoded
  239. // copy is damaged; the check after the open finds it, decodes it again, and the message thread swaps the new copy
  240. // into the channel (AudioEngine::reloadSampleEverywhere), logged "was damaged (...); rebuilt and reloaded"
  241. {
  242. AudioEngine engine (false);
  243. auto song = Song::makeDefault();
  244. song.channels.edit()[0].instrument = InstrumentKind::sampler;
  245. song.channels.edit()[0].samplePath = path.toStdString();
  246. engine.setSong (song);
  247. SampleLibrary::waitForCacheChecks (60000);
  248. engine.setSong (Song::makeDefault()); // (nothing holds the copy: the file can be changed, also on Windows)
  249. library.forget (path);
  250. const auto flipped = left != juce::File() && flipByte (left, left.getSize() / 2, 0x40);
  251. before = cachecheck::rebuiltCount();
  252. engine.setSong (song); // (the open: header and size checked, the samples later)
  253. auto playing = library.findLoaded (path);
  254. const auto damagedNow = playing != nullptr && samplesOf (*playing) != fresh;
  255. const auto done = SampleLibrary::waitForCacheChecks (60000);
  256. const auto pump = [] (int ms, const std::function<bool()>& until) {
  257. const auto start = juce::Time::getMillisecondCounter();
  258. while (juce::Time::getMillisecondCounter() - start < (juce::uint32) ms && ! until())
  259. {
  260. #if JUCE_LINUX || JUCE_WINDOWS
  261. for (int i = 0; i < 256 && juce::detail::dispatchNextMessageOnSystemQueue (true); ++i) {}
  262. #elif JUCE_MAC
  263. for (int i = 0; i < 256 && CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource; ++i) {}
  264. #endif
  265. juce::Thread::sleep (5);
  266. }
  267. };
  268. pump (60000, [before] { return cachecheck::rebuiltCount() > before; });
  269. const auto line = juce::String (cachecheck::lastReport());
  270. const auto now = library.findLoaded (path);
  271. check ("after the open: the damaged copy that plays (" + juce::String (damagedNow ? "damaged" : "NOT damaged") + ") is found by the background check: \""
  272. + line.fromFirstOccurrenceOf ("was damaged", true, false) + "\"",
  273. flipped && damagedNow && done && cachecheck::rebuiltCount() == before + 1 && line.contains (left.getFileName())
  274. && line.contains ("was damaged (its content hash does not match") && line.contains ("rebuilt and reloaded (1 channel)"));
  275. // the damaged copy is let go by the engine (its rack holds the new one): nothing but this check holds it
  276. std::weak_ptr<const SampleData> old = playing;
  277. const auto oldPtr = playing.get();
  278. playing.reset();
  279. pump (5000, [&old, &engine] { engine.dispatchPendingMessages(); return old.expired(); });
  280. 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",
  281. now != nullptr && now.get() != oldPtr && samplesOf (*now) == fresh && old.expired());
  282. }
  283. library.forget (path);
  284. // the next load (nothing holds the old copy now; on Windows the damaged file goes only now) and its files
  285. read.clear();
  286. {
  287. const auto again = library.load (path);
  288. if (again != nullptr)
  289. read = samplesOf (*again);
  290. }
  291. SampleLibrary::waitForCacheChecks (60000);
  292. library.forget (path);
  293. juce::MemoryBlock b;
  294. check ("after the open: a later load is bit for bit the fresh one, from a valid file, nothing more logged, no marker left",
  295. read == fresh && cachecheck::rebuiltCount() == before + 1 && left.loadFileAsData (b)
  296. && cachecheck::pcm::verify (b.getData(), b.getSize(), 44100.0, (std::int64_t) (fresh.size() / 2)) == cachecheck::Verdict::ok
  297. && ! left.getSiblingFile (left.getFileName() + ".bad").exists());
  298. SampleLibrary::setInlineCacheChecks (true);
  299. }
  300. // --- FL's plugin database cache (text, its last line the hash) ------------------------------------------------
  301. {
  302. FlStudioInstall fl;
  303. fl.userData = dir.getChildFile ("FL user data");
  304. const auto nfo = fl.pluginDatabase().getChildFile ("Generators").getChildFile ("VST3").getChildFile ("Alpha190tg.nfo");
  305. const auto cacheFile = dir.getChildFile ("fl-plugin-database-cache.txt");
  306. auto ok = nfo.getParentDirectory().createDirectory()
  307. && nfo.replaceWithText ("ps_name=Alpha190tg\r\nps_file_name_0=C:\\VST3\\Alpha190tg.vst3\r\nps_file_vendorname_0=Vendor\r\nps_file_type_0=2\r\n");
  308. const auto plain = readFlPluginDatabase (fl);
  309. readFlPluginDatabase (fl, nullptr, cacheFile);
  310. juce::MemoryBlock b;
  311. std::string_view body;
  312. ok = ok && cacheFile.loadFileAsData (b)
  313. && cachecheck::unsealText ({ static_cast<const char*> (b.getData()), b.getSize() }, body) == cachecheck::Verdict::ok;
  314. check ("FL plugin database cache: written with its hash line", ok && plain.entries().size() == 1);
  315. // a flipped bit in the entry's vendor ("Vendor" -> "Vendgr"): without the check the cache would give it as it is
  316. const auto text = cacheFile.loadFileAsString();
  317. const auto at = text.indexOf ("Vendor") + 4;
  318. const auto before = cachecheck::rebuiltCount();
  319. const auto read = at > 4 && flipByte (cacheFile, at, 0x08) ? readFlPluginDatabase (fl, nullptr, cacheFile) : FlPluginDb();
  320. const auto logged = cachecheck::rebuiltCount() - before;
  321. check ("FL plugin database cache: a flipped bit is found (" + juce::String (logged) + " logged, at " + juce::String (at) + "), the database is the plain read ("
  322. + juce::String ((int) read.entries().size()) + " entries, vendor \"" + (read.entries().empty() ? juce::String() : juce::String (read.entries()[0].vendor)) + "\"), the cache written again",
  323. logged == 1 && read.entries().size() == 1 && read.entries()[0].vendor == "Vendor"
  324. && [&cacheFile] {
  325. juce::MemoryBlock again; // (loadFileAsData appends to a block: a fresh one)
  326. std::string_view rest;
  327. return cacheFile.loadFileAsData (again)
  328. && cachecheck::unsealText ({ static_cast<const char*> (again.getData()), again.getSize() }, rest) == cachecheck::Verdict::ok;
  329. }());
  330. }
  331. // the log line in the settings folder
  332. const auto logText = platform::settingsFile ("cache-check.log").loadFileAsString();
  333. check ("the log (cache-check.log in the settings folder) has the lines", logText.contains ("failed its check") && logText.contains ("and was rebuilt"));
  334. library.forget (dir.getChildFile ("stereo 190tg.wav").getFullPathName());
  335. library.forget (dir.getChildFile ("mono 190tg.wav").getFullPathName());
  336. library.forget (dir.getChildFile ("long 190tg.wav").getFullPathName());
  337. library.forget (dir.getChildFile ("later 190tg.wav").getFullPathName());
  338. SampleLibrary::setInlineCacheChecks (false); // (the app's way again)
  339. dir.deleteRecursively();
  340. return result;
  341. }