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