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