Extracted image cache

This commit is contained in:
emeric
2024-03-29 21:02:36 +01:00
parent fb6670290e
commit 58df9284d4
4 changed files with 162 additions and 102 deletions
+3 -52
View File
@@ -19,19 +19,14 @@
#pragma once
#include <atomic>
#include <filesystem>
#include <map>
#include <optional>
#include <shared_mutex>
#include <string_view>
#include <unordered_map>
#include <variant>
#include <vector>
#include "services/cover/ICoverService.hpp"
#include "image/IEncodedImage.hpp"
#include "database/Types.hpp"
#include "ImageCache.hpp"
namespace lms::db
{
@@ -43,42 +38,6 @@ namespace lms::av
class IAudioFile;
}
namespace lms::cover
{
struct CacheEntryDesc
{
std::variant<db::ArtistId, db::ReleaseId, db::TrackId> id;
std::size_t size;
bool operator==(const CacheEntryDesc& other) const
{
return id == other.id
&& size == other.size;
}
};
} // ns Cover
namespace std
{
template<>
class hash<lms::cover::CacheEntryDesc>
{
public:
size_t operator()(const lms::cover::CacheEntryDesc& e) const
{
size_t h{};
std::visit([&](auto id)
{
using IdType = std::decay_t<decltype(id)>;
h ^= std::hash<IdType>{}(id);
}, e.id);
h ^= std::hash<std::size_t>{}(e.size) << 1;
return h;
}
};
} // ns std
namespace lms::cover
{
class CoverService : public ICoverService
@@ -106,21 +65,13 @@ namespace lms::cover
std::unique_ptr<image::IEncodedImage> getFromDirectory(const std::filesystem::path& directory, image::ImageSize width, const std::vector<std::string>& preferredFileNames, bool allowPickRandom) const;
std::unique_ptr<image::IEncodedImage> getFromSameNamedFile(const std::filesystem::path& filePath, image::ImageSize width) const;
bool checkCoverFile(const std::filesystem::path& directoryPath) const;
bool checkCoverFile(const std::filesystem::path& filePath) const;
db::Db& _db;
std::shared_mutex _cacheMutex;
std::unordered_map<CacheEntryDesc, std::shared_ptr<image::IEncodedImage>> _cache;
ImageCache _cache;
std::shared_ptr<image::IEncodedImage> _defaultCover;
std::atomic<std::size_t> _cacheMisses{};
std::atomic<std::size_t> _cacheHits{};
std::size_t _cacheSize{};
void saveToCache(const CacheEntryDesc& entryDesc, std::shared_ptr<image::IEncodedImage> image);
std::shared_ptr<image::IEncodedImage> loadFromCache(const CacheEntryDesc& entryDesc);
const std::size_t _maxCacheSize;
static inline const std::vector<std::filesystem::path> _fileExtensions{ ".jpg", ".jpeg", ".png", ".bmp" }; // TODO parametrize
const std::size_t _maxFileSize;
const std::vector<std::string> _preferredFileNames;