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