summaryrefslogtreecommitdiff
path: root/Source/Core/VideoCommon/Assets/CustomAssetCache.cpp
blob: 3b15d5733e9fd5c396a15ed13a06f94c710819c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2025 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "VideoCommon/Assets/CustomAssetCache.h"

#include "Common/Logging/Log.h"
#include "Common/MemoryUtil.h"

#include "UICommon/UICommon.h"

#include "VideoCommon/Assets/CustomAsset.h"

namespace VideoCommon
{
void CustomAssetCache::Initialize()
{
  // Use half of available system memory but leave at least 2GiB unused for system stability.
  constexpr size_t must_keep_unused = 2 * size_t(1024 * 1024 * 1024);

  const size_t sys_mem = Common::MemPhysical();
  const size_t keep_unused_mem = std::max(sys_mem / 2, std::min(sys_mem, must_keep_unused));

  m_max_ram_available = sys_mem - keep_unused_mem;

  if (m_max_ram_available == 0)
    ERROR_LOG_FMT(VIDEO, "Not enough system memory for custom resources.");

  m_asset_loader.Initialize();
}

void CustomAssetCache::Shutdown()
{
  Reset();

  m_asset_loader.Shutdown();
}

void CustomAssetCache::Reset()
{
  m_asset_loader.Reset(true);

  m_active_assets = {};
  m_pending_assets = {};
  m_asset_handle_to_data.clear();
  m_asset_id_to_handle.clear();
  m_dirty_assets.clear();
  m_ram_used = 0;
}

void CustomAssetCache::MarkAssetDirty(const CustomAssetLibrary::AssetID& asset_id)
{
  std::lock_guard guard(m_dirty_mutex);
  m_dirty_assets.insert(asset_id);
}

void CustomAssetCache::MarkAssetPending(CustomAsset* asset)
{
  m_pending_assets.MakeAssetHighestPriority(asset->GetHandle(), asset);
}

void CustomAssetCache::MarkAssetActive(CustomAsset* asset)
{
  m_active_assets.MakeAssetHighestPriority(asset->GetHandle(), asset);
}

void CustomAssetCache::Update()
{
  ProcessDirtyAssets();
  ProcessLoadedAssets();

  if (m_ram_used > m_max_ram_available)
  {
    RemoveAssetsUntilBelowMemoryLimit();
  }

  if (m_pending_assets.IsEmpty())
    return;

  if (m_ram_used > m_max_ram_available)
    return;

  const u64 allowed_memory = m_max_ram_available - m_ram_used;
  m_asset_loader.ScheduleAssetsToLoad(m_pending_assets.Elements(), allowed_memory);
}

void CustomAssetCache::ProcessDirtyAssets()
{
  decltype(m_dirty_assets) dirty_assets;

  if (const auto lk = std::unique_lock{m_dirty_mutex, std::try_to_lock})
    std::swap(dirty_assets, m_dirty_assets);

  const auto now = CustomAsset::ClockType::now();
  for (const auto& asset_id : dirty_assets)
  {
    if (const auto it = m_asset_id_to_handle.find(asset_id); it != m_asset_id_to_handle.end())
    {
      const auto asset_handle = it->second;
      AssetData& asset_data = m_asset_handle_to_data[asset_handle];
      asset_data.load_status = AssetData::LoadStatus::PendingReload;
      asset_data.load_request_time = now;

      // Asset was reloaded, clear any errors we might have
      asset_data.has_load_error = false;

      m_pending_assets.InsertAsset(it->second, asset_data.asset.get());

      DEBUG_LOG_FMT(VIDEO, "Dirty asset pending reload: {}", asset_data.asset->GetAssetId());
    }
  }
}

void CustomAssetCache::ProcessLoadedAssets()
{
  const auto load_results = m_asset_loader.TakeLoadResults();

  // Update the ram with the change in memory from the loader
  //
  // Note: Assets with outstanding reload requests will have
  // two copies in memory temporarily (the old data stored in
  // the asset shared_ptr that the resource manager owns, and
  // the new data loaded from the loader in the asset's shared_ptr)
  // This temporary duplication will not be reflected in the
  // resource manager's ram used
  m_ram_used += load_results.change_in_memory;

  for (const auto& [handle, load_successful] : load_results.asset_handles)
  {
    AssetData& asset_data = m_asset_handle_to_data[handle];

    // If we have a reload request that is newer than our loaded time
    // we need to wait for another reload.
    if (asset_data.load_request_time > asset_data.asset->GetLastLoadedTime())
      continue;

    m_pending_assets.RemoveAsset(handle);

    asset_data.load_request_time = {};
    if (!load_successful)
    {
      asset_data.has_load_error = true;
    }
    else
    {
      m_active_assets.InsertAsset(handle, asset_data.asset.get());
      asset_data.load_status = AssetData::LoadStatus::LoadFinished;
    }

    for (const auto& listener : asset_data.listeners)
    {
      if (load_successful)
        listener->NotifyAssetLoadSuccess();
      else
        listener->NotifyAssetLoadFailed();
    }
  }
}

void CustomAssetCache::RemoveAssetsUntilBelowMemoryLimit()
{
  const u64 threshold_ram = m_max_ram_available * 8 / 10;

  if (m_ram_used > threshold_ram)
  {
    INFO_LOG_FMT(VIDEO, "Memory usage over threshold: {}", UICommon::FormatSize(m_ram_used));
  }

  // Clear out least recently used resources until
  // we get safely in our threshold
  while (m_ram_used > threshold_ram && m_active_assets.Size() > 0)
  {
    auto* const asset = m_active_assets.RemoveLowestPriorityAsset();

    AssetData& asset_data = m_asset_handle_to_data[asset->GetHandle()];

    for (const auto& listener : asset_data.listeners)
    {
      listener->AssetUnloaded();
    }

    // Remove the asset's copy
    const std::size_t bytes_unloaded = asset_data.asset->Unload();
    m_ram_used -= bytes_unloaded;

    asset_data.load_status = AssetData::LoadStatus::Unloaded;
    asset_data.load_request_time = {};

    INFO_LOG_FMT(VIDEO, "Unloading asset: {} ({})", asset_data.asset->GetAssetId(),
                 UICommon::FormatSize(bytes_unloaded));
  }
}

}  // namespace VideoCommon