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