Overte C++ Documentation
ResourceCache.h
1  //
2 // ResourceCache.h
3 // libraries/shared/src
4 //
5 // Created by Andrzej Kapolka on 2/27/14.
6 // Copyright 2014 High Fidelity, Inc.
7 // Copyright 2023 Overte e.V.
8 //
9 // Distributed under the Apache License, Version 2.0.
10 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
11 // SPDX-License-Identifier: Apache-2.0
12 //
13 
14 #ifndef hifi_ResourceCache_h
15 #define hifi_ResourceCache_h
16 
17 #include <atomic>
18 #include <mutex>
19 
20 #include <QtCore/QHash>
21 #include <QtCore/QList>
22 #include <QtCore/QObject>
23 #include <QtCore/QPointer>
24 #include <QtCore/QSharedPointer>
25 #include <QtCore/QUrl>
26 #include <QtCore/QWeakPointer>
27 #include <QtCore/QReadWriteLock>
28 #include <QtCore/QQueue>
29 
30 #include <QtNetwork/QNetworkReply>
31 #include <QtNetwork/QNetworkRequest>
32 
33 #include <DependencyManager.h>
34 
35 #include "ResourceManager.h"
36 
37 Q_DECLARE_METATYPE(size_t)
38 
39 class QNetworkReply;
40 class QTimer;
41 
42 class Resource;
43 
44 static const qint64 BYTES_PER_MEGABYTES = 1024 * 1024;
45 static const qint64 BYTES_PER_GIGABYTES = 1024 * BYTES_PER_MEGABYTES;
46 static const qint64 MAXIMUM_CACHE_SIZE = 10 * BYTES_PER_GIGABYTES; // 10GB
47 
48 // Windows can have troubles allocating that much memory in ram sometimes
49 // so default cache size at 100 MB on windows (1GB otherwise)
50 #ifdef Q_OS_WIN32
51 static const qint64 DEFAULT_UNUSED_MAX_SIZE = 100 * BYTES_PER_MEGABYTES;
52 #else
53 static const qint64 DEFAULT_UNUSED_MAX_SIZE = 1024 * BYTES_PER_MEGABYTES;
54 #endif
55 static const qint64 MIN_UNUSED_MAX_SIZE = 0;
56 static const qint64 MAX_UNUSED_MAX_SIZE = MAXIMUM_CACHE_SIZE;
57 
58 // We need to make sure that these items are available for all instances of
59 // ResourceCache derived classes. Since we can't count on the ordering of
60 // static members destruction, we need to use this Dependency manager implemented
61 // object instead
62 class ResourceCacheSharedItems : public Dependency {
63  SINGLETON_DEPENDENCY
64 
65  using Mutex = std::recursive_mutex;
66  using Lock = std::unique_lock<Mutex>;
67 
68 public:
69  bool appendRequest(QWeakPointer<Resource> newRequest);
70  void removeRequest(QWeakPointer<Resource> doneRequest);
71  void setRequestLimit(uint32_t limit);
72  uint32_t getRequestLimit() const;
73  QList<QSharedPointer<Resource>> getPendingRequests() const;
74  QSharedPointer<Resource> getHighestPendingRequest();
75  uint32_t getPendingRequestsCount() const;
76  QList<QSharedPointer<Resource>> getLoadingRequests() const;
77  uint32_t getLoadingRequestsCount() const;
78  void clear();
79 
80 private:
81  ResourceCacheSharedItems() = default;
82 
83  mutable Mutex _mutex;
84  QList<QWeakPointer<Resource>> _pendingRequests;
85  QList<QWeakPointer<Resource>> _loadingRequests;
86  const uint32_t DEFAULT_REQUEST_LIMIT = 10;
87  uint32_t _requestLimit { DEFAULT_REQUEST_LIMIT };
88 };
89 
91 class ScriptableResource : public QObject {
92 
93  /*@jsdoc
94  * Information about a cached resource. Created by {@link AnimationCache.prefetch}, {@link MaterialCache.prefetch},
95  * {@link ModelCache.prefetch}, {@link SoundCache.prefetch}, or {@link TextureCache.prefetch}.
96  *
97  * @class ResourceObject
98  * @hideconstructor
99  *
100  * @hifi-interface
101  * @hifi-client-entity
102  * @hifi-avatar
103  * @hifi-server-entity
104  * @hifi-assignment-client
105  *
106  * @property {string} url - URL of the resource. <em>Read-only.</em>
107  * @property {Resource.State} state - Current loading state. <em>Read-only.</em>
108  */
109  Q_OBJECT
110  Q_PROPERTY(QUrl url READ getURL)
111  Q_PROPERTY(int state READ getState NOTIFY stateChanged)
112 
113 public:
114 
115  /*@jsdoc
116  * The loading state of a resource.
117  * @typedef {object} Resource.State
118  * @property {number} QUEUED - The resource is queued up, waiting to be loaded.
119  * @property {number} LOADING - The resource is downloading.
120  * @property {number} LOADED - The resource has finished downloading but is not complete.
121  * @property {number} FINISHED - The resource has completely finished loading and is ready.
122  * @property {number} FAILED - The resource has failed to download.
123  */
124  enum State {
125  QUEUED,
126  LOADING,
127  LOADED,
128  FINISHED,
129  FAILED,
130  };
131  Q_ENUM(State)
132 
133  ScriptableResource(const QUrl& url);
134  virtual ~ScriptableResource() = default;
135 
136  /*@jsdoc
137  * Releases the resource.
138  * @function ResourceObject#release
139  */
140  Q_INVOKABLE void release();
141 
142  const QUrl& getURL() const { return _url; }
143  int getState() const { return (int)_state; }
144  const QSharedPointer<Resource>& getResource() const { return _resource; }
145 
146  bool isInScript() const;
147  void setInScript(bool isInScript);
148 
149 signals:
150 
151  /*@jsdoc
152  * Triggered when the resource's download progress changes.
153  * @function ResourceObject#progressChanged
154  * @param {number} bytesReceived - Bytes downloaded so far.
155  * @param {number} bytesTotal - Total number of bytes in the resource.
156  * @returns {Signal}
157  */
158  void progressChanged(uint64_t bytesReceived, uint64_t bytesTotal);
159 
160  /*@jsdoc
161  * Triggered when the resource's loading state changes.
162  * @function ResourceObject#stateChanged
163  * @param {Resource.State} state - New state.
164  * @returns {Signal}
165  */
166  void stateChanged(int state);
167 
168 protected:
169  void setState(State state) { _state = state; emit stateChanged(_state); }
170 
171 private slots:
172  void loadingChanged();
173  void loadedChanged();
174  void finished(bool success);
175 
176 private:
177  void disconnectHelper();
178 
179  friend class ResourceCache;
180 
181  // Holds a ref to the resource to keep it in scope
182  QSharedPointer<Resource> _resource;
183 
184  QMetaObject::Connection _progressConnection;
185  QMetaObject::Connection _loadingConnection;
186  QMetaObject::Connection _loadedConnection;
187  QMetaObject::Connection _finishedConnection;
188 
189  QUrl _url;
190  State _state{ QUEUED };
191 };
192 
193 Q_DECLARE_METATYPE(ScriptableResource*);
194 
196 class ResourceCache : public QObject {
197  Q_OBJECT
198 
199  Q_PROPERTY(size_t numTotal READ getNumTotalResources NOTIFY dirty)
200  Q_PROPERTY(size_t numCached READ getNumCachedResources NOTIFY dirty)
201  Q_PROPERTY(size_t sizeTotal READ getSizeTotalResources NOTIFY dirty)
202  Q_PROPERTY(size_t sizeCached READ getSizeCachedResources NOTIFY dirty)
203 
204 public:
205 
206  size_t getNumTotalResources() const { return _numTotalResources; }
207  size_t getSizeTotalResources() const { return _totalResourcesSize; }
208  size_t getNumCachedResources() const { return _numUnusedResources; }
209  size_t getSizeCachedResources() const { return _unusedResourcesSize; }
210 
211  Q_INVOKABLE QVariantList getResourceList();
212 
213  static void setRequestLimit(uint32_t limit);
214  static uint32_t getRequestLimit() { return DependencyManager::get<ResourceCacheSharedItems>()->getRequestLimit(); }
215 
216  void setUnusedResourceCacheSize(qint64 unusedResourcesMaxSize);
217  qint64 getUnusedResourceCacheSize() const { return _unusedResourcesMaxSize; }
218 
219  static QList<QSharedPointer<Resource>> getLoadingRequests();
220  static uint32_t getPendingRequestCount();
221  static uint32_t getLoadingRequestCount();
222 
223  ResourceCache(QObject* parent = nullptr);
224  virtual ~ResourceCache();
225 
226  void refreshAll();
227  void clearUnusedResources();
228 
229 signals:
230 
231  void dirty();
232 
233 protected slots:
234 
235  void updateTotalSize(const qint64& deltaSize);
236 
237  // Prefetches a resource to be held by the ScriptEngine.
238  // Left as a protected member so subclasses can overload prefetch
239  // and delegate to it (see TextureCache::prefetch(const QUrl&, int).
240  ScriptableResource* prefetch(const QUrl& url, void* extra, size_t extraHash);
241 
242  // FIXME: The return type is not recognized by JavaScript.
247  // FIXME: std::numeric_limits<size_t>::max() could be a valid extraHash
248  QSharedPointer<Resource> getResource(const QUrl& url, const QUrl& fallback = QUrl()) { return getResource(url, fallback, nullptr, std::numeric_limits<size_t>::max()); }
249  QSharedPointer<Resource> getResource(const QUrl& url, const QUrl& fallback, void* extra, size_t extraHash);
250 
251 private slots:
252  void clearATPAssets();
253 
254 protected:
255  // Prefetches a resource to be held by the ScriptEngine.
256  // Pointers created through this method should be owned by the caller,
257  // which should be a ScriptEngine with ScriptableResource registered, so that
258  // the ScriptEngine will delete the pointer when it is garbage collected.
259  // JSDoc is provided on more general function signature.
260  Q_INVOKABLE ScriptableResource* prefetch(const QUrl& url) { return prefetch(url, nullptr, std::numeric_limits<size_t>::max()); }
261 
263  virtual QSharedPointer<Resource> createResource(const QUrl& url) = 0;
264  virtual QSharedPointer<Resource> createResourceCopy(const QSharedPointer<Resource>& resource) = 0;
265 
266  void addUnusedResource(const QSharedPointer<Resource>& resource);
267  void removeUnusedResource(const QSharedPointer<Resource>& resource);
268 
271  static bool attemptRequest(QSharedPointer<Resource> resource);
272  static void requestCompleted(QWeakPointer<Resource> resource);
273  static bool attemptHighestPriorityRequest();
274 
275 private:
276  friend class Resource;
277  friend class ScriptableResourceCache;
278 
279  void reserveUnusedResource(qint64 resourceSize);
280  void removeResource(const QUrl& url, size_t extraHash, qint64 size = 0);
281 
282  void resetTotalResourceCounter();
283  void resetUnusedResourceCounter();
284  void resetResourceCounters();
285 
286  // Resources
287  QHash<QUrl, QMultiHash<size_t, QWeakPointer<Resource>>> _resources;
288  QReadWriteLock _resourcesLock { QReadWriteLock::Recursive };
289  int _lastLRUKey = 0;
290 
291  std::atomic<size_t> _numTotalResources { 0 };
292  std::atomic<qint64> _totalResourcesSize { 0 };
293 
294  // Cached resources
295  QMap<int, QSharedPointer<Resource>> _unusedResources;
296  QReadWriteLock _unusedResourcesLock { QReadWriteLock::Recursive };
297  qint64 _unusedResourcesMaxSize = DEFAULT_UNUSED_MAX_SIZE;
298 
299  std::atomic<size_t> _numUnusedResources { 0 };
300  std::atomic<qint64> _unusedResourcesSize { 0 };
301 };
302 
304 class ScriptableResourceCache : public QObject {
305  Q_OBJECT
306 
307  // JSDoc 3.5.5 doesn't augment name spaces with @property definitions so the following properties JSDoc is copied to the
308  // different exposed cache classes.
309 
310  /*@jsdoc
311  * @property {number} numTotal - Total number of total resources. <em>Read-only.</em>
312  * @property {number} numCached - Total number of cached resource. <em>Read-only.</em>
313  * @property {number} sizeTotal - Size in bytes of all resources. <em>Read-only.</em>
314  * @property {number} sizeCached - Size in bytes of all cached resources. <em>Read-only.</em>
315  */
316  Q_PROPERTY(size_t numTotal READ getNumTotalResources NOTIFY dirty)
317  Q_PROPERTY(size_t numCached READ getNumCachedResources NOTIFY dirty)
318  Q_PROPERTY(size_t sizeTotal READ getSizeTotalResources NOTIFY dirty)
319  Q_PROPERTY(size_t sizeCached READ getSizeCachedResources NOTIFY dirty)
320 
321  /*@jsdoc
322  * @property {number} numGlobalQueriesPending - Total number of global queries pending (across all resource cache managers).
323  * <em>Read-only.</em>
324  * @property {number} numGlobalQueriesLoading - Total number of global queries loading (across all resource cache managers).
325  * <em>Read-only.</em>
326  */
327  Q_PROPERTY(size_t numGlobalQueriesPending READ getNumGlobalQueriesPending NOTIFY dirty)
328  Q_PROPERTY(size_t numGlobalQueriesLoading READ getNumGlobalQueriesLoading NOTIFY dirty)
329 
330 public:
331  ScriptableResourceCache(QSharedPointer<ResourceCache> resourceCache);
332 
333  /*@jsdoc
334  * Gets the URLs of all resources in the cache.
335  * @function ResourceCache.getResourceList
336  * @returns {string[]} The URLs of all resources in the cache.
337  * @example <caption>Report cached resources.</caption>
338  * // Replace AnimationCache with MaterialCache, ModelCache, SoundCache, or TextureCache as appropriate.
339  *
340  * var cachedResources = AnimationCache.getResourceList();
341  * print("Cached resources: " + JSON.stringify(cachedResources));
342  */
343  Q_INVOKABLE QVariantList getResourceList();
344 
345  /*@jsdoc
346  * @function ResourceCache.updateTotalSize
347  * @param {number} deltaSize - Delta size.
348  * @deprecated This function is deprecated and will be removed.
349  */
350  Q_INVOKABLE void updateTotalSize(const qint64& deltaSize);
351 
352  /*@jsdoc
353  * Prefetches a resource.
354  * @function ResourceCache.prefetch
355  * @param {string} url - The URL of the resource to prefetch.
356  * @returns {ResourceObject} A resource object.
357  * @example <caption>Prefetch a resource and wait until it has loaded.</caption>
358  * // Replace AnimationCache with MaterialCache, ModelCache, SoundCache, or TextureCache as appropriate.
359  * // TextureCache has its own version of this function.
360  *
361  * var resourceURL = "https://apidocs.overte.org/examples/Silly%20Dancing.fbx";
362  * var resourceObject = AnimationCache.prefetch(resourceURL);
363  *
364  * function checkIfResourceLoaded(state) {
365  * if (state === Resource.State.FINISHED) {
366  * print("Resource loaded and ready.");
367  * } else if (state === Resource.State.FAILED) {
368  * print("Resource not loaded.");
369  * }
370  * }
371  *
372  * // Resource may have already been loaded.
373  * print("Resource state: " + resourceObject.state);
374  * checkIfResourceLoaded(resourceObject.state);
375  *
376  * // Resource may still be loading.
377  * resourceObject.stateChanged.connect(function (state) {
378  * print("Resource state changed to: " + state);
379  * checkIfResourceLoaded(state);
380  * });
381  */
382  Q_INVOKABLE ScriptableResource* prefetch(const QUrl& url) { return prefetch(url, nullptr, std::numeric_limits<size_t>::max()); }
383 
384  // FIXME: This function variation shouldn't be in the API.
385  Q_INVOKABLE ScriptableResource* prefetch(const QUrl& url, void* extra, size_t extraHash);
386 
387 signals:
388 
389  /*@jsdoc
390  * Triggered when the cache content has changed.
391  * @function ResourceCache.dirty
392  * @returns {Signal}
393  */
394  void dirty();
395 
396 private:
397  QSharedPointer<ResourceCache> _resourceCache;
398 
399  size_t getNumTotalResources() const { return _resourceCache->getNumTotalResources(); }
400  size_t getSizeTotalResources() const { return _resourceCache->getSizeTotalResources(); }
401  size_t getNumCachedResources() const { return _resourceCache->getNumCachedResources(); }
402  size_t getSizeCachedResources() const { return _resourceCache->getSizeCachedResources(); }
403 
404  size_t getNumGlobalQueriesPending() const { return ResourceCache::getPendingRequestCount(); }
405  size_t getNumGlobalQueriesLoading() const { return ResourceCache::getLoadingRequestCount(); }
406 };
407 
409 class Resource : public QObject {
410  Q_OBJECT
411 
412 public:
413  Resource() : QObject(), _loaded(true) {}
414  Resource(const Resource& other);
415  Resource(const QUrl& url);
416  virtual ~Resource();
417 
418  virtual QString getType() const { return "Resource"; }
419 
421  int getLRUKey() const { return _lruKey; }
422 
424  void ensureLoading();
425 
427  virtual void setLoadPriority(const QPointer<QObject>& owner, float priority);
428 
430  virtual void setLoadPriorities(const QHash<QPointer<QObject>, float>& priorities);
431 
433  virtual void clearLoadPriority(const QPointer<QObject>& owner);
434 
436  float getLoadPriority();
437 
439  virtual bool isLoaded() const { return _loaded; }
440 
442  virtual bool isFailed() const { return _failedToLoad; }
443 
445  qint64 getBytesReceived() const { return _bytesReceived; }
446 
448  qint64 getBytesTotal() const { return _bytesTotal; }
449 
451  qint64 getBytes() const { return _bytes; }
452 
454  float getProgress() const { return (_bytesTotal <= 0) ? 0.0f : (float)_bytesReceived / _bytesTotal; }
455 
457  virtual void refresh();
458 
459  void setSelf(const QWeakPointer<Resource>& self) { _self = self; }
460 
461  void setCache(ResourceCache* cache) { _cache = cache; }
462 
463  virtual void deleter() { allReferencesCleared(); }
464 
465  const QUrl& getURL() const { return _url; }
466 
467  unsigned int getDownloadAttempts() { return _attempts; }
468  unsigned int getDownloadAttemptsRemaining() { return _attemptsRemaining; }
469 
470  virtual void setExtra(void* extra) {};
471  void setExtraHash(size_t extraHash) { _extraHash = extraHash; }
472  size_t getExtraHash() const { return _extraHash; }
473 
474 signals:
476  void loading();
477 
480  void loaded(const QByteArray request);
481 
483  void finished(bool success);
484 
486  void failed(QNetworkReply::NetworkError error);
487 
489  void onRefresh();
490 
492  void onProgress(uint64_t bytesReceived, uint64_t bytesTotal);
493 
495  void updateSize(qint64 deltaSize);
496 
497 protected slots:
498  void attemptRequest();
499 
500 protected:
501  virtual void init(bool resetLoaded = true);
502 
506  virtual void makeRequest();
507 
509  virtual bool isCacheable() const { return _loaded; }
510 
513  virtual void downloadFinished(const QByteArray& data) { finishedLoading(true); }
514 
516  void setSize(const qint64& bytes);
517 
520  Q_INVOKABLE void finishedLoading(bool success);
521 
522  Q_INVOKABLE void allReferencesCleared();
523 
525  virtual bool handleFailedRequest(ResourceRequest::Result result);
526 
527  QUrl _url;
528  QUrl _effectiveBaseURL { _url };
529  QUrl _activeUrl;
530  ByteRange _requestByteRange;
531  bool _shouldFailOnRedirect { false };
532 
533  // _loaded == true means we are in a loaded and usable state. It is possible that there may still be
534  // active requests/loading while in this state. Example: Progressive KTX downloads, where higher resolution
535  // mips are being download.
536  bool _startedLoading = false;
537  bool _failedToLoad = false;
538  bool _loaded = false;
539 
540  QHash<QPointer<QObject>, float> _loadPriorities;
541  QWeakPointer<Resource> _self;
542  QPointer<ResourceCache> _cache;
543 
544  qint64 _bytesReceived { 0 };
545  qint64 _bytesTotal { 0 };
546  qint64 _bytes { 0 };
547 
548  int _requestID;
549  ResourceRequest* _request { nullptr };
550 
551  size_t _extraHash { std::numeric_limits<size_t>::max() };
552 
553 public slots:
554  void handleDownloadProgress(uint64_t bytesReceived, uint64_t bytesTotal);
555  void handleReplyFinished();
556 
557 private:
558  friend class ResourceCache;
559  friend class ScriptableResource;
560 
561  void setLRUKey(int lruKey) { _lruKey = lruKey; }
562 
563  void retry();
564  void reinsert();
565 
566  bool isInScript() const { return _isInScript; }
567  void setInScript(bool isInScript) { _isInScript = isInScript; }
568 
569  int _lruKey{ 0 };
570  QTimer* _replyTimer{ nullptr };
571  unsigned int _attempts{ 0 };
572  static const int MAX_ATTEMPTS = 8;
573  unsigned int _attemptsRemaining { MAX_ATTEMPTS };
574  bool _isInScript{ false };
575 };
576 
577 uint qHash(const QPointer<QObject>& value, uint seed = 0);
578 
579 #endif // hifi_ResourceCache_h
Base class for resource caches.
Definition: ResourceCache.h:196
virtual QSharedPointer< Resource > createResource(const QUrl &url)=0
Creates a new resource.
static bool attemptRequest(QSharedPointer< Resource > resource)
Definition: ResourceCache.cpp:534
QSharedPointer< Resource > getResource(const QUrl &url, const QUrl &fallback=QUrl())
Definition: ResourceCache.h:248
Base class for resources.
Definition: ResourceCache.h:409
void loading()
Fired when the resource begins downloading.
qint64 getBytesReceived() const
For loading resources, returns the number of bytes received.
Definition: ResourceCache.h:445
virtual bool isCacheable() const
Checks whether the resource is cacheable.
Definition: ResourceCache.h:509
qint64 getBytes() const
For loaded resources, returns the number of actual bytes (defaults to total bytes if not explicitly s...
Definition: ResourceCache.h:451
virtual void refresh()
Refreshes the resource.
Definition: ResourceCache.cpp:647
virtual bool isLoaded() const
Checks whether the resource has loaded.
Definition: ResourceCache.h:439
virtual bool isFailed() const
Checks whether the resource has failed to download.
Definition: ResourceCache.h:442
void finished(bool success)
Fired when the resource has finished loading.
void onProgress(uint64_t bytesReceived, uint64_t bytesTotal)
Fired on progress updates.
void onRefresh()
Fired when the resource is refreshed.
float getProgress() const
For loading resources, returns the load progress.
Definition: ResourceCache.h:454
void loaded(const QByteArray request)
void failed(QNetworkReply::NetworkError error)
Fired when the resource failed to load.
float getLoadPriority()
Returns the highest load priority across all owners.
Definition: ResourceCache.cpp:630
virtual void setLoadPriority(const QPointer< QObject > &owner, float priority)
Sets the load priority for one owner.
Definition: ResourceCache.cpp:608
virtual void setLoadPriorities(const QHash< QPointer< QObject >, float > &priorities)
Sets a set of priorities at once.
Definition: ResourceCache.cpp:614
Q_INVOKABLE void finishedLoading(bool success)
Definition: ResourceCache.cpp:743
virtual void clearLoadPriority(const QPointer< QObject > &owner)
Clears the load priority for one owner.
Definition: ResourceCache.cpp:624
virtual void downloadFinished(const QByteArray &data)
Definition: ResourceCache.h:513
void setSize(const qint64 &bytes)
Called when the download is finished and processed, sets the number of actual bytes.
Definition: ResourceCache.cpp:753
int getLRUKey() const
Returns the key last used to identify this resource in the unused map.
Definition: ResourceCache.h:421
qint64 getBytesTotal() const
For loading resources, returns the number of total bytes (<= zero if unknown).
Definition: ResourceCache.h:448
virtual bool handleFailedRequest(ResourceRequest::Result result)
Return true if the resource will be retried.
Definition: ResourceCache.cpp:853
void ensureLoading()
Makes sure that the resource has started loading.
Definition: ResourceCache.cpp:602
virtual void makeRequest()
Definition: ResourceCache.cpp:764
void updateSize(qint64 deltaSize)
Fired when the size changes (through setSize).
Wrapper to expose resource caches to JS/QML.
Definition: ResourceCache.h:304
Wrapper to expose resources to JS/QML.
Definition: ResourceCache.h:91