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