Merge "Add ApplyCustomFragmentPrefix" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.cpp
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/visuals/texture-manager-impl.h>
20
21 // EXTERNAL HEADERS
22 #include <dali/devel-api/adaptor-framework/environment-variable.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
25 #include <dali/devel-api/common/hash.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/math/vector4.h>
28 #include <dali/public-api/rendering/geometry.h>
29 #include <cstdlib>
30 #include <string>
31
32 // INTERNAL HEADERS
33 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
34 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
35 #include <dali-toolkit/internal/visuals/rendering-addon.h>
36 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
37
38 namespace
39 {
40 constexpr auto INITIAL_CACHE_NUMBER                    = size_t{0u};
41 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS  = size_t{4u};
42 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
43
44 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV  = "DALI_TEXTURE_LOCAL_THREADS";
45 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
46
47 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
48 {
49   using Dali::EnvironmentVariable::GetEnvironmentVariable;
50   auto           numberString          = GetEnvironmentVariable(environmentVariable);
51   auto           numberOfThreads       = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
52   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
53   DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
54   return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
55 }
56
57 size_t GetNumberOfLocalLoaderThreads()
58 {
59   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
60 }
61
62 size_t GetNumberOfRemoteLoaderThreads()
63 {
64   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
65 }
66
67 } // namespace
68
69 namespace Dali
70 {
71 namespace Toolkit
72 {
73 namespace Internal
74 {
75 namespace
76 {
77 #ifdef DEBUG_ENABLED
78 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
79
80 #define GET_LOAD_STATE_STRING(loadState)                                                                                                              \
81   loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : loadState == TextureManager::LoadState::LOADING          ? "LOADING"          \
82                                                                       : loadState == TextureManager::LoadState::LOAD_FINISHED    ? "LOAD_FINISHED"    \
83                                                                       : loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" \
84                                                                       : loadState == TextureManager::LoadState::MASK_APPLYING    ? "MASK_APPLYING"    \
85                                                                       : loadState == TextureManager::LoadState::MASK_APPLIED     ? "MASK_APPLIED"     \
86                                                                       : loadState == TextureManager::LoadState::UPLOADED         ? "UPLOADED"         \
87                                                                       : loadState == TextureManager::LoadState::CANCELLED        ? "CANCELLED"        \
88                                                                       : loadState == TextureManager::LoadState::LOAD_FAILED      ? "LOAD_FAILED"      \
89                                                                                                                                  : "Unknown"
90
91 #endif
92
93 const uint32_t DEFAULT_ATLAS_SIZE(1024u);               ///< This size can fit 8 by 8 images of average size 128 * 128
94 const Vector4  FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
95 const int      INVALID_INDEX(-1);                       ///< Invalid index used to represent a non-existant TextureInfo struct
96 const int      INVALID_CACHE_INDEX(-1);                 ///< Invalid Cache index
97
98 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
99 {
100   if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
101   {
102     if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
103     {
104       pixelBuffer.MultiplyColorByAlpha();
105     }
106   }
107   else
108   {
109     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
110   }
111 }
112
113 } // Anonymous namespace
114
115 TextureManager::MaskingData::MaskingData()
116 : mAlphaMaskUrl(),
117   mAlphaMaskId(INVALID_TEXTURE_ID),
118   mContentScaleFactor(1.0f),
119   mCropToMask(true)
120 {
121 }
122
123 TextureManager::TextureManager()
124 : mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }),
125   mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }),
126   mExternalTextures(),
127   mLifecycleObservers(),
128   mLoadQueue(),
129   mCurrentTextureId(0),
130   mQueueLoadFlag(false)
131 {
132   // Initialize the AddOn
133   RenderingAddOn::Get();
134 }
135
136 TextureManager::~TextureManager()
137 {
138   for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
139   {
140     (*iter)->TextureManagerDestroyed();
141   }
142 }
143
144 TextureSet TextureManager::LoadAnimatedImageTexture(
145   Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver)
146 {
147   TextureSet textureSet;
148
149   if(synchronousLoading)
150   {
151     Devel::PixelBuffer pixelBuffer;
152     if(animatedImageLoading)
153     {
154       pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
155     }
156     if(!pixelBuffer)
157     {
158       DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
159     }
160     else
161     {
162       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
163       if(!textureSet)
164       {
165         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
166         texture.Upload(pixelData);
167         textureSet = TextureSet::New();
168         textureSet.SetTexture(0u, texture);
169       }
170     }
171   }
172   else
173   {
174     auto preMultiply                    = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
175     textureId                           = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex);
176     TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
177     if(loadState == TextureManager::LoadState::UPLOADED)
178     {
179       // UploadComplete has already been called - keep the same texture set
180       textureSet = GetTextureSet(textureId);
181     }
182   }
183
184   if(textureSet)
185   {
186     Sampler sampler = Sampler::New();
187     sampler.SetWrapMode(wrapModeU, wrapModeV);
188     textureSet.SetSampler(0u, sampler);
189   }
190
191   return textureSet;
192 }
193
194 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
195   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
196 {
197   Devel::PixelBuffer pixelBuffer;
198   if(synchronousLoading)
199   {
200     if(url.IsValid())
201     {
202       pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
203       if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
204       {
205         PreMultiply(pixelBuffer, preMultiplyOnLoad);
206       }
207     }
208   }
209   else
210   {
211     RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
212   }
213
214   return pixelBuffer;
215 }
216
217 TextureSet TextureManager::LoadTexture(
218   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
219 {
220   TextureSet textureSet;
221
222   loadingStatus = false;
223   textureRect   = FULL_ATLAS_RECT;
224
225   if(VisualUrl::TEXTURE == url.GetProtocolType())
226   {
227     std::string location = url.GetLocation();
228     if(location.size() > 0u)
229     {
230       TextureId id = std::stoi(location);
231       for(auto&& elem : mExternalTextures)
232       {
233         if(elem.textureId == id)
234         {
235           preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
236           textureId         = elem.textureId;
237           return elem.textureSet;
238         }
239       }
240     }
241   }
242   else if(synchronousLoading)
243   {
244     PixelData data;
245     if(url.IsValid())
246     {
247       Devel::PixelBuffer pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
248       if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
249       {
250         Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
251         if(maskPixelBuffer)
252         {
253           pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
254         }
255       }
256       if(pixelBuffer)
257       {
258         PreMultiply(pixelBuffer, preMultiplyOnLoad);
259         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
260       }
261     }
262     if(!data)
263     {
264       DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous loading is failed\n");
265     }
266     else
267     {
268       if(atlasingStatus) // attempt atlasing
269       {
270         textureSet = imageAtlasManager->Add(textureRect, data);
271       }
272       if(!textureSet) // big image, no atlasing or atlasing failed
273       {
274         atlasingStatus  = false;
275         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), data.GetWidth(), data.GetHeight());
276         texture.Upload(data);
277         textureSet = TextureSet::New();
278         textureSet.SetTexture(0u, texture);
279       }
280       else
281       {
282         textureRectSize.SetWidth(data.GetWidth());
283         textureRectSize.SetHeight(data.GetHeight());
284       }
285     }
286   }
287   else
288   {
289     loadingStatus = true;
290     if(atlasingStatus)
291     {
292       textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
293     }
294     if(!textureSet) // big image, no atlasing or atlasing failed
295     {
296       atlasingStatus = false;
297       if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
298       {
299         textureId = RequestLoad(url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad);
300       }
301       else
302       {
303         maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl);
304         textureId              = RequestLoad(url,
305                                 maskInfo->mAlphaMaskId,
306                                 maskInfo->mContentScaleFactor,
307                                 desiredSize,
308                                 fittingMode,
309                                 samplingMode,
310                                 TextureManager::NO_ATLAS,
311                                 maskInfo->mCropToMask,
312                                 textureObserver,
313                                 orientationCorrection,
314                                 reloadPolicy,
315                                 preMultiplyOnLoad);
316       }
317
318       TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
319       if(loadState == TextureManager::LoadState::UPLOADED)
320       {
321         // UploadComplete has already been called - keep the same texture set
322         textureSet = GetTextureSet(textureId);
323       }
324
325       // If we are loading the texture, or waiting for the ready signal handler to complete, inform
326       // caller that they need to wait.
327       loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
328                        loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
329                        loadState == TextureManager::LoadState::MASK_APPLYING ||
330                        loadState == TextureManager::LoadState::MASK_APPLIED ||
331                        loadState == TextureManager::LoadState::NOT_STARTED ||
332                        mQueueLoadFlag);
333     }
334     else
335     {
336       textureRectSize = desiredSize;
337     }
338   }
339
340   if(!atlasingStatus && textureSet)
341   {
342     Sampler sampler = Sampler::New();
343     sampler.SetWrapMode(wrapModeU, wrapModeV);
344     textureSet.SetSampler(0u, sampler);
345   }
346
347   return textureSet;
348 }
349
350 TextureManager::TextureId TextureManager::RequestLoad(
351   const VisualUrl&                url,
352   const ImageDimensions           desiredSize,
353   FittingMode::Type               fittingMode,
354   Dali::SamplingMode::Type        samplingMode,
355   const UseAtlas                  useAtlas,
356   TextureUploadObserver*          observer,
357   bool                            orientationCorrection,
358   TextureManager::ReloadPolicy    reloadPolicy,
359   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
360 {
361   return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
362 }
363
364 TextureManager::TextureId TextureManager::RequestLoad(
365   const VisualUrl&                url,
366   TextureId                       maskTextureId,
367   float                           contentScale,
368   const ImageDimensions           desiredSize,
369   FittingMode::Type               fittingMode,
370   Dali::SamplingMode::Type        samplingMode,
371   const UseAtlas                  useAtlas,
372   bool                            cropToMask,
373   TextureUploadObserver*          observer,
374   bool                            orientationCorrection,
375   TextureManager::ReloadPolicy    reloadPolicy,
376   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
377 {
378   return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
379 }
380
381 TextureManager::TextureId TextureManager::RequestMaskLoad(const VisualUrl& maskUrl)
382 {
383   // Use the normal load procedure to get the alpha mask.
384   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
385   return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u);
386 }
387
388 TextureManager::TextureId TextureManager::RequestLoadInternal(
389   const VisualUrl&                url,
390   TextureId                       maskTextureId,
391   float                           contentScale,
392   const ImageDimensions           desiredSize,
393   FittingMode::Type               fittingMode,
394   Dali::SamplingMode::Type        samplingMode,
395   UseAtlas                        useAtlas,
396   bool                            cropToMask,
397   StorageType                     storageType,
398   TextureUploadObserver*          observer,
399   bool                            orientationCorrection,
400   TextureManager::ReloadPolicy    reloadPolicy,
401   TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
402   Dali::AnimatedImageLoading      animatedImageLoading,
403   uint32_t                        frameIndex)
404 {
405   // First check if the requested Texture is cached.
406   bool isAnimatedImage = (animatedImageLoading) ? true : false;
407
408   TextureHash textureHash = INITIAL_CACHE_NUMBER;
409   int         cacheIndex  = INVALID_CACHE_INDEX;
410   if(storageType != StorageType::RETURN_PIXEL_BUFFER && !isAnimatedImage)
411   {
412     textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId);
413
414     // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
415     cacheIndex = FindCachedTexture(textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, preMultiplyOnLoad);
416   }
417
418   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
419   // Check if the requested Texture exists in the cache.
420   if(cacheIndex != INVALID_CACHE_INDEX)
421   {
422     if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
423     {
424       // Mark this texture being used by another client resource. Forced reload would replace the current texture
425       // without the need for incrementing the reference count.
426       ++(mTextureInfoContainer[cacheIndex].referenceCount);
427     }
428     textureId = mTextureInfoContainer[cacheIndex].textureId;
429
430     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
431     preMultiplyOnLoad = mTextureInfoContainer[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
432
433     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
434   }
435
436   if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
437   {
438     // We need a new Texture.
439     textureId        = GenerateUniqueTextureId();
440     bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
441     mTextureInfoContainer.push_back(TextureInfo(textureId, maskTextureId, url.GetUrl(), desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
442     cacheIndex = mTextureInfoContainer.size() - 1u;
443
444     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
445   }
446
447   // The below code path is common whether we are using the cache or not.
448   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
449   // or a new TextureInfo just created.
450   TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
451   textureInfo.maskTextureId         = maskTextureId;
452   textureInfo.storageType           = storageType;
453   textureInfo.orientationCorrection = orientationCorrection;
454
455   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
456
457   // Force reloading of texture by setting loadState unless already loading or cancelled.
458   if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
459      TextureManager::LoadState::LOADING != textureInfo.loadState &&
460      TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
461      TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
462      TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
463      TextureManager::LoadState::CANCELLED != textureInfo.loadState)
464   {
465     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
466
467     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
468   }
469
470   // Check if we should add the observer.
471   // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
472   switch(textureInfo.loadState)
473   {
474     case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
475     case TextureManager::LoadState::NOT_STARTED:
476     {
477       LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
478       break;
479     }
480     case TextureManager::LoadState::LOADING:
481     case TextureManager::LoadState::WAITING_FOR_MASK:
482     case TextureManager::LoadState::MASK_APPLYING:
483     case TextureManager::LoadState::MASK_APPLIED:
484     {
485       ObserveTexture(textureInfo, observer);
486       break;
487     }
488     case TextureManager::LoadState::UPLOADED:
489     {
490       if(observer)
491       {
492         LoadOrQueueTexture(textureInfo, observer);
493       }
494       break;
495     }
496     case TextureManager::LoadState::CANCELLED:
497     {
498       // A cancelled texture hasn't finished loading yet. Treat as a loading texture
499       // (it's ref count has already been incremented, above)
500       textureInfo.loadState = TextureManager::LoadState::LOADING;
501       ObserveTexture(textureInfo, observer);
502       break;
503     }
504     case TextureManager::LoadState::LOAD_FINISHED:
505     {
506       // Loading has already completed.
507       if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
508       {
509         LoadOrQueueTexture(textureInfo, observer);
510       }
511       break;
512     }
513   }
514
515   // Return the TextureId for which this Texture can now be referenced by externally.
516   return textureId;
517 }
518
519 void TextureManager::Remove(const TextureManager::TextureId textureId, TextureUploadObserver* observer)
520 {
521   int textureInfoIndex = GetCacheIndexFromId(textureId);
522
523   if(textureInfoIndex != INVALID_INDEX)
524   {
525     TextureInfo& textureInfo(mTextureInfoContainer[textureInfoIndex]);
526
527     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) url:%s\n  cacheIdx:%d loadState:%s reference count = %d\n", textureId, textureInfo.url.GetUrl().c_str(), textureInfoIndex, GET_LOAD_STATE_STRING(textureInfo.loadState), textureInfo.referenceCount);
528
529     // Decrement the reference count and check if this is the last user of this Texture.
530     if(--textureInfo.referenceCount <= 0)
531     {
532       // This is the last remove for this Texture.
533       textureInfo.referenceCount = 0;
534       bool removeTextureInfo     = false;
535
536       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
537       if(textureInfo.loadState == LoadState::UPLOADED)
538       {
539         if(textureInfo.atlas)
540         {
541           textureInfo.atlas.Remove(textureInfo.atlasRect);
542         }
543         removeTextureInfo = true;
544       }
545       else if(textureInfo.loadState == LoadState::LOADING)
546       {
547         // We mark the textureInfo for removal.
548         // Once the load has completed, this method will be called again.
549         textureInfo.loadState = LoadState::CANCELLED;
550       }
551       else
552       {
553         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
554         removeTextureInfo = true;
555       }
556
557       // If the state allows us to remove the TextureInfo data, we do so.
558       if(removeTextureInfo)
559       {
560         // Permanently remove the textureInfo struct.
561         mTextureInfoContainer.erase(mTextureInfoContainer.begin() + textureInfoIndex);
562       }
563     }
564
565     if(observer)
566     {
567       // Remove element from the LoadQueue
568       for(auto&& element : mLoadQueue)
569       {
570         if(element.mObserver == observer)
571         {
572           // Do not erase the item. We will clear it later in ProcessQueuedTextures().
573           element.mObserver = nullptr;
574           break;
575         }
576       }
577     }
578   }
579 }
580
581 VisualUrl TextureManager::GetVisualUrl(TextureId textureId)
582 {
583   VisualUrl visualUrl("");
584   int       cacheIndex = GetCacheIndexFromId(textureId);
585
586   if(cacheIndex != INVALID_CACHE_INDEX)
587   {
588     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", cacheIndex, textureId);
589
590     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
591     visualUrl = cachedTextureInfo.url;
592   }
593   return visualUrl;
594 }
595
596 TextureManager::LoadState TextureManager::GetTextureState(TextureId textureId)
597 {
598   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
599
600   int cacheIndex = GetCacheIndexFromId(textureId);
601   if(cacheIndex != INVALID_CACHE_INDEX)
602   {
603     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
604     loadState = cachedTextureInfo.loadState;
605   }
606   else
607   {
608     for(auto&& elem : mExternalTextures)
609     {
610       if(elem.textureId == textureId)
611       {
612         loadState = LoadState::UPLOADED;
613         break;
614       }
615     }
616   }
617   return loadState;
618 }
619
620 TextureManager::LoadState TextureManager::GetTextureStateInternal(TextureId textureId)
621 {
622   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
623
624   int cacheIndex = GetCacheIndexFromId(textureId);
625   if(cacheIndex != INVALID_CACHE_INDEX)
626   {
627     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
628     loadState = cachedTextureInfo.loadState;
629   }
630
631   return loadState;
632 }
633
634 TextureSet TextureManager::GetTextureSet(TextureId textureId)
635 {
636   TextureSet textureSet; // empty handle
637
638   int cacheIndex = GetCacheIndexFromId(textureId);
639   if(cacheIndex != INVALID_CACHE_INDEX)
640   {
641     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
642     textureSet = cachedTextureInfo.textureSet;
643   }
644   else
645   {
646     for(auto&& elem : mExternalTextures)
647     {
648       if(elem.textureId == textureId)
649       {
650         textureSet = elem.textureSet;
651         break;
652       }
653     }
654   }
655   return textureSet;
656 }
657
658 std::string TextureManager::AddExternalTexture(TextureSet& textureSet)
659 {
660   TextureManager::ExternalTextureInfo info;
661   info.textureId  = GenerateUniqueTextureId();
662   info.textureSet = textureSet;
663   mExternalTextures.emplace_back(info);
664
665   return VisualUrl::CreateTextureUrl(std::to_string(info.textureId));
666 }
667
668 TextureSet TextureManager::RemoveExternalTexture(const std::string& url)
669 {
670   if(url.size() > 0u)
671   {
672     // get the location from the Url
673     if(VisualUrl::TEXTURE == VisualUrl::GetProtocolType(url))
674     {
675       std::string location = VisualUrl::GetLocation(url);
676       if(location.size() > 0u)
677       {
678         TextureId  id  = std::stoi(location);
679         const auto end = mExternalTextures.end();
680         for(auto iter = mExternalTextures.begin(); iter != end; ++iter)
681         {
682           if(iter->textureId == id)
683           {
684             auto textureSet = iter->textureSet;
685             if(--(iter->referenceCount) <= 0)
686             {
687               mExternalTextures.erase(iter);
688             }
689             return textureSet;
690           }
691         }
692       }
693     }
694   }
695   return TextureSet();
696 }
697
698 void TextureManager::UseExternalTexture(const VisualUrl& url)
699 {
700   if(VisualUrl::TEXTURE == url.GetProtocolType())
701   {
702     std::string location = url.GetLocation();
703     if(location.size() > 0u)
704     {
705       TextureId id = std::stoi(location);
706       for(auto&& elem : mExternalTextures)
707       {
708         if(elem.textureId == id)
709         {
710           elem.referenceCount++;
711           return;
712         }
713       }
714     }
715   }
716 }
717
718 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
719 {
720   // make sure an observer doesn't observe the same object twice
721   // otherwise it will get multiple calls to ObjectDestroyed()
722   DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
723   mLifecycleObservers.PushBack(&observer);
724 }
725
726 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
727 {
728   // Find the observer...
729   auto endIter = mLifecycleObservers.End();
730   for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
731   {
732     if((*iter) == &observer)
733     {
734       mLifecycleObservers.Erase(iter);
735       break;
736     }
737   }
738   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
739 }
740
741 void TextureManager::LoadOrQueueTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
742 {
743   switch(textureInfo.loadState)
744   {
745     case LoadState::NOT_STARTED:
746     case LoadState::LOAD_FAILED:
747     {
748       if(mQueueLoadFlag)
749       {
750         QueueLoadTexture(textureInfo, observer);
751       }
752       else
753       {
754         LoadTexture(textureInfo, observer);
755       }
756       break;
757     }
758     case LoadState::UPLOADED:
759     {
760       if(mQueueLoadFlag)
761       {
762         QueueLoadTexture(textureInfo, observer);
763       }
764       else
765       {
766         // The Texture has already loaded. The other observers have already been notified.
767         // We need to send a "late" loaded notification for this observer.
768         observer->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
769       }
770       break;
771     }
772     case LoadState::LOADING:
773     case LoadState::CANCELLED:
774     case LoadState::LOAD_FINISHED:
775     case LoadState::WAITING_FOR_MASK:
776     case LoadState::MASK_APPLYING:
777     case LoadState::MASK_APPLIED:
778     {
779       break;
780     }
781   }
782 }
783
784 void TextureManager::QueueLoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
785 {
786   auto textureId = textureInfo.textureId;
787   mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
788
789   observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
790 }
791
792 void TextureManager::LoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
793 {
794   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
795
796   textureInfo.loadState = LoadState::LOADING;
797   if(!textureInfo.loadSynchronously)
798   {
799     auto& loadersContainer  = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
800     auto  loadingHelperIt   = loadersContainer.GetNext();
801     auto  premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
802     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
803     if(textureInfo.animatedImageLoading)
804     {
805       loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
806     }
807     else
808     {
809       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
810     }
811   }
812   ObserveTexture(textureInfo, observer);
813 }
814
815 void TextureManager::ProcessQueuedTextures()
816 {
817   for(auto&& element : mLoadQueue)
818   {
819     if(!element.mObserver)
820     {
821       continue;
822     }
823
824     int cacheIndex = GetCacheIndexFromId(element.mTextureId);
825     if(cacheIndex != INVALID_CACHE_INDEX)
826     {
827       TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
828       if(textureInfo.loadState == LoadState::UPLOADED)
829       {
830         element.mObserver->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
831       }
832       else if(textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
833       {
834         element.mObserver->LoadComplete(true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied);
835       }
836       else
837       {
838         LoadTexture(textureInfo, element.mObserver);
839       }
840     }
841   }
842   mLoadQueue.Clear();
843 }
844
845 void TextureManager::ObserveTexture(TextureInfo&           textureInfo,
846                                     TextureUploadObserver* observer)
847 {
848   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
849
850   if(observer)
851   {
852     textureInfo.observerList.PushBack(observer);
853     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
854   }
855 }
856
857 void TextureManager::AsyncLoadComplete(AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, Devel::PixelBuffer pixelBuffer)
858 {
859   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id);
860
861   if(loadingContainer.size() >= 1u)
862   {
863     AsyncLoadingInfo loadingInfo = loadingContainer.front();
864
865     if(loadingInfo.loadId == id)
866     {
867       int cacheIndex = GetCacheIndexFromId(loadingInfo.textureId);
868       if(cacheIndex != INVALID_CACHE_INDEX)
869       {
870         TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
871
872         DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "  textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState);
873
874         if(textureInfo.loadState != LoadState::CANCELLED)
875         {
876           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
877           PostLoad(textureInfo, pixelBuffer);
878         }
879         else
880         {
881           Remove(textureInfo.textureId, nullptr);
882         }
883       }
884     }
885
886     loadingContainer.pop_front();
887   }
888 }
889
890 void TextureManager::PostLoad(TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
891 {
892   // Was the load successful?
893   if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
894   {
895     // No atlas support for now
896     textureInfo.useAtlas      = NO_ATLAS;
897     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
898
899     if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
900     {
901       // If there is a mask texture ID associated with this texture, then apply the mask
902       // if it's already loaded. If it hasn't, and the mask is still loading,
903       // wait for the mask to finish loading.
904       if(textureInfo.maskTextureId != INVALID_TEXTURE_ID)
905       {
906         if(textureInfo.loadState == LoadState::MASK_APPLYING)
907         {
908           textureInfo.loadState = LoadState::MASK_APPLIED;
909           UploadTexture(pixelBuffer, textureInfo);
910           NotifyObservers(textureInfo, true);
911         }
912         else
913         {
914           LoadState maskLoadState = GetTextureStateInternal(textureInfo.maskTextureId);
915           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
916           if(maskLoadState == LoadState::LOADING)
917           {
918             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
919           }
920           else if(maskLoadState == LoadState::LOAD_FINISHED)
921           {
922             // Send New Task to Thread
923             ApplyMask(textureInfo, textureInfo.maskTextureId);
924           }
925         }
926       }
927       else
928       {
929         UploadTexture(pixelBuffer, textureInfo);
930         NotifyObservers(textureInfo, true);
931       }
932     }
933     else
934     {
935       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
936       textureInfo.loadState   = LoadState::LOAD_FINISHED;
937
938       if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
939       {
940         NotifyObservers(textureInfo, true);
941       }
942       else
943       {
944         // Check if there was another texture waiting for this load to complete
945         // (e.g. if this was an image mask, and its load is on a different thread)
946         CheckForWaitingTexture(textureInfo);
947       }
948     }
949   }
950   else
951   {
952     textureInfo.loadState = LoadState::LOAD_FAILED;
953     CheckForWaitingTexture(textureInfo);
954     NotifyObservers(textureInfo, false);
955   }
956 }
957
958 void TextureManager::CheckForWaitingTexture(TextureInfo& maskTextureInfo)
959 {
960   // Search the cache, checking if any texture has this texture id as a
961   // maskTextureId:
962   const unsigned int size = mTextureInfoContainer.size();
963
964   for(unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex)
965   {
966     if(mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
967        mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
968     {
969       TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
970
971       if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
972       {
973         // Send New Task to Thread
974         ApplyMask(textureInfo, maskTextureInfo.textureId);
975       }
976       else
977       {
978         textureInfo.pixelBuffer.Reset();
979         textureInfo.loadState = LoadState::LOAD_FAILED;
980         NotifyObservers(textureInfo, false);
981       }
982     }
983   }
984 }
985
986 void TextureManager::ApplyMask(TextureInfo& textureInfo, TextureId maskTextureId)
987 {
988   int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
989   if(maskCacheIndex != INVALID_CACHE_INDEX)
990   {
991     Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
992     Devel::PixelBuffer pixelBuffer     = textureInfo.pixelBuffer;
993     textureInfo.pixelBuffer.Reset();
994
995     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
996
997     textureInfo.loadState   = LoadState::MASK_APPLYING;
998     auto& loadersContainer  = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
999     auto  loadingHelperIt   = loadersContainer.GetNext();
1000     auto  premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1001     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1002     loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1003   }
1004 }
1005
1006 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo)
1007 {
1008   if(textureInfo.useAtlas != USE_ATLAS)
1009   {
1010     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1011
1012     // Check if this pixelBuffer is premultiplied
1013     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1014
1015     auto& renderingAddOn = RenderingAddOn::Get();
1016     if(renderingAddOn.IsValid())
1017     {
1018       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1019     }
1020
1021     Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1022
1023     PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1024     texture.Upload(pixelData);
1025     if(!textureInfo.textureSet)
1026     {
1027       textureInfo.textureSet = TextureSet::New();
1028     }
1029     textureInfo.textureSet.SetTexture(0u, texture);
1030   }
1031
1032   // Update the load state.
1033   // Note: This is regardless of success as we care about whether a
1034   // load attempt is in progress or not.  If unsuccessful, a broken
1035   // image is still loaded.
1036   textureInfo.loadState = LoadState::UPLOADED;
1037 }
1038
1039 void TextureManager::NotifyObservers(TextureInfo& textureInfo, bool success)
1040 {
1041   TextureId textureId = textureInfo.textureId;
1042
1043   // If there is an observer: Notify the load is complete, whether successful or not,
1044   // and erase it from the list
1045   TextureInfo* info = &textureInfo;
1046
1047   mQueueLoadFlag = true;
1048
1049   while(info->observerList.Count())
1050   {
1051     TextureUploadObserver* observer = info->observerList[0];
1052
1053     // During UploadComplete() a Control ResourceReady() signal is emitted.
1054     // During that signal the app may add remove /add Textures (e.g. via
1055     // ImageViews).
1056     // It is possible for observers to be removed from the observer list,
1057     // and it is also possible for the mTextureInfoContainer to be modified,
1058     // invalidating the reference to the textureInfo struct.
1059     // Texture load requests for the same URL are deferred until the end of this
1060     // method.
1061     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState));
1062
1063     // It is possible for the observer to be deleted.
1064     // Disconnect and remove the observer first.
1065     observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1066
1067     info->observerList.Erase(info->observerList.begin());
1068
1069     if(info->storageType == StorageType::RETURN_PIXEL_BUFFER)
1070     {
1071       observer->LoadComplete(success, info->pixelBuffer, info->url, info->preMultiplied);
1072     }
1073     else
1074     {
1075       observer->UploadComplete(success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, info->preMultiplied);
1076     }
1077
1078     // Get the textureInfo from the container again as it may have been invalidated.
1079     int textureInfoIndex = GetCacheIndexFromId(textureId);
1080     if(textureInfoIndex == INVALID_CACHE_INDEX)
1081     {
1082       break; // texture has been removed - can stop.
1083     }
1084     info = &mTextureInfoContainer[textureInfoIndex];
1085   }
1086
1087   mQueueLoadFlag = false;
1088   ProcessQueuedTextures();
1089
1090   if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1091   {
1092     Remove(info->textureId, nullptr);
1093   }
1094 }
1095
1096 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
1097 {
1098   return mCurrentTextureId++;
1099 }
1100
1101 int TextureManager::GetCacheIndexFromId(const TextureId textureId)
1102 {
1103   const unsigned int size = mTextureInfoContainer.size();
1104
1105   for(unsigned int i = 0; i < size; ++i)
1106   {
1107     if(mTextureInfoContainer[i].textureId == textureId)
1108     {
1109       return i;
1110     }
1111   }
1112
1113   return INVALID_CACHE_INDEX;
1114 }
1115
1116 TextureManager::TextureHash TextureManager::GenerateHash(
1117   const std::string&             url,
1118   const ImageDimensions          size,
1119   const FittingMode::Type        fittingMode,
1120   const Dali::SamplingMode::Type samplingMode,
1121   const UseAtlas                 useAtlas,
1122   TextureId                      maskTextureId)
1123 {
1124   std::string    hashTarget(url);
1125   const size_t   urlLength = hashTarget.length();
1126   const uint16_t width     = size.GetWidth();
1127   const uint16_t height    = size.GetWidth();
1128
1129   // If either the width or height has been specified, include the resizing options in the hash
1130   if(width != 0 || height != 0)
1131   {
1132     // We are appending 5 bytes to the URL to form the hash input.
1133     hashTarget.resize(urlLength + 5u);
1134     char* hashTargetPtr = &(hashTarget[urlLength]);
1135
1136     // Pack the width and height (4 bytes total).
1137     *hashTargetPtr++ = size.GetWidth() & 0xff;
1138     *hashTargetPtr++ = (size.GetWidth() >> 8u) & 0xff;
1139     *hashTargetPtr++ = size.GetHeight() & 0xff;
1140     *hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff;
1141
1142     // Bit-pack the FittingMode, SamplingMode and atlasing.
1143     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1144     *hashTargetPtr = (fittingMode << 4u) | (samplingMode << 1) | useAtlas;
1145   }
1146   else
1147   {
1148     // We are not including sizing information, but we still need an extra byte for atlasing.
1149     hashTarget.resize(urlLength + 1u);
1150
1151     // Add the atlasing to the hash input.
1152     switch(useAtlas)
1153     {
1154       case UseAtlas::NO_ATLAS:
1155       {
1156         hashTarget[urlLength] = 'f';
1157         break;
1158       }
1159       case UseAtlas::USE_ATLAS:
1160       {
1161         hashTarget[urlLength] = 't';
1162         break;
1163       }
1164     }
1165   }
1166
1167   if(maskTextureId != INVALID_TEXTURE_ID)
1168   {
1169     auto textureIdIndex = hashTarget.length();
1170     hashTarget.resize(hashTarget.length() + sizeof(TextureId));
1171     unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&(hashTarget[textureIdIndex]));
1172
1173     // Append the texture id to the end of the URL byte by byte:
1174     // (to avoid SIGBUS / alignment issues)
1175     for(size_t byteIter = 0; byteIter < sizeof(TextureId); ++byteIter)
1176     {
1177       *hashTargetPtr++ = maskTextureId & 0xff;
1178       maskTextureId >>= 8u;
1179     }
1180   }
1181
1182   return Dali::CalculateHash(hashTarget);
1183 }
1184
1185 int TextureManager::FindCachedTexture(
1186   const TextureManager::TextureHash hash,
1187   const std::string&                url,
1188   const ImageDimensions             size,
1189   const FittingMode::Type           fittingMode,
1190   const Dali::SamplingMode::Type    samplingMode,
1191   const bool                        useAtlas,
1192   TextureId                         maskTextureId,
1193   TextureManager::MultiplyOnLoad    preMultiplyOnLoad)
1194 {
1195   // Default to an invalid ID, in case we do not find a match.
1196   int cacheIndex = INVALID_CACHE_INDEX;
1197
1198   // Iterate through our hashes to find a match.
1199   const unsigned int count = mTextureInfoContainer.size();
1200   for(unsigned int i = 0u; i < count; ++i)
1201   {
1202     if(mTextureInfoContainer[i].hash == hash)
1203     {
1204       // We have a match, now we check all the original parameters in case of a hash collision.
1205       TextureInfo& textureInfo(mTextureInfoContainer[i]);
1206
1207       if((url == textureInfo.url.GetUrl()) &&
1208          (useAtlas == textureInfo.useAtlas) &&
1209          (maskTextureId == textureInfo.maskTextureId) &&
1210          (size == textureInfo.desiredSize) &&
1211          ((size.GetWidth() == 0 && size.GetHeight() == 0) ||
1212           (fittingMode == textureInfo.fittingMode &&
1213            samplingMode == textureInfo.samplingMode)))
1214       {
1215         // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1216         // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1217         if((preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad) || (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied))
1218         {
1219           // The found Texture is a match.
1220           cacheIndex = i;
1221           break;
1222         }
1223       }
1224     }
1225   }
1226
1227   return cacheIndex;
1228 }
1229
1230 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1231 {
1232   const unsigned int count = mTextureInfoContainer.size();
1233   for(unsigned int i = 0; i < count; ++i)
1234   {
1235     TextureInfo& textureInfo(mTextureInfoContainer[i]);
1236     for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1237         j != textureInfo.observerList.End();)
1238     {
1239       if(*j == observer)
1240       {
1241         j = textureInfo.observerList.Erase(j);
1242       }
1243       else
1244       {
1245         ++j;
1246       }
1247     }
1248   }
1249
1250   // Remove element from the LoadQueue
1251   for(auto&& element : mLoadQueue)
1252   {
1253     if(element.mObserver == observer)
1254     {
1255       element.mObserver = nullptr;
1256     }
1257   }
1258 }
1259
1260 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1261 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, AsyncLoadingInfoContainerType())
1262 {
1263 }
1264
1265 void TextureManager::AsyncLoadingHelper::LoadAnimatedImage(TextureId                  textureId,
1266                                                            Dali::AnimatedImageLoading animatedImageLoading,
1267                                                            uint32_t                   frameIndex)
1268 {
1269   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1270   auto id                             = DevelAsyncImageLoader::LoadAnimatedImage(mLoader, animatedImageLoading, frameIndex);
1271   mLoadingInfoContainer.back().loadId = id;
1272 }
1273
1274 void TextureManager::AsyncLoadingHelper::Load(TextureId                                textureId,
1275                                               const VisualUrl&                         url,
1276                                               ImageDimensions                          desiredSize,
1277                                               FittingMode::Type                        fittingMode,
1278                                               SamplingMode::Type                       samplingMode,
1279                                               bool                                     orientationCorrection,
1280                                               DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1281 {
1282   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1283   auto id                             = DevelAsyncImageLoader::Load(mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
1284   mLoadingInfoContainer.back().loadId = id;
1285 }
1286
1287 void TextureManager::AsyncLoadingHelper::ApplyMask(TextureId                                textureId,
1288                                                    Devel::PixelBuffer                       pixelBuffer,
1289                                                    Devel::PixelBuffer                       maskPixelBuffer,
1290                                                    float                                    contentScale,
1291                                                    bool                                     cropToMask,
1292                                                    DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1293 {
1294   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1295   auto id                             = DevelAsyncImageLoader::ApplyMask(mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad);
1296   mLoadingInfoContainer.back().loadId = id;
1297 }
1298
1299 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1300 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1301 {
1302 }
1303
1304 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1305   Toolkit::AsyncImageLoader       loader,
1306   TextureManager&                 textureManager,
1307   AsyncLoadingInfoContainerType&& loadingInfoContainer)
1308 : mLoader(loader),
1309   mTextureManager(textureManager),
1310   mLoadingInfoContainer(std::move(loadingInfoContainer))
1311 {
1312   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1313     this, &AsyncLoadingHelper::AsyncLoadComplete);
1314 }
1315
1316 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
1317                                                            Devel::PixelBuffer pixelBuffer)
1318 {
1319   mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1320 }
1321
1322 Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements)
1323 {
1324   return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1325 }
1326
1327 } // namespace Internal
1328
1329 } // namespace Toolkit
1330
1331 } // namespace Dali