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