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