[dali_2.3.20] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / texture-manager / texture-cache-manager.h
1 #ifndef DALI_TOOLKIT_TEXTURE_CACHE_MANAGER_H
2 #define DALI_TOOLKIT_TEXTURE_CACHE_MANAGER_H
3
4 /*
5  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 // EXTERNAL INCLUDES
21 #include <dali/devel-api/common/free-list.h>
22 #include <dali/public-api/adaptor-framework/encoded-image-buffer.h>
23 #include <unordered_map>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/texture-manager/texture-manager-type.h>
27 #include <dali-toolkit/internal/texture-manager/texture-upload-observer.h>
28 #include <dali-toolkit/internal/visuals/visual-url.h>
29
30 namespace Dali
31 {
32 namespace Toolkit
33 {
34 namespace Internal
35 {
36 /**
37  * @brief The contain and managing cached textures.
38  * Each Texture hold there TextureId. These TextureId can be used outside of TextureManager.
39  * Internally, each cached texture can be accessed by TextureCacheIndex.
40  * You can Convert TextureId into TextureCacheIndex by this class.
41  *
42  * Also, You can store external TextureSet or EncodedImageBuffer here.
43  *
44  * There are 3 type of CachedContainer in this manager
45  *  - mTextureInfoContainer : Cache all kind of textures that need some load/upload jobs.
46  *                            All kind of images that visual using (not vector image) will be stored here.
47  *                            This container will use TEXTURE_CACHE_INDEX_TYPE_LOCAL
48  *
49  *  - mExternalTextures : External appended TextureSet cache container.
50  *                        External TextureSet can be Something like NativeImageSource, FrameBuffer and PixelData.
51  *                        This container will use TEXTURE_CACHE_INDEX_TYPE_TEXTURE
52  *                        The textureId will be used for VisualUrl. ex) dali://1
53  *
54  *  - mEncodedImageBuffers : External appended EncodedImageBuffer cache container.
55  *                           This container will use TEXTURE_CACHE_INDEX_TYPE_BUFFER
56  *                           The bufferId will be used for VisualUrl. ex) enbuf://1
57  *                           Note that this bufferId is not equal with textureId in mTextureInfoContainer.
58  */
59 class TextureCacheManager
60 {
61 public:
62   // Copy enum and types and const values that TextureCacheManager will use.
63   using TextureCacheIndexType = TextureManagerType::TextureCacheIndexType;
64   using TextureCacheIndexData = TextureManagerType::TextureCacheIndexData;
65
66   using TextureId         = TextureManagerType::TextureId;
67   using TextureCacheIndex = TextureManagerType::TextureCacheIndex;
68   using TextureHash       = TextureManagerType::TextureHash;
69
70   static constexpr TextureId         INVALID_TEXTURE_ID  = TextureManagerType::INVALID_TEXTURE_ID;
71   static constexpr TextureCacheIndex INVALID_CACHE_INDEX = TextureManagerType::INVALID_CACHE_INDEX;
72
73   using StorageType         = TextureManagerType::StorageType;
74   using LoadState           = TextureManagerType::LoadState;
75   using ReloadPolicy        = TextureManagerType::ReloadPolicy;
76   using MultiplyOnLoad      = TextureManagerType::MultiplyOnLoad;
77   using TextureInfo         = TextureManagerType::TextureInfo;
78   using ExternalTextureInfo = TextureManagerType::ExternalTextureInfo;
79
80 public:
81   /**
82    * Constructor.
83    */
84   TextureCacheManager();
85
86   /**
87    * Destructor.
88    */
89   ~TextureCacheManager();
90
91 public:
92   // TextureCacheManager Main API:
93
94   /**
95    * @brief Get the visualUrl associated with the texture id.
96    * @param[in] textureId The texture Id to get
97    * @return The visual Url associated with the texture id.
98    */
99   VisualUrl GetVisualUrl(const TextureCacheManager::TextureId textureId);
100
101   /**
102    * @brief Get the current state of a texture
103    * @note This API doesn't consider encodedimagebuffer.
104    * @param[in] textureId The texture id to query.defaul value is 0.
105    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
106    * is not valid.
107    */
108   TextureCacheManager::LoadState GetTextureState(const TextureCacheManager::TextureId textureId);
109
110   /**
111    * @brief Get the current state of a texture
112    * @note This API doesn't consider external & encodedimagebuffer.
113    * @param[in] textureId The texture id to query
114    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
115    * is not valid.
116    */
117   TextureCacheManager::LoadState GetTextureStateInternal(const TextureCacheManager::TextureId textureId);
118
119   /**
120    * @brief Get the associated texture set if the texture id is valid
121    * @param[in] textureId The texture Id to look up
122    * @param[in] textureIndex The texture index to query
123    * @return the associated texture, or an empty handle if textureId is not valid
124    */
125   Texture GetTexture(const TextureCacheManager::TextureId textureId, const uint32_t textureIndex = 0);
126
127   /**
128    * @brief Get the external texture set information if the texture id is valid
129    * @param[in] textureId The texture Id to look up
130    * @return the external texture information. Assert if textureId is not valid
131    */
132   TextureCacheManager::ExternalTextureInfo& GetExternalTextureInfo(const TextureCacheManager::TextureId textureId);
133
134   /**
135    * @brief Get the encoded image buffer
136    * @param[in] bufferId The bufferId to look up
137    * @return the encoded image buffer, or an empty handle if bufferId is not valid
138    */
139   EncodedImageBuffer GetEncodedImageBuffer(const TextureCacheManager::TextureId bufferId);
140
141   /**
142    * @brief Get the encoded image buffer by VisualUrl
143    * @param[in] url The url to look up
144    * @return the encoded image buffer, or an empty handle if url is not buffer resource or buffer is not valid
145    */
146   EncodedImageBuffer GetEncodedImageBuffer(const VisualUrl& url);
147
148   /**
149    * Adds an external texture to the texture manager
150    * @param[in] texture The texture to add
151    * @param[in] preMultiplied Whether this external texture preMultiplied or not. Default as false.
152    * @return string containing the URL for the texture
153    */
154   std::string AddExternalTexture(const TextureSet& texture, const bool preMultiplied);
155
156   /**
157    * Adds an encoded image buffer to the texture manager
158    * @param[in] encodedImageBuffer The image buffer to add
159    * @return string containing the URL for the texture
160    */
161   std::string AddEncodedImageBuffer(const EncodedImageBuffer& encodedImageBuffer);
162
163   /**
164    * Removes an external texture from texture manager
165    * @param[in] url The string containing the texture to remove
166    * @return handle to the texture
167    */
168   TextureSet RemoveExternalTexture(const VisualUrl& url);
169
170   /**
171    * Removes an external encoded image buffer from texture manager
172    * @param[in] url The string containing the encoded image buffer to remove
173    * @return handle to the encoded image buffer
174    */
175   EncodedImageBuffer RemoveEncodedImageBuffer(const VisualUrl& url);
176
177   /**
178    * @brief Notify that external textures or encoded image buffers are used.
179    * @param[in] url The URL of the texture to use.
180    */
181   void UseExternalResource(const VisualUrl& url);
182
183 public:
184   // To Generate / Get / Remove TextureId.
185
186   /**
187    * @brief Generates a new valid TextureId.
188    * @param[in] textureCacheIndex the index of the cache container. If we don't setup this value, default is INVALID_CACHE_INDEX
189    * @return A TextureId
190    */
191   TextureCacheManager::TextureId GenerateTextureId(const TextureCacheIndex& textureCacheIndex = INVALID_CACHE_INDEX);
192
193   /**
194    * @brief Used to lookup an index into the TextureInfoContainer from a TextureId
195    * @param[in] textureId The TextureId to look up
196    * @return              The cache index
197    */
198   TextureCacheManager::TextureCacheIndex GetCacheIndexFromId(const TextureCacheManager::TextureId textureId);
199
200   /**
201    * @brief Generates a hash for caching based on the input parameters.
202    * Only applies size, fitting mode andsampling mode if the size is specified.
203    * Only applies maskTextureId if it isn't INVALID_TEXTURE_ID
204    * Only applied frameIndex if it is not 0.
205    * @param[in] url              The URL of the image to load
206    * @param[in] size             The image size
207    * @param[in] fittingMode      The FittingMode to use
208    * @param[in] samplingMode     The SamplingMode to use
209    * @param[in] maskTextureId    The masking texture id (or INVALID_TEXTURE_ID)
210    * @param[in] cropToMask       True if crop to mask
211    * @param[in] frameIndex       The frame index to use
212    * @return                     A hash of the provided data for caching.
213    */
214   TextureCacheManager::TextureHash GenerateHash(
215     const VisualUrl&                     url,
216     const Dali::ImageDimensions&         size,
217     const Dali::FittingMode::Type        fittingMode,
218     const Dali::SamplingMode::Type       samplingMode,
219     const TextureCacheManager::TextureId maskTextureId,
220     const bool                           cropToMask,
221     const uint32_t                       frameIndex);
222
223   /**
224    * @brief Looks up a cached texture by its hash.
225    * If found, the given parameters are used to check there is no hash-collision.
226    * @param[in] hash              The hash to look up
227    * @param[in] url               The URL of the image to load
228    * @param[in] size              The image size
229    * @param[in] fittingMode       The FittingMode to use
230    * @param[in] samplingMode      The SamplingMode to use
231    * @param[in] storageType       Whether the pixel data is stored in the cache or uploaded to the GPU
232    * @param[in] maskTextureId     Optional texture ID to use to mask this image
233    * @param[in] cropToMask        True if crop to mask
234    * @param[in] preMultiplyOnLoad if the image's color should be multiplied by it's alpha. Set to OFF if there is no alpha.
235    * @param[in] isAnimatedImage   True if the texture is from animated image.
236    * @param[in] frameIndex        The frame index to use
237    * @return                      A TextureCacheIndex of a cached Texture if found. Or INVALID_CACHE_INDEX if not found.
238    */
239   TextureCacheManager::TextureCacheIndex FindCachedTexture(
240     const TextureCacheManager::TextureHash    hash,
241     const VisualUrl&                          url,
242     const Dali::ImageDimensions&              size,
243     const Dali::FittingMode::Type             fittingMode,
244     const Dali::SamplingMode::Type            samplingMode,
245     const TextureCacheManager::StorageType    storageType,
246     const TextureCacheManager::TextureId      maskTextureId,
247     const bool                                cropToMask,
248     const TextureCacheManager::MultiplyOnLoad preMultiplyOnLoad,
249     const bool                                isAnimatedImage,
250     const uint32_t                            frameIndex);
251
252   /**
253    * @brief Append a Texture to the TextureCacheManager.
254    * @note This API doesn't check duplication of TextureId.
255    * @note This API doesn't consider external & encodedimagebuffer.
256    *
257    * @param[in] textureInfo TextureInfo that want to cache in container.
258    * @return Index of newly appended texture info.
259    */
260   TextureCacheManager::TextureCacheIndex AppendCache(const TextureCacheManager::TextureInfo& textureInfo);
261
262   /**
263    * @brief Remove a Texture from the TextureCacheManager.
264    * @note This API doesn't consider external & encodedimagebuffer.
265    *
266    * Textures are cached and therefore only the removal of the last
267    * occurrence of a Texture will cause its removal internally.
268    *
269    * @param[in] textureInfo TextureInfo that want to cache in container.
270    */
271   void RemoveCache(TextureCacheManager::TextureInfo& textureInfo);
272
273 public:
274   /**
275    * @brief Get TextureInfo as TextureCacheIndex.
276    * @note This API doesn't consider external & encodedimagebuffer.
277    * @param[in] textureCacheIndex Index of cahced texture.
278    * @return TextureInfo as textureCacheIndex
279    */
280   inline TextureCacheManager::TextureInfo& operator[](const TextureCacheManager::TextureCacheIndex& textureCacheIndex) noexcept
281   {
282     return mTextureInfoContainer[textureCacheIndex.GetIndex()];
283   }
284
285   /**
286    * @brief The number of associated cached image
287    * @note This API doesn't consider external & encodedimagebuffer.
288    * @return The number of associated cached image
289    */
290   inline size_t size() noexcept
291   {
292     return mTextureInfoContainer.size();
293   }
294
295 private:
296   // Private defined structs.
297
298   /**
299    * @brief This struct is used to manage the life-cycle of EncodedImageBuffer url.
300    */
301   struct EncodedImageBufferInfo
302   {
303     EncodedImageBufferInfo(const TextureCacheManager::TextureId   bufferId,
304                            const TextureCacheManager::TextureHash bufferHash,
305                            const EncodedImageBuffer&              encodedImageBuffer)
306     : bufferId(bufferId),
307       bufferHash(bufferHash),
308       encodedImageBuffer(encodedImageBuffer),
309       referenceCount(1)
310     {
311     }
312     TextureCacheManager::TextureId   bufferId;
313     TextureCacheManager::TextureHash bufferHash;
314     EncodedImageBuffer               encodedImageBuffer;
315     int32_t                          referenceCount;
316   };
317
318   typedef Dali::FreeList TextureIdConverterType; ///< The converter type from TextureId to index of TextureInfoContainer.
319
320   typedef std::unordered_map<TextureCacheManager::TextureHash, std::vector<TextureCacheManager::TextureId>> TextureHashContainerType;            ///< The container type used to fast-find the TextureId by TextureHash.
321   typedef std::vector<TextureCacheManager::TextureInfo>                                                     TextureInfoContainerType;            ///< The container type used to manage the life-cycle and caching of Textures
322   typedef std::vector<TextureCacheManager::ExternalTextureInfo>                                             ExternalTextureInfoContainerType;    ///< The container type used to manage the life-cycle and caching of ExternalTexture url
323   typedef std::vector<TextureCacheManager::EncodedImageBufferInfo>                                          EncodedImageBufferInfoContainerType; ///< The container type used to manage the life-cycle and caching of EncodedImageBuffer url
324
325 private:
326   // Private API: only used internally
327
328   /**
329    * @brief Used to lookup an index into the ExternalTextureInfoContainer from a textureId
330    * @param[in] textureId The TextureId to look up
331    * @return              The cache index
332    */
333   TextureCacheManager::TextureCacheIndex GetCacheIndexFromExternalTextureId(const TextureCacheManager::TextureId textureId);
334
335   /**
336    * @brief Used to lookup an index into the EncodedImageBufferInfoContainer from a bufferId
337    * @param[in] bufferId The bufferId to look up
338    * @return             The cache index
339    */
340   TextureCacheManager::TextureCacheIndex GetCacheIndexFromEncodedImageBufferId(const TextureCacheManager::TextureId bufferId);
341
342   /**
343    * @brief Looks up a cached encoded image buffer cached by its hash.
344    * If found, the given parameters are used to check there is no hash-collision.
345    * @param[in] hash               The hash to look up
346    * @param[in] encodedImageBuffer The image buffer to load
347    * @return                       A TextureCacheIndex of a cached Texture if found. Or INVALID_CACHE_INDEX if not found.
348    */
349   TextureCacheManager::TextureCacheIndex FindCachedEncodedImageBuffer(const TextureCacheManager::TextureHash hash, const EncodedImageBuffer& encodedImageBuffer);
350
351   /**
352    * @brief Remove id in HashContainer.
353    * @param[in] hash The hash of the texture/buffer to be delete
354    * @param[in] id   The texture/buffer id to be deleted.
355    */
356   void RemoveHashId(const TextureCacheManager::TextureHash hash, const TextureCacheManager::TextureId id);
357
358   /**
359    * @brief Remove data from container by the TextureCacheIndex.
360    * It also valiate the TextureIdConverter internally.
361    * We will assume that only valid TextureCacheIndex will come.
362    *
363    * @tparam ContainerType The type of container. It will automatically defined
364    * @param[in] cacheContainer The container that will remove texture info.
365    * @param[in] removeContainerIndex The index of texture info that will remove.
366    */
367   template<class ContainerType>
368   void RemoveTextureInfoByIndex(ContainerType& cacheContainer, const TextureCacheManager::TextureCacheIndex& removeContainerIndex);
369
370 private:
371   /**
372    * Deleted copy constructor.
373    */
374   TextureCacheManager(const TextureCacheManager&) = delete;
375
376   /**
377    * Deleted assignment operator.
378    */
379   TextureCacheManager& operator=(const TextureCacheManager& rhs) = delete;
380
381 private:                                            // Member Variables:
382   TextureIdConverterType   mTextureIdConverter{};   ///< Convert TextureId into various container's index.
383   TextureHashContainerType mTextureHashContainer{}; ///< Used to manage the life-cycle and caching of Textures + EncodedImageBuffer by TextureHash
384
385   TextureInfoContainerType            mTextureInfoContainer{}; ///< Used to manage the life-cycle and caching of Textures
386   ExternalTextureInfoContainerType    mExternalTextures{};     ///< Externally provided textures
387   EncodedImageBufferInfoContainerType mEncodedImageBuffers{};  ///< Externally encoded image buffer
388 };
389
390 } // namespace Internal
391
392 } // namespace Toolkit
393
394 } // namespace Dali
395
396 #endif // DALI_TOOLKIT_TEXTURE_CACHE_MANAGER_H