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